test: overhaul deterministic suite architecture
This commit is contained in:
@@ -0,0 +1,424 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
containsProcess,
|
||||
getDescendants,
|
||||
maxTreeDepth,
|
||||
reconstructProcessTree,
|
||||
type ProcessTreeEvent,
|
||||
type ProcessEventType,
|
||||
type ProcessNode,
|
||||
type ProcessTreeReconstruction,
|
||||
} from "../../../src/domain/eventProcessTree.js";
|
||||
|
||||
describe("event-backed process tree reconstruction", () => {
|
||||
it("reconstructs a simple process tree", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/child",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "exit",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 3,
|
||||
at_ms: 30,
|
||||
type: "exit",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.processes).toHaveLength(2);
|
||||
expect(result.events_consumed).toBe(4);
|
||||
expect(result.events_unmatched).toBe(0);
|
||||
expect(result.short_lived_descendants).toBe(2);
|
||||
});
|
||||
|
||||
it("detects short-lived descendants", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "short",
|
||||
executable: "/short",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 11,
|
||||
type: "exit",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "short",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.short_lived_descendants).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree transitions", () => {
|
||||
it("detects re-exec", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "re_exec",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/newroot",
|
||||
arguments: ["--new"],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.has_re_exec).toBe(true);
|
||||
const root = result.processes.find((p) => p.pid === 1)!;
|
||||
expect(root.is_re_exec).toBe(true);
|
||||
expect(root.executable).toBe("/newroot");
|
||||
});
|
||||
|
||||
it("detects reparenting", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/child",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "reparent",
|
||||
pid: 2,
|
||||
ppid: 0,
|
||||
process_name: "child",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: 1,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.has_reparenting).toBe(true);
|
||||
const child = result.processes.find((p) => p.pid === 2)!;
|
||||
expect(child.is_reparented).toBe(true);
|
||||
expect(child.previous_ppid).toBe(1);
|
||||
expect(child.ppid).toBe(0);
|
||||
});
|
||||
|
||||
it("reports unmatched events for unknown exits", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "exit",
|
||||
pid: 999,
|
||||
ppid: null,
|
||||
process_name: null,
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 1,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.events_unmatched).toBe(1);
|
||||
expect(result.processes).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree queries", () => {
|
||||
it("gets descendants", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child1",
|
||||
executable: "/c1",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "spawn",
|
||||
pid: 3,
|
||||
ppid: 2,
|
||||
process_name: "grandchild",
|
||||
executable: "/gc",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
const descendants = getDescendants(result.processes, 1);
|
||||
expect(descendants).toHaveLength(2);
|
||||
expect(descendants).toContain(2);
|
||||
expect(descendants).toContain(3);
|
||||
});
|
||||
|
||||
it("checks process containment", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(containsProcess(result.processes, 1)).toBe(true);
|
||||
expect(containsProcess(result.processes, 999)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree depth and types", () => {
|
||||
it("computes max tree depth", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/c",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "spawn",
|
||||
pid: 3,
|
||||
ppid: 2,
|
||||
process_name: "gc",
|
||||
executable: "/gc",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(maxTreeDepth(result.processes, 1)).toBe(2);
|
||||
});
|
||||
|
||||
it("uses exported types", () => {
|
||||
const node: ProcessNode = {
|
||||
pid: 1,
|
||||
ppid: null,
|
||||
process_name: "test",
|
||||
executable: "/test",
|
||||
arguments: [],
|
||||
children: [],
|
||||
spawn_time_ms: 0,
|
||||
exit_time_ms: null,
|
||||
exit_code: null,
|
||||
is_re_exec: false,
|
||||
is_reparented: false,
|
||||
previous_ppid: null,
|
||||
};
|
||||
expect(node.pid).toBe(1);
|
||||
const recon: ProcessTreeReconstruction = {
|
||||
root_pid: 1,
|
||||
processes: [node],
|
||||
events_consumed: 1,
|
||||
events_unmatched: 0,
|
||||
short_lived_descendants: 0,
|
||||
has_re_exec: false,
|
||||
has_reparenting: false,
|
||||
};
|
||||
expect(recon.root_pid).toBe(1);
|
||||
});
|
||||
|
||||
it("uses ProcessEventType", () => {
|
||||
const t: ProcessEventType = "spawn";
|
||||
expect(t).toBe("spawn");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,354 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { createElectronEvidence } from "../../../src/application/ElectronEvidence.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
|
||||
import { reconcileJavaScriptRuntime } from "../../../src/domain/javascriptRuntimeReconciliation.js";
|
||||
import { createWebTextArtifact } from "../../../src/domain/webContentArtifact.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
|
||||
const SOURCE = `const worker = new Worker("./worker.js");\nexport const observed = worker;\n`;
|
||||
const execute = promisify(execFile);
|
||||
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps byte-identical cross-layer candidates explicitly ambiguous", async () => {
|
||||
const application = await applicationFixture();
|
||||
const assets = await createTestTempDirectory("rea-runtime-assets-static-");
|
||||
const runtime = await createTestTempDirectory("rea-runtime-assets-live-");
|
||||
temporary.push(application, assets, runtime);
|
||||
await Promise.all([
|
||||
writeFile(join(assets, "app.js"), SOURCE),
|
||||
writeFile(join(runtime, "app.js"), SOURCE),
|
||||
writeFile(join(runtime, "index.html"), "<script></script>"),
|
||||
]);
|
||||
const result = reconcileJavaScriptRuntime({
|
||||
static_layers: [
|
||||
{
|
||||
role: "application",
|
||||
analysis: await analyzeFixture(application),
|
||||
},
|
||||
{ role: "assets", analysis: await analyzeFixture(assets) },
|
||||
],
|
||||
runtime_observations: [
|
||||
electronRuntimeEvidence(runtime, SOURCE, { includeWorker: false }),
|
||||
],
|
||||
});
|
||||
const script = result.reconciliations.find(
|
||||
({ entity_kind: kind }) => kind === "script",
|
||||
);
|
||||
|
||||
expect(script).toMatchObject({
|
||||
status: "ambiguous",
|
||||
reason: "ambiguous-static-candidates",
|
||||
candidate_static_count: 2,
|
||||
});
|
||||
expect(script?.candidate_static_nodes).toHaveLength(2);
|
||||
expect(
|
||||
new Set(
|
||||
script?.candidate_static_nodes.map(
|
||||
({ static_layer_id: layerId }) => layerId,
|
||||
),
|
||||
).size,
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
it("retains one target per capture and keeps load-state absence unknown when output is bounded", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
temporary.push(fixture);
|
||||
const staticEvidence = await analyzeFixture(fixture);
|
||||
const runtimeObservations = [
|
||||
electronRuntimeEvidence(fixture, SOURCE, {
|
||||
includeWorker: false,
|
||||
targetId: "target-one",
|
||||
}),
|
||||
electronRuntimeEvidence(fixture, SOURCE, {
|
||||
includeWorker: false,
|
||||
targetId: "target-two",
|
||||
}),
|
||||
];
|
||||
|
||||
const result = reconcileJavaScriptRuntime({
|
||||
static_layers: [{ role: "application", analysis: staticEvidence }],
|
||||
runtime_observations: runtimeObservations,
|
||||
limits: {
|
||||
max_runtime_entities: 2,
|
||||
max_reconciliation_items: 2,
|
||||
max_static_load_states: 20_000,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.runtime_captures).toHaveLength(2);
|
||||
expect(
|
||||
new Set(result.runtime_captures.map(({ target_node_id: id }) => id)).size,
|
||||
).toBe(2);
|
||||
expect(result.summary).toMatchObject({
|
||||
runtime_targets: 2,
|
||||
runtime_frames: 0,
|
||||
runtime_scripts: 0,
|
||||
runtime_workers: 0,
|
||||
static_not_observed: 0,
|
||||
});
|
||||
expect(result.coverage).toMatchObject({
|
||||
status: "truncated",
|
||||
truncated: true,
|
||||
omitted_runtime_entities: 4,
|
||||
});
|
||||
expect(
|
||||
result.static_load_states.every(({ status }) => status === "unknown"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects runtime source bytes whose Evidence omits source-capture approval", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
temporary.push(fixture);
|
||||
const staticEvidence = await analyzeFixture(fixture);
|
||||
const contradictoryRuntime = electronRuntimeEvidence(fixture, SOURCE, {
|
||||
includeWorker: false,
|
||||
sourceCaptureApproved: false,
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
reconcileJavaScriptRuntime({
|
||||
static_layers: [{ role: "application", analysis: staticEvidence }],
|
||||
runtime_observations: [contradictoryRuntime],
|
||||
}),
|
||||
).toThrow(/source-capture approval/u);
|
||||
});
|
||||
|
||||
it("keeps graph omission counts unknown when a runtime section is unavailable", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
temporary.push(fixture);
|
||||
const result = reconcileJavaScriptRuntime({
|
||||
static_layers: [
|
||||
{ role: "application", analysis: await analyzeFixture(fixture) },
|
||||
],
|
||||
runtime_observations: [
|
||||
electronRuntimeEvidence(fixture, SOURCE, {
|
||||
includeWorker: false,
|
||||
workersUnavailable: true,
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
});
|
||||
expect(result.graph.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("runs the local verifier from operator-provided paths without emitting source", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
const evidenceRoot = await createTestTempDirectory("rea-runtime-evidence-");
|
||||
const evidencePath = join(evidenceRoot, "runtime-evidence.json");
|
||||
temporary.push(fixture, evidenceRoot);
|
||||
await writeFile(
|
||||
evidencePath,
|
||||
JSON.stringify(electronRuntimeEvidence(fixture, SOURCE)),
|
||||
);
|
||||
|
||||
const { stdout } = await execute(
|
||||
process.execPath,
|
||||
[
|
||||
"scripts/verify-local-javascript-runtime.mjs",
|
||||
"--application",
|
||||
fixture,
|
||||
"--runtime-evidence",
|
||||
evidencePath,
|
||||
],
|
||||
{ cwd: process.cwd(), maxBuffer: 16 * 1_024 * 1_024 },
|
||||
);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
|
||||
expect(output).toMatchObject({
|
||||
verified: true,
|
||||
summary: { runtime_scripts: 1 },
|
||||
});
|
||||
expect(stdout).not.toContain(SOURCE.trim());
|
||||
}, 10_000);
|
||||
|
||||
const applicationFixture = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-runtime-reconciliation-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "rea-runtime-reconciliation-fixture",
|
||||
version: "1.0.0",
|
||||
renderer: "index.html",
|
||||
}),
|
||||
),
|
||||
writeFile(join(root, "index.html"), "<script src='./app.js'></script>"),
|
||||
writeFile(join(root, "app.js"), SOURCE),
|
||||
writeFile(join(root, "worker.js"), "self.onmessage = () => undefined;\n"),
|
||||
]);
|
||||
return root;
|
||||
};
|
||||
|
||||
const analyzeFixture = async (root: string) => {
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_input"],
|
||||
["investigation_input"],
|
||||
);
|
||||
const result = await analyzeJavaScriptApplication(authority, {
|
||||
input_path: root,
|
||||
approved: true,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
return result.value;
|
||||
};
|
||||
|
||||
const electronRuntimeEvidence = (
|
||||
root: string,
|
||||
source: string,
|
||||
options: {
|
||||
readonly scriptFile?: string;
|
||||
readonly includeWorker?: boolean;
|
||||
readonly targetId?: string;
|
||||
readonly sourceCaptureApproved?: boolean;
|
||||
readonly workersUnavailable?: boolean;
|
||||
} = {},
|
||||
) => {
|
||||
const scriptFile = options.scriptFile ?? "app.js";
|
||||
const includeWorker = options.includeWorker ?? true;
|
||||
const targetId = options.targetId ?? "target-main";
|
||||
const sourceCaptureApproved = options.sourceCaptureApproved ?? true;
|
||||
const input = {
|
||||
cdp_endpoint: "http://127.0.0.1:9223",
|
||||
allowed_file_roots: [root],
|
||||
target_id: targetId,
|
||||
approved: true as const,
|
||||
observation_ms: 100,
|
||||
include_script_sources: sourceCaptureApproved,
|
||||
source_capture_approved: sourceCaptureApproved,
|
||||
limits: {
|
||||
max_frames: 200,
|
||||
max_dom_nodes: 2_000,
|
||||
max_scripts: 500,
|
||||
max_resources: 2_000,
|
||||
max_workers: 500,
|
||||
max_script_source_bytes: 1_048_576,
|
||||
max_total_script_source_bytes: 4_194_304,
|
||||
},
|
||||
};
|
||||
return createElectronEvidence(
|
||||
"inspect_electron_page",
|
||||
input,
|
||||
{
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
product: "Electron/fixture",
|
||||
protocol_version: "1.3",
|
||||
revision: "fixture",
|
||||
user_agent: "Electron fixture",
|
||||
js_version: "13",
|
||||
},
|
||||
target: {
|
||||
target_id: targetId,
|
||||
type: "page",
|
||||
title: "Fixture",
|
||||
file_path: join(root, "index.html"),
|
||||
attached: false,
|
||||
},
|
||||
capture_window: {
|
||||
started_at: "2026-07-15T00:00:00.000Z",
|
||||
ended_at: "2026-07-15T00:00:00.100Z",
|
||||
observation_ms: 100,
|
||||
},
|
||||
completeness: options.workersUnavailable
|
||||
? {
|
||||
...completeCapture(),
|
||||
status: "attach_limited" as const,
|
||||
conditions: ["attach_limited" as const],
|
||||
attach_limited_sections: ["workers" as const],
|
||||
unavailable_sections: ["workers" as const],
|
||||
}
|
||||
: completeCapture(),
|
||||
frames: [
|
||||
{
|
||||
frame_id: "frame-main",
|
||||
parent_frame_id: null,
|
||||
file_path: join(root, "index.html"),
|
||||
},
|
||||
],
|
||||
dom: { total_nodes: 0, nodes: [] },
|
||||
scripts: {
|
||||
total: 1,
|
||||
items: [
|
||||
{
|
||||
script_key: `electron_script_${"1".repeat(64)}`,
|
||||
frame_id: "frame-main",
|
||||
file_path: join(root, scriptFile),
|
||||
cdp_hash: "fixture",
|
||||
length: Buffer.byteLength(source),
|
||||
is_module: true,
|
||||
language: "JavaScript",
|
||||
source: {
|
||||
included: true as const,
|
||||
artifact: createWebTextArtifact(source, "text/javascript"),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
resources: [],
|
||||
workers: includeWorker
|
||||
? [
|
||||
{
|
||||
target_id: "worker-main",
|
||||
type: "worker",
|
||||
file_path: join(root, "worker.js"),
|
||||
attached: false,
|
||||
opener_target_id: targetId,
|
||||
parent_frame_id: "frame-main",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
limitations: ["Synthetic passive capture fixture."],
|
||||
},
|
||||
{
|
||||
id: "rea-cdp-electron",
|
||||
name: "REA Electron file-page CDP observation provider",
|
||||
version: "1",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const completeCapture = () => ({
|
||||
status: "complete_within_window" as const,
|
||||
conditions: ["complete_within_window" as const],
|
||||
policy_filtered_sections: [],
|
||||
attach_limited_sections: [],
|
||||
truncated_sections: [],
|
||||
unavailable_sections: [],
|
||||
excluded: [],
|
||||
dropped_events: {
|
||||
scripts: 0,
|
||||
network_requests: 0,
|
||||
console_events: 0,
|
||||
websocket_connections: 0,
|
||||
websocket_frames: 0,
|
||||
webmcp_tools: 0,
|
||||
timeline_events: 0,
|
||||
total: 0,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
digestProcessCommitment,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
|
||||
const emptyCapture = (): ProcessCapture => {
|
||||
const normalization = {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
};
|
||||
const scenario = { executable_sha256: "0".repeat(64) };
|
||||
const comparisonContract = {};
|
||||
const shimPlan: readonly unknown[] = [];
|
||||
const replayPlan = {};
|
||||
return {
|
||||
schema_version: 4,
|
||||
manifest: {
|
||||
rea_version: "test",
|
||||
provider_version: "3",
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
pty_backend: "node-pty",
|
||||
started_at: "2026-01-01T00:00:00.000Z",
|
||||
completed_at: "2026-01-01T00:00:00.001Z",
|
||||
scenario,
|
||||
comparison_contract: comparisonContract,
|
||||
shim_plan: shimPlan,
|
||||
replay_plan: replayPlan,
|
||||
full_scenario_sha256: digestProcessCommitment(scenario),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: "0".repeat(64),
|
||||
normalization_sha256: digestProcessCommitment(normalization),
|
||||
shim_plan_sha256: digestProcessCommitment(shimPlan),
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
normalization,
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" },
|
||||
settlement: {
|
||||
state: "quiesced",
|
||||
elapsed_ms: 50,
|
||||
cleanup_outcome: "not_required",
|
||||
},
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
event_journal: [],
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
it("classifies missing observations as unknown and one-sided evidence as added", () => {
|
||||
const base = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
const added = compareProcessCaptures(base, {
|
||||
...base,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "new" }],
|
||||
rendered_frames: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
columns: 3,
|
||||
rows: 1,
|
||||
cursor_x: 3,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["new"],
|
||||
serialized_state: "new",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(added.terminal).toBe("added");
|
||||
expect(added.status).toBe("changed");
|
||||
const unknown = compareProcessCaptures(
|
||||
{ ...base, residual_unknowns: [{ scope: "process", reason: "sampled" }] },
|
||||
base,
|
||||
);
|
||||
expect(unknown.process).toBe("unknown");
|
||||
expect(unknown.shim).toBe("unchanged");
|
||||
expect(unknown.status).toBe("unknown");
|
||||
});
|
||||
|
||||
it("compares raw terminal chunks even when rendered states agree", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "bar" }],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, {
|
||||
...capture,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "foo\rbar" }],
|
||||
});
|
||||
expect(comparison.terminal).toBe("changed");
|
||||
expect(comparison.first_divergence).toMatchObject({
|
||||
status: "found",
|
||||
dimension: "terminal",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps filesystem evidence unknown when stable snapshots match", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [
|
||||
{ scope: "filesystem" as const, reason: "watcher unavailable" },
|
||||
],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, capture);
|
||||
expect(comparison.filesystem).toBe("unknown");
|
||||
expect(comparison.status).toBe("unknown");
|
||||
|
||||
const complete = { ...capture, residual_unknowns: [] };
|
||||
const transient = compareProcessCaptures(complete, {
|
||||
...complete,
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "during_run",
|
||||
at_ms: 10,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(transient.filesystem).toBe("changed");
|
||||
expect(transient.status).toBe("changed");
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
import { execFile } from "node:child_process";
|
||||
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 { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
captureProcessScenario,
|
||||
probeProcessCaptureCapability,
|
||||
ProcessCaptureError,
|
||||
} from "../../../src/application/ProcessHarness.js";
|
||||
import {
|
||||
parseProcessScenario,
|
||||
type ProcessExecutionPolicy,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
|
||||
const processFixture = fileURLToPath(
|
||||
new URL("../../fixtures/processFidelity.mjs", import.meta.url),
|
||||
);
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
it("does not follow or disclose symlink targets outside declared roots", async () => {
|
||||
const root = await createTestTempDirectory("rea-symlink-test-");
|
||||
await symlink("/etc/passwd", join(root, "escape"));
|
||||
try {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: "/usr/bin/true",
|
||||
working_directory: root,
|
||||
filesystem_roots: [root],
|
||||
}),
|
||||
{
|
||||
enabled: true,
|
||||
executableRoots: ["/usr/bin"],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
const escaped = result.value.files_after.find((file) =>
|
||||
file.path.endsWith(":escape"),
|
||||
);
|
||||
expect(escaped?.symlink_target).toBe("<outside-declared-root>");
|
||||
expect(result.value.truncated).toBe(true);
|
||||
expect(JSON.stringify(result.value.files_after)).not.toContain(root);
|
||||
expect(JSON.stringify(result.value.files_after)).not.toContain(
|
||||
"/etc/passwd",
|
||||
);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("does not launch when policy denies capture", async () => {
|
||||
const scenario = parseProcessScenario({
|
||||
approved: true,
|
||||
executable: "/bin/sh",
|
||||
working_directory: "/tmp",
|
||||
});
|
||||
const result = await captureProcessScenario(scenario, {
|
||||
enabled: false,
|
||||
executableRoots: [],
|
||||
workingRoots: [],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected policy refusal");
|
||||
expect(result.error).toBeInstanceOf(ProcessCaptureError);
|
||||
});
|
||||
|
||||
it("distinguishes timeout from cancellation and cleans both runs", async () => {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const policy: ProcessExecutionPolicy = {
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [dirname(processFixture)],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
};
|
||||
const timedOut = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "hang"],
|
||||
working_directory: dirname(processFixture),
|
||||
timeout_ms: 50,
|
||||
idle_timeout_ms: 5_000,
|
||||
}),
|
||||
policy,
|
||||
);
|
||||
expect(timedOut.ok).toBe(true);
|
||||
if (!timedOut.ok) throw timedOut.error;
|
||||
expect(timedOut.value.exit.reason).toBe("timeout");
|
||||
expect(timedOut.value.cleanup).toEqual({
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
});
|
||||
|
||||
const controller = new AbortController();
|
||||
setTimeout(() => controller.abort(), 50);
|
||||
const cancelled = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "hang"],
|
||||
working_directory: dirname(processFixture),
|
||||
timeout_ms: 5_000,
|
||||
idle_timeout_ms: 5_000,
|
||||
}),
|
||||
policy,
|
||||
controller.signal,
|
||||
);
|
||||
expect(cancelled.ok).toBe(false);
|
||||
if (cancelled.ok) throw new Error("expected cancellation");
|
||||
expect(cancelled.error.message).toContain("cancelled");
|
||||
});
|
||||
|
||||
it("captures source-owned interactive, resize, Unicode, and signal behavior", async () => {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "interactive"],
|
||||
working_directory: dirname(processFixture),
|
||||
events: [
|
||||
{ type: "input", at_ms: 100, data: "answer" },
|
||||
{ type: "resize", at_ms: 300, columns: 100, rows: 40 },
|
||||
{ type: "signal", at_ms: 700, signal: "SIGINT" },
|
||||
],
|
||||
normalization: { time_bucket_ms: 60_000 },
|
||||
timeout_ms: 2_000,
|
||||
idle_timeout_ms: 2_000,
|
||||
}),
|
||||
{
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [dirname(processFixture)],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.ok).toBe(true);
|
||||
const output = result.value.frames.map(({ data }) => data).join("");
|
||||
expect(output).toContain("prompt>");
|
||||
expect(output).toContain("input:answer unicode:雪");
|
||||
expect(output).toContain("resize:100x40");
|
||||
expect(output).toContain("signal:SIGINT");
|
||||
expect(result.value.exit.code).toBe(0);
|
||||
});
|
||||
|
||||
it("dispatches scheduled events before a silent PTY produces output", async () => {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "silent-interactive"],
|
||||
working_directory: dirname(processFixture),
|
||||
events: [
|
||||
{ type: "resize", at_ms: 25, columns: 100, rows: 40 },
|
||||
{ type: "input", at_ms: 50, data: "answer" },
|
||||
],
|
||||
timeout_ms: 2_000,
|
||||
idle_timeout_ms: 2_000,
|
||||
}),
|
||||
{
|
||||
enabled: true,
|
||||
executableRoots: [
|
||||
join(dirname(process.execPath), "missing"),
|
||||
dirname(process.execPath),
|
||||
],
|
||||
workingRoots: [
|
||||
join(dirname(processFixture), "missing"),
|
||||
dirname(processFixture),
|
||||
],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.frames.map(({ data }) => data).join("")).toContain(
|
||||
"input:answer",
|
||||
);
|
||||
expect(result.value.interaction_events).toMatchObject([
|
||||
{ type: "resize", outcome: "dispatched" },
|
||||
{ type: "input", outcome: "dispatched" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("samples and cleans a source-owned child and grandchild process tree", async () => {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "tree"],
|
||||
working_directory: dirname(processFixture),
|
||||
timeout_ms: 2_000,
|
||||
idle_timeout_ms: 2_000,
|
||||
}),
|
||||
{
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [dirname(processFixture)],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
const commands = result.value.process_samples.map(({ command }) => command);
|
||||
expect(commands.some((command) => command.includes("tree-child"))).toBe(true);
|
||||
expect(commands.some((command) => command.includes("forks.js"))).toBe(false);
|
||||
expect(commands.some((command) => command.includes("tree-grandchild"))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(JSON.stringify(result.value.process_samples)).not.toContain(
|
||||
dirname(processFixture),
|
||||
);
|
||||
const { stdout } = await execFileAsync("ps", ["-axo", "command="]);
|
||||
expect(stdout).not.toContain(`${processFixture} tree-child`);
|
||||
expect(stdout).not.toContain(`${processFixture} tree-grandchild`);
|
||||
}, 20_000);
|
||||
@@ -0,0 +1,269 @@
|
||||
import { rm } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
captureProcessScenario,
|
||||
probeProcessCaptureCapability,
|
||||
} from "../../../src/application/ProcessHarness.js";
|
||||
import {
|
||||
parseProcessScenario,
|
||||
validateProcessCapture,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/processCapture.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,
|
||||
view: "decoded" as const,
|
||||
encoding: "utf8" as const,
|
||||
literal,
|
||||
case_sensitive: true,
|
||||
control_sequences: "include" as const,
|
||||
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: 1,
|
||||
},
|
||||
["at_ms"],
|
||||
),
|
||||
eventTrigger(
|
||||
"filesystem",
|
||||
{
|
||||
name: "ready_snapshot",
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
["at_ms"],
|
||||
),
|
||||
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({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [script, "codex"],
|
||||
working_directory: root,
|
||||
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: {
|
||||
version: 1,
|
||||
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",
|
||||
view: "decoded",
|
||||
encoding: "utf8",
|
||||
literal: "Ready",
|
||||
case_sensitive: true,
|
||||
control_sequences: "include",
|
||||
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", outcome: "passed" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// This is the single multi-source acceptance matrix for the process boundary.
|
||||
it("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), {
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
});
|
||||
try {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
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(
|
||||
validateProcessCapture(failedActionCapture).filter(({ path }) =>
|
||||
path.startsWith("reactive_run"),
|
||||
),
|
||||
).toEqual([]);
|
||||
}
|
||||
expect(first.value.truncated).toBe(false);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
@@ -0,0 +1,407 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { snapshotRoots } from "../../../src/application/FilesystemSnapshot.js";
|
||||
import {
|
||||
buildCaptureResult,
|
||||
prepareProcessCapture,
|
||||
type ProcessPreparationHost,
|
||||
} from "../../../src/application/ProcessCaptureLifecycle.js";
|
||||
import { ProcessCheckpoints } from "../../../src/application/ProcessCheckpoints.js";
|
||||
import { normalizeProcessSamples } from "../../../src/application/ProcessNormalization.js";
|
||||
import {
|
||||
isInitializedPtyRoot,
|
||||
readLinuxChildren,
|
||||
} from "../../../src/application/ProcessSampling.js";
|
||||
import { TerminalRenderer } from "../../../src/application/TerminalRenderer.js";
|
||||
import {
|
||||
authorizeProcessScenario,
|
||||
compareProcessCaptures,
|
||||
digestProcessCommitment,
|
||||
parseProcessCapture,
|
||||
parseProcessScenario,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
|
||||
const base = {
|
||||
approved: true as const,
|
||||
executable: "/bin/sh",
|
||||
working_directory: "/tmp",
|
||||
};
|
||||
|
||||
const emptyCapture = (): ProcessCapture => {
|
||||
const normalization = {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
};
|
||||
const scenario = { executable_sha256: "0".repeat(64) };
|
||||
const comparisonContract = {};
|
||||
const shimPlan: readonly unknown[] = [];
|
||||
const replayPlan = {};
|
||||
return {
|
||||
schema_version: 4,
|
||||
manifest: {
|
||||
rea_version: "test",
|
||||
provider_version: "3",
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
pty_backend: "node-pty",
|
||||
started_at: "2026-01-01T00:00:00.000Z",
|
||||
completed_at: "2026-01-01T00:00:00.001Z",
|
||||
scenario,
|
||||
comparison_contract: comparisonContract,
|
||||
shim_plan: shimPlan,
|
||||
replay_plan: replayPlan,
|
||||
full_scenario_sha256: digestProcessCommitment(scenario),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: "0".repeat(64),
|
||||
normalization_sha256: digestProcessCommitment(normalization),
|
||||
shim_plan_sha256: digestProcessCommitment(shimPlan),
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
normalization,
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" },
|
||||
settlement: {
|
||||
state: "quiesced",
|
||||
elapsed_ms: 50,
|
||||
cleanup_outcome: "not_required",
|
||||
},
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
event_journal: [],
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
it("returns detached terminal and filesystem checkpoint observations", async () => {
|
||||
const observed: string[] = [];
|
||||
const renderer = new TerminalRenderer({
|
||||
columns: 40,
|
||||
rows: 12,
|
||||
scrollback: 100,
|
||||
maxFrames: 10,
|
||||
maxBytes: 10_000,
|
||||
normalize: (value) => value,
|
||||
recordEvent: (collection, index) =>
|
||||
observed.push(`${collection}:${String(index)}`),
|
||||
});
|
||||
renderer.write("A", 20);
|
||||
renderer.resize(40, 12, 10);
|
||||
const frames = await renderer.frames();
|
||||
expect(frames.map(({ at_ms }) => at_ms)).toEqual([20, 10]);
|
||||
expect(observed).toEqual(["rendered_frames:0", "rendered_frames:1"]);
|
||||
if (frames[0] !== undefined) Reflect.set(frames[0], "cursor_x", 999);
|
||||
expect((await renderer.frames())[0]?.cursor_x).not.toBe(999);
|
||||
await renderer.dispose();
|
||||
|
||||
const scenario = parseProcessScenario(base);
|
||||
const checkpoints = new ProcessCheckpoints(
|
||||
scenario,
|
||||
Date.now(),
|
||||
{ files: [], truncated: false },
|
||||
{ signal: undefined },
|
||||
);
|
||||
const first = await checkpoints.finish({ files: [], truncated: false });
|
||||
if (first[0] !== undefined) Reflect.set(first[0], "name", "tampered");
|
||||
const second = await checkpoints.finish({ files: [], truncated: false });
|
||||
expect(second[0]?.name).toBe("before");
|
||||
await checkpoints.dispose();
|
||||
});
|
||||
|
||||
it("preserves rendered observation order instead of timestamp sorting", () => {
|
||||
const capture = emptyCapture();
|
||||
const renderedFrames: ProcessCapture["rendered_frames"] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 20,
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["first"],
|
||||
serialized_state: "first",
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["second"],
|
||||
serialized_state: "second",
|
||||
},
|
||||
];
|
||||
const result = buildCaptureResult({
|
||||
frames: [],
|
||||
reactiveRun: null,
|
||||
exit: { exitCode: 0, reason: "exited" },
|
||||
samples: [],
|
||||
replay: {
|
||||
httpUrl: "http://127.0.0.1",
|
||||
websocketUrl: "ws://127.0.0.1/ws",
|
||||
events: [],
|
||||
transitions: [],
|
||||
truncated: false,
|
||||
close: () => Promise.resolve(),
|
||||
},
|
||||
before: { files: [], truncated: false },
|
||||
after: { files: [], truncated: false },
|
||||
truncated: false,
|
||||
scenario: parseProcessScenario(base),
|
||||
rootPid: 1,
|
||||
samplingPartial: false,
|
||||
renderedFrames,
|
||||
interactions: [],
|
||||
checkpoints: capture.filesystem_checkpoints,
|
||||
shimEvents: [],
|
||||
settlement: capture.settlement,
|
||||
manifest: capture.manifest,
|
||||
eventJournal: [],
|
||||
});
|
||||
|
||||
expect(result.rendered_frames).toEqual(renderedFrames);
|
||||
});
|
||||
|
||||
it("cleans the temporary root when capture home creation fails", async () => {
|
||||
const cleaned: string[] = [];
|
||||
const host: ProcessPreparationHost = {
|
||||
createTemporaryRoot: () => Promise.resolve("/tmp/rea-process-fixture"),
|
||||
createHome: () => Promise.reject(new Error("mkdir failed")),
|
||||
cleanup: (path) => {
|
||||
cleaned.push(path);
|
||||
return Promise.resolve();
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
prepareProcessCapture(
|
||||
parseProcessScenario(base),
|
||||
{
|
||||
enabled: true,
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
undefined,
|
||||
host,
|
||||
),
|
||||
).rejects.toThrow("mkdir failed");
|
||||
expect(cleaned).toEqual(["/tmp/rea-process-fixture"]);
|
||||
});
|
||||
|
||||
it("normalizes every sampled process identifier in command text", () => {
|
||||
const samples = normalizeProcessSamples(
|
||||
[
|
||||
{
|
||||
at_ms: 0,
|
||||
pid: 101,
|
||||
parent_pid: 0,
|
||||
process_group_id: 101,
|
||||
session_id: 101,
|
||||
command: "root 101",
|
||||
},
|
||||
{
|
||||
at_ms: 10,
|
||||
pid: 202,
|
||||
parent_pid: 101,
|
||||
process_group_id: 101,
|
||||
session_id: 101,
|
||||
command: "child 202 peer=101 unrelated 1202",
|
||||
},
|
||||
],
|
||||
parseProcessScenario(base),
|
||||
101,
|
||||
);
|
||||
|
||||
expect(samples[1]?.command).toBe("child <pid> peer=<pid> unrelated 1202");
|
||||
});
|
||||
|
||||
it("collects and deduplicates children from every Linux thread", async () => {
|
||||
const signal = new AbortController().signal;
|
||||
expect(
|
||||
await readLinuxChildren(100, signal, {
|
||||
taskIds: () => Promise.resolve([100, 101, 102]),
|
||||
children: (_pid, taskId) =>
|
||||
Promise.resolve(
|
||||
taskId === 100 ? "201 202" : taskId === 101 ? "202 203" : "",
|
||||
),
|
||||
}),
|
||||
).toEqual([201, 202, 203]);
|
||||
});
|
||||
|
||||
it("admits PTY samples only after stable session and token setup", () => {
|
||||
const initialized = {
|
||||
pid: 100,
|
||||
parent_pid: 10,
|
||||
process_group_id: 100,
|
||||
session_id: 100,
|
||||
startTime: "200",
|
||||
};
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: { ...initialized, process_group_id: 10, session_id: 10 },
|
||||
observedRunId: undefined,
|
||||
after: initialized,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: initialized,
|
||||
observedRunId: "run-token",
|
||||
after: { ...initialized, startTime: "201" },
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: initialized,
|
||||
observedRunId: "run-token",
|
||||
after: initialized,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: { ...initialized, session_id: null },
|
||||
observedRunId: "run-token",
|
||||
after: { ...initialized, session_id: null },
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps interaction and shim residual uncertainty in separate scopes", () => {
|
||||
const baseCapture = emptyCapture();
|
||||
const interaction = parseProcessCapture({
|
||||
...baseCapture,
|
||||
residual_unknowns: [
|
||||
{ scope: "interaction", reason: "Interaction capture was partial." },
|
||||
],
|
||||
});
|
||||
const shim = parseProcessCapture({
|
||||
...baseCapture,
|
||||
residual_unknowns: [{ scope: "shim", reason: "Shim capture was partial." }],
|
||||
});
|
||||
|
||||
expect(compareProcessCaptures(interaction, baseCapture)).toMatchObject({
|
||||
status: "unknown",
|
||||
terminal: "unchanged",
|
||||
interaction: "unknown",
|
||||
shim: "unchanged",
|
||||
});
|
||||
expect(compareProcessCaptures(shim, baseCapture)).toMatchObject({
|
||||
status: "unknown",
|
||||
terminal: "unchanged",
|
||||
interaction: "unchanged",
|
||||
shim: "unknown",
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels filesystem snapshots before traversing declared roots", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(
|
||||
snapshotRoots(
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
filesystem_roots: ["/tmp"],
|
||||
}),
|
||||
controller.signal,
|
||||
),
|
||||
).rejects.toMatchObject({ name: "AbortError" });
|
||||
});
|
||||
|
||||
it("parses bounded scenarios and rejects unordered events", () => {
|
||||
expect(parseProcessScenario(base).timeout_ms).toBe(30_000);
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
events: [
|
||||
{ type: "input", at_ms: 2, data: "a" },
|
||||
{ type: "input", at_ms: 1, data: "b" },
|
||||
],
|
||||
}),
|
||||
).toThrow(/ordered/);
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
environment: { HOME: "/unsafe" },
|
||||
}),
|
||||
).toThrow(/reserved/);
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
events: [{ type: "input", at_ms: 31_000, data: "late" }],
|
||||
}),
|
||||
).toThrow(/after the scenario timeout/);
|
||||
});
|
||||
|
||||
it("requires explicit operator approval for host network access", () => {
|
||||
expect(
|
||||
authorizeProcessScenario(parseProcessScenario(base), {
|
||||
enabled: true,
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: false,
|
||||
}),
|
||||
).toEqual({
|
||||
allowed: false,
|
||||
reason: "host network access is not approved by operator policy",
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses paths and environment outside operator policy", () => {
|
||||
const scenario = parseProcessScenario({
|
||||
...base,
|
||||
environment: { TOKEN: "secret" },
|
||||
});
|
||||
expect(
|
||||
authorizeProcessScenario(scenario, {
|
||||
enabled: true,
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
}),
|
||||
).toEqual({
|
||||
allowed: false,
|
||||
reason: "scenario requests an environment variable not allowed by policy",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,424 @@
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
captureProcessScenario,
|
||||
probeProcessCaptureCapability,
|
||||
} from "../../../src/application/ProcessHarness.js";
|
||||
import {
|
||||
parseProcessScenario,
|
||||
validateProcessCapture,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
|
||||
function createInteractiveScenario(root: string, script: string) {
|
||||
return parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [script],
|
||||
working_directory: root,
|
||||
reactive: {
|
||||
version: 1,
|
||||
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",
|
||||
view: "decoded",
|
||||
encoding: "utf8",
|
||||
literal: "Ready",
|
||||
case_sensitive: true,
|
||||
control_sequences: "include",
|
||||
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",
|
||||
view: "decoded",
|
||||
encoding: "utf8",
|
||||
literal: "Done",
|
||||
case_sensitive: true,
|
||||
control_sequences: "include",
|
||||
occurrence: 1,
|
||||
since: { kind: "state_entry" },
|
||||
consume: true,
|
||||
},
|
||||
actions: [],
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
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(
|
||||
validateProcessCapture({
|
||||
...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(
|
||||
validateProcessCapture({
|
||||
...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(
|
||||
validateProcessCapture({
|
||||
...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(
|
||||
validateProcessCapture({
|
||||
...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(
|
||||
validateProcessCapture({
|
||||
...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(
|
||||
validateProcessCapture({
|
||||
...capture,
|
||||
reactive_run: { ...reactiveRun, status: "running", outcome: null },
|
||||
}),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
message: "completed capture requires a finished reactive outcome",
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
validateProcessCapture({
|
||||
...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",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
it("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 capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(scenario, {
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
assertCompletedCapture(result.value);
|
||||
assertControlAndTransitionValidation(result.value);
|
||||
assertReplayValidation(result.value);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("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({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [script],
|
||||
working_directory: root,
|
||||
settle_ms: 500,
|
||||
reactive: {
|
||||
version: 1,
|
||||
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",
|
||||
view: "decoded",
|
||||
encoding: "utf8",
|
||||
literal: "never-produced",
|
||||
case_sensitive: true,
|
||||
control_sequences: "include",
|
||||
occurrence: 1,
|
||||
since: { kind: "scenario_start" },
|
||||
consume: true,
|
||||
},
|
||||
actions: [],
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
try {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(scenario, {
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
});
|
||||
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(
|
||||
validateProcessCapture(withLaterMatch).filter(({ path }) =>
|
||||
path.startsWith("reactive_run"),
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
validateProcessCapture({
|
||||
...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);
|
||||
@@ -0,0 +1,230 @@
|
||||
import { readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
captureProcessScenario,
|
||||
probeProcessCaptureCapability,
|
||||
} from "../../../src/application/ProcessHarness.js";
|
||||
import {
|
||||
digestProcessCommitment,
|
||||
parseProcessScenario,
|
||||
type ProcessExecutionPolicy,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
|
||||
it("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({
|
||||
approved: true,
|
||||
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 capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const capture = await captureProcessScenario(scenario, {
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
});
|
||||
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);
|
||||
|
||||
it("captures PTY, filesystem, descendants, HTTP replay, and redacts environment", 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 policy: ProcessExecutionPolicy = {
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: ["SECRET"],
|
||||
allowExternalNetwork: true,
|
||||
};
|
||||
const scenario = parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [script],
|
||||
working_directory: root,
|
||||
filesystem_roots: [root],
|
||||
environment: { SECRET: "do-not-record" },
|
||||
secret_aliases: ["SECRET"],
|
||||
replay: {
|
||||
http: [{ method: "GET", path: "/probe", status: 200, body: "ok" }],
|
||||
},
|
||||
});
|
||||
try {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) {
|
||||
expect(capability.reason).toMatch(/native PTY/);
|
||||
return;
|
||||
}
|
||||
const capture = await captureProcessScenario(scenario, policy);
|
||||
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:<redacted>",
|
||||
);
|
||||
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)).not.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 });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,328 @@
|
||||
import { expect, it } 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({
|
||||
approved: true,
|
||||
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 bounded HTTP scripts without persisting request secrets", async () => {
|
||||
const scenario = parseProcessScenario({
|
||||
approved: true,
|
||||
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("consumes ordered WebSocket reconnect scripts and reports exhaustion", async () => {
|
||||
const scenario = parseProcessScenario({
|
||||
approved: true,
|
||||
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({
|
||||
approved: true,
|
||||
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({
|
||||
approved: true,
|
||||
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({
|
||||
approved: true,
|
||||
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();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,190 @@
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
captureProcessScenario,
|
||||
probeProcessCaptureCapability,
|
||||
} from "../../../src/application/ProcessHarness.js";
|
||||
import { parseProcessScenario } from "../../../src/domain/processCapture.js";
|
||||
|
||||
const buildTerminalScenario = (root: string, script: string) =>
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [script],
|
||||
working_directory: root,
|
||||
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: {
|
||||
version: 1,
|
||||
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",
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
ignore_fields: ["at_ms"],
|
||||
since: { kind: "scenario_start" },
|
||||
consume: true,
|
||||
cardinality: { min: 1, max: 1 },
|
||||
},
|
||||
actions: [],
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
// 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");
|
||||
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}`);",
|
||||
].join("\n"),
|
||||
);
|
||||
try {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(
|
||||
buildTerminalScenario(root, script),
|
||||
{
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.schema_version).toBe(4);
|
||||
expect(result.value.rendered_frames.at(-1)?.lines.join("\n")).toContain(
|
||||
"probe:codex 1.2.3",
|
||||
);
|
||||
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.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),
|
||||
],
|
||||
}),
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 20_000);
|
||||
@@ -0,0 +1,197 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
digestProcessCommitment,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
|
||||
const emptyCapture = (): ProcessCapture => {
|
||||
const normalization = {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
};
|
||||
const scenario = { executable_sha256: "0".repeat(64) };
|
||||
const comparisonContract = {};
|
||||
const shimPlan: readonly unknown[] = [];
|
||||
const replayPlan = {};
|
||||
return {
|
||||
schema_version: 4,
|
||||
manifest: {
|
||||
rea_version: "test",
|
||||
provider_version: "3",
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
pty_backend: "node-pty",
|
||||
started_at: "2026-01-01T00:00:00.000Z",
|
||||
completed_at: "2026-01-01T00:00:00.001Z",
|
||||
scenario,
|
||||
comparison_contract: comparisonContract,
|
||||
shim_plan: shimPlan,
|
||||
replay_plan: replayPlan,
|
||||
full_scenario_sha256: digestProcessCommitment(scenario),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: "0".repeat(64),
|
||||
normalization_sha256: digestProcessCommitment(normalization),
|
||||
shim_plan_sha256: digestProcessCommitment(shimPlan),
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
normalization,
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" },
|
||||
settlement: {
|
||||
state: "quiesced",
|
||||
elapsed_ms: 50,
|
||||
cleanup_outcome: "not_required",
|
||||
},
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
event_journal: [],
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
it("detects changes in normalized process sample metadata", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [
|
||||
{
|
||||
at_ms: 10,
|
||||
pid: 1,
|
||||
parent_pid: 0,
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
command: "worker",
|
||||
},
|
||||
],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
const changed = {
|
||||
...capture,
|
||||
process_samples: [
|
||||
{
|
||||
at_ms: 20,
|
||||
pid: 1,
|
||||
parent_pid: 2,
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
command: "worker",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, changed);
|
||||
expect(comparison.process).toBe("changed");
|
||||
expect(comparison.status).toBe("changed");
|
||||
});
|
||||
|
||||
it("compares replay state transitions as protocol evidence", () => {
|
||||
const replayPlan = {
|
||||
machine: {
|
||||
initial_state: "anonymous",
|
||||
states: [
|
||||
{ name: "anonymous" },
|
||||
{ name: "authenticated", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "login",
|
||||
from: "anonymous",
|
||||
to: "authenticated",
|
||||
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,
|
||||
},
|
||||
],
|
||||
max_transitions: 1,
|
||||
},
|
||||
};
|
||||
const empty = emptyCapture();
|
||||
const baseline = {
|
||||
...empty,
|
||||
manifest: {
|
||||
...empty.manifest,
|
||||
replay_plan: replayPlan,
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
};
|
||||
const transitioned = {
|
||||
...baseline,
|
||||
replay_transitions: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
transition_id: "login",
|
||||
state_before: "anonymous",
|
||||
state_after: "authenticated",
|
||||
sensitive_aliases: ["token"],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(compareProcessCaptures(baseline, transitioned)).toMatchObject({
|
||||
status: "changed",
|
||||
protocol: "added",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,328 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createProcessCaptureJournal } from "../../../src/application/ProcessCaptureJournal.js";
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
digestProcessCommitment,
|
||||
LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
parseProcessCapture,
|
||||
processCaptureSchema,
|
||||
validateProcessCapture,
|
||||
type ProcessCapture,
|
||||
type ProcessCaptureEventJournalEntry,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
|
||||
const emptyCapture = (): ProcessCapture => {
|
||||
const normalization = {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
};
|
||||
const scenario = { executable_sha256: "0".repeat(64) };
|
||||
const comparisonContract = {};
|
||||
const shimPlan: readonly unknown[] = [];
|
||||
const replayPlan = {};
|
||||
return {
|
||||
schema_version: 4,
|
||||
manifest: {
|
||||
rea_version: "test",
|
||||
provider_version: "3",
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
pty_backend: "node-pty",
|
||||
started_at: "2026-01-01T00:00:00.000Z",
|
||||
completed_at: "2026-01-01T00:00:00.001Z",
|
||||
scenario,
|
||||
comparison_contract: comparisonContract,
|
||||
shim_plan: shimPlan,
|
||||
replay_plan: replayPlan,
|
||||
full_scenario_sha256: digestProcessCommitment(scenario),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: "0".repeat(64),
|
||||
normalization_sha256: digestProcessCommitment(normalization),
|
||||
shim_plan_sha256: digestProcessCommitment(shimPlan),
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
normalization,
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" },
|
||||
settlement: {
|
||||
state: "quiesced",
|
||||
elapsed_ms: 50,
|
||||
cleanup_outcome: "not_required",
|
||||
},
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
event_journal: [],
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
it("never considers truncated captures equivalent", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: true,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
expect(compareProcessCaptures(capture, capture).status).toBe("truncated");
|
||||
});
|
||||
|
||||
it("rejects altered v4 commitments and accepts canonical key reordering", () => {
|
||||
const capture = emptyCapture();
|
||||
expect(parseProcessCapture(capture)).toEqual(capture);
|
||||
expect(digestProcessCommitment({ second: 2, first: 1 })).toBe(
|
||||
digestProcessCommitment({ first: 1, second: 2 }),
|
||||
);
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
normalization_sha256: "f".repeat(64),
|
||||
},
|
||||
}),
|
||||
).toThrow("normalization_sha256");
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
executable_sha256: "f".repeat(64),
|
||||
},
|
||||
}),
|
||||
).toThrow("executable_sha256");
|
||||
});
|
||||
|
||||
it("accepts old captures without a journal and validates complete journals", () => {
|
||||
const journal = createProcessCaptureJournal();
|
||||
const observed: ProcessCaptureEventJournalEntry[] = [];
|
||||
const unsubscribe = journal.subscribe((entry) => observed.push(entry));
|
||||
journal.recordEvent("lifecycle", 0);
|
||||
const settlementEntry = journal.record("lifecycle", 1);
|
||||
unsubscribe();
|
||||
journal.recordEvent("frames", 0);
|
||||
expect(journal.entries).toEqual([
|
||||
{ capture_order: 0, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 1, collection: "lifecycle", index: 1 },
|
||||
{ capture_order: 2, collection: "frames", index: 0 },
|
||||
]);
|
||||
expect(observed).toEqual(journal.entries.slice(0, 2));
|
||||
expect(settlementEntry).toEqual(journal.entries[1]);
|
||||
|
||||
const nestedJournal = createProcessCaptureJournal();
|
||||
const notifications: string[] = [];
|
||||
nestedJournal.subscribe((entry) => {
|
||||
notifications.push(`a:${String(entry.capture_order)}`);
|
||||
if (entry.capture_order === 0) nestedJournal.record("frames", 1);
|
||||
});
|
||||
nestedJournal.subscribe((entry) =>
|
||||
notifications.push(`b:${String(entry.capture_order)}`),
|
||||
);
|
||||
nestedJournal.record("frames", 0);
|
||||
expect(notifications).toEqual(["a:0", "b:0", "a:1", "b:1"]);
|
||||
|
||||
const capture = emptyCapture();
|
||||
const { event_journal: _eventJournal, ...oldCapture } = capture;
|
||||
expect(parseProcessCapture(oldCapture).event_journal).toEqual([]);
|
||||
|
||||
const eventJournal = [
|
||||
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
|
||||
{ capture_order: 1, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 2, collection: "lifecycle", index: 1 },
|
||||
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
|
||||
] as const;
|
||||
expect(
|
||||
validateProcessCapture({ ...capture, event_journal: eventJournal }),
|
||||
).toEqual([]);
|
||||
|
||||
for (const [candidate, message] of [
|
||||
[
|
||||
eventJournal.map((entry, index) =>
|
||||
index === 1 ? { ...entry, capture_order: 2 } : entry,
|
||||
),
|
||||
"contiguous",
|
||||
],
|
||||
[
|
||||
eventJournal.map((entry, index) =>
|
||||
index === 3
|
||||
? { ...entry, collection: "lifecycle" as const, index: 1 }
|
||||
: entry,
|
||||
),
|
||||
"unique",
|
||||
],
|
||||
[eventJournal.slice(0, 3), "every captured observation"],
|
||||
[
|
||||
eventJournal.map((entry, index) =>
|
||||
index === 3 ? { ...entry, index: 2 } : entry,
|
||||
),
|
||||
"outside",
|
||||
],
|
||||
] as const) {
|
||||
expect(
|
||||
validateProcessCapture({ ...capture, event_journal: candidate }),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
message: expect.stringContaining(message),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["machine limit", 1, 5, 10],
|
||||
["transition use limit", 5, 1, 10],
|
||||
["state visit limit", 5, 5, 1],
|
||||
])(
|
||||
"rejects replay journals that exceed the declared %s",
|
||||
(_name, maxTransitions, maxUses, maxVisits) => {
|
||||
const replayPlan = {
|
||||
machine: {
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: maxVisits },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "again",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: {
|
||||
protocol: "websocket_message",
|
||||
path: "/ws",
|
||||
body: "again",
|
||||
},
|
||||
actions: [{ type: "websocket_send", data: "again" }],
|
||||
max_uses: maxUses,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "complete",
|
||||
trigger: {
|
||||
protocol: "websocket_message",
|
||||
path: "/ws",
|
||||
body: "finish",
|
||||
},
|
||||
actions: [{ type: "websocket_send", data: "done" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: maxTransitions,
|
||||
},
|
||||
};
|
||||
const capture = emptyCapture();
|
||||
const candidate: ProcessCapture = {
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
replay_plan: replayPlan,
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
replay_transitions: [0, 1].map((sequence) => ({
|
||||
sequence,
|
||||
at_ms: sequence,
|
||||
transition_id: "again",
|
||||
state_before: "active",
|
||||
state_after: "active",
|
||||
sensitive_aliases: [],
|
||||
})),
|
||||
};
|
||||
|
||||
expect(validateProcessCapture(candidate)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
message: expect.stringContaining("limit"),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("tells agents and users to recapture unsupported v3 evidence", () => {
|
||||
const legacy = { ...emptyCapture(), schema_version: 3 };
|
||||
expect(() => parseProcessCapture(legacy)).toThrow(
|
||||
LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
);
|
||||
const parsed = processCaptureSchema.safeParse(legacy);
|
||||
expect(parsed.success).toBe(false);
|
||||
if (parsed.success) throw new Error("expected legacy capture rejection");
|
||||
expect(parsed.error.issues[0]?.message).toBe(LEGACY_PROCESS_CAPTURE_MESSAGE);
|
||||
});
|
||||
|
||||
it("requires compatible contracts and enforces capture age through a clock seam", () => {
|
||||
const capture = emptyCapture();
|
||||
expect(() =>
|
||||
compareProcessCaptures(capture, {
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
comparison_contract: { changed: true },
|
||||
comparison_contract_sha256: digestProcessCommitment({
|
||||
changed: true,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
).toThrow("incompatible comparison contracts");
|
||||
expect(() =>
|
||||
compareProcessCaptures(capture, capture, {
|
||||
maxCaptureAgeMs: 1,
|
||||
now: () => Date.parse("2026-01-01T00:00:01.000Z"),
|
||||
}),
|
||||
).toThrow("max_capture_age_ms");
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
|
||||
import {
|
||||
processCaptureSchema,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
import {
|
||||
createProcessObservation,
|
||||
projectProcessObservation,
|
||||
} from "../../../src/domain/processObservation.js";
|
||||
|
||||
const emptyCapture = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
|
||||
const capture: ProcessCapture = {
|
||||
...emptyCapture,
|
||||
frames: [{ sequence: 0, at_ms: 1, data: "Ready" }],
|
||||
rendered_frames: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 2,
|
||||
columns: 80,
|
||||
rows: 24,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["Ready"],
|
||||
serialized_state: "Ready",
|
||||
},
|
||||
],
|
||||
interaction_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
scheduled_at_ms: 2,
|
||||
dispatched_at_ms: 3,
|
||||
type: "signal",
|
||||
data: "SIGINT",
|
||||
outcome: "dispatched",
|
||||
},
|
||||
],
|
||||
process_samples: [
|
||||
{
|
||||
at_ms: 4,
|
||||
pid: 2,
|
||||
parent_pid: 1,
|
||||
command: "worker",
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
},
|
||||
],
|
||||
shim_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 5,
|
||||
command: "helper",
|
||||
route_index: 0,
|
||||
arguments: [],
|
||||
working_directory: "/fixture",
|
||||
outcome: "matched",
|
||||
},
|
||||
],
|
||||
protocol_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 6,
|
||||
protocol: "http",
|
||||
direction: "request",
|
||||
method: "GET",
|
||||
path: "/done",
|
||||
data: "",
|
||||
outcome: "matched",
|
||||
},
|
||||
],
|
||||
replay_transitions: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 7,
|
||||
transition_id: "done",
|
||||
state_before: "open",
|
||||
state_after: "closed",
|
||||
sensitive_aliases: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("process observation vocabulary", () => {
|
||||
it("projects every capture collection without timestamp sorting", () => {
|
||||
const locations = [
|
||||
{ collection: "frames", index: 0, capture_order: 4 },
|
||||
{ collection: "rendered_frames", index: 0, capture_order: 3 },
|
||||
{ collection: "interaction_events", index: 0, capture_order: 2 },
|
||||
{ collection: "lifecycle", index: 0, capture_order: 8 },
|
||||
{ collection: "lifecycle", index: 1, capture_order: 9 },
|
||||
{ collection: "process_samples", index: 0, capture_order: 1 },
|
||||
{ collection: "filesystem_checkpoints", index: 0, capture_order: 0 },
|
||||
{ collection: "shim_events", index: 0, capture_order: 5 },
|
||||
{ collection: "protocol_events", index: 0, capture_order: 6 },
|
||||
{ collection: "replay_transitions", index: 0, capture_order: 7 },
|
||||
] as const;
|
||||
const observations = locations.map((location) =>
|
||||
projectProcessObservation(capture, location),
|
||||
);
|
||||
|
||||
expect(observations.map((value) => value?.source)).toEqual([
|
||||
"terminal_raw",
|
||||
"terminal_rendered",
|
||||
"interaction",
|
||||
"lifecycle",
|
||||
"lifecycle",
|
||||
"process",
|
||||
"filesystem",
|
||||
"shim",
|
||||
"http",
|
||||
"replay_transition",
|
||||
]);
|
||||
expect(observations.map((value) => value?.capture_order)).toEqual(
|
||||
locations.map(({ capture_order }) => capture_order),
|
||||
);
|
||||
expect(observations[5]).toMatchObject({
|
||||
event_id: "obs.process_samples.0",
|
||||
source_sequence: 0,
|
||||
captured_at_ms: 4,
|
||||
subject_id: "process:2",
|
||||
});
|
||||
expect(observations[7]).toMatchObject({
|
||||
event_id: "obs.shim_events.0",
|
||||
subject_id: "shim:helper:route:0",
|
||||
});
|
||||
expect(observations[3]?.captured_at_ms).toBeNull();
|
||||
expect(observations[4]?.captured_at_ms).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the same constructor for live and post-hoc observations", () => {
|
||||
const location = {
|
||||
collection: "frames" as const,
|
||||
index: 0,
|
||||
capture_order: 4,
|
||||
};
|
||||
const projected = projectProcessObservation(capture, location);
|
||||
const live = createProcessObservation({
|
||||
source: "terminal_raw",
|
||||
source_sequence: 0,
|
||||
captured_at_ms: 1,
|
||||
subject_id: null,
|
||||
location,
|
||||
payload: capture.frames[0],
|
||||
});
|
||||
expect(live).toEqual(projected);
|
||||
});
|
||||
|
||||
it("returns no observation for a missing raw record", () => {
|
||||
expect(
|
||||
projectProcessObservation(capture, {
|
||||
collection: "frames",
|
||||
index: 1,
|
||||
capture_order: 10,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
parseProcessEnvironment,
|
||||
selectCapturedProcessGroupIds,
|
||||
type ProcessOwnershipHost,
|
||||
} from "../../../src/process/ProcessOwnership.js";
|
||||
import { matchesOwnedProcessCommand } from "../../../src/process/ProcessCommandIdentity.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
const host = (
|
||||
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
|
||||
): {
|
||||
readonly adapter: ProcessOwnershipHost;
|
||||
readonly signalGroup: ReturnType<typeof vi.fn>;
|
||||
} => {
|
||||
const signalGroup = vi.fn();
|
||||
return {
|
||||
adapter: {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
Object.keys(environments).map((pid) => ({
|
||||
pid: Number(pid),
|
||||
parentPid: Number(pid) === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
|
||||
signalGroup,
|
||||
},
|
||||
signalGroup,
|
||||
};
|
||||
};
|
||||
describe("owned process-group cleanup discovery", () => {
|
||||
it("excludes sampled groups whose leader was outside the captured tree", () => {
|
||||
expect(
|
||||
selectCapturedProcessGroupIds(100, [
|
||||
{ pid: 100, process_group_id: 42 },
|
||||
{ pid: 100, process_group_id: 100 },
|
||||
{ pid: 101, process_group_id: 42 },
|
||||
{ pid: 102, process_group_id: 102 },
|
||||
{ pid: 103, process_group_id: 102 },
|
||||
]),
|
||||
).toEqual([100, 102]);
|
||||
});
|
||||
it("drops nameless Linux environment entries", () => {
|
||||
expect(
|
||||
parseProcessEnvironment("=ignored\0REA_PROCESS_RUN_ID=owned\0EMPTY=\0"),
|
||||
).toEqual({ REA_PROCESS_RUN_ID: "owned", EMPTY: "" });
|
||||
});
|
||||
it("matches macOS executable names after process-table normalization", () => {
|
||||
expect(
|
||||
matchesOwnedProcessCommand(
|
||||
"node /tmp/fake-launcher.mjs",
|
||||
"/opt/node/bin/node",
|
||||
"darwin",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesOwnedProcessCommand("(node)", "/opt/node/bin/node", "darwin"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesOwnedProcessCommand(
|
||||
"node /tmp/fake-launcher.mjs",
|
||||
"/opt/python/bin/python3",
|
||||
"darwin",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
matchesOwnedProcessCommand(
|
||||
"node /tmp/fake-launcher.mjs",
|
||||
"/opt/node/bin/node",
|
||||
"linux",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
matchesOwnedProcessCommand("(node)", "/opt/node/bin/node", "linux"),
|
||||
).toBe(false);
|
||||
});
|
||||
it("signals only a group whose every member carries the run token", async () => {
|
||||
const { adapter, signalGroup } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
101: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
});
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
});
|
||||
expect(signalGroup).toHaveBeenCalledWith(100, "SIGKILL");
|
||||
});
|
||||
it("validates and signals rooted descendant groups once, root first", async () => {
|
||||
const processes = [
|
||||
{ pid: 100, parentPid: 1, processGroupId: 100 },
|
||||
{ pid: 110, parentPid: 100, processGroupId: 100 },
|
||||
{ pid: 101, parentPid: 100, processGroupId: 101 },
|
||||
{ pid: 102, parentPid: 101, processGroupId: 102 },
|
||||
{ pid: 103, parentPid: 102, processGroupId: 102 },
|
||||
].map((process) => ({
|
||||
...process,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
}));
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () => Promise.resolve(processes),
|
||||
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{ cleaned: true, signaled: true },
|
||||
);
|
||||
expect(signalGroup.mock.calls).toEqual([
|
||||
[100, "SIGKILL"],
|
||||
[101, "SIGKILL"],
|
||||
[102, "SIGKILL"],
|
||||
]);
|
||||
});
|
||||
it("leaves an unrelated Hopper process group outside the rooted tree untouched", async () => {
|
||||
const processes = [
|
||||
{ pid: 100, parentPid: 1, processGroupId: 100, command: "rea-hopper" },
|
||||
{ pid: 101, parentPid: 100, processGroupId: 101, command: "owned-child" },
|
||||
{
|
||||
pid: 900,
|
||||
parentPid: 1,
|
||||
processGroupId: 900,
|
||||
command:
|
||||
"/Applications/Hopper Disassembler.app/Contents/MacOS/Hopper Disassembler",
|
||||
},
|
||||
].map((process) => ({ ...process, state: "S" }));
|
||||
const environment = vi.fn((pid: number) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 900 ? "unrelated-run" : "run-token",
|
||||
}),
|
||||
);
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () => Promise.resolve(processes),
|
||||
environment,
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{ cleaned: true, signaled: true },
|
||||
);
|
||||
expect(signalGroup.mock.calls).toEqual([
|
||||
[100, "SIGKILL"],
|
||||
[101, "SIGKILL"],
|
||||
]);
|
||||
expect(environment.mock.calls.some(([pid]) => pid === 900)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
observeOwnedProcessLineage,
|
||||
type ProcessOwnershipHost,
|
||||
} from "../../../src/process/ProcessOwnership.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
const host = (
|
||||
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
|
||||
): {
|
||||
readonly adapter: ProcessOwnershipHost;
|
||||
readonly signalGroup: ReturnType<typeof vi.fn>;
|
||||
} => {
|
||||
const signalGroup = vi.fn();
|
||||
return {
|
||||
adapter: {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
Object.keys(environments).map((pid) => ({
|
||||
pid: Number(pid),
|
||||
parentPid: Number(pid) === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
|
||||
signalGroup,
|
||||
},
|
||||
signalGroup,
|
||||
};
|
||||
};
|
||||
describe("owned process-group cleanup discovery", () => {
|
||||
it("fails before signaling when any descendant-group member is unowned", async () => {
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "child-session",
|
||||
},
|
||||
{
|
||||
pid: 104,
|
||||
parentPid: 101,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "child-helper",
|
||||
},
|
||||
]),
|
||||
environment: (pid) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 104 ? "other-run" : "run-token",
|
||||
}),
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{
|
||||
cleaned: false,
|
||||
reason: "process tree contains an unowned or PID-reused process",
|
||||
failures: [{ pid: 104, reason: "run-token-mismatch" }],
|
||||
},
|
||||
);
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("fails before signaling when a descendant group leader is not rooted", async () => {
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 105,
|
||||
parentPid: 100,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "descendant",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 999,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "unrelated-group-leader",
|
||||
},
|
||||
]),
|
||||
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{
|
||||
cleaned: false,
|
||||
reason:
|
||||
"descendant process-group leader identity could not be verified",
|
||||
},
|
||||
);
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("records sorted launcher and descendant lineage after token checks", async () => {
|
||||
const { adapter } = host({
|
||||
102: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
101: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
});
|
||||
await expect(
|
||||
observeOwnedProcessLineage(ownership, adapter),
|
||||
).resolves.toEqual({
|
||||
status: "verified",
|
||||
observedAt: expect.any(String),
|
||||
lineage: {
|
||||
schemaVersion: 1,
|
||||
runId: "run-token",
|
||||
launcherPid: 100,
|
||||
launcherParentPid: 1,
|
||||
processGroupId: 100,
|
||||
descendants: [
|
||||
{ pid: 101, parentPid: 100, processGroupId: 100 },
|
||||
{ pid: 102, parentPid: 100, processGroupId: 100 },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
observeOwnedProcessLineage,
|
||||
type ProcessOwnershipHost,
|
||||
} from "../../../src/process/ProcessOwnership.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
describe("owned process-group cleanup discovery", () => {
|
||||
it("walks the PPID tree across process-group boundaries", async () => {
|
||||
const environment = vi.fn((pid: number) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 103 ? "unrelated-run" : "run-token",
|
||||
}),
|
||||
);
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 103,
|
||||
parentPid: 999,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "unrelated-same-group",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
parentPid: 101,
|
||||
processGroupId: 102,
|
||||
state: "S",
|
||||
command: "grandchild-session",
|
||||
},
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "child-group",
|
||||
},
|
||||
]),
|
||||
environment,
|
||||
signalGroup: vi.fn(),
|
||||
};
|
||||
await expect(
|
||||
observeOwnedProcessLineage(ownership, adapter),
|
||||
).resolves.toEqual({
|
||||
status: "verified",
|
||||
observedAt: expect.any(String),
|
||||
lineage: {
|
||||
schemaVersion: 1,
|
||||
runId: "run-token",
|
||||
launcherPid: 100,
|
||||
launcherParentPid: 1,
|
||||
processGroupId: 100,
|
||||
descendants: [
|
||||
{ pid: 101, parentPid: 100, processGroupId: 101 },
|
||||
{ pid: 102, parentPid: 101, processGroupId: 102 },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(environment.mock.calls.map(([pid]) => pid)).toEqual([100, 101, 102]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
observeOwnedProcessLineage,
|
||||
type ProcessOwnershipHost,
|
||||
} from "../../../src/process/ProcessOwnership.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
const host = (
|
||||
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
|
||||
): {
|
||||
readonly adapter: ProcessOwnershipHost;
|
||||
readonly signalGroup: ReturnType<typeof vi.fn>;
|
||||
} => {
|
||||
const signalGroup = vi.fn();
|
||||
return {
|
||||
adapter: {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
Object.keys(environments).map((pid) => ({
|
||||
pid: Number(pid),
|
||||
parentPid: Number(pid) === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
|
||||
signalGroup,
|
||||
},
|
||||
signalGroup,
|
||||
};
|
||||
};
|
||||
describe("owned process-group cleanup validation", () => {
|
||||
it("fails closed when a descendant in another process group lacks the token", async () => {
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "child-session",
|
||||
},
|
||||
]),
|
||||
environment: (pid) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 100 ? "run-token" : "other-run",
|
||||
}),
|
||||
signalGroup: vi.fn(),
|
||||
};
|
||||
await expect(
|
||||
observeOwnedProcessLineage(ownership, adapter),
|
||||
).resolves.toEqual({
|
||||
status: "unavailable",
|
||||
observedAt: expect.any(String),
|
||||
runId: "run-token",
|
||||
launcherPid: 100,
|
||||
processGroupId: 100,
|
||||
reason: "process lineage contains an unowned or PID-reused process",
|
||||
});
|
||||
});
|
||||
it("does not publish lineage when any member fails ownership checks", async () => {
|
||||
const { adapter } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
101: { REA_PROCESS_RUN_ID: "other-run" },
|
||||
});
|
||||
await expect(
|
||||
observeOwnedProcessLineage(ownership, adapter),
|
||||
).resolves.toEqual({
|
||||
status: "unavailable",
|
||||
observedAt: expect.any(String),
|
||||
runId: "run-token",
|
||||
launcherPid: 100,
|
||||
processGroupId: 100,
|
||||
reason: "process lineage contains an unowned or PID-reused process",
|
||||
});
|
||||
});
|
||||
it("fails closed for stale metadata or an unrelated concurrent process", async () => {
|
||||
const { adapter, signalGroup } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
101: { REA_PROCESS_RUN_ID: "different-run" },
|
||||
});
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: false,
|
||||
reason: "process tree contains an unowned or PID-reused process",
|
||||
failures: [{ pid: 101, reason: "run-token-mismatch" }],
|
||||
});
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("checks every member and aggregates ownership read failures", async () => {
|
||||
const environment = vi.fn((pid: number) => {
|
||||
if (pid === 100)
|
||||
return Promise.reject(new Error("transient procfs read"));
|
||||
return Promise.resolve(
|
||||
pid === 101
|
||||
? { REA_PROCESS_RUN_ID: "different-run" }
|
||||
: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
);
|
||||
});
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
[100, 101, 102].map((pid) => ({
|
||||
pid,
|
||||
parentPid: pid === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment,
|
||||
signalGroup,
|
||||
};
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: false,
|
||||
reason: "process tree contains an unowned or PID-reused process",
|
||||
failures: [
|
||||
{ pid: 100, reason: "environment-unreadable" },
|
||||
{ pid: 101, reason: "run-token-mismatch" },
|
||||
],
|
||||
});
|
||||
expect(environment.mock.calls.map(([pid]) => pid)).toEqual([100, 101, 102]);
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("accepts a member that exits during ownership revalidation", async () => {
|
||||
const liveLauncher = {
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
};
|
||||
const listProcesses = vi
|
||||
.fn<ProcessOwnershipHost["listProcesses"]>()
|
||||
.mockResolvedValueOnce([liveLauncher])
|
||||
.mockResolvedValue([]);
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses,
|
||||
environment: () =>
|
||||
Promise.reject(new Error("process exited before environment read")),
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{
|
||||
cleaned: true,
|
||||
signaled: false,
|
||||
},
|
||||
);
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
observeOwnedProcessGroup,
|
||||
type ProcessOwnershipHost,
|
||||
} from "../../../src/process/ProcessOwnership.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
const host = (
|
||||
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
|
||||
): {
|
||||
readonly adapter: ProcessOwnershipHost;
|
||||
readonly signalGroup: ReturnType<typeof vi.fn>;
|
||||
} => {
|
||||
const signalGroup = vi.fn();
|
||||
return {
|
||||
adapter: {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
Object.keys(environments).map((pid) => ({
|
||||
pid: Number(pid),
|
||||
parentPid: Number(pid) === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
|
||||
signalGroup,
|
||||
},
|
||||
signalGroup,
|
||||
};
|
||||
};
|
||||
describe("owned process-group cleanup validation", () => {
|
||||
it("ignores exited zombie members during live ownership checks", async () => {
|
||||
const environment = vi.fn((pid: number) =>
|
||||
Promise.resolve(pid === 101 ? {} : { REA_PROCESS_RUN_ID: "run-token" }),
|
||||
);
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 100,
|
||||
state: "Z",
|
||||
command: "[node] <defunct>",
|
||||
},
|
||||
]),
|
||||
environment,
|
||||
signalGroup,
|
||||
};
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
});
|
||||
expect(environment.mock.calls).toEqual([[100], [100]]);
|
||||
expect(signalGroup).toHaveBeenCalledWith(100, "SIGKILL");
|
||||
});
|
||||
it("observes a zombie-only group as settled", async () => {
|
||||
const environment = vi.fn(() => Promise.resolve({}));
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "Z+",
|
||||
command: "[node] <defunct>",
|
||||
},
|
||||
]),
|
||||
environment,
|
||||
signalGroup: vi.fn(),
|
||||
};
|
||||
expect(await observeOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
state: "empty",
|
||||
});
|
||||
expect(environment).not.toHaveBeenCalled();
|
||||
});
|
||||
it("is idempotent when the owned group has already exited", async () => {
|
||||
const { adapter } = host({});
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: true,
|
||||
signaled: false,
|
||||
});
|
||||
});
|
||||
it("fails closed when the launcher command identity changes", async () => {
|
||||
const { adapter, signalGroup } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
});
|
||||
expect(
|
||||
await cleanupOwnedProcessGroup(
|
||||
{
|
||||
...ownership,
|
||||
expectedCommand: "/owned/hopper",
|
||||
expectedParentPid: 1,
|
||||
},
|
||||
adapter,
|
||||
),
|
||||
).toEqual({
|
||||
cleaned: false,
|
||||
reason:
|
||||
"owned launcher command identity did not match (observed=fixture; expected=/owned/hopper)",
|
||||
});
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("fails closed when the launcher parent identity changes", async () => {
|
||||
const { adapter, signalGroup } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
});
|
||||
expect(
|
||||
await cleanupOwnedProcessGroup(
|
||||
{ ...ownership, expectedCommand: "fixture", expectedParentPid: 999 },
|
||||
adapter,
|
||||
),
|
||||
).toEqual({
|
||||
cleaned: false,
|
||||
reason: "owned launcher parent identity did not match",
|
||||
});
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
cleanupWindowsProcessTree,
|
||||
type WindowsProcessTreeHost,
|
||||
} from "../../../src/process/ProcessOwnership.js";
|
||||
describe("Windows P0 process-tree cleanup", () => {
|
||||
it("reports whether taskkill signaled or found an exited tree", async () => {
|
||||
const terminated: WindowsProcessTreeHost = {
|
||||
terminateTree: () => Promise.resolve("terminated"),
|
||||
};
|
||||
const missing: WindowsProcessTreeHost = {
|
||||
terminateTree: () => Promise.resolve("missing"),
|
||||
};
|
||||
await expect(cleanupWindowsProcessTree(42, terminated)).resolves.toEqual({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
});
|
||||
await expect(cleanupWindowsProcessTree(42, missing)).resolves.toEqual({
|
||||
cleaned: true,
|
||||
signaled: false,
|
||||
});
|
||||
});
|
||||
it("keeps invalid identity and termination failures explicit", async () => {
|
||||
const failing: WindowsProcessTreeHost = {
|
||||
terminateTree: () => Promise.reject(new Error("taskkill failed")),
|
||||
};
|
||||
await expect(cleanupWindowsProcessTree(0, failing)).resolves.toEqual({
|
||||
cleaned: false,
|
||||
reason: "Windows process-tree PID is invalid",
|
||||
});
|
||||
await expect(cleanupWindowsProcessTree(42, failing)).resolves.toEqual({
|
||||
cleaned: false,
|
||||
reason:
|
||||
"Windows P0 process-tree termination failed; Job Object ownership is unavailable",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,365 @@
|
||||
import { getEventListeners } from "node:events";
|
||||
import { access, stat } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { PendingOperations } from "../../../src/process/PendingOperations.js";
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import { ProviderStartupDeadline } from "../../../src/process/ProviderDeadline.js";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
observeOwnedProcessLineage,
|
||||
} from "../../../src/process/ProcessOwnership.js";
|
||||
import {
|
||||
ProviderProcessSupervisor,
|
||||
spawnOwnedProviderProcess,
|
||||
type ProviderProcessDiagnostic,
|
||||
} from "../../../src/process/ProviderProcess.js";
|
||||
import {
|
||||
spawnProviderProcessFixture,
|
||||
stopProviderProcessFixture,
|
||||
waitForDetachedProviderChild,
|
||||
waitForProviderProcessReady,
|
||||
} from "../../fixtures/providerProcess.js";
|
||||
|
||||
const processFixturePath = fileURLToPath(
|
||||
new URL("../../fixtures/providerProcess.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
const waitForPidExit = async (
|
||||
pid: number,
|
||||
timeoutMs = 2_000,
|
||||
): Promise<void> => {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "ESRCH")
|
||||
return;
|
||||
throw cause;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
throw new Error(`Process ${String(pid)} did not exit within the test bound`);
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("provider process runtime and wait primitives", () => {
|
||||
it("allocates a private runtime root and removes it idempotently", async () => {
|
||||
const runtime = await PrivateRuntimeRoot.create({
|
||||
parent: tmpdir(),
|
||||
prefix: "rea-provider-test-",
|
||||
});
|
||||
expect((await stat(runtime.path)).mode & 0o777).toBe(0o700);
|
||||
|
||||
const first = runtime.close();
|
||||
const second = runtime.close();
|
||||
expect(second).toBe(first);
|
||||
await Promise.all([first, second]);
|
||||
await expect(access(runtime.path)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
});
|
||||
|
||||
it("clears the startup timer and external cancellation listener", async () => {
|
||||
vi.useFakeTimers();
|
||||
const controller = new AbortController();
|
||||
const deadline = new ProviderStartupDeadline(1_000, controller.signal);
|
||||
expect(getEventListeners(controller.signal, "abort")).toHaveLength(1);
|
||||
|
||||
const waiting = deadline.wait(1_000);
|
||||
controller.abort();
|
||||
await expect(waiting).resolves.toBe("aborted");
|
||||
expect(deadline.cancelled).toBe(true);
|
||||
expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
deadline.dispose();
|
||||
});
|
||||
|
||||
it("uses one absolute startup deadline across interval waits", async () => {
|
||||
vi.useFakeTimers();
|
||||
const deadline = new ProviderStartupDeadline(100);
|
||||
const waiting = deadline.wait(1_000);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
|
||||
await expect(waiting).resolves.toBe("aborted");
|
||||
expect(deadline.timedOut).toBe(true);
|
||||
expect(deadline.remainingMs()).toBe(0);
|
||||
deadline.dispose();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("does not reclassify an elapsed deadline as later cancellation", async () => {
|
||||
vi.useFakeTimers();
|
||||
const controller = new AbortController();
|
||||
const deadline = new ProviderStartupDeadline(50, controller.signal);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
controller.abort();
|
||||
|
||||
expect(deadline.signal.reason).toMatchObject({ name: "TimeoutError" });
|
||||
expect(deadline.timedOut).toBe(true);
|
||||
expect(deadline.cancelled).toBe(false);
|
||||
expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
deadline.dispose();
|
||||
});
|
||||
|
||||
it("releases pending request timers and abort listeners on every outcome", async () => {
|
||||
vi.useFakeTimers();
|
||||
const operations = new PendingOperations<number, string>();
|
||||
const controller = new AbortController();
|
||||
const cancelled = operations.wait(1, {
|
||||
timeoutMs: 1_000,
|
||||
signal: controller.signal,
|
||||
timeoutValue: () => "timeout",
|
||||
cancelledValue: () => "cancelled",
|
||||
});
|
||||
expect(getEventListeners(controller.signal, "abort")).toHaveLength(1);
|
||||
controller.abort();
|
||||
await expect(cancelled).resolves.toBe("cancelled");
|
||||
expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
|
||||
|
||||
const timedOut = operations.wait(2, {
|
||||
timeoutMs: 50,
|
||||
timeoutValue: () => "timeout",
|
||||
cancelledValue: () => "cancelled",
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
await expect(timedOut).resolves.toBe("timeout");
|
||||
|
||||
const failed = operations.wait(3, {
|
||||
timeoutMs: 1_000,
|
||||
timeoutValue: () => "timeout",
|
||||
cancelledValue: () => "cancelled",
|
||||
});
|
||||
operations.failAll((key) => `failed:${String(key)}`);
|
||||
await expect(failed).resolves.toBe("failed:3");
|
||||
expect(operations.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider process output and cleanup primitives", () => {
|
||||
it("captures exact byte totals while bounding retained stdout and stderr", async () => {
|
||||
const child = spawnProviderProcessFixture("burst", 4_096);
|
||||
const diagnostics: ProviderProcessDiagnostic[] = [];
|
||||
const supervisor = new ProviderProcessSupervisor(
|
||||
{ process: child, ownsProcessLifetime: true },
|
||||
{
|
||||
maxOutputBytesPerStream: 64,
|
||||
onDiagnostic: (event) => diagnostics.push(event),
|
||||
},
|
||||
);
|
||||
|
||||
await expect(supervisor.waitForExit(2_000)).resolves.toBe(true);
|
||||
const snapshot = supervisor.snapshot();
|
||||
expect(snapshot).toMatchObject({
|
||||
stdout: { bytes: 4_096, retainedBytes: 64, truncated: true },
|
||||
stderr: { bytes: 4_096, retainedBytes: 64, truncated: true },
|
||||
exitCode: 23,
|
||||
signal: null,
|
||||
});
|
||||
expect(snapshot.stdout.text).toBe("o".repeat(64));
|
||||
expect(snapshot.stderr.text).toBe("e".repeat(64));
|
||||
expect(diagnostics).toContainEqual(
|
||||
expect.objectContaining({ type: "exit", code: 23 }),
|
||||
);
|
||||
await expect(supervisor.stop()).resolves.toEqual({
|
||||
status: "already-exited",
|
||||
});
|
||||
});
|
||||
|
||||
it("shares double-stop and escalates a stubborn child from TERM to KILL", async () => {
|
||||
const child = spawnProviderProcessFixture("stubborn");
|
||||
const supervisor = new ProviderProcessSupervisor({
|
||||
process: child,
|
||||
ownsProcessLifetime: true,
|
||||
});
|
||||
await waitForProviderProcessReady(child);
|
||||
|
||||
const first = supervisor.stop({ terminationGraceMs: 20, killGraceMs: 500 });
|
||||
const second = supervisor.stop({
|
||||
terminationGraceMs: 20,
|
||||
killGraceMs: 500,
|
||||
});
|
||||
expect(second).toBe(first);
|
||||
await expect(first).resolves.toEqual({ status: "killed" });
|
||||
expect(child.signalCode).toBe("SIGKILL");
|
||||
expect(getEventListeners(child, "exit")).toHaveLength(0);
|
||||
expect(getEventListeners(child, "close")).toHaveLength(0);
|
||||
expect(getEventListeners(child, "error")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("honors verified group cleanup instead of direct process signaling", async () => {
|
||||
const child = spawnProviderProcessFixture("stubborn");
|
||||
await waitForProviderProcessReady(child);
|
||||
const cleanup = vi.fn(async () => {
|
||||
child.kill("SIGKILL");
|
||||
return { cleaned: true, signaled: true } as const;
|
||||
});
|
||||
const supervisor = new ProviderProcessSupervisor({
|
||||
process: child,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup,
|
||||
});
|
||||
|
||||
await expect(supervisor.stop({ killGraceMs: 500 })).resolves.toEqual({
|
||||
status: "verified-cleanup",
|
||||
});
|
||||
expect(cleanup).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("cleans an owned group even after its launcher leader has exited", async () => {
|
||||
const child = spawnProviderProcessFixture("exit", 0);
|
||||
const cleanup = vi.fn(
|
||||
async () => ({ cleaned: true, signaled: false }) as const,
|
||||
);
|
||||
const supervisor = new ProviderProcessSupervisor({
|
||||
process: child,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup,
|
||||
});
|
||||
await expect(supervisor.waitForExit(2_000)).resolves.toBe(true);
|
||||
|
||||
await expect(supervisor.stop()).resolves.toEqual({
|
||||
status: "verified-cleanup",
|
||||
});
|
||||
expect(cleanup).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("reports incomplete cleanup when a verified callback leaves the child alive", async () => {
|
||||
const child = spawnProviderProcessFixture("stubborn");
|
||||
await waitForProviderProcessReady(child);
|
||||
const cleanup = vi.fn(
|
||||
async () => ({ cleaned: true, signaled: false }) as const,
|
||||
);
|
||||
const supervisor = new ProviderProcessSupervisor({
|
||||
process: child,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup,
|
||||
});
|
||||
try {
|
||||
await expect(supervisor.stop({ killGraceMs: 20 })).resolves.toEqual({
|
||||
status: "incomplete",
|
||||
reason: "verified process-group cleanup did not stop the launcher",
|
||||
});
|
||||
expect(cleanup).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
await stopProviderProcessFixture(child);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider process spawning primitives", () => {
|
||||
it("spawns an owned process group with exact identity coordinates", async () => {
|
||||
const runId = "provider-process-run";
|
||||
const spawned = await spawnOwnedProviderProcess({
|
||||
command: process.execPath,
|
||||
arguments: [processFixturePath, "graceful"],
|
||||
runId,
|
||||
});
|
||||
try {
|
||||
expect(spawned.ownership).toMatchObject({
|
||||
runId,
|
||||
leaderPid: spawned.process.pid,
|
||||
processGroupId: spawned.process.pid,
|
||||
expectedCommand: process.execPath,
|
||||
expectedParentPid: process.pid,
|
||||
});
|
||||
expect(spawned.process.stdout).not.toBeNull();
|
||||
expect(spawned.process.stderr).not.toBeNull();
|
||||
} finally {
|
||||
await stopProviderProcessFixture(spawned.process);
|
||||
}
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"cleans a real descendant that starts a distinct process group",
|
||||
async () => {
|
||||
const spawned = await spawnOwnedProviderProcess({
|
||||
command: process.execPath,
|
||||
arguments: [processFixturePath, "detached-child"],
|
||||
runId: "provider-process-lineage-run",
|
||||
});
|
||||
let detachedChildPid: number | undefined;
|
||||
try {
|
||||
detachedChildPid = await waitForDetachedProviderChild(spawned.process);
|
||||
const observation = await observeOwnedProcessLineage(spawned.ownership);
|
||||
expect(observation).toEqual({
|
||||
status: "verified",
|
||||
observedAt: expect.stringMatching(
|
||||
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u,
|
||||
),
|
||||
lineage: {
|
||||
schemaVersion: 1,
|
||||
runId: "provider-process-lineage-run",
|
||||
launcherPid: spawned.process.pid,
|
||||
launcherParentPid: process.pid,
|
||||
processGroupId: spawned.process.pid,
|
||||
descendants: [
|
||||
{
|
||||
pid: detachedChildPid,
|
||||
parentPid: spawned.process.pid,
|
||||
processGroupId: detachedChildPid,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
cleanupOwnedProcessGroup(spawned.ownership),
|
||||
).resolves.toEqual({ cleaned: true, signaled: true });
|
||||
await Promise.all([
|
||||
waitForPidExit(spawned.ownership.leaderPid),
|
||||
waitForPidExit(detachedChildPid),
|
||||
]);
|
||||
} finally {
|
||||
await cleanupOwnedProcessGroup(spawned.ownership);
|
||||
if (detachedChildPid !== undefined)
|
||||
await cleanupOwnedProcessGroup({
|
||||
runId: spawned.ownership.runId,
|
||||
leaderPid: detachedChildPid,
|
||||
processGroupId: detachedChildPid,
|
||||
});
|
||||
await waitForPidExit(spawned.ownership.leaderPid);
|
||||
if (detachedChildPid !== undefined)
|
||||
await waitForPidExit(detachedChildPid);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("allows interpreter launchers to rely on parent and run-token identity", async () => {
|
||||
const spawned = await spawnOwnedProviderProcess({
|
||||
command: process.execPath,
|
||||
arguments: [processFixturePath, "graceful"],
|
||||
runId: "provider-process-interpreter-run",
|
||||
expectedCommand: null,
|
||||
});
|
||||
try {
|
||||
expect(spawned.ownership).toMatchObject({
|
||||
expectedParentPid: process.pid,
|
||||
runId: "provider-process-interpreter-run",
|
||||
});
|
||||
expect(spawned.ownership).not.toHaveProperty("expectedCommand");
|
||||
} finally {
|
||||
await stopProviderProcessFixture(spawned.process);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects deterministic spawn failures without producing a process", async () => {
|
||||
await expect(
|
||||
spawnOwnedProviderProcess({
|
||||
command: `${tmpdir()}/rea-provider-command-that-does-not-exist`,
|
||||
arguments: [],
|
||||
runId: "missing-provider",
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
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" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
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