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:
@@ -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);
|
||||
};
|
||||
Reference in New Issue
Block a user