refactor!: simplify runtime tools and remove replay engines (#572)

* fix(hopper): report unavailable procedure body coverage

* refactor!: simplify runtime tools and remove replay engines

Keep direct inspection, capture, and comparison tools. Bind handlers to named contracts and let agents compose experiments with commands and local fixture servers.

BREAKING CHANGE: Remove controlled replay, Node characterization, finite replay-machine, managed runtime planning, and redundant string-tracing tools. Retire process replay, shims, reactive scenarios, custom checkpoints, and active browser replay and origin-scope inputs.
This commit is contained in:
morluto
2026-10-05 21:15:04 +08:00
committed by GitHub
parent c6d3bdf597
commit e07b81649e
258 changed files with 1193 additions and 22444 deletions
@@ -1,240 +0,0 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { createHash } from "node:crypto";
import { readFile, realpath } from "node:fs/promises";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import type { JavaScriptReplayConfiguration } from "../../../src/application/JavaScriptReplayPlanning.js";
import { controlledReplayOutputSchema } from "../../../src/domain/javascriptReplay.js";
import { nodeCharacterizationPreparationOutputSchema } from "../../../src/domain/nodeRuntimeCharacterization.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
function createReplayConfiguration(): JavaScriptReplayConfiguration {
return {
nodePath: process.execPath,
bubblewrapPath: process.execPath,
systemdRunPath: process.execPath,
systemctlPath: process.execPath,
shellPath: process.execPath,
};
}
function createReplayScenario(root: string) {
const configuration = createReplayConfiguration();
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
availabilityPolicy: () => ({
processCaptureEnabled: true,
controlledReplayEnabled: true,
}),
javascriptReplayConfiguration: () => configuration,
javascriptReplayHost: {
readSource: async (path) => ({
canonicalPath: await realpath(path),
bytes: await readFile(path),
}),
identifyExecutable: async (path) => ({
path,
version: "fixture",
sha256: "1".repeat(64),
}),
identifyWorker: async () => ({
path: "/fixture/worker.js",
version: "fixture-worker-1",
sha256: "2".repeat(64),
}),
identifyRuntimeClosure: async (path) => [
{
sourcePath: path,
destinationPath: "/runtime/node",
sha256: "1".repeat(64),
},
],
seccompDigest: () => "3".repeat(64),
probe: async () => undefined,
},
javascriptReplayRunner: {
execute: async (prepared) => ({
plan_digest: prepared.publicPlan.plan_digest,
outcomes: [
{
case_id: "heading",
outcome: "return",
value: { type: "heading", text: "Title" },
input_sha256:
prepared.publicPlan.cases[0]?.sha256 ?? "0".repeat(64),
output_sha256: "2".repeat(64),
truncated: false,
},
],
stderr: "",
termination: "completed",
cleanup: { state: "complete", residual_resources: [] },
limitations: ["fixture runner"],
reproducer: null,
}),
},
});
const client = new Client({ name: "replay-parity-test", version: "1" });
return { client, server, session };
}
function createReplayInput(root: string) {
return {
mode: "plan",
left: {
modules: [
{
alias: "parser",
path: resolve(root, "parser.mjs"),
format: "esm",
role: "module",
dependencies: {},
},
],
entry_alias: "parser",
entry_export: "default",
},
cases: [{ case_id: "heading", arguments: ["# Title"] }],
};
}
async function executeReplayScenario(
client: Client,
session: BinarySession,
root: string,
) {
const input = createReplayInput(root);
const planned = await client.callTool({
name: "run_controlled_replay",
arguments: input,
});
expect(planned.isError).not.toBe(true);
const digest = controlledReplayOutputSchema.parse(planned.structuredContent)
.plan?.plan_digest;
expect(digest).toMatch(/^[a-f0-9]{64}$/u);
const executed = await client.callTool({
name: "run_controlled_replay",
arguments: {
...input,
mode: "execute",
plan_digest: digest,
},
});
expect(executed.isError).not.toBe(true);
expect(executed.structuredContent).toMatchObject({
phase: "execute",
evidence: {
authority: "controlled-replay",
provider: { id: "rea-javascript-replay" },
},
});
expect(session.exportEvidenceBundle().records).toEqual(
expect.arrayContaining([
expect.objectContaining({ authority: "controlled-replay" }),
]),
);
}
async function createCharacterizationInput(root: string) {
const factoryPath = resolve(root, "sanitizer.factory.txt");
const factoryBytes = await readFile(factoryPath);
const factorySha256 = createHash("sha256").update(factoryBytes).digest("hex");
return {
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"] }],
},
};
}
async function executeCharacterizationScenario(
client: Client,
session: BinarySession,
root: string,
) {
const input = await createCharacterizationInput(root);
const plan = await client.callTool({
name: "prepare_node_characterization",
arguments: input,
});
expect(plan.isError).not.toBe(true);
const preparedPlan = nodeCharacterizationPreparationOutputSchema.parse(
plan.structuredContent,
).plan;
const characterized = await client.callTool({
name: "execute_node_characterization",
arguments: {
plan_sha256: preparedPlan.plan_sha256,
preparation: input,
},
});
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",
}),
expect.objectContaining({
predicate_type: "rea.runtime-characterization",
}),
]),
);
}
describe("application workflow MCP parity", () => {
it("plans and executes the same controlled replay contract", async () => {
const root = resolve("tests/fixtures/replay");
const { client, server, session } = createReplayScenario(root);
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await executeReplayScenario(client, session, root);
await executeCharacterizationScenario(client, session, root);
} finally {
await client.close();
await server.close();
await session.close();
}
});
});
@@ -13,7 +13,6 @@ import {
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
} from "../../../src/contracts/javascriptApplicationWorkflowExamples.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";
const execute = promisify(execFile);
@@ -269,7 +268,7 @@ describe("application workflow CLI export Evidence", () => {
}, 20_000);
});
describe("application workflow CLI validation and replay", () => {
describe("application workflow CLI validation", () => {
it("returns safe actionable JSON validation details", async () => {
const malformed = await runCli([
"trace-application-feature",
@@ -298,64 +297,6 @@ describe("application workflow CLI validation and replay", () => {
},
});
}, 20_000);
it("runs a replay machine from inline and file-backed JSON", async () => {
const input = REPLAY_MACHINE_RUN_EXAMPLE;
const inline = await runCli([
"run-replay-machine",
JSON.stringify(input),
"--json",
]);
expect(inline).toMatchObject({
final_state: "complete",
decisions: [{ outcome: "matched" }],
transition_journal: [
{ captured_aliases: [{ name: "token", sensitive: true }] },
],
});
expect(JSON.stringify(inline)).not.toContain("opaque");
const root = await createTestTempDirectory("rea-replay-machine-cli-");
temporary.push(root);
const inputPath = join(root, "run.json");
await writeFile(inputPath, JSON.stringify(input));
const fileBacked = await runCli([
"run-replay-machine",
inputPath,
"--json",
]);
expect(fileBacked).toEqual(inline);
const invalid = await runCli([
"run-replay-machine",
JSON.stringify({
machine: input.machine,
events: [
{
protocol: "http",
connection: "not_applicable",
at_ms: 0,
method: null,
path: "/callback",
headers: {},
body: "private-cli-body",
},
],
}),
"--json",
]);
expect(invalid).toMatchObject({
code: "invalid_request",
details: {
issues: expect.arrayContaining([
expect.objectContaining({
path: ["events", 0, "method"],
}),
]),
},
});
expect(JSON.stringify(invalid)).not.toContain("private-cli-body");
}, 20_000);
});
const runCli = async (
@@ -104,10 +104,6 @@ describe("local application workflow verifier", () => {
right: { availability: "literal", value: 1 },
},
],
runtime_validation: {
recommended_tool: "run_controlled_replay",
automatically_started: false,
},
});
}, 20_000);
});
-1
View File
@@ -302,7 +302,6 @@ const completeScenarioCapture = () => {
},
scenario: {
start_origin: "https://app.example.test",
allowed_origins: ["https://app.example.test"],
action_count: 1,
secret_references: [],
},
@@ -126,9 +126,6 @@ describe("canonical product catalog", () => {
"compare_javascript_export_shapes",
"compare_source_to_bundle",
"evaluate_reconstruction_coverage",
"execute_node_characterization",
"prepare_node_characterization",
"run_controlled_replay",
"trace_application_feature",
"trace_javascript_semantics",
]);
@@ -138,7 +135,6 @@ describe("canonical product catalog", () => {
).toEqual([
"compare_managed_members",
"import_managed_reconstruction",
"plan_managed_runtime_correlation",
"project_managed_application_graph",
"verify_managed_native_boundaries",
]);
@@ -3,22 +3,6 @@ import { describe, expect } from "vitest";
import { cliTest } from "../../support/cli/cliFixture.js";
describe("projected CLI failures", () => {
cliTest(
"exits unsuccessfully for invalid replay configuration",
async ({ cli }) => {
const result = await cli.run({
arguments: ["run-controlled-replay", "{}", "--json"],
environment: { REA_JAVASCRIPT_REPLAY_NODE_PATH: "relative/node" },
});
expect(result.json).toMatchObject({
code: "configuration_invalid",
category: "execution_failure",
retryable: false,
});
expect(result.exitCode).toBe(1);
},
);
cliTest(
"exits unsuccessfully for invalid managed reconstruction input",
async ({ cli }) => {
@@ -64,11 +64,9 @@ describe("JavaScript export return-shape comparison", () => {
unpaired_left_variants: 0,
unpaired_right_variants: 0,
});
expect(first.runtime_validation).toEqual({
recommended_tool: "run_controlled_replay",
automatically_started: false,
required_for: "runtime-semantics",
});
expect(first.limitations).toContain(
"This static comparison cannot establish runtime semantics; run behavioral probes directly against the relevant application versions when that evidence is required.",
);
});
it("keeps additions unknown when spread coverage is incomplete", async () => {
@@ -1,178 +0,0 @@
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { planManagedRuntimeCorrelationEvidence } from "../../../src/application/ManagedRuntimeCorrelationService.js";
import { MANAGED_STATIC_PROVIDER } from "../../../src/application/InvestigationProviders.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import {
managedRuntimeCorrelationInputSchema,
managedRuntimeCorrelationResultSchema,
} from "../../../src/domain/managedRuntimeCorrelation.js";
import { inspectManagedMembersBytes } from "../../../src/dotnet/ManagedMemberInspector.js";
import {
buildManagedPeFixture,
managedPeFixtureTarget,
} from "../../../src/dotnet/ManagedPe.fixture.js";
describe("managed runtime correlation planning", () => {
it("records an exact-build non-executing plan without REA permission grants", async () => {
const directory = await createTestTempDirectory("rea-managed-runtime-");
const artifactPath = join(directory, "fixture.dll");
const executablePath = process.execPath;
const fixture = inspect(buildManagedPeFixture(), artifactPath);
let configurationReads = 0;
const result = await planManagedRuntimeCorrelationEvidence(
{
configuration: () => {
configurationReads += 1;
return { executablePath };
},
},
{
...inputFor(fixture.evidence, fixture.method),
bounds: {
timeout_ms: 5_000,
max_threads: 32,
max_output_bytes: 65_536,
allow_network: true,
allow_ui: true,
},
},
);
expect(configurationReads).toBe(1);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.operation).toBe("plan_managed_runtime_correlation");
expect(result.value.confidence).toBe("derived");
expect(result.value.authority).toBe("analyst-inference");
const plan = managedRuntimeCorrelationResultSchema.parse(
result.value.normalized_result,
);
expect(
managedRuntimeCorrelationInputSchema.safeParse({
...inputFor(fixture.evidence, fixture.method),
bounds: {
timeout_ms: 60_001,
max_threads: 257,
max_output_bytes: 1_048_577,
allow_network: true,
allow_ui: true,
},
}).success,
).toBe(true);
expect(
managedRuntimeCorrelationResultSchema.safeParse({
...plan,
limitations: Array.from({ length: 1_001 }, () => "x".repeat(4_097)),
}).success,
).toBe(true);
expect(plan).toMatchObject({
executed: false,
method_lock: {
token: "0x06000001",
exact_build_required: true,
},
requested_runtime: {
effect: "instrumentation",
executable_path: executablePath,
network: "host",
confinement: "not-established",
},
effect_taxonomy: {
instruments_code: true,
invokes_target_code: false,
},
unsupported_until_executor_exists: true,
});
});
it("rejects a method lock that no longer matches static Evidence", async () => {
const directory = await createTestTempDirectory("rea-managed-runtime-");
const artifactPath = join(directory, "fixture.dll");
const executablePath = process.execPath;
const fixture = inspect(buildManagedPeFixture(), artifactPath);
const result = await planManagedRuntimeCorrelationEvidence(
{ configuration: () => ({ executablePath }) },
{
...inputFor(fixture.evidence, fixture.method),
method: {
...inputFor(fixture.evidence, fixture.method).method,
normalized_il_sha256: "0".repeat(64),
},
},
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error._tag).toBe("AnalysisInputError");
});
it("plans without probing or requiring an installed runtime executable", async () => {
const fixture = inspect(
buildManagedPeFixture(),
"/tmp/managed-runtime.dll",
);
const result = await planManagedRuntimeCorrelationEvidence(
{ configuration: () => ({ executablePath: undefined }) },
inputFor(fixture.evidence, fixture.method),
);
expect(result.ok).toBe(true);
if (!result.ok) return;
const plan = managedRuntimeCorrelationResultSchema.parse(
result.value.normalized_result,
);
expect(plan.executed).toBe(false);
expect(plan.requested_runtime.executable_path).toBe("dotnet");
expect(plan.limitations.join(" ")).toContain(
"prerequisites are unverified",
);
});
});
const inputFor = (
staticMembers: ReturnType<typeof createEvidence>,
method: ReturnType<typeof inspect>["method"],
) => ({
static_members: staticMembers,
method: {
token: method.token,
signature_sha256: method.signature.raw_sha256,
normalized_il_sha256: method.body.normalized_il_sha256,
},
requested_effect: "instrumentation" as const,
host: {
os: "linux" as const,
clr_family: "dotnet" as const,
architecture: "x86_64" as const,
},
bounds: {
timeout_ms: 5_000,
max_threads: 32,
max_output_bytes: 65_536,
allow_network: false as const,
allow_ui: false as const,
},
});
const inspect = (bytes: Buffer, path: string) => {
const target = managedPeFixtureTarget(bytes, path);
const result = inspectManagedMembersBytes(bytes, target);
const method = result.methods[0];
if (method === undefined) throw new Error("fixture has no method");
return {
result,
method,
evidence: createEvidence(target, MANAGED_STATIC_PROVIDER, {
operation: "inspect_managed_members",
parameters: {},
result,
rawResult: null,
limitations: result.limitations,
}),
};
};
@@ -1,282 +0,0 @@
import { createHash } from "node:crypto";
import { readFile, realpath, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
executeNodeCharacterization,
prepareNodeCharacterization,
} from "../../../src/application/NodeRuntimeCharacterizationService.js";
import type {
JavaScriptReplayConfiguration,
JavaScriptReplayHost,
JavaScriptReplayRunner,
} from "../../../src/application/JavaScriptReplayPlanning.js";
import {
nodeCharacterizationPreparationInputSchema,
nodeCharacterizationPreparationOutputSchema,
} from "../../../src/domain/nodeRuntimeCharacterization.js";
import { createRuntimeCharacterizationPlan } from "../../../src/domain/runtimeCharacterization.js";
const sha256 = (value: Uint8Array): string =>
createHash("sha256").update(value).digest("hex");
describe("Node runtime characterization", () => {
it("prepares without execution, then requires the exact prepared plan hash", 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" },
},
transformation: {
original_sha256: fixture.sha256,
output_format: "commonjs-factory",
},
transformation_evidence: {
predicate_type: "rea.javascript-export-transformation",
authority: "shipped-artifact",
},
replay: { phase: "plan" },
});
expect(() =>
nodeCharacterizationPreparationOutputSchema.parse({
...output,
plan: { ...output.plan, expected_effect: "bounded-effects" },
}),
).toThrow();
const stale = await executeNodeCharacterization(dependencies, {
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, {
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",
authority: "controlled-replay",
},
});
expect(executions).toBe(1);
expect(await readFile(fixture.path)).toEqual(Buffer.from(fixture.bytes));
});
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),
},
},
});
});
// Neither the declared call budget nor the alias length has a ceiling. The
// absence of a cap cannot be asserted through the preparation path, because
// the budget is derived from the case count, so reaching a large value end to
// end would mean submitting tens of thousands of cases. Assert it where a
// bound would actually be added, at a value far above any ceiling a change
// would plausibly introduce.
it("admits call budgets and aliases beyond any plausible ceiling", async () => {
const fixture = await createFixture();
const input = preparationInput(fixture);
const alias = "a".repeat(4_096);
const parsed = nodeCharacterizationPreparationInputSchema.parse({
...input,
selected_alias: alias,
replay: {
...input.replay,
left: {
...input.replay.left,
entry_alias: alias,
modules: input.replay.left.modules.map((module) => ({
...module,
alias,
})),
},
},
});
expect(parsed.selected_alias).toBe(alias);
const prepared = await prepareNodeCharacterization(
dependenciesFor(fixture.root, () => undefined),
input,
);
expect(prepared.ok).toBe(true);
if (!prepared.ok) return;
const { plan_sha256: _digest, ...plan } =
nodeCharacterizationPreparationOutputSchema.parse(prepared.value).plan;
expect(
createRuntimeCharacterizationPlan({
...plan,
limits: { ...plan.limits, max_calls: 10_000_001 },
}).limits.max_calls,
).toBe(10_000_001);
});
});
const createFixture = async () => {
const root = await createTestTempDirectory("rea-characterization-");
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>>,
) => ({
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 "] }],
},
});
const dependenciesFor = (root: string, onExecute: () => void) => {
const configuration: JavaScriptReplayConfiguration = {
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 {
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,
};
},
};
return { configuration: () => configuration, host, runner };
};
@@ -1,44 +0,0 @@
import { access, readFile } from "node:fs/promises";
import { dirname } from "node:path";
import { describe, expect, it } from "vitest";
import { buildLinuxX64ReplaySeccomp } from "../../../src/replay/LinuxSeccompPolicy.js";
import { temporaryFilterHandle } from "../../../src/replay/ReplaySeccompFile.js";
describe("replay seccomp file ownership", () => {
it("writes the policy bytes and removes its private directory on close", async () => {
const filter = await temporaryFilterHandle();
try {
expect(await readFile(filter.path)).toEqual(
Buffer.from(buildLinuxX64ReplaySeccomp()),
);
expect(await filter.handle.readFile()).toEqual(
Buffer.from(buildLinuxX64ReplaySeccomp()),
);
} finally {
await filter.close();
}
await expect(access(dirname(filter.path))).rejects.toThrow();
await filter.close();
});
it.skipIf(process.platform !== "linux")(
"removes the directory even when descriptor cleanup rejects",
async () => {
const filter = await temporaryFilterHandle();
const close = filter.handle.close.bind(filter.handle);
const failure = new Error("injected descriptor cleanup failure");
filter.handle.close = async () => {
throw failure;
};
try {
await expect(filter.close()).rejects.toBe(failure);
await expect(access(dirname(filter.path))).rejects.toThrow();
} finally {
filter.handle.close = close;
await filter.close();
}
},
);
});
@@ -1,79 +0,0 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { prepareReplayPlan } from "../../../src/application/JavaScriptReplayPlanning.js";
import { controlledReplayInputSchema } from "../../../src/domain/javascriptReplay.js";
import { SystemJavaScriptReplayHost } from "../../../src/replay/SystemJavaScriptReplayHost.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("replay source byte admission", () => {
it.each([0, 16, 65_537])("reads exactly %i admitted bytes", async (limit) => {
const root = await createTestTempDirectory("rea-replay-source-");
const path = join(root, "module.mjs");
const bytes = Buffer.alloc(limit, 0x61);
await writeFile(path, bytes);
expect(
await new SystemJavaScriptReplayHost().readSource(path, limit),
).toEqual({
canonicalPath: path,
bytes,
});
});
it("rejects an oversized source and a directory", async () => {
const root = await createTestTempDirectory("rea-replay-source-");
const path = join(root, "module.mjs");
await writeFile(path, "oversized");
const host = new SystemJavaScriptReplayHost();
await expect(host.readSource(path, 1)).rejects.toThrow("declared limit");
await expect(host.readSource(root, 1)).rejects.toThrow();
});
});
it("rejects a host result larger than the remaining module budget", async () => {
const path = process.execPath;
const identity = { path, version: "fixture", sha256: "1".repeat(64) };
const input = controlledReplayInputSchema.parse({
mode: "plan",
left: {
modules: [
{
alias: "entry",
path,
format: "esm",
role: "module",
dependencies: {},
},
],
entry_alias: "entry",
entry_export: "default",
},
cases: [{ case_id: "one", arguments: [] }],
limits: { module_bytes: 16 },
});
await expect(
prepareReplayPlan(
input,
{
nodePath: path,
bubblewrapPath: path,
systemdRunPath: path,
systemctlPath: path,
shellPath: path,
},
{
readSource: async (canonicalPath, maximumBytes) => ({
canonicalPath,
bytes: Buffer.alloc(maximumBytes + 1),
}),
identifyExecutable: async () => identity,
identifyWorker: async () => identity,
identifyRuntimeClosure: async () => [],
seccompDigest: () => "2".repeat(64),
probe: async () => undefined,
},
),
).rejects.toThrow("Replay module bytes exceed the aggregate limit");
});
@@ -81,7 +81,6 @@ const captureFor = (scenario: BrowserScenario): BrowserScenarioCapture => {
},
scenario: {
start_origin: new URL(start).origin,
allowed_origins: scenario.allowed_origins,
action_count: scenario.actions.length,
secret_references: scenario.secrets.map(({ secret_id: id }) => id),
},
@@ -109,7 +108,6 @@ const minimalScenario = (origin = "https://app.example.test") => ({
executable_path: process.execPath,
},
start_url: { url: `${origin}/`, query: [] },
allowed_origins: [origin],
actions: [
{
step_id: "settle",
@@ -173,7 +171,6 @@ describe("browser scenario MCP tool", () => {
expect(provider.scenarios[0]).toMatchObject({
environment: { color_scheme: "light", service_workers: "block" },
storage: { cookies: [], local_storage: [], session_storage: [] },
request_replay: { mode: "disabled" },
capture: { after_each_step: [], at_end: ["url"], events: [] },
});
-1
View File
@@ -18,6 +18,5 @@ describe("MCP server composition", () => {
expect(client.getInstructions()).not.toContain("open_binary");
const names = (await client.listTools()).tools.map(({ name }) => name);
expect(names).not.toContain("compare_managed_members");
expect(names).not.toContain("plan_managed_runtime_correlation");
});
});
@@ -214,7 +214,6 @@ describe("enhanced MCP tools", () => {
["analyze_function", { procedure: "0x1" }],
["inspect_native_api", { procedure: "0x1" }],
["trace_feature", { query: "hello" }],
["find_code_for_string", { query: "hello" }],
["trace_call_path", { start: "0x1", goal: "0x2" }],
["trace_native_ui_action", { action: "missing-selector" }],
["inspect_native_dispatch_metadata", { max_records: 100 }],
@@ -294,11 +293,6 @@ describe("enhanced MCP tools", () => {
],
});
expect(results[10]).toMatchObject({
query: "hello",
matches: [{ type: "string", address: "0x30", value: "hello" }],
truncated: false,
});
expect(results[11]).toMatchObject({
start: "0x1",
goal: "0x2",
direction: "forward",
@@ -310,11 +304,11 @@ describe("enhanced MCP tools", () => {
],
truncated: false,
});
expect(results[12]).toMatchObject({
expect(results[11]).toMatchObject({
start: "missing-selector",
reason: "ui_action_or_object_not_found",
});
expect(results[13]).toMatchObject({
expect(results[12]).toMatchObject({
target_sha256: "a".repeat(64),
provider: {
id: "fixture",
@@ -327,7 +321,7 @@ describe("enhanced MCP tools", () => {
]),
},
});
expect(results[14]).toMatchObject({
expect(results[13]).toMatchObject({
target_sha256: "a".repeat(64),
decompilations: 1,
unknowns: [
+29 -56
View File
@@ -1,68 +1,42 @@
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { describe, expect, it } from "vitest";
import { run } from "../../../src/main.js";
import {
createServer,
type CreateServerOptions,
} from "../../../src/server/createServer.js";
type RuntimeDependencies = NonNullable<Parameters<typeof run>[0]>;
import { parseConfig } from "../../../src/config.js";
import { silentLogger } from "../../../src/logger.js";
import { registerConfigReload } from "../../../src/main/reload.js";
import type { RuntimeDependencies } from "../../../src/main/types.js";
import { createRuntimeState } from "../../../src/main/state.js";
describe("runtime configuration reload", () => {
it("updates runtime executable configuration for connected server factories", async () => {
const env: NodeJS.ProcessEnv = {
REA_JAVASCRIPT_REPLAY_NODE_PATH: "/first/node",
REA_MANAGED_RUNTIME_EXECUTABLE_PATH: "/first/dotnet",
};
const runtime = await startRuntime(env);
it("applies a valid configuration reload", () => {
const env: NodeJS.ProcessEnv = { REA_LOG_LEVEL: "info" };
const runtime = setupReload(env);
expect(runtime.options.javascriptReplayConfiguration?.()).toMatchObject({
nodePath: "/first/node",
});
expect(runtime.options.managedRuntimeConfiguration?.()).toEqual({
executablePath: "/first/dotnet",
});
env.REA_JAVASCRIPT_REPLAY_NODE_PATH = "/second/node";
env.REA_MANAGED_RUNTIME_EXECUTABLE_PATH = "/second/dotnet";
env.REA_LOG_LEVEL = "debug";
runtime.reload();
expect(runtime.options.javascriptReplayConfiguration?.()).toMatchObject({
nodePath: "/second/node",
});
expect(runtime.options.managedRuntimeConfiguration?.()).toEqual({
executablePath: "/second/dotnet",
});
expect(runtime.state.currentConfig.logLevel).toBe("debug");
});
it("retains the last valid runtime configuration after an invalid reload", async () => {
const env: NodeJS.ProcessEnv = {
REA_JAVASCRIPT_REPLAY_NODE_PATH: "/valid/node",
REA_MANAGED_RUNTIME_EXECUTABLE_PATH: "/valid/dotnet",
};
const runtime = await startRuntime(env);
it("retains the last valid configuration after an invalid reload", () => {
const env: NodeJS.ProcessEnv = { REA_LOG_LEVEL: "info" };
const runtime = setupReload(env);
env.REA_JAVASCRIPT_REPLAY_BWRAP_PATH = "relative/bwrap";
env.REA_LOG_LEVEL = "invalid";
runtime.reload();
expect(runtime.options.javascriptReplayConfiguration?.()).toMatchObject({
nodePath: "/valid/node",
});
expect(runtime.options.managedRuntimeConfiguration?.()).toEqual({
executablePath: "/valid/dotnet",
});
expect(runtime.state.currentConfig.logLevel).toBe("info");
});
});
const startRuntime = async (env: NodeJS.ProcessEnv) => {
const setupReload = (env: NodeJS.ProcessEnv) => {
const parsed = parseConfig(env);
if (!parsed.ok) throw parsed.error;
const state = createRuntimeState(parsed.value);
let reload: (() => void) | undefined;
let options: CreateServerOptions | undefined;
const dependencies: RuntimeDependencies = {
env,
serve: (factory) => {
void factory({ era: "legacy" });
return { close: () => Promise.resolve() };
},
serve: serveStdio,
writeStderr: () => undefined,
setExitCode: () => undefined,
registerShutdown: () => () => undefined,
@@ -70,14 +44,13 @@ const startRuntime = async (env: NodeJS.ProcessEnv) => {
reload = handler;
return () => undefined;
},
createServer: (analysis, session, received) => {
options = received;
return createServer(analysis, session, received);
},
};
expect(await run(dependencies)).toBe(0);
if (reload === undefined || options === undefined)
throw new Error("Runtime reload seam was not initialized");
return { reload, options };
registerConfigReload({
dependencies,
runtimeState: state,
serverLogger: silentLogger,
});
if (reload === undefined)
throw new Error("Reload handler was not registered");
return { reload, state };
};
-49
View File
@@ -29,13 +29,11 @@ it("opens a managed PE and executes the managed static provider through MCP", as
]),
);
const server = createServer(session, session, {
managedRuntimeConfiguration: () => ({ executablePath: process.execPath }),
availabilityPolicy: () => ({
processCaptureEnabled: false,
investigationInputRoots: 0,
browserObservationEnabled: false,
electronObservationEnabled: false,
javascriptReplayEnabled: false,
}),
});
const client = new Client({ name: "managed-mcp-test", version: "1.0.0" });
@@ -66,7 +64,6 @@ const verifyManagedCatalogAndNativeWorkflow = async (
"compare_managed_members",
"import_managed_reconstruction",
"verify_managed_native_boundaries",
"plan_managed_runtime_correlation",
]),
);
for (const evidence of [
@@ -221,7 +218,6 @@ const verifyManagedComparisonAndReconstruction = async (
expect(method).toBeDefined();
if (method === undefined) return;
await verifyImport(client, members, method);
await verifyRuntimePlan(client, members, method);
};
type ManagedMethod = NonNullable<ReturnType<typeof methodFrom>>;
@@ -278,51 +274,6 @@ const verifyImport = async (
});
};
const verifyRuntimePlan = async (
client: Client,
members: Record<string, unknown>,
method: ManagedMethod,
): Promise<void> => {
const planned = inlineEvidence(
structured(
await client.callTool({
name: "plan_managed_runtime_correlation",
arguments: {
static_members: members,
method: {
token: method.token,
signature_sha256: method.signature.raw_sha256,
normalized_il_sha256: method.body.normalized_il_sha256,
},
requested_effect: "attach",
host: {
os: "linux",
clr_family: "dotnet",
architecture: "x86_64",
},
bounds: {
timeout_ms: 5000,
max_threads: 32,
max_output_bytes: 65536,
allow_network: false,
allow_ui: false,
},
},
}),
),
);
expect(planned).toMatchObject({
operation: "plan_managed_runtime_correlation",
provider: { id: "rea-dotnet-workflows" },
confidence: "derived",
normalized_result: {
executed: false,
requested_runtime: { effect: "attach", network: "none" },
effect_taxonomy: { attaches_process: true },
},
});
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (
typeof result.structuredContent !== "object" ||
@@ -1,70 +0,0 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { REPLAY_MACHINE_RUN_EXAMPLE } from "../../../src/contracts/replayMachineExample.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
describe("direct replay machine MCP parity", () => {
it("returns typed journal output and safe validation failures", async () => {
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session);
const client = new Client({ name: "replay-machine-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const example = REPLAY_MACHINE_RUN_EXAMPLE;
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "run_replay_machine",
arguments: example,
});
expect(result).toMatchObject({
structuredContent: {
result: {
final_state: "complete",
terminal: true,
decisions: [{ outcome: "matched", transition_sequence: 0 }],
transition_journal: [
{
transition_id: "accept_callback",
captured_aliases: [{ name: "token", sensitive: true }],
},
],
},
},
});
expect(JSON.stringify(result)).not.toContain("opaque");
const invalid = await client.callTool({
name: "run_replay_machine",
arguments: {
...example,
events: [
{
protocol: "http",
connection: "not_applicable",
at_ms: 0,
method: null,
path: "/callback",
headers: {},
body: "private-request-body",
},
],
},
});
expect(invalid.isError).toBe(true);
expect(invalid.structuredContent).toBeUndefined();
expect(JSON.stringify(invalid)).not.toContain("private-request-body");
} finally {
await client.close();
await server.close();
await session.close();
}
});
});
+2 -13
View File
@@ -128,7 +128,7 @@ it("does not record capability unavailability without supporting Evidence", asyn
});
});
it("records approved capture disagreement as a contradicted unknown", async () => {
it("records capture disagreement as a contradicted unknown", async () => {
const session = createTestBinarySession(
() =>
({
@@ -149,17 +149,6 @@ it("records approved capture disagreement as a contradicted unknown", async () =
outcome: "dispatched",
},
],
shim_events: [
{
sequence: 0,
at_ms: 0,
command: "fixture",
route_index: null,
arguments: [],
working_directory: "/tmp",
outcome: "unmatched",
},
],
});
const captureEvidence = (capture: typeof left) =>
createEvidence(undefined, PROCESS_PROVIDER, {
@@ -213,7 +202,7 @@ it("records approved capture disagreement as a contradicted unknown", async () =
{
status: "contradicted",
domain: "process-comparison",
question: "Process captures disagree across: interaction, shim",
question: "Process captures disagree across: interaction",
contradicting_evidence_ids: [rightEvidence.evidence_id],
},
],
@@ -99,24 +99,6 @@ describe("MCP JSON Schema validity", () => {
const { tools } = await client.listTools();
const advertised = new Map(tools.map((tool) => [tool.name, tool]));
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const replayContract = TOOL_CONTRACTS.find(
({ name }) => name === "run_controlled_replay",
);
const replayTool = advertised.get("run_controlled_replay");
if (replayContract === undefined || replayTool === undefined)
throw new Error("Controlled replay tool was not advertised");
const replayExample = replayContract.examples[0];
if (replayExample === undefined)
throw new Error("Controlled replay tool has no valid example");
const invalidReplay = {
...replayExample.input,
cases: [],
};
expect(replayContract.inputSchema.safeParse(invalidReplay).success).toBe(
false,
);
expect(ajv.compile(replayTool.inputSchema)(invalidReplay)).toBe(false);
const graphContract = TOOL_CONTRACTS.find(
({ name }) => name === "project_managed_application_graph",
);
@@ -3,14 +3,11 @@ import { rm, symlink } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { itWithCaptureCapability } from "./processCaptureCapability.js";
import {
captureProcessScenario,
ProcessCaptureError,
} from "../../../src/application/ProcessHarness.js";
import { captureProcessScenario } from "../../../src/application/ProcessHarness.js";
import { parseProcessScenario } from "../../../src/domain/processCapture.js";
const processFixture = fileURLToPath(
@@ -86,15 +83,8 @@ itWithCaptureCapability(
},
);
// Each action is triggered by observed terminal output rather than a wall-clock
// offset. A fixed `at_ms` can fire before the child has written its prompt under
// host contention, which drops the input and the resize echo and made this test
// load-flaky.
//
// This also covers the reactive `resize` path against time bucketing: rendered
// frames must share the normalized clock used by captured frames. They did not,
// so the capture failed validation with "rendered_frames: timestamps must be
// ordered" until the renderer call in ProcessReactiveEffects was normalized.
// Events are scheduled relative to PTY startup, so the child is already live
// before the input, resize, and signal are delivered.
itWithCaptureCapability(
"captures source-owned interactive, resize, Unicode, and signal behavior",
async () => {
@@ -103,86 +93,14 @@ itWithCaptureCapability(
executable: process.execPath,
arguments: [processFixture, "interactive"],
working_directory: dirname(processFixture),
events: [
{ type: "input", at_ms: 200, data: "answer" },
{ type: "resize", at_ms: 400, columns: 100, rows: 40 },
{ type: "signal", at_ms: 700, signal: "SIGINT" },
],
normalization: { time_bucket_ms: 10 },
timeout_ms: 20_000,
idle_timeout_ms: 10_000,
reactive: {
initial_state: "awaiting_prompt",
deadline_ms: 15_000,
states: [
{
id: "awaiting_prompt",
max_visits: 1,
deadline_ms: 10_000,
on: [
{
id: "answer",
priority: 0,
max_uses: 1,
when: {
kind: "terminal_text",
literal: "prompt>",
occurrence: 1,
since: { kind: "scenario_start" },
consume: true,
},
actions: [
{ type: "send_input", data: "answer", sensitive: false },
],
target: { kind: "goto", state: "awaiting_resize" },
},
],
},
{
id: "awaiting_resize",
max_visits: 1,
deadline_ms: 10_000,
on: [
{
id: "resize",
priority: 0,
max_uses: 1,
when: {
kind: "terminal_text",
literal: "input:answer",
occurrence: 1,
since: { kind: "scenario_start" },
consume: true,
},
actions: [{ type: "resize", columns: 100, rows: 40 }],
target: { kind: "goto", state: "awaiting_signal" },
},
],
},
{
id: "awaiting_signal",
max_visits: 1,
deadline_ms: 10_000,
on: [
{
id: "signal",
priority: 0,
max_uses: 1,
when: {
kind: "terminal_text",
literal: "resize:100x40",
occurrence: 1,
since: { kind: "scenario_start" },
consume: true,
},
actions: [
{
type: "send_signal",
target: { kind: "root" },
signal: "SIGINT",
},
],
target: { kind: "finish" },
},
],
},
],
},
}),
);
if (!result.ok) throw result.error;
@@ -1,253 +0,0 @@
import { rm } from "node:fs/promises";
import { dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { itWithCaptureCapability } from "./processCaptureCapability.js";
import { captureProcessScenario } from "../../../src/application/ProcessHarness.js";
import {
parseProcessScenario,
type ProcessCapture,
} from "../../../src/domain/processCapture.js";
import { processCaptureIssues } from "../../../src/domain/processCapture.fixture.js";
type EventSource = "process" | "filesystem" | "http" | "websocket" | "shim";
function eventTrigger(
source: EventSource,
exact: Record<string, unknown>,
ignoreFields: readonly string[],
) {
return {
kind: "event" as const,
source,
exact,
ignore_fields: ignoreFields,
since: { kind: "scenario_start" as const },
consume: true,
cardinality: { min: 1, max: 1 },
};
}
function collectionTriggers() {
const terminalTrigger = (literal: string) => ({
kind: "terminal_text" as const,
literal,
occurrence: 1,
since: { kind: "scenario_start" as const },
consume: false,
});
return [
{
kind: "any" as const,
triggers: [
terminalTrigger("Collecting"),
terminalTrigger("unreachable-alternative"),
],
},
eventTrigger(
"process",
{
pid: 3,
parent_pid: 1,
command: "rea-reactive-worker",
process_group_id: 1,
session_id: process.platform === "darwin" ? null : 1,
},
["at_ms"],
),
eventTrigger(
"filesystem",
{
name: "ready_snapshot",
truncated: false,
},
["at_ms", "files", "effects"],
),
eventTrigger(
"shim",
{
command: "codex",
route_index: 0,
arguments: ["probe"],
working_directory: "<working-directory>",
outcome: "matched",
},
["sequence", "at_ms"],
),
{
kind: "sequence" as const,
triggers: [
eventTrigger(
"http",
{
protocol: "http",
direction: "request",
method: "GET",
path: "/reactive",
data: "",
outcome: "matched",
},
["sequence", "at_ms"],
),
eventTrigger(
"websocket",
{
protocol: "websocket",
direction: "received",
method: null,
path: "/ws",
data: "reactive-client",
outcome: "matched",
},
["sequence", "at_ms"],
),
],
},
];
}
function createMultiSourceScenario(root: string, script: string) {
return parseProcessScenario({
executable: process.execPath,
arguments: [script, "codex"],
working_directory: root,
filesystem_observation_paths: [root],
normalization: { paths: true },
replay: {
http: [{ method: "GET", path: "/reactive", status: 200, body: "ok" }],
websocket_messages: ["reactive-server"],
},
command_shims: [
{
name: "codex",
routes: [
{
arguments: ["probe"],
outputs: [],
termination: { type: "exit", code: 0 },
},
],
},
],
reactive: {
initial_state: "ready",
deadline_ms: 8_000,
states: [
{
id: "ready",
max_visits: 1,
deadline_ms: 3_000,
on: [
{
id: "checkpoint_ready",
priority: 0,
max_uses: 1,
when: {
kind: "terminal_text",
literal: "Ready",
occurrence: 1,
since: { kind: "scenario_start" },
consume: true,
},
actions: [{ type: "checkpoint", name: "ready_snapshot" }],
target: { kind: "goto", state: "collecting" },
},
],
},
{
id: "collecting",
max_visits: 1,
deadline_ms: 5_000,
on: [
{
id: "finish_all_sources",
priority: 0,
max_uses: 1,
when: { kind: "all", triggers: collectionTriggers() },
actions: [],
target: { kind: "finish" },
},
],
},
],
},
});
}
// This is the single multi-source acceptance matrix for the process boundary.
itWithCaptureCapability(
"runs the committed multi-source reactive fixture deterministically",
async () => {
const root = await createTestTempDirectory("rea-reactive-e2e-");
const script = fileURLToPath(
new URL("../../fixtures/processReactiveScenario.mjs", import.meta.url),
);
const run = () =>
captureProcessScenario(createMultiSourceScenario(root, script));
try {
const first = await run();
const second = await run();
if (!first.ok) throw first.error;
if (!second.ok) throw second.error;
expect(first.ok).toBe(true);
expect(second.ok).toBe(true);
const trace = (capture: ProcessCapture) =>
capture.reactive_run?.transitions.map((transition) => ({
transition_id: transition.transition_id,
from: transition.state_before,
to: transition.state_after,
outcome: transition.outcome,
trigger_collections: transition.trigger_event_ids.map(
(id) => id.split(".")[1],
),
}));
expect(
first.value.reactive_run?.outcome,
JSON.stringify({
run: first.value.reactive_run,
processes: first.value.process_samples,
checkpoints: first.value.filesystem_checkpoints,
shims: first.value.shim_events,
protocols: first.value.protocol_events,
}),
).toBe("passed");
expect(trace(first.value)).toEqual(trace(second.value));
expect(trace(first.value)).toEqual([
expect.objectContaining({ transition_id: "checkpoint_ready" }),
expect.objectContaining({
transition_id: "finish_all_sources",
trigger_collections: expect.arrayContaining([
"frames",
"process_samples",
"filesystem_checkpoints",
"shim_events",
"protocol_events",
]),
}),
]);
for (const outcome of ["action_rejected", "target_lost"] as const) {
const failedActionCapture = {
...first.value,
reactive_run: {
status: "finished" as const,
outcome,
active_state: "ready",
transitions: [],
controls: [],
},
};
expect(
processCaptureIssues(failedActionCapture).filter(({ path }) =>
path.startsWith("reactive_run"),
),
).toEqual([]);
}
expect(first.value.truncated).toBe(false);
} finally {
await rm(root, { recursive: true, force: true });
}
},
30_000,
);
@@ -1,399 +0,0 @@
import { rm, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { itWithCaptureCapability } from "./processCaptureCapability.js";
import { captureProcessScenario } from "../../../src/application/ProcessHarness.js";
import {
parseProcessScenario,
type ProcessCapture,
} from "../../../src/domain/processCapture.js";
import { processCaptureIssues } from "../../../src/domain/processCapture.fixture.js";
function createInteractiveScenario(root: string, script: string) {
return parseProcessScenario({
executable: process.execPath,
arguments: [script],
working_directory: root,
reactive: {
initial_state: "waiting",
deadline_ms: 5_000,
states: [
{
id: "waiting",
max_visits: 1,
deadline_ms: 2_000,
on: [
{
id: "answer",
priority: 0,
max_uses: 1,
when: {
kind: "terminal_text",
literal: "Ready",
occurrence: 1,
since: { kind: "scenario_start" },
consume: true,
},
actions: [
{ type: "send_input", data: "accepted\n", sensitive: true },
{ type: "close_stdin" },
],
target: { kind: "goto", state: "finishing" },
},
],
},
{
id: "finishing",
max_visits: 1,
deadline_ms: 2_000,
on: [
{
id: "complete",
priority: 0,
max_uses: 1,
when: {
kind: "terminal_text",
literal: "Done",
occurrence: 1,
since: { kind: "state_entry" },
consume: true,
},
actions: [],
target: { kind: "finish" },
},
],
},
],
},
});
}
function assertCompletedCapture(capture: ProcessCapture): void {
expect(capture.reactive_run).toMatchObject({
status: "finished",
outcome: "passed",
active_state: "finishing",
});
expect(
capture.reactive_run?.transitions.map(({ transition_id }) => transition_id),
).toEqual(["answer", "complete"]);
expect(capture.interaction_events).toContainEqual(
expect.objectContaining({
type: "input",
data: "<redacted-input:9-bytes>",
outcome: "dispatched",
}),
);
expect(capture.interaction_events).toContainEqual(
expect.objectContaining({
type: "stdin_close",
data: "",
outcome: "dispatched",
}),
);
expect(capture.frames.map(({ data }) => data).join("")).toContain("Done");
expect(capture.manifest.comparison_contract).toHaveProperty("reactive");
expect(JSON.stringify(capture.manifest.comparison_contract)).not.toContain(
"accepted",
);
expect(JSON.stringify(capture.manifest.scenario)).not.toContain("accepted");
}
function assertControlAndTransitionValidation(capture: ProcessCapture): void {
const reactiveRun = capture.reactive_run;
if (reactiveRun === null) throw new Error("reactive result missing");
const lastOrder = capture.event_journal
?.filter(({ collection }) =>
[
"frames",
"interaction_events",
"filesystem_checkpoints",
"shim_events",
].includes(collection),
)
.at(-1)?.capture_order;
if (lastOrder === undefined)
throw new Error("reactive observation order missing");
expect(
processCaptureIssues({
...capture,
reactive_run: {
...reactiveRun,
controls: [
...reactiveRun.controls,
{
sequence: reactiveRun.controls.length,
kind: "target_lost",
after_capture_order: lastOrder,
},
],
},
}),
).toContainEqual(
expect.objectContaining({
path: `reactive_run.controls[${String(reactiveRun.controls.length)}]`,
message: "reactive control cannot follow a finished run",
}),
);
expect(
processCaptureIssues({
...capture,
reactive_run: {
...reactiveRun,
transitions: reactiveRun.transitions.map((transition, index) =>
index === 0
? { ...transition, transition_id: "fabricated" }
: transition,
),
},
}),
).toContainEqual(
expect.objectContaining({
path: "reactive_run.transitions[0]",
message:
"reactive transition is not declared by its recorded source state",
}),
);
expect(
processCaptureIssues({
...capture,
reactive_run: {
status: "finished",
outcome: "passed",
active_state: "waiting",
transitions: [],
controls: [],
},
}),
).toContainEqual(
expect.objectContaining({
path: "reactive_run.outcome",
message: "reactive outcome differs from deterministic journal replay",
}),
);
const suffix = reactiveRun.transitions
.slice(1)
.map((transition, sequence) => ({
...transition,
sequence,
}));
expect(
processCaptureIssues({
...capture,
reactive_run: { ...reactiveRun, transitions: suffix },
}),
).toContainEqual(
expect.objectContaining({
path: "reactive_run.transitions[0].state_before",
message:
"reactive transition journal must start at the declared initial state",
}),
);
}
function assertReplayValidation(capture: ProcessCapture): void {
const reactiveRun = capture.reactive_run;
if (reactiveRun === null) throw new Error("reactive result missing");
expect(
processCaptureIssues({
...capture,
reactive_run: {
...reactiveRun,
transitions: reactiveRun.transitions.map((transition, index) =>
index === 0
? { ...transition, trigger_event_ids: [], action_event_ids: [] }
: transition,
),
},
}),
).toEqual(
expect.arrayContaining([
expect.objectContaining({
path: "reactive_run.transitions",
message: expect.stringContaining(
"reactive transition journal is not reproduced",
),
}),
expect.objectContaining({
path: "reactive_run.transitions[0].action_event_ids",
message: expect.stringContaining(
"recorded action observations do not match proposed effects",
),
}),
]),
);
expect(
processCaptureIssues({
...capture,
reactive_run: { ...reactiveRun, status: "running", outcome: null },
}),
).toContainEqual(
expect.objectContaining({
message: "completed capture requires a finished reactive outcome",
}),
);
expect(
processCaptureIssues({
...capture,
reactive_run: {
...reactiveRun,
transitions: [
reactiveRun.transitions[0]!,
{ ...reactiveRun.transitions[0]!, sequence: 1 },
],
},
}),
).toEqual(
expect.arrayContaining([
expect.objectContaining({
message: "reactive transition states must be contiguous",
}),
expect.objectContaining({
message:
"reactive transition differs from deterministic journal replay",
}),
]),
);
}
itWithCaptureCapability(
"drives a process from terminal observations and retains the reactive transition journal",
async () => {
const root = await createTestTempDirectory("rea-reactive-harness-test-");
const script = join(root, "reactive.mjs");
await writeFile(
script,
[
'import { createInterface } from "node:readline";',
"const input = createInterface({ input: process.stdin, terminal: false });",
'process.stdout.write("Ready\\n");',
'input.once("line", () => { process.stdout.write("Done\\n"); input.close(); });',
].join("\n"),
);
const scenario = createInteractiveScenario(root, script);
try {
const result = await captureProcessScenario(scenario);
if (!result.ok) throw result.error;
assertCompletedCapture(result.value);
assertControlAndTransitionValidation(result.value);
assertReplayValidation(result.value);
} finally {
await rm(root, { recursive: true, force: true });
}
},
);
itWithCaptureCapability(
"records target loss before post-exit settlement can win the deadline race",
async () => {
const root = await createTestTempDirectory(
"rea-reactive-target-loss-test-",
);
const script = join(root, "exit.mjs");
await writeFile(script, 'process.stdout.write("exiting\\n");\n');
const scenario = parseProcessScenario({
executable: process.execPath,
arguments: [script],
working_directory: root,
settle_ms: 500,
reactive: {
initial_state: "waiting",
deadline_ms: 5_000,
states: [
{
id: "waiting",
max_visits: 1,
// Leave process startup scheduling headroom; this test targets
// post-exit settlement ordering, not a 300ms startup deadline.
deadline_ms: 2_000,
on: [
{
id: "unreachable",
priority: 0,
max_uses: 1,
when: {
kind: "terminal_text",
literal: "never-produced",
occurrence: 1,
since: { kind: "scenario_start" },
consume: true,
},
actions: [],
target: { kind: "finish" },
},
],
},
],
},
});
try {
const result = await captureProcessScenario(scenario);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.reactive_run).toMatchObject({
status: "finished",
outcome: "target_lost",
active_state: "waiting",
transitions: [],
controls: [
expect.objectContaining({
kind: "target_lost",
}),
],
});
const frame = result.value.frames.at(-1);
const journal = result.value.event_journal;
const reactiveRun = result.value.reactive_run;
if (frame === undefined || journal === undefined || reactiveRun === null)
throw new Error("ordered reactive evidence missing");
const laterCaptureOrder = journal.length;
const withLaterMatch = {
...result.value,
frames: [
...result.value.frames,
{
...frame,
sequence: result.value.frames.length,
at_ms: frame.at_ms + 1,
data: "never-produced",
},
],
event_journal: [
...journal,
{
capture_order: laterCaptureOrder,
collection: "frames" as const,
index: result.value.frames.length,
},
],
};
expect(
processCaptureIssues(withLaterMatch).filter(({ path }) =>
path.startsWith("reactive_run"),
),
).toEqual([]);
expect(
processCaptureIssues({
...withLaterMatch,
reactive_run: {
...reactiveRun,
controls: reactiveRun.controls.map((control) => ({
...control,
after_capture_order: laterCaptureOrder,
})),
},
}),
).toContainEqual(
expect.objectContaining({
path: "reactive_run.outcome",
message: "reactive outcome differs from deterministic journal replay",
}),
);
} finally {
await rm(root, { recursive: true, force: true });
}
},
10_000,
);
@@ -1,215 +0,0 @@
import { readFile, rm, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { itWithCaptureCapability } from "./processCaptureCapability.js";
import { captureProcessScenario } from "../../../src/application/ProcessHarness.js";
import {
digestProcessCommitment,
parseProcessScenario,
} from "../../../src/domain/processCapture.js";
itWithCaptureCapability(
"runs a login and reconnect replay machine inside process capture",
async () => {
const root = await createTestTempDirectory("rea-replay-machine-test-");
const script = join(root, "client.mjs");
await writeFile(
script,
[
'const token = "machine-secret";',
'await fetch(`${process.env.REA_REPLAY_HTTP_URL}/login`, { method: "POST", body: JSON.stringify({ token }) });',
"const api = await fetch(`${process.env.REA_REPLAY_HTTP_URL}/api`, { headers: { authorization: token } });",
'if (await api.text() !== "connect") throw new Error("bad API response");',
"const connect = (acknowledge) => new Promise((resolve, reject) => {",
" const socket = new WebSocket(process.env.REA_REPLAY_WEBSOCKET_URL);",
" socket.addEventListener('error', reject);",
" socket.addEventListener('message', (event) => {",
" if (acknowledge) socket.send('ack');",
" else { console.log(`reply:${event.data}`); socket.close(); resolve(); }",
" });",
" if (acknowledge) socket.addEventListener('close', () => resolve());",
"});",
"await connect(true);",
"await connect(false);",
].join("\n"),
);
const scenario = parseProcessScenario({
executable: process.execPath,
arguments: [script],
working_directory: root,
replay: {
machine: {
initial_state: "login",
states: [
{ name: "login" },
{ name: "api" },
{ name: "socket" },
{ name: "ack" },
{ name: "reconnect" },
{ name: "complete", terminal: true },
],
transitions: [
{
id: "login",
from: "login",
to: "api",
trigger: { protocol: "http", method: "POST", path: "/login" },
captures: [
{
variable: "token",
value: { source: "request_json", path: ["token"] },
sensitive: true,
},
],
actions: [{ type: "http_response", status: 204, body: "" }],
max_uses: 1,
},
{
id: "api",
from: "api",
to: "socket",
trigger: { protocol: "http", method: "GET", path: "/api" },
guards: [
{
variable: "token",
value: { source: "request_header", name: "authorization" },
},
],
actions: [
{ type: "http_response", status: 200, body: "connect" },
],
max_uses: 1,
},
{
id: "initial_socket",
from: "socket",
to: "ack",
trigger: { protocol: "websocket_connect", path: "/ws" },
actions: [{ type: "websocket_send", data: "welcome" }],
max_uses: 1,
},
{
id: "ack",
from: "ack",
to: "reconnect",
trigger: {
protocol: "websocket_message",
path: "/ws",
body: "ack",
},
actions: [{ type: "disconnect" }],
max_uses: 1,
},
{
id: "reconnect",
from: "reconnect",
to: "complete",
trigger: { protocol: "websocket_connect", path: "/ws" },
actions: [{ type: "websocket_send", data: "done" }],
max_uses: 1,
},
],
max_transitions: 5,
},
},
});
try {
const capture = await captureProcessScenario(scenario);
expect(capture.ok).toBe(true);
if (!capture.ok) throw capture.error;
expect(
capture.value.replay_transitions.map(
({ transition_id }) => transition_id,
),
).toEqual(["login", "api", "initial_socket", "ack", "reconnect"]);
expect(capture.value.frames.map(({ data }) => data).join("")).toContain(
"reply:done",
);
expect(JSON.stringify(capture.value)).not.toContain("machine-secret");
expect(capture.value.manifest.replay_plan_sha256).toBe(
digestProcessCommitment(scenario.replay),
);
expect(
capture.value.event_journal?.filter(
({ collection }) => collection === "replay_transitions",
),
).toHaveLength(capture.value.replay_transitions.length);
for (const [index, entry] of (
capture.value.event_journal ?? []
).entries())
if (entry.collection === "replay_transitions")
expect(capture.value.event_journal?.[index - 1]?.collection).toBe(
"protocol_events",
);
} finally {
await rm(root, { recursive: true, force: true });
}
},
20_000,
);
itWithCaptureCapability(
"captures PTY, filesystem, descendants, and HTTP replay with local values",
async () => {
const root = await createTestTempDirectory("rea-harness-test-");
const script = join(root, "fixture.mjs");
await writeFile(
script,
[
'import { writeFile } from "node:fs/promises";',
'import { spawn } from "node:child_process";',
'await writeFile(new URL("result.txt", `file://${process.cwd()}/`), "created");',
"const response = await fetch(`${process.env.REA_REPLAY_HTTP_URL}/probe`);",
"console.log(`reply:${await response.text()}`);",
"console.log(`sensitive:${process.env.SECRET}`);",
'const child = spawn(process.execPath, ["-e", "setTimeout(()=>{}, 150)"], { stdio: "ignore" });',
"await new Promise((resolve) => setTimeout(resolve, 80));",
"child.kill();",
].join("\n"),
);
const scenario = parseProcessScenario({
executable: process.execPath,
arguments: [script],
working_directory: root,
filesystem_observation_paths: [root],
environment: { SECRET: "do-not-record" },
replay: {
http: [{ method: "GET", path: "/probe", status: 200, body: "ok" }],
},
});
try {
const capture = await captureProcessScenario(scenario);
expect(capture.ok).toBe(true);
if (!capture.ok) throw capture.error;
expect(
capture.value.frames.map((frame) => frame.data).join(""),
).toContain("reply:ok");
expect(
capture.value.frames.map((frame) => frame.data).join(""),
).toContain("sensitive:do-not-record");
expect(
capture.value.files_after.some((file) =>
file.path.endsWith("result.txt"),
),
).toBe(true);
expect(
capture.value.filesystem_effects.some(
(effect) =>
effect.path.endsWith(":result.txt") && effect.status === "created",
),
).toBe(true);
expect(
capture.value.protocol_events.some(
(event) => event.protocol === "http" && event.path === "/probe",
),
).toBe(true);
expect(JSON.stringify(capture.value)).toContain("do-not-record");
expect(await readFile(join(root, "result.txt"), "utf8")).toBe("created");
expect(JSON.stringify(capture.value.files_after)).not.toContain(root);
} finally {
await rm(root, { recursive: true, force: true });
}
},
);
@@ -1,380 +0,0 @@
import { expect, it, vi } from "vitest";
import WebSocket from "ws";
import { startLoopbackReplay } from "../../../src/application/LoopbackReplay.js";
import { parseProcessScenario } from "../../../src/domain/processCapture.js";
it("serves bounded HTTP and WebSocket replay on loopback", async () => {
const scenario = parseProcessScenario({
executable: "/bin/sh",
working_directory: "/tmp",
replay: {
http: [{ method: "GET", path: "/ready", status: 201, body: "ready" }],
websocket_messages: ["welcome"],
},
});
const replay = await startLoopbackReplay(scenario);
try {
const response = await fetch(`${replay.httpUrl}/ready`);
expect(response.status).toBe(201);
expect(await response.text()).toBe("ready");
const websocketMessage = await new Promise<string>(
(resolveMessage, rejectMessage) => {
const socket = new WebSocket(replay.websocketUrl);
socket.once("message", (value) => {
resolveMessage(value.toString());
socket.close();
});
socket.once("error", rejectMessage);
},
);
expect(websocketMessage).toBe("welcome");
expect(replay.events.map((event) => event.protocol)).toContain("websocket");
} finally {
await replay.close();
}
});
it("matches and records the full HTTP request target including its query", async () => {
const scenario = parseProcessScenario({
executable: "/bin/sh",
working_directory: "/tmp",
replay: {
http: [
{ method: "GET", path: "/item?id=1", status: 200, body: "matched" },
],
},
});
const replay = await startLoopbackReplay(scenario);
try {
const matched = await fetch(`${replay.httpUrl}/item?id=1`);
expect(matched.status).toBe(200);
expect(await matched.text()).toBe("matched");
const differentQuery = await fetch(`${replay.httpUrl}/item?id=2`);
expect(differentQuery.status).toBe(404);
expect(
replay.events
.filter(({ direction }) => direction === "request")
.map(({ path }) => path),
).toEqual(["/item?id=1", "/item?id=2"]);
} finally {
await replay.close();
}
});
it("matches bounded HTTP scripts without persisting request secrets", async () => {
const scenario = parseProcessScenario({
executable: "/bin/sh",
working_directory: "/tmp",
replay: {
http: [
{
method: "POST",
path: "/callback",
request_headers: { authorization: "Bearer fixture-secret" },
request_body: "credential-body",
status: 302,
response_headers: { location: "/done" },
body: "redirecting",
max_calls: 1,
},
{
method: "GET",
path: "/disconnect",
status: 200,
body: "",
disconnect: true,
},
],
},
});
const replay = await startLoopbackReplay(scenario);
try {
const request = () =>
fetch(`${replay.httpUrl}/callback`, {
method: "POST",
headers: { authorization: "Bearer fixture-secret" },
body: "credential-body",
redirect: "manual",
});
const matched = await request();
expect(matched.status).toBe(302);
expect(matched.headers.get("location")).toBe("/done");
expect((await request()).status).toBe(409);
expect((await fetch(`${replay.httpUrl}/missing`)).status).toBe(404);
await expect(fetch(`${replay.httpUrl}/disconnect`)).rejects.toThrow();
expect(replay.events.map(({ outcome }) => outcome)).toEqual(
expect.arrayContaining([
"matched",
"script_exhausted",
"unmatched",
"disconnected",
]),
);
expect(JSON.stringify(replay.events)).not.toContain("fixture-secret");
expect(JSON.stringify(replay.events)).not.toContain("credential-body");
} finally {
await replay.close();
}
});
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",
working_directory: "/tmp",
replay: {
websocket_connections: [
{
messages: [{ data: "first", delay_ms: 1 }],
disconnect_after: true,
},
{
messages: [{ data: "second" }],
disconnect_after: true,
},
],
},
});
const replay = await startLoopbackReplay(scenario);
const receive = () =>
new Promise<string>((resolveMessage, rejectMessage) => {
const socket = new WebSocket(replay.websocketUrl);
socket.once("message", (value) => resolveMessage(value.toString()));
socket.once("error", rejectMessage);
});
try {
await expect(receive()).resolves.toBe("first");
await expect(receive()).resolves.toBe("second");
await new Promise<void>((resolveClose, rejectClose) => {
const socket = new WebSocket(replay.websocketUrl);
socket.once("close", () => resolveClose());
socket.once("error", rejectClose);
});
expect(replay.events.at(-1)?.outcome).toBe("script_exhausted");
} finally {
await replay.close();
}
});
it("serializes WebSocket transition actions across rapid messages", async () => {
const scenario = parseProcessScenario({
executable: "/bin/sh",
working_directory: "/tmp",
replay: {
machine: {
initial_state: "connecting",
states: [
{ name: "connecting" },
{ name: "first" },
{ name: "second" },
{ name: "complete", terminal: true },
],
transitions: [
{
id: "connect",
from: "connecting",
to: "first",
trigger: { protocol: "websocket_connect", path: "/ws" },
actions: [{ type: "websocket_send", data: "ready" }],
max_uses: 1,
},
{
id: "first",
from: "first",
to: "second",
trigger: {
protocol: "websocket_message",
path: "/ws",
body: "first",
},
actions: [
{ type: "delay", duration_ms: 30 },
{ type: "websocket_send", data: "first-done" },
],
max_uses: 1,
},
{
id: "second",
from: "second",
to: "complete",
trigger: {
protocol: "websocket_message",
path: "/ws",
body: "second",
},
actions: [{ type: "websocket_send", data: "second-done" }],
max_uses: 1,
},
],
max_transitions: 3,
},
},
});
const replay = await startLoopbackReplay(scenario);
try {
const messages = await new Promise<string[]>((resolve, reject) => {
const received: string[] = [];
const socket = new WebSocket(replay.websocketUrl);
socket.on("message", (value) => {
received.push(value.toString());
if (received.length === 1) {
socket.send("first");
socket.send("second");
}
if (received.length === 3) {
socket.close();
resolve(received);
}
});
socket.once("error", reject);
});
expect(messages).toEqual(["ready", "first-done", "second-done"]);
} finally {
await replay.close();
}
});
it("drains queued machine work before exposing finalized snapshots", async () => {
const scenario = parseProcessScenario({
executable: "/bin/sh",
working_directory: "/tmp",
replay: {
machine: {
initial_state: "connecting",
states: [
{ name: "connecting" },
{ name: "first" },
{ name: "second" },
{ name: "complete", terminal: true },
],
transitions: [
{
id: "connect",
from: "connecting",
to: "first",
trigger: { protocol: "websocket_connect", path: "/ws" },
actions: [{ type: "websocket_send", data: "ready" }],
max_uses: 1,
},
{
id: "first",
from: "first",
to: "second",
trigger: {
protocol: "websocket_message",
path: "/ws",
body: "first",
},
actions: [
{ type: "delay", duration_ms: 30 },
{ type: "disconnect" },
],
max_uses: 1,
},
{
id: "second",
from: "second",
to: "complete",
trigger: {
protocol: "websocket_message",
path: "/ws",
body: "second",
},
actions: [{ type: "websocket_send", data: "done" }],
max_uses: 1,
},
],
max_transitions: 3,
},
},
});
const replay = await startLoopbackReplay(scenario);
await new Promise<void>((resolve, reject) => {
const socket = new WebSocket(replay.websocketUrl);
socket.once("message", () => {
socket.send("first");
socket.send("second");
setTimeout(resolve, 5);
});
socket.once("error", reject);
});
await replay.close();
const finalized = replay.transitions;
expect(finalized.map(({ transition_id }) => transition_id)).toEqual([
"connect",
"first",
"second",
]);
await new Promise((resolve) => setTimeout(resolve, 40));
expect(replay.transitions).toEqual(finalized);
});
it("enforces replay duration before normalizing recorded timestamps", async () => {
const scenario = parseProcessScenario({
executable: "/bin/sh",
working_directory: "/tmp",
normalization: { time_bucket_ms: 60_000 },
replay: {
machine: {
initial_state: "waiting",
states: [{ name: "waiting" }, { name: "complete", terminal: true }],
transitions: [
{
id: "late",
from: "waiting",
to: "complete",
trigger: { protocol: "http", method: "GET", path: "/late" },
actions: [{ type: "http_response", status: 200, body: "late" }],
max_uses: 1,
},
],
max_transitions: 1,
limits: { duration_ms: 5 },
},
},
});
const replay = await startLoopbackReplay(scenario);
try {
await new Promise((resolve) => setTimeout(resolve, 20));
const response = await fetch(`${replay.httpUrl}/late`);
expect(response.status).toBe(409);
expect(replay.events.at(-1)).toMatchObject({
at_ms: 0,
outcome: "limit_exhausted",
});
} finally {
await replay.close();
}
});
@@ -1,5 +1,5 @@
import { rm, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -9,170 +9,43 @@ import {
} from "../../../src/application/ProcessHarness.js";
import { parseProcessScenario } from "../../../src/domain/processCapture.js";
const buildTerminalScenario = (root: string, script: string) =>
parseProcessScenario({
executable: process.execPath,
arguments: [script],
working_directory: root,
filesystem_observation_paths: [root],
normalization: { paths: true },
checkpoints: [
{
name: "probe_seen",
trigger: { type: "terminal_literal", value: "probe:codex 1.2.3" },
},
],
command_shims: [
{
name: "codex",
routes: [
{
arguments: ["--version"],
outputs: [{ at_ms: 0, stream: "stdout", data: "codex 1.2.3\n" }],
termination: { type: "exit", code: 0 },
},
],
},
{
name: "node",
routes: [
{
arguments: ["--version"],
outputs: [{ at_ms: 0, stream: "stdout", data: "node 9.8.7\n" }],
termination: { type: "exit", code: 0 },
},
],
},
],
reactive: {
initial_state: "waiting_for_shim",
deadline_ms: 5_000,
states: [
{
id: "waiting_for_shim",
max_visits: 1,
deadline_ms: 2_000,
on: [
{
id: "record_shim",
priority: 0,
max_uses: 1,
when: {
kind: "event",
source: "shim",
exact: {
command: "codex",
route_index: 0,
arguments: ["--version"],
working_directory: "<working-directory>",
outcome: "matched",
},
ignore_fields: ["sequence", "at_ms"],
since: { kind: "scenario_start" },
consume: true,
cardinality: { min: 1, max: 1 },
},
actions: [{ type: "checkpoint", name: "reactive_shim_seen" }],
target: {
kind: "goto",
state: "waiting_for_checkpoint",
},
},
],
},
{
id: "waiting_for_checkpoint",
max_visits: 1,
deadline_ms: 2_000,
on: [
{
id: "finish_checkpoint",
priority: 0,
max_uses: 1,
when: {
kind: "event",
source: "filesystem",
exact: {
name: "reactive_shim_seen",
truncated: false,
},
ignore_fields: ["at_ms", "files", "effects"],
since: { kind: "scenario_start" },
consume: true,
cardinality: { min: 1, max: 1 },
},
actions: [],
target: { kind: "finish" },
},
],
},
],
},
});
// The assertions share one captured process and therefore one cleanup scope.
it("renders terminal state, records shim invocations, and captures literal checkpoints", async () => {
const root = await createTestTempDirectory("rea-v3-test-");
const script = join(root, "scenario.mjs");
it("captures one command's terminal output, selected files, and owned cleanup", async () => {
const root = await createTestTempDirectory("rea-process-capture-");
const script = join(root, "task.mjs");
await writeFile(
script,
[
'import { spawnSync } from "node:child_process";',
'const result = spawnSync("codex", ["--version"], { encoding: "utf8" });',
'const node = spawnSync("node", ["--version"], { encoding: "utf8" });',
"process.stdout.write(`probe:${result.stdout}`);",
"process.stdout.write(`runtime:${node.stdout}`);",
'import { writeFile } from "node:fs/promises";',
"process.stdout.write(`value:${process.env.CAPTURE_VALUE}\\n`);",
'await writeFile("state.txt", "created");',
].join("\n"),
);
try {
const capability = await probeProcessCaptureCapability();
if (!capability.available) return;
const result = await captureProcessScenario(
buildTerminalScenario(root, script),
parseProcessScenario({
executable: process.execPath,
arguments: [script],
working_directory: root,
environment: { CAPTURE_VALUE: "caller-selected" },
filesystem_observation_paths: ["."],
}),
);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.rendered_frames.at(-1)?.lines.join("\n")).toContain(
"probe:codex 1.2.3",
expect(result.value.frames.map(({ data }) => data).join("")).toContain(
"value:caller-selected",
);
expect(result.value.shim_events).toEqual([
expect.objectContaining({
command: "codex",
arguments: ["--version"],
outcome: "matched",
}),
expect.objectContaining({
command: "node",
arguments: ["--version"],
outcome: "matched",
}),
]);
expect(result.value.filesystem_checkpoints.map(({ name }) => name)).toEqual(
expect.arrayContaining([
"before",
"reactive_shim_seen",
"probe_seen",
"after_settlement",
]),
expect(result.value.files_after).toContainEqual(
expect.objectContaining({ path: "root_0:state.txt" }),
);
expect(result.value.reactive_run).toMatchObject({
status: "finished",
outcome: "passed",
transitions: [
expect.objectContaining({
transition_id: "record_shim",
trigger_event_ids: ["obs.shim_events.0"],
action_event_ids: [
expect.stringMatching(/^obs\.filesystem_checkpoints\./u),
],
}),
expect.objectContaining({
transition_id: "finish_checkpoint",
trigger_event_ids: [
expect.stringMatching(/^obs\.filesystem_checkpoints\./u),
],
}),
],
expect(result.value.filesystem_effects).toContainEqual(
expect.objectContaining({ status: "created", path: "root_0:state.txt" }),
);
expect(result.value.cleanup).toEqual({
owned_process_group: "verified",
temporary_root: "removed",
});
} finally {
await rm(root, { recursive: true, force: true });
@@ -1,202 +0,0 @@
import { chmod, rm, symlink, writeFile } from "node:fs/promises";
import { delimiter, join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
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" },
});
});
});
describe("complete runtime diagnostics", () => {
it("reports every PATH candidate", async () => {
const directories = await Promise.all(
Array.from({ length: 17 }, () => temporaryRoot()),
);
await Promise.all(
directories.map((directory) =>
symlink(process.execPath, join(directory, "node")),
),
);
const inventory = await inspectRuntimeExecutables({
platform: process.platform,
path: directories.join(delimiter),
launcherNode: process.execPath,
});
expect(
inventory.candidates.filter(
({ tool, path_index: pathIndex }) =>
tool === "node" && pathIndex !== null,
),
).toHaveLength(17);
});
it("preserves complete diagnostics", async () => {
const root = await temporaryRoot();
await executable(
join(root, "node"),
"#!/bin/sh\nprintf '%070000d' 0 >&2\nexit 17\n",
);
const inventory = await inspectRuntimeExecutables({
platform: process.platform,
path: root,
launcherNode: process.execPath,
});
const candidate = inventory.candidates.find(
({ tool, path_index: pathIndex }) => tool === "node" && pathIndex === 0,
);
expect(candidate?.failure?.stderr).toHaveLength(70_000);
});
});
const temporaryRoot = async (): Promise<string> => {
const root = await createTestTempDirectory("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);
};
@@ -3,6 +3,7 @@ import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { OFFICIAL_TOOL_CONTRACTS } from "../../../../src/contracts/toolContracts.js";
const execute = promisify(execFile);
const bridgePath = new URL(
@@ -21,12 +22,42 @@ const probeResultSchema = z.strictObject({
}),
current_document: z.literal("fixture"),
current_address: z.literal("0x401000"),
containing_procedure: z.strictObject({
query_address: z.literal("0x401000"),
found: z.literal(true),
procedure: z.strictObject({
address: z.literal("0x401000"),
name: z.literal("fixture-procedure"),
classification: z.null(),
body: z.strictObject({
available: z.literal(false),
reason: z.string(),
}),
}),
}),
procedure_info: z.strictObject({
name: z.literal("fixture-procedure"),
entrypoint: z.literal("0x401000"),
basicblock_count: z.literal(1),
length: z.number(),
signature: z.literal("int fixture-procedure()"),
locals: z.array(z.unknown()),
classification: z.null(),
body: z.strictObject({
available: z.literal(false),
reason: z.string(),
}),
}),
strings: z.strictObject({ "0x401234": z.literal("fixture string") }),
procedure_references: z.strictObject({
procedure: z.strictObject({
address: z.literal("0x401000"),
name: z.literal("fixture-procedure"),
classification: z.null(),
body: z.strictObject({
available: z.literal(false),
reason: z.string(),
}),
}),
direction: z.literal("outgoing"),
reference_kinds_available: z.literal(false),
@@ -117,6 +148,19 @@ describe("Hopper API facade", () => {
},
);
const result = probeResultSchema.parse(JSON.parse(stdout));
for (const [name, value] of [
["resolve_containing_procedure", result.containing_procedure],
["procedure_references", result.procedure_references],
["procedure_info", result.procedure_info],
] as const) {
const contract = OFFICIAL_TOOL_CONTRACTS.find(
(candidate) => candidate.name === name,
);
if (contract === undefined) throw new Error(`missing ${name} contract`);
const parsed = contract.outputSchema.shape.result.safeParse(value);
if (!parsed.success) throw new Error(`${name}: ${parsed.error.message}`);
expect(parsed.success, name).toBe(true);
}
expect(result.provider_faults.map((reply) => reply.error.message)).toEqual([
"TypeError: Hopper bridge operation failed",
"ValueError: Hopper bridge operation failed",
@@ -168,12 +212,45 @@ describe("Hopper API facade", () => {
address: "0x401000",
name: "fixture-procedure",
classification: null,
body: {
available: false,
reason:
"Hopper's public Python API does not expose complete function body ranges",
},
},
direction: "outgoing",
reference_kinds_available: false,
unresolved_calls: [],
references: [],
});
expect(result.containing_procedure).toEqual({
query_address: "0x401000",
found: true,
procedure: {
address: "0x401000",
name: "fixture-procedure",
classification: null,
body: {
available: false,
reason:
"Hopper's public Python API does not expose complete function body ranges",
},
},
});
expect(result.procedure_info).toEqual({
name: "fixture-procedure",
entrypoint: "0x401000",
basicblock_count: 1,
length: 4,
signature: "int fixture-procedure()",
locals: [],
classification: null,
body: {
available: false,
reason:
"Hopper's public Python API does not expose complete function body ranges",
},
});
expect(stdout).not.toContain("supersecret");
expect(result.analysis_guard.message).toContain(
"requires completed Hopper background analysis",
@@ -1,435 +0,0 @@
import { readFile, realpath, rm, stat } from "node:fs/promises";
import { join, resolve } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { runControlledReplay } from "../../../../src/application/JavaScriptReplayService.js";
import type {
JavaScriptReplayConfiguration,
JavaScriptReplayHost,
JavaScriptReplayRunner,
} from "../../../../src/application/JavaScriptReplayPlanning.js";
import {
controlledReplayInputSchema,
controlledReplayOutputSchema,
} from "../../../../src/domain/javascriptReplay.js";
const root = resolve("tests/fixtures/replay");
const configuration: JavaScriptReplayConfiguration = {
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-1",
sha256: "1".repeat(64),
}),
identifyWorker: async () => ({
path: "/fixture/worker.js",
version: "fixture-worker-1",
sha256: "2".repeat(64),
}),
identifyRuntimeClosure: async (path) => [
{
sourcePath: path,
destinationPath: "/runtime/node",
sha256: "1".repeat(64),
},
],
seccompDigest: () => "3".repeat(64),
probe: async () => undefined,
};
const input = (
mode: "plan" | "execute",
path = resolve(root, "parser.mjs"),
) => ({
mode,
left: {
modules: [
{
alias: "parser",
path,
format: "esm" as const,
role: "module" as const,
dependencies: {},
},
],
entry_alias: "parser",
entry_export: "default",
},
cases: [{ case_id: "heading", arguments: ["# Title"] }],
});
const completedRunner = (): JavaScriptReplayRunner => ({
execute: async (prepared) => ({
plan_digest: prepared.publicPlan.plan_digest,
outcomes: [
{
case_id: "heading",
outcome: "return",
value: { type: "heading", text: "Title" },
input_sha256: prepared.publicPlan.cases[0]?.sha256 ?? "0".repeat(64),
output_sha256: "2".repeat(64),
truncated: false,
},
],
stderr: "",
termination: "completed",
cleanup: { state: "complete", residual_resources: [] },
limitations: ["fixture runner"],
reproducer: null,
}),
});
describe("controlled JavaScript replay planning", () => {
it("requires an exact digest for execution and keeps plan input separate", () => {
expect(
controlledReplayInputSchema.safeParse({
...input("execute"),
plan_digest: "0".repeat(64),
}).success,
).toBe(true);
expect(
controlledReplayInputSchema.safeParse({
...input("execute"),
}).success,
).toBe(false);
expect(
controlledReplayInputSchema.safeParse({
...input("plan"),
plan_digest: "0".repeat(64),
}).success,
).toBe(false);
expect(
controlledReplayInputSchema.safeParse({
...input("plan"),
}).success,
).toBe(true);
expect(
controlledReplayInputSchema.safeParse({
...input("execute"),
plan_digest: "0".repeat(64),
reproducer_export: {
path: "/tmp/reproducer",
},
}).success,
).toBe(true);
});
it("rejects relative module paths", () => {
expect(
controlledReplayInputSchema.safeParse({
...input("plan", "relative/parser.mjs"),
}).success,
).toBe(false);
});
it("accepts caller replay budgets above former tool-side ceilings", () => {
expect(
controlledReplayInputSchema.safeParse({
...input("plan"),
generator: { preset: "parser-boundaries", seed: 1, count: 65 },
limits: {
wall_time_ms: 60_000,
memory_bytes: 1024 * 1024 * 1024,
tasks: 64,
cpu_quota_percent: 200,
tmpfs_bytes: 128 * 1024 * 1024,
module_bytes: 32 * 1024 * 1024,
input_bytes: 2 * 1024 * 1024,
protocol_bytes: 128 * 1024 * 1024,
output_bytes: 8 * 1024 * 1024,
stderr_bytes: 512 * 1024,
result_depth: 128,
result_nodes: 200_000,
},
}).success,
).toBe(true);
});
it("rejects oversized aggregate cases before probing or reading", async () => {
const probe = vi.fn(host.probe);
const readSource = vi.fn(host.readSource);
const result = await runControlledReplay(
{
configuration: () => configuration,
host: { ...host, probe, readSource },
runner: completedRunner(),
},
{
...input("plan"),
cases: [{ case_id: "large", arguments: ["too large"] }],
limits: { input_bytes: 1 },
},
);
expect(result.ok).toBe(false);
expect(probe).not.toHaveBeenCalled();
expect(readSource).not.toHaveBeenCalled();
});
it("returns a deterministic plan without admitting application code", async () => {
const execute = vi.fn(completedRunner().execute);
const first = await runControlledReplay(
{
configuration: () => configuration,
host,
runner: { execute },
},
input("plan"),
);
const second = await runControlledReplay(
{
configuration: () => configuration,
host,
runner: { execute },
},
input("plan"),
);
expect(first).toEqual(second);
expect(execute).not.toHaveBeenCalled();
expect(first.ok && first.value).toMatchObject({
phase: "plan",
plan: { network: "none", filesystem: { host_writes: false } },
evidence: null,
});
if (!first.ok) throw first.error;
const output = controlledReplayOutputSchema.parse(first.value);
expect(
controlledReplayOutputSchema.safeParse({ ...output, plan: null }).success,
).toBe(false);
expect(
controlledReplayOutputSchema.safeParse({ ...output, phase: "execute" })
.success,
).toBe(false);
});
it("rejects a stale digest before worker admission", async () => {
const execute = vi.fn(completedRunner().execute);
const result = await runControlledReplay(
{
configuration: () => configuration,
host,
runner: { execute },
},
{ ...input("execute"), plan_digest: "0".repeat(64) },
);
expect(result.ok).toBe(false);
expect(!result.ok && result.error._tag).toBe("ReplayPlanStaleError");
expect(execute).not.toHaveBeenCalled();
});
});
describe("controlled JavaScript replay configuration snapshots", () => {
it("uses one configuration snapshot for the complete planning operation", async () => {
let reads = 0;
const configuredReplay = (): JavaScriptReplayConfiguration => {
reads += 1;
return configuration;
};
const result = await runControlledReplay(
{
configuration: configuredReplay,
host,
runner: completedRunner(),
},
input("plan"),
);
expect([result.ok, reads]).toEqual([true, 1]);
});
});
describe("controlled JavaScript replay evidence and plan identity", () => {
it("plans and executes without grants after matching the content-bound plan", async () => {
const dependencies = {
configuration: () => configuration,
host,
runner: completedRunner(),
};
const planned = await runControlledReplay(dependencies, input("plan"));
if (
!planned.ok ||
typeof planned.value !== "object" ||
planned.value === null ||
Array.isArray(planned.value)
)
throw new Error("missing fixture plan");
const plan = planned.value.plan;
if (
typeof plan !== "object" ||
plan === null ||
Array.isArray(plan) ||
typeof plan.plan_digest !== "string"
)
throw new Error("missing fixture digest");
const executed = await runControlledReplay(dependencies, {
...input("execute"),
plan_digest: plan.plan_digest,
});
expect(executed.ok && executed.value).toMatchObject({
phase: "execute",
plan: null,
evidence: {
provider: { id: "rea-javascript-replay" },
authority: "controlled-replay",
confidence: "observed",
environment: { isolation: "container" },
},
});
if (!executed.ok) throw executed.error;
const output = controlledReplayOutputSchema.parse(executed.value);
expect(output.source_evidence).toHaveLength(1);
expect(output.source_evidence[0]?.confidence).toBe("observed");
expect(output.evidence?.evidence_links).toEqual([
output.source_evidence[0]?.evidence_id,
]);
expect(
controlledReplayOutputSchema.safeParse({
...output,
source_evidence: [],
}).success,
).toBe(false);
});
it("changes the commitment when selected module bytes change", async () => {
const dependencies = {
configuration: () => configuration,
host,
runner: completedRunner(),
};
const left = await runControlledReplay(dependencies, input("plan"));
const right = await runControlledReplay(
dependencies,
input("plan", resolve(root, "parser-v2.mjs")),
);
expect(left.ok && right.ok && left.value).not.toEqual(
right.ok && right.value,
);
});
});
describe("controlled JavaScript replay cancellation and export", () => {
it("projects an observed cancelled termination through the shared error algebra", async () => {
const execute = vi.fn<JavaScriptReplayRunner["execute"]>(
async (prepared) => ({
plan_digest: prepared.publicPlan.plan_digest,
outcomes: [
{
case_id: "heading",
outcome: "cancelled",
input_sha256:
prepared.publicPlan.cases[0]?.sha256 ?? "0".repeat(64),
output_sha256: null,
truncated: false,
},
],
stderr: "",
termination: "cancelled",
cleanup: { state: "complete", residual_resources: [] },
limitations: ["fixture cancellation"],
reproducer: null,
}),
);
const dependencies = {
configuration: () => configuration,
host,
runner: { execute },
};
const planned = await runControlledReplay(dependencies, input("plan"));
if (!planned.ok) throw planned.error;
const plan = controlledReplayOutputSchema.parse(planned.value).plan;
if (plan === null) throw new Error("missing cancellation plan");
const controller = new AbortController();
const result = await runControlledReplay(
dependencies,
{
...input("execute"),
plan_digest: plan.plan_digest,
},
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
expect(!result.ok && result.error._tag).toBe("AnalysisCancelledError");
expect(execute).toHaveBeenCalledWith(
expect.any(Object),
configuration,
controller.signal,
);
});
it("does not admit a worker after cancellation during planning", async () => {
const controller = new AbortController();
const execute = vi.fn(completedRunner().execute);
const result = await runControlledReplay(
{
configuration: () => configuration,
host: {
...host,
probe: async () => {
controller.abort();
},
},
runner: { execute },
},
{ ...input("execute"), plan_digest: "0".repeat(64) },
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
expect(!result.ok && result.error._tag).toBe("AnalysisCancelledError");
expect(execute).not.toHaveBeenCalled();
});
it("exports an owner-only source-free reproducer after cleanup", async () => {
const directory = await createTestTempDirectory("rea-reproducer-test-");
const path = join(directory, "reproducer.json");
const dependencies = {
configuration: () => configuration,
host,
runner: completedRunner(),
};
const export_ = {
path,
include_sources: false,
};
try {
const planned = await runControlledReplay(dependencies, {
...input("plan"),
reproducer_export: export_,
});
if (!planned.ok) throw new Error("missing export plan");
const plan = controlledReplayOutputSchema.parse(planned.value).plan;
if (plan === null) throw new Error("missing export plan");
const executed = await runControlledReplay(dependencies, {
...input("execute"),
reproducer_export: export_,
plan_digest: plan.plan_digest,
});
expect(executed.ok && executed.value).toMatchObject({
evidence: {
normalized_result: {
reproducer: { state: "written", path },
},
},
});
const metadata = await stat(path);
expect(metadata.mode & 0o777).toBe(0o600);
expect(JSON.parse(await readFile(path, "utf8"))).toMatchObject({
sources: null,
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
});
@@ -1,644 +0,0 @@
import { execFile, spawn } from "node:child_process";
import { readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import type { WorkerModule } from "../../../../src/replay/JavaScriptReplayWorkerTypes.js";
const fixture = async (name: string): Promise<string> =>
readFile(resolve("tests/fixtures/replay", name), "utf8");
const runWorker = async (request: unknown) =>
new Promise<{ code: number | null; stdout: string; stderr: string }>(
(resolvePromise, reject) => {
const child = spawn(
process.execPath,
[
"--experimental-vm-modules",
resolve("dist/replay/JavaScriptReplayWorker.js"),
],
{ stdio: ["pipe", "pipe", "pipe"] },
);
let stdout = "";
let stderr = "";
child.stdout.on("data", (chunk: Buffer) => {
stdout += chunk.toString("utf8");
});
child.stderr.on("data", (chunk: Buffer) => {
stderr += chunk.toString("utf8");
});
child.once("error", reject);
child.once("close", (code) => resolvePromise({ code, stdout, stderr }));
child.stdin.end(JSON.stringify(request));
},
);
const request = async (
name: string,
format: "esm" | "commonjs-factory",
entryExport: string,
arguments_: readonly unknown[],
) => ({
left: {
modules: [
{
alias: "entry",
format,
dependencies: {},
source: await fixture(name),
},
],
entryAlias: "entry",
entryExport,
},
cases: [
{
caseId: "case",
arguments: arguments_,
inputSha256: "a".repeat(64),
},
],
determinism: {
clockIso: "2000-01-01T00:00:00.000Z",
randomSeed: 7,
},
limits: { resultDepth: 16, resultNodes: 10_000, exceptionBytes: 4096 },
});
it("uses the caller's full output budget for exception text", async () => {
const message = "x".repeat(70_000);
const workerRequest = await request("exception.mjs", "esm", "default", [
message,
]);
workerRequest.limits.exceptionBytes = 80_000;
const result = await runWorker(workerRequest);
expect(result.code).toBe(0);
const response = JSON.parse(result.stdout) as {
readonly left: readonly {
readonly exception: { readonly message: string };
}[];
};
expect(response.left[0]?.exception.message).toBe(`fixture:${message}`);
});
describe("disposable JavaScript replay worker", () => {
it("rejects malformed runtime-hop requests before loading modules", async () => {
const result = await runWorker({
left: { modules: "not-an-array", entryAlias: "entry", entryExport: "x" },
cases: [],
determinism: { clockIso: "2000-01-01T00:00:00.000Z", randomSeed: 7 },
limits: { resultDepth: 16, resultNodes: 10_000, exceptionBytes: 4096 },
});
expect(result.code).toBe(70);
expect(result.stdout).toBe("");
expect(result.stderr).toContain("Invalid replay worker modules");
});
it("runs an ESM parser with projected plain data", async () => {
const result = await runWorker(
await request("parser.mjs", "esm", "default", ["# Title"]),
);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "return",
value: { type: "heading", text: "Title" },
},
],
});
});
it("supports extracted Rspack factories and helper-defined exports", async () => {
const result = await runWorker(
await request("clipboard.factory.txt", "commonjs-factory", "normalize", [
"a\r\nb",
]),
);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "return",
value: { text: "a\nb", bytes: 4 },
},
],
});
});
it("runs the source-owned sanitizer fixture", async () => {
const result = await runWorker(
await request("sanitizer.factory.txt", "commonjs-factory", "sanitize", [
"<script>alert(1)</script><b onclick=bad>ok</b>",
]),
);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value: "<b>ok</b>" }],
});
});
it("denies dynamic imports and undeclared requires", async () => {
const dynamic = await runWorker(
await request("dynamic-import.mjs", "esm", "default", []),
);
expect(JSON.parse(dynamic.stdout)).toMatchObject({
left: [
{
outcome: "denied",
exception: {
message: "Dynamic import is unavailable in controlled replay",
},
},
],
});
const undeclared = await runWorker(
await request(
"undeclared-require.factory.txt",
"commonjs-factory",
"default",
[],
),
);
expect(JSON.parse(undeclared.stdout)).toMatchObject({
left: [
{
outcome: "denied",
exception: { message: "Undeclared require: node:fs" },
},
],
});
});
it("retains exceptions as observations", async () => {
const result = await runWorker(
await request("exception.mjs", "esm", "default", ["value"]),
);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "exception",
exception: { name: "TypeError", message: "fixture:value" },
},
],
});
});
it("rejects Proxy results without invoking descriptor traps", async () => {
const result = await runWorker(
await request("proxy-result.mjs", "esm", "default", []),
);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "serialization_error",
exception: {
name: "TypeError",
message: "Proxy replay results are unavailable",
},
},
],
});
expect(result.stderr).not.toContain("proxy trap must not run");
});
it("does not expose ambient process, require, network, buffers, or timers", async () => {
const result = await runWorker(
await request("side-effect-attempt.mjs", "esm", "default", []),
);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "return",
value: {
process: "undefined",
require: "undefined",
fetch: "undefined",
buffer: "undefined",
timer: "undefined",
},
},
],
});
});
});
describe("ESM imports of CommonJS replay factories", () => {
it.each([false, true])(
"matches native Node default import when __esModule is %s",
async (marked) => {
const directory = await createTestTempDirectory("rea-replay-interop-");
const source = `module.exports={default:'named-default',answer:42,__esModule:${String(marked)}};`;
const path = join(directory, "dependency.cjs");
await writeFile(path, source, "utf8");
const { stdout } = await promisify(execFile)(
process.execPath,
[
"--input-type=module",
"-e",
"const {default:value}=await import(process.argv[1]); console.log(JSON.stringify({kind:typeof value,property:value.default,answer:value.answer}));",
pathToFileURL(path).href,
],
{ timeout: 5000 },
);
const expected: unknown = JSON.parse(stdout);
expect(expected).toEqual({
kind: "object",
property: "named-default",
answer: 42,
});
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules = [
{
alias: "entry",
format: "esm",
dependencies: { "./dependency": "dependency" },
source:
"import value from './dependency'; export default function(){ return {kind:typeof value,property:value.default,answer:value.answer}; }",
},
{
alias: "dependency",
format: "commonjs-factory",
dependencies: {},
source: `function(module){ ${source} }`,
},
];
const result = await runWorker(workerRequest);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value: expected }],
});
},
);
it.each([false, true])(
"preserves Rspack require.n behavior when __esModule is %s",
async (marked) => {
const workerRequest = await request(
"clipboard.factory.txt",
"commonjs-factory",
"default",
[],
);
workerRequest.left.modules = [
{
alias: "entry",
format: "commonjs-factory",
dependencies: { "./dependency": "dependency" },
source:
"function(module,exports,require){ const normalized=require.n(require('./dependency'))(); module.exports.default=()=>typeof normalized; }",
},
{
alias: "dependency",
format: "commonjs-factory",
dependencies: {},
source: `function(module){ module.exports={default:'named-default',answer:42,__esModule:${String(marked)}}; }`,
},
];
const result = await runWorker(workerRequest);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value: marked ? "string" : "object" }],
});
},
);
it("preserves direct factory default-export selection", async () => {
const workerRequest = await request(
"clipboard.factory.txt",
"commonjs-factory",
"default",
[],
);
workerRequest.left.modules[0] = {
alias: "entry",
format: "commonjs-factory",
dependencies: {},
source: "function(module){ module.exports={default:()=>42}; }",
};
const result = await runWorker(workerRequest);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value: 42 }],
});
});
});
describe("replay ESM graph linking", () => {
const esmModule = (
alias: string,
source: string,
dependencies: Record<string, string> = {},
): WorkerModule => ({ alias, source, dependencies, format: "esm" });
it.each([
{
name: "two-module cycle",
value: 8,
modules: [
esmModule(
"entry",
"import { value } from './dep'; export default function(){ return value(); } export function base(){ return 7; }",
{ "./dep": "dep" },
),
esmModule(
"dep",
"import { base } from './entry'; export function value(){ return base()+1; }",
{ "./entry": "entry" },
),
],
},
{
name: "three-module cycle",
value: 8,
modules: [
esmModule(
"entry",
"import { value } from './dep'; export default function(){ return value(); } export function base(){ return 7; }",
{ "./dep": "dep" },
),
esmModule(
"dep",
"import { value as next } from './third'; export function value(){ return next(); }",
{ "./third": "third" },
),
esmModule(
"third",
"import { base } from './entry'; export function value(){ return base()+1; }",
{ "./entry": "entry" },
),
],
},
{
name: "acyclic evaluation order",
value: 8,
modules: [
esmModule(
"entry",
"import { value } from './dep'; const answer=value+1; export default function(){ return answer; }",
{ "./dep": "dep" },
),
esmModule("dep", "export const value=7;"),
],
},
{
name: "diamond single initialization",
value: [1, 1],
modules: [
esmModule(
"entry",
"import { a } from './a'; import { b } from './b'; export default function(){ return [a,b]; }",
{ "./a": "a", "./b": "b" },
),
esmModule(
"a",
"import { value } from './shared'; export const a=value;",
{
"./shared": "shared",
},
),
esmModule(
"b",
"import { value } from './shared'; export const b=value;",
{
"./shared": "shared",
},
),
esmModule(
"shared",
"globalThis.initializations=(globalThis.initializations??0)+1; export const value=globalThis.initializations;",
),
],
},
{
name: "mixed CommonJS factory",
value: 8,
modules: [
esmModule(
"entry",
"import value from './dep'; export default function(){ return value.answer; }",
{ "./dep": "dep" },
),
{
alias: "dep",
source: "function(module) { module.exports={answer:8}; }",
dependencies: {},
format: "commonjs-factory" as const,
},
],
},
])("links $name before evaluation", async ({ modules, value }) => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules = modules;
const result = await runWorker(workerRequest);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value }],
});
});
it("still denies undeclared static imports", async () => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules = [
esmModule(
"entry",
"import './undeclared'; export default function(){ return 1; }",
),
];
const result = await runWorker(workerRequest);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "denied",
exception: { message: "Undeclared import: ./undeclared" },
},
],
});
});
});
describe("deterministic replay Date compatibility", () => {
it.each([
["new Date(2020, 0, 2).getFullYear()", 2020],
["new Date(2020, 0, 2, 3, 4, 5, 6).getMilliseconds()", 6],
["typeof Date()", "string"],
["Date() === new Date().toString()", true],
["new Date().toISOString()", "2000-01-01T00:00:00.000Z"],
["Date.now()", 946684800000],
["new Date(0).getTime()", 0],
[
"new Date('2020-01-02T00:00:00Z').toISOString()",
"2020-01-02T00:00:00.000Z",
],
["new Date() instanceof Date", true],
[
"(() => { class ChildDate extends Date {} const date = new ChildDate(2020, 0, 2); return [date instanceof ChildDate, date instanceof Date, date.getFullYear(), date.constructor === ChildDate]; })()",
[true, true, 2020, true],
],
["Date.UTC(2020, 0, 2)", 1577923200000],
])("preserves %s", async (expression, expected) => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules[0] = {
alias: "entry",
format: "esm",
dependencies: {},
source: `export default function () { return ${expression}; }`,
};
const result = await runWorker(workerRequest);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value: expected }],
});
});
});
it("rejects results the JSON projection cannot represent faithfully", async () => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules[0] = {
alias: "entry",
format: "esm",
dependencies: {},
source: "export default function () { return { a: 1, [Symbol('s')]: 2 }; }",
};
const result = await runWorker(workerRequest);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "serialization_error",
exception: {
message: "Symbol-keyed replay results are unavailable",
},
},
],
});
});
it("keeps an own __proto__ property instead of mutating the output", async () => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules[0] = {
alias: "entry",
format: "esm",
dependencies: {},
source: `export default function () {
const value = {};
Object.defineProperty(value, "__proto__", {
value: { injected: true },
enumerable: true,
});
return value;
}`,
};
const result = await runWorker(workerRequest);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "return",
value: { __proto__: { injected: true } },
},
],
});
});
describe("replay determinism and builtin identity", () => {
const evaluate = async (
expression: string,
randomSeed: number,
): Promise<unknown> => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.determinism.randomSeed = randomSeed;
workerRequest.left.modules[0] = {
alias: "entry",
format: "esm",
dependencies: {},
source: `export default function () { return ${expression}; }`,
};
const result = await runWorker(workerRequest);
expect(result.code).toBe(0);
return JSON.parse(result.stdout).left[0];
};
it("varies Math.random across draws when seeded with zero", async () => {
const outcome = (await evaluate(
"[Math.random(), Math.random(), Math.random()]",
0,
)) as { outcome: string; value?: number[] };
expect(outcome.outcome).toBe("return");
expect(new Set(outcome.value).size).toBe(3);
});
it("produces an identical stream for the same seed", async () => {
const first = await evaluate("[Math.random(), Math.random()]", 5);
const second = await evaluate("[Math.random(), Math.random()]", 5);
expect(first).toEqual(second);
});
it("presents Date with real builtin identity", async () => {
expect(await evaluate("[Date.name, Date.length]", 3)).toMatchObject({
outcome: "return",
value: ["Date", 7],
});
});
it("presents Math with real descriptors and unaffected members", async () => {
// Object identity is realm-specific inside the vm, so the meaningful checks
// are the descriptor and the untouched members.
const outcome = (await evaluate(
"[Object.getOwnPropertyDescriptor(Math, 'random').configurable, Object.getOwnPropertyDescriptor(Math, 'random').writable, Math.max(1, 2), Math.floor(1.7), Math.PI > 3]",
3,
)) as { outcome: string; value?: unknown[] };
expect(outcome).toMatchObject({
outcome: "return",
value: [true, true, 2, 1, true],
});
});
});
describe("replay array projection", () => {
it.each([
["Array(3)", [null, null, null]],
[
"(() => { const value = Array(3); value[1] = 42; return value; })()",
[null, 42, null],
],
["[1, null, 3]", [1, null, 3]],
["[]", []],
])("preserves JSON array positions for %s", async (expression, expected) => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules[0] = {
alias: "entry",
format: "esm",
dependencies: {},
source: `export default function () { return ${expression}; }`,
};
const result = await runWorker(workerRequest);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value: expected }],
});
});
it("accounts for holes in the existing result node budget", async () => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules[0] = {
alias: "entry",
format: "esm",
dependencies: {},
source: "export default function () { return Array(4); }",
};
workerRequest.limits.resultNodes = 3;
const result = await runWorker(workerRequest);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "serialization_error",
exception: { message: "Replay result projection limit exceeded" },
},
],
});
});
});
+1 -1
View File
@@ -58,7 +58,7 @@ versions against this historical capture.
`mcp-initialize.json` captures the `initialize` request emitted by the pinned
`@modelcontextprotocol/client` 2.0.0 SDK on 2026-10-04. The client connected to
the actual `scripts/rea.mjs mcp` subprocess and completed `listTools` (122 tools).
the actual `scripts/rea.mjs mcp` subprocess and completed `listTools` (the current catalog).
The recorder intercepted `transport.send`, serialized the message, and delegated
the unchanged message to the real SDK transport. The committed JSON is formatted
for review; whitespace is not a wire identity claim. No provider was launched.
+32
View File
@@ -101,6 +101,26 @@ class FakeProcedure:
def getSegment(self):
return self.segment
def basicBlockIterator(self):
return [FakeBlock()]
def getBasicBlockCount(self):
return 1
def signatureString(self):
return "int fixture-procedure()"
def getLocalVariableList(self):
return []
class FakeBlock:
def getStartingAddress(self):
return 0x401000
def getEndingAddress(self):
return 0x401004
class FakeStringsDocument:
def getSegmentsList(self):
@@ -185,10 +205,20 @@ def main():
bridge["_procedure"] = lambda document, value=None: reference_procedure
bridge["_instruction_addresses"] = lambda procedure: [0x401000]
bridge["_segment"] = lambda document, address: reference_segment
bridge["_containing_procedure"] = lambda document, address: (
reference_procedure,
None,
)
containing_procedure = bridge["_dispatch"](
"resolve_containing_procedure", {"address": "0x401000"}
)
procedure_references = bridge["_dispatch"](
"procedure_references",
{"procedure": "0x401000", "direction": "outgoing"},
)
procedure_info = bridge["_dispatch"](
"procedure_info", {"procedure": "0x401000"}
)
inventories = bridge_replies(bridge, [
request(method, params, index)
for index, (method, params) in enumerate([
@@ -251,7 +281,9 @@ def main():
"current_address": current_address,
"strings": strings,
"inventory_replies": inventories,
"containing_procedure": containing_procedure,
"procedure_references": procedure_references,
"procedure_info": procedure_info,
"provider_faults": provider_faults,
"malformed_requests": malformed_requests,
"session_document_reused": selected,