test: overhaul deterministic suite architecture

This commit is contained in:
morluto
2026-07-29 22:00:38 +00:00
parent 7f2348619a
commit 513d9b1555
371 changed files with 30879 additions and 24389 deletions
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import { processCapturePermissionRequest } from "../../../src/application/ProcessCapturePermission.js";
import { parseProcessScenario } from "../../../src/domain/processCapture.js";
describe("process capture permission request", () => {
it("projects the complete adapter-neutral authority scope", () => {
const scenario = parseProcessScenario({
approved: true,
executable: "/bin/tool",
arguments: ["--probe"],
working_directory: "/workspace",
environment: { FIXTURE_TOKEN: "secret" },
inherit_environment: ["PATH"],
filesystem_roots: ["/workspace/output"],
network_access: "host",
events: [],
});
expect(processCapturePermissionRequest(scenario)).toEqual({
capability: "process_capture",
roots: ["/workspace", "/workspace/output"],
executables: ["/bin/tool"],
environment_names: ["FIXTURE_TOKEN", "PATH"],
network: "external",
mount: false,
operation_identity: "capture_process_scenario:/bin/tool",
});
});
});
@@ -0,0 +1,251 @@
import { describe, expect, it } from "vitest";
import {
runPairedProcessExperiment,
type ProcessCapturePort,
} from "../../../src/application/ProcessPairedExperiment.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
import { parseProcessCapture } from "../../../src/domain/processCapture.js";
import {
analyzeProcessRepeatability,
bindProcessScenario,
processPairedExperimentSchema,
} from "../../../src/domain/processPairedExperiment.js";
import { ok } from "../../../src/domain/result.js";
const experiment = () =>
processPairedExperimentSchema.parse({
approved: true,
shared_scenario: {
approved: true,
executable: "/bin/template",
arguments: ["shared"],
working_directory: "/tmp",
environment: { SHARED: "yes" },
},
authority: {
id: "authority",
executable: "/bin/authority",
environment: { SIDE: "authority" },
},
candidate: {
id: "candidate",
executable: "/bin/candidate",
arguments: ["candidate"],
environment: { SIDE: "candidate" },
},
repeat_count: 3,
freshness_policy: { max_capture_age_ms: 60_000 },
required_dimensions: [
"terminal",
"interaction",
"exit",
"filesystem",
"protocol",
"process",
"shim",
],
});
const policy = {
enabled: true,
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: ["SHARED", "SIDE"],
allowExternalNetwork: false,
};
describe("paired process experiments", () => {
it("binds only declared side inputs onto the shared observation contract", () => {
const parsed = experiment();
const authority = bindProcessScenario(
parsed.shared_scenario,
parsed.authority,
);
const candidate = bindProcessScenario(
parsed.shared_scenario,
parsed.candidate,
);
expect(authority).toMatchObject({
executable: "/bin/authority",
arguments: ["shared"],
environment: { SHARED: "yes", SIDE: "authority" },
});
expect(candidate).toMatchObject({
executable: "/bin/candidate",
arguments: ["candidate"],
environment: { SHARED: "yes", SIDE: "candidate" },
});
});
it("runs same-side comparisons first and compares stable sides", async () => {
const observedExecutables: string[] = [];
const capture = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const capturePort: ProcessCapturePort = {
capture: (scenario) => {
observedExecutables.push(scenario.executable);
return Promise.resolve(ok(structuredClone(capture)));
},
};
const result = await runPairedProcessExperiment(experiment(), policy, {
capturePort,
now: () => Date.parse("2026-01-01T00:00:01.000Z"),
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(observedExecutables).toEqual([
"/bin/authority",
"/bin/authority",
"/bin/authority",
"/bin/candidate",
"/bin/candidate",
"/bin/candidate",
]);
expect(result.value.authority_repeatability.stable).toBe(true);
expect(result.value.candidate_repeatability.stable).toBe(true);
expect(result.value.cross_side?.status).toBe("unchanged");
});
it("blocks cross-side claims when a candidate has a flaky exit", async () => {
const base = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
let candidateRun = 0;
const capturePort: ProcessCapturePort = {
capture: (scenario) => {
let capture = structuredClone(base);
if (scenario.executable === "/bin/candidate") {
candidateRun += 1;
if (candidateRun === 2)
capture = {
...capture,
exit: { code: 1, signal: null, reason: "exited" },
};
}
return Promise.resolve(ok(capture));
},
};
const result = await runPairedProcessExperiment(experiment(), policy, {
capturePort,
now: () => Date.parse("2026-01-01T00:00:01.000Z"),
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.candidate_repeatability).toMatchObject({
stable: false,
classification: "flaky_exit",
unstable_dimensions: ["exit"],
});
expect(result.value.cross_side).toBeNull();
expect(result.value.cross_side_blocked_reason).toMatch(/unstable/u);
});
});
describe("paired process experiment comparisons", () => {
it("distinguishes normalized timing variance from semantic output drift", () => {
const base = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const early = {
...base,
frames: [{ sequence: 0, at_ms: 10, data: "ready" }],
};
const late = {
...base,
frames: [{ sequence: 0, at_ms: 20, data: "ready" }],
};
expect(
analyzeProcessRepeatability([early, late], ["terminal"]),
).toMatchObject({
stable: false,
classification: "timing_variance",
unstable_dimensions: ["terminal"],
});
const changed = {
...base,
frames: [{ sequence: 0, at_ms: 20, data: "failed" }],
};
expect(
analyzeProcessRepeatability([early, changed], ["terminal"]),
).toMatchObject({ classification: "nondeterministic_output" });
});
it("stops before capture when the experiment is cancelled", async () => {
const controller = new AbortController();
controller.abort();
const capturePort: ProcessCapturePort = {
capture: () => {
throw new Error("capture must not start after cancellation");
},
};
const result = await runPairedProcessExperiment(experiment(), policy, {
capturePort,
signal: controller.signal,
});
expect(result).toMatchObject({
ok: false,
error: { _tag: "ProcessCaptureError", reason: "cancelled" },
});
});
it("blocks full cross-side output when only a subset was repeatable", async () => {
const capture = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const capturePort: ProcessCapturePort = {
capture: () => Promise.resolve(ok(structuredClone(capture))),
};
const subset = processPairedExperimentSchema.parse({
...experiment(),
required_dimensions: ["exit"],
});
const result = await runPairedProcessExperiment(subset, policy, {
capturePort,
});
expect(result).toMatchObject({
ok: true,
value: {
cross_side: null,
cross_side_blocked_reason: expect.stringMatching(/every returned/u),
},
});
});
});
describe("paired process experiment freshness", () => {
it("compares the newest stable captures under the freshness policy", async () => {
const base = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
let captureIndex = 0;
const capturePort: ProcessCapturePort = {
capture: () => {
const completedAt =
captureIndex === 0
? "2026-01-01T00:00:00.000Z"
: "2026-01-01T00:00:09.500Z";
captureIndex += 1;
return Promise.resolve(
ok({
...structuredClone(base),
manifest: {
...base.manifest,
started_at: completedAt,
completed_at: completedAt,
},
}),
);
},
};
const shortFreshness = processPairedExperimentSchema.parse({
...experiment(),
freshness_policy: { max_capture_age_ms: 1_000 },
});
const result = await runPairedProcessExperiment(shortFreshness, policy, {
capturePort,
now: () => Date.parse("2026-01-01T00:00:10.000Z"),
});
expect(result).toMatchObject({
ok: true,
value: { cross_side: { status: "unchanged" } },
});
});
});
@@ -0,0 +1,302 @@
import { describe, expect, it } from "vitest";
import {
ProcessReactiveCoordinator,
type ProcessReactiveTimerHost,
} from "../../../src/application/ProcessReactiveCoordinator.js";
import { executeProcessReactiveEffects } from "../../../src/application/ProcessReactiveEffects.js";
import { createProcessCaptureJournal } from "../../../src/application/ProcessCaptureJournal.js";
import { subscribeProcessReactiveObservations } from "../../../src/application/ProcessReactiveObservations.js";
import type {
FilesystemCheckpoint,
InteractionEvent,
TerminalFrame,
} from "../../../src/domain/processCapture.js";
import {
processReactiveScenarioSchema,
type ProcessReactiveScenario,
} from "../../../src/domain/processReactiveScenario.js";
const terminalTrigger = () => ({
kind: "terminal_text" as const,
view: "decoded" as const,
encoding: "utf8" as const,
literal: "Ready",
case_sensitive: true,
control_sequences: "include" as const,
occurrence: 1,
since: { kind: "scenario_start" as const },
consume: true,
});
const timerHost = () => {
const scheduled: Array<{
readonly callback: () => void;
readonly delayMs: number;
cancelled: boolean;
}> = [];
const host: ProcessReactiveTimerHost = {
schedule: (callback, delayMs) => {
const timer = { callback, delayMs, cancelled: false };
scheduled.push(timer);
return { cancel: () => (timer.cancelled = true) };
},
};
return { host, scheduled };
};
const twoStateScenario = (): ProcessReactiveScenario =>
processReactiveScenarioSchema.parse({
version: 1,
initial_state: "starting",
deadline_ms: 30000,
states: [
{
id: "starting",
max_visits: 1,
deadline_ms: 5000,
on: [
{
id: "send",
priority: 1,
max_uses: 1,
when: terminalTrigger(),
actions: [{ type: "send_input", data: "go", sensitive: false }],
target: { kind: "goto", state: "sent" },
},
],
},
{
id: "sent",
max_visits: 1,
deadline_ms: 5000,
on: [
{
id: "confirm",
priority: 1,
max_uses: 1,
when: {
kind: "event",
source: "interaction",
exact: { type: "input", data: "go", outcome: "dispatched" },
ignore_fields: [
"sequence",
"scheduled_at_ms",
"dispatched_at_ms",
],
since: { kind: "scenario_start" },
consume: true,
cardinality: { min: 1, max: 1 },
},
actions: [],
target: { kind: "finish", outcome: "passed" },
},
],
},
],
});
const createHarness = (scenario: ProcessReactiveScenario) => {
const journal = createProcessCaptureJournal();
const frames: TerminalFrame[] = [];
const interactions: InteractionEvent[] = [];
const checkpoints: FilesystemCheckpoint[] = [];
const terminalCalls: string[] = [];
const timers = timerHost();
let now = 100;
const effectHost = {
terminal: () => ({
write: (data: string) => terminalCalls.push(`write:${data}`),
resize: (columns: number, rows: number) =>
terminalCalls.push(`resize:${String(columns)}x${String(rows)}`),
closeInput: () => terminalCalls.push("close-input"),
kill: (signal: "SIGINT" | "SIGTERM" | "SIGKILL") =>
terminalCalls.push(`kill:${signal}`),
}),
renderer: {
resize: (columns: number, rows: number) =>
terminalCalls.push(`render:${String(columns)}x${String(rows)}`),
},
checkpoints: {
captureAndRead: async (name: string) => {
const index = checkpoints.length;
const checkpoint: FilesystemCheckpoint = {
name,
at_ms: now - 100,
files: [],
effects: [],
truncated: false,
};
checkpoints.push(checkpoint);
journal.record("filesystem_checkpoints", index);
return { index, checkpoint };
},
},
interactions,
journal,
startedAtMs: 100,
now: () => now,
};
const coordinator = new ProcessReactiveCoordinator({
scenario,
executor: {
execute: (actions, signal) =>
executeProcessReactiveEffects(effectHost, actions, signal),
},
timerHost: timers.host,
});
const unsubscribe = subscribeProcessReactiveObservations({
journal,
frames,
interactions,
checkpointAt: (index) => checkpoints[index],
processSampleAt: () => undefined,
protocolEventAt: () => undefined,
shimEventAt: () => undefined,
sink: coordinator,
});
return {
coordinator,
frames,
interactions,
checkpoints,
journal,
terminalCalls,
timers: timers.scheduled,
setNow: (value: number) => (now = value),
unsubscribe,
};
};
describe("process reactive coordinator ordering", () => {
it("commits terminal effects before evaluating their journal observations", async () => {
const harness = createHarness(twoStateScenario());
harness.frames.push({ sequence: 0, at_ms: 0, data: "Ready" });
harness.journal.record("frames", 0);
await harness.coordinator.drain();
expect(harness.coordinator.snapshot).toMatchObject({
status: "finished",
outcome: "passed",
active_state: "sent",
});
expect(
harness.coordinator.snapshot.transitions.map(
({ transition_id }) => transition_id,
),
).toEqual(["send", "confirm"]);
expect(harness.terminalCalls).toEqual(["write:go"]);
expect(harness.journal.entries).toEqual([
{ collection: "frames", index: 0, capture_order: 0 },
{ collection: "interaction_events", index: 0, capture_order: 1 },
]);
expect(harness.interactions[0]).toMatchObject({
type: "input",
data: "go",
outcome: "dispatched",
});
harness.unsubscribe();
await harness.coordinator.close();
});
it("executes input, resize, root signal, and checkpoint in journal order", async () => {
const scenario = processReactiveScenarioSchema.parse({
version: 1,
initial_state: "ready",
deadline_ms: 30000,
states: [
{
id: "ready",
max_visits: 1,
deadline_ms: 5000,
on: [
{
id: "act",
priority: 1,
max_uses: 1,
when: terminalTrigger(),
actions: [
{ type: "send_input", data: "secret", sensitive: true },
{ type: "resize", columns: 100, rows: 40 },
{ type: "close_stdin" },
{
type: "send_signal",
target: { kind: "root" },
signal: "SIGINT",
},
{ type: "checkpoint", name: "stopped" },
],
target: { kind: "finish", outcome: "passed" },
},
],
},
],
});
const harness = createHarness(scenario);
harness.setNow(125);
harness.frames.push({ sequence: 0, at_ms: 20, data: "Ready" });
harness.journal.record("frames", 0);
await harness.coordinator.drain();
expect(harness.terminalCalls).toEqual([
"write:secret",
"resize:100x40",
"render:100x40",
"close-input",
"kill:SIGINT",
]);
expect(harness.interactions.map(({ data }) => data)).toEqual([
"<redacted-input:6-bytes>",
"100x40",
"",
"SIGINT",
]);
expect(harness.checkpoints).toHaveLength(1);
expect(
harness.coordinator.snapshot.transitions[0]?.action_event_ids,
).toEqual([
"obs.interaction_events.0",
"obs.interaction_events.1",
"obs.interaction_events.2",
"obs.interaction_events.3",
"obs.filesystem_checkpoints.0",
]);
await harness.coordinator.close();
});
it("ignores a stale state timer after a transition", async () => {
const base = twoStateScenario();
const first = base.states[0];
const second = base.states[1];
if (first === undefined || second === undefined)
throw new Error("two-state fixture is incomplete");
const scenario = processReactiveScenarioSchema.parse({
...base,
states: [
{
...first,
on: first.on.map((transition) => ({
...transition,
actions: [],
})),
},
{
...second,
on: second.on.map((transition) => ({
...transition,
when: { ...terminalTrigger(), literal: "Later" },
})),
},
],
});
const harness = createHarness(scenario);
const oldStateTimer = harness.timers[1];
expect(oldStateTimer?.delayMs).toBe(5000);
harness.frames.push({ sequence: 0, at_ms: 0, data: "Ready" });
harness.journal.record("frames", 0);
await harness.coordinator.drain();
expect(oldStateTimer?.cancelled).toBe(true);
oldStateTimer?.callback();
await harness.coordinator.drain();
expect(harness.coordinator.snapshot).toMatchObject({
status: "running",
active_state: "sent",
outcome: null,
});
const currentStateTimer = harness.timers[2];
currentStateTimer?.callback();
await harness.coordinator.drain();
expect(harness.coordinator.snapshot.outcome).toBe("predicate_timeout");
await harness.coordinator.close();
});
});
@@ -0,0 +1,229 @@
import { describe, expect, it } from "vitest";
import {
ProcessReactiveCoordinator,
type ProcessReactiveTimerHost,
} from "../../../src/application/ProcessReactiveCoordinator.js";
import { unsupportedProcessReactiveFeatures } from "../../../src/application/ProcessReactiveEffects.js";
import { createProcessObservation } from "../../../src/domain/processObservation.js";
import type { ProcessReactiveEffectResult } from "../../../src/domain/processReactiveRuntime.js";
import {
processReactiveScenarioSchema,
type ProcessReactiveScenario,
} from "../../../src/domain/processReactiveScenario.js";
const terminalTrigger = () => ({
kind: "terminal_text" as const,
view: "decoded" as const,
encoding: "utf8" as const,
literal: "Ready",
case_sensitive: true,
control_sequences: "include" as const,
occurrence: 1,
since: { kind: "scenario_start" as const },
consume: true,
});
const timerHost = () => {
const scheduled: Array<{
readonly callback: () => void;
readonly delayMs: number;
cancelled: boolean;
}> = [];
const host: ProcessReactiveTimerHost = {
schedule: (callback, delayMs) => {
const timer = { callback, delayMs, cancelled: false };
scheduled.push(timer);
return { cancel: () => (timer.cancelled = true) };
},
};
return { host, scheduled };
};
const twoStateScenario = (): ProcessReactiveScenario =>
processReactiveScenarioSchema.parse({
version: 1,
initial_state: "starting",
deadline_ms: 30000,
states: [
{
id: "starting",
max_visits: 1,
deadline_ms: 5000,
on: [
{
id: "send",
priority: 1,
max_uses: 1,
when: terminalTrigger(),
actions: [{ type: "send_input", data: "go", sensitive: false }],
target: { kind: "goto", state: "sent" },
},
],
},
{
id: "sent",
max_visits: 1,
deadline_ms: 5000,
on: [
{
id: "confirm",
priority: 1,
max_uses: 1,
when: {
kind: "event",
source: "interaction",
exact: { type: "input", data: "go", outcome: "dispatched" },
ignore_fields: [
"sequence",
"scheduled_at_ms",
"dispatched_at_ms",
],
since: { kind: "scenario_start" },
consume: true,
cardinality: { min: 1, max: 1 },
},
actions: [],
target: { kind: "finish", outcome: "passed" },
},
],
},
],
});
describe("process reactive coordinator failures", () => {
it("preflights signal selectors the host cannot execute", () => {
const input = twoStateScenario();
const first = input.states[0];
const second = input.states[1];
const transition = first?.on[0];
if (first === undefined || second === undefined || transition === undefined)
throw new Error("two-state fixture is incomplete");
const scenario = processReactiveScenarioSchema.parse({
...input,
states: [
{
...first,
on: [
{
...transition,
actions: [
{
type: "send_signal",
target: { kind: "process_group" },
signal: "SIGTERM",
},
],
},
],
},
second,
],
});
expect(unsupportedProcessReactiveFeatures(scenario)).toEqual([
"send:target:process_group",
]);
});
it("orders delayed effect observations before later producer records", async () => {
const timers = timerHost();
let executions = 0;
let resolveEffects:
| ((results: readonly ProcessReactiveEffectResult[]) => void)
| undefined;
const effects = new Promise<readonly ProcessReactiveEffectResult[]>(
(resolve) => (resolveEffects = resolve),
);
const coordinator = new ProcessReactiveCoordinator({
scenario: twoStateScenario(),
executor: {
execute: () => {
executions += 1;
return executions === 1 ? effects : Promise.resolve([]);
},
},
timerHost: timers.host,
});
coordinator.enqueue({
kind: "observation",
observation: createProcessObservation({
source: "terminal_raw",
source_sequence: 0,
captured_at_ms: 0,
subject_id: null,
location: { collection: "frames", index: 0, capture_order: 0 },
payload: { sequence: 0, at_ms: 0, data: "Ready" },
}),
});
await Promise.resolve();
coordinator.enqueue({
kind: "observation",
observation: createProcessObservation({
source: "terminal_raw",
source_sequence: 1,
captured_at_ms: 2,
subject_id: null,
location: { collection: "frames", index: 1, capture_order: 2 },
payload: { sequence: 1, at_ms: 2, data: "later" },
}),
});
if (resolveEffects === undefined)
throw new Error("effect executor did not start");
resolveEffects([
{
status: "succeeded",
observation: createProcessObservation({
source: "interaction",
source_sequence: 0,
captured_at_ms: 1,
subject_id: null,
location: {
collection: "interaction_events",
index: 0,
capture_order: 1,
},
payload: {
sequence: 0,
scheduled_at_ms: 1,
dispatched_at_ms: 1,
type: "input",
data: "go",
outcome: "dispatched",
},
}),
},
]);
await coordinator.drain();
expect(coordinator.snapshot).toMatchObject({
status: "finished",
outcome: "passed",
});
expect(
coordinator.snapshot.transitions.map(
({ transition_id }) => transition_id,
),
).toEqual(["send", "confirm"]);
await coordinator.close();
});
it("cancels timers and rejects later work after an executor failure", async () => {
const timers = timerHost();
let calls = 0;
const coordinator = new ProcessReactiveCoordinator({
scenario: twoStateScenario(),
executor: {
execute: () => {
calls += 1;
throw new Error("executor failed");
},
},
timerHost: timers.host,
});
const ready = createProcessObservation({
source: "terminal_raw",
source_sequence: 0,
captured_at_ms: 0,
subject_id: null,
location: { collection: "frames", index: 0, capture_order: 0 },
payload: { sequence: 0, at_ms: 0, data: "Ready" },
});
coordinator.enqueue({ kind: "observation", observation: ready });
await expect(coordinator.drain()).rejects.toThrow("executor failed");
coordinator.enqueue({ kind: "observation", observation: ready });
expect(calls).toBe(1);
expect(timers.scheduled.every(({ cancelled }) => cancelled)).toBe(true);
});
});
@@ -0,0 +1,131 @@
import { describe, expect, it } from "vitest";
import {
ProcessReactiveCoordinator,
type ProcessReactiveTimerHost,
} from "../../../src/application/ProcessReactiveCoordinator.js";
import { createProcessObservation } from "../../../src/domain/processObservation.js";
import {
processReactiveScenarioSchema,
type ProcessReactiveScenario,
} from "../../../src/domain/processReactiveScenario.js";
const terminalTrigger = () => ({
kind: "terminal_text" as const,
view: "decoded" as const,
encoding: "utf8" as const,
literal: "Ready",
case_sensitive: true,
control_sequences: "include" as const,
occurrence: 1,
since: { kind: "scenario_start" as const },
consume: true,
});
const timerHost = () => {
const scheduled: Array<{
readonly callback: () => void;
readonly delayMs: number;
cancelled: boolean;
}> = [];
const host: ProcessReactiveTimerHost = {
schedule: (callback, delayMs) => {
const timer = { callback, delayMs, cancelled: false };
scheduled.push(timer);
return { cancel: () => (timer.cancelled = true) };
},
};
return { host, scheduled };
};
const twoStateScenario = (): ProcessReactiveScenario =>
processReactiveScenarioSchema.parse({
version: 1,
initial_state: "starting",
deadline_ms: 30000,
states: [
{
id: "starting",
max_visits: 1,
deadline_ms: 5000,
on: [
{
id: "send",
priority: 1,
max_uses: 1,
when: terminalTrigger(),
actions: [{ type: "send_input", data: "go", sensitive: false }],
target: { kind: "goto", state: "sent" },
},
],
},
{
id: "sent",
max_visits: 1,
deadline_ms: 5000,
on: [
{
id: "confirm",
priority: 1,
max_uses: 1,
when: {
kind: "event",
source: "interaction",
exact: { type: "input", data: "go", outcome: "dispatched" },
ignore_fields: [
"sequence",
"scheduled_at_ms",
"dispatched_at_ms",
],
since: { kind: "scenario_start" },
consume: true,
cardinality: { min: 1, max: 1 },
},
actions: [],
target: { kind: "finish", outcome: "passed" },
},
],
},
],
});
describe("process reactive coordinator failures", () => {
it("aborts an in-flight effect before committing a state deadline", async () => {
const timers = timerHost();
let effectAborted = false;
const coordinator = new ProcessReactiveCoordinator({
scenario: twoStateScenario(),
executor: {
execute: (_actions, signal) =>
new Promise((resolve) => {
signal.addEventListener(
"abort",
() => {
effectAborted = true;
resolve([]);
},
{ once: true },
);
}),
},
timerHost: timers.host,
});
coordinator.enqueue({
kind: "observation",
observation: createProcessObservation({
source: "terminal_raw",
source_sequence: 0,
captured_at_ms: 0,
subject_id: null,
location: { collection: "frames", index: 0, capture_order: 0 },
payload: { sequence: 0, at_ms: 0, data: "Ready" },
}),
});
await Promise.resolve();
timers.scheduled[1]?.callback();
await coordinator.drain();
expect(effectAborted).toBe(true);
expect(coordinator.snapshot).toMatchObject({
status: "finished",
outcome: "predicate_timeout",
active_state: "starting",
transitions: [],
});
await coordinator.close();
});
});
@@ -0,0 +1,234 @@
import { describe, expect, it } from "vitest";
import {
createProcessObservation,
type ProcessObservationSource,
} from "../../../src/domain/processObservation.js";
import {
commitProcessReactiveProposal,
createProcessReactiveSnapshot,
reduceProcessReactiveScenario,
} from "../../../src/domain/processReactiveRuntime.js";
import {
processReactiveScenarioSchema,
type ProcessReactiveAction,
type ProcessReactiveScenario,
} from "../../../src/domain/processReactiveScenario.js";
const terminalTrigger = (literal = "Ready") => ({
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,
});
const scenarioWith = (
transitions: readonly unknown[],
): ProcessReactiveScenario =>
processReactiveScenarioSchema.parse({
version: 1,
initial_state: "starting",
deadline_ms: 30000,
states: [
{
id: "starting",
max_visits: 4,
deadline_ms: 5000,
on: transitions,
},
],
});
const finish = (
id: string,
when: unknown,
priority = 100,
actions: readonly unknown[] = [],
) => ({
id,
priority,
max_uses: 4,
when,
actions,
target: { kind: "finish", outcome: "passed" },
});
const collectionFor = (source: ProcessObservationSource) => {
switch (source) {
case "terminal_raw":
return "frames" as const;
case "terminal_rendered":
return "rendered_frames" as const;
case "process":
return "process_samples" as const;
case "filesystem":
return "filesystem_checkpoints" as const;
case "shim":
return "shim_events" as const;
case "http":
case "websocket":
return "protocol_events" as const;
case "replay_transition":
return "replay_transitions" as const;
case "interaction":
return "interaction_events" as const;
case "lifecycle":
return "lifecycle" as const;
}
};
const observation = (
source: ProcessObservationSource,
order: number,
payload: unknown,
) =>
createProcessObservation({
source,
source_sequence: order,
captured_at_ms: order,
subject_id: null,
location: {
collection: collectionFor(source),
index: order,
capture_order: order,
},
payload,
});
const succeededEffect = (action: ProcessReactiveAction, order: number) => ({
status: "succeeded" as const,
observation:
action.type === "checkpoint"
? observation("filesystem", order, { name: action.name })
: observation("interaction", order, {
type:
action.type === "send_input"
? "input"
: action.type === "resize"
? "resize"
: action.type === "close_stdin"
? "stdin_close"
: "signal",
data:
action.type === "send_input"
? action.sensitive
? `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`
: action.data
: action.type === "resize"
? `${String(action.columns)}x${String(action.rows)}`
: action.type === "close_stdin"
? ""
: action.signal,
outcome: "dispatched",
}),
});
const offer = (
scenario: ProcessReactiveScenario,
snapshot: ReturnType<typeof createProcessReactiveSnapshot>,
value: ReturnType<typeof observation>,
) => {
const proposed = reduceProcessReactiveScenario(scenario, snapshot, {
kind: "observation",
observation: value,
});
return proposed.kind === "proposal"
? commitProcessReactiveProposal(
scenario,
proposed,
proposed.effects.map((effect, index) => ({
...succeededEffect(
effect,
(proposed.snapshot.observations.at(-1)?.capture_order ?? -1) +
index +
1,
),
})),
)
: proposed;
};
describe("process reactive runtime lifecycle", () => {
it("matches decoded terminal text across PTY chunks and emits declarative effects", () => {
const scenario = scenarioWith([
finish("ready", terminalTrigger(), 100, [
{ type: "send_signal", target: { kind: "root" }, signal: "SIGINT" },
{ type: "checkpoint", name: "ready" },
]),
]);
const first = offer(
scenario,
createProcessReactiveSnapshot(scenario),
observation("terminal_raw", 0, {
sequence: 0,
at_ms: 0,
data: "Re",
}),
);
expect(first.kind).toBe("waiting");
const second = offer(
scenario,
first.snapshot,
observation("terminal_raw", 1, {
sequence: 1,
at_ms: 1,
data: "ady\n",
}),
);
expect(second.kind).toBe("transition");
if (second.kind !== "transition") return;
expect(second.record).toEqual({
sequence: 0,
transition_id: "ready",
state_before: "starting",
state_after: null,
outcome: "passed",
trigger_event_ids: ["obs.frames.0", "obs.frames.1"],
action_event_ids: [
"obs.interaction_events.2",
"obs.filesystem_checkpoints.3",
],
action_types: ["send_signal", "checkpoint"],
});
});
it("treats redaction-shaped live input as ordinary sensitive data", () => {
const scenario = scenarioWith([
finish("ready", terminalTrigger(), 100, [
{
type: "send_input",
data: "<redacted-input:1-bytes>",
sensitive: true,
},
]),
]);
const decision = offer(
scenario,
createProcessReactiveSnapshot(scenario),
observation("terminal_raw", 0, { data: "Ready" }),
);
expect(decision).toMatchObject({
kind: "transition",
record: { outcome: "passed" },
});
});
it("reports only the minimal terminal chunk span containing the occurrence", () => {
const scenario = scenarioWith([finish("ready", terminalTrigger())]);
let snapshot = createProcessReactiveSnapshot(scenario);
for (const [order, data] of ["unrelated\n", "Re"].entries()) {
const decision = offer(
scenario,
snapshot,
observation("terminal_raw", order, { data }),
);
expect(decision.kind).toBe("waiting");
snapshot = decision.snapshot;
}
const matched = offer(
scenario,
snapshot,
observation("terminal_raw", 2, { data: "ady" }),
);
expect(matched.kind).toBe("transition");
if (matched.kind === "transition")
expect(matched.record.trigger_event_ids).toEqual([
"obs.frames.1",
"obs.frames.2",
]);
});
});
@@ -0,0 +1,250 @@
import { describe, expect, it } from "vitest";
import {
createProcessObservation,
type ProcessObservationSource,
} from "../../../src/domain/processObservation.js";
import {
commitProcessReactiveProposal,
createProcessReactiveSnapshot,
reduceProcessReactiveScenario,
} from "../../../src/domain/processReactiveRuntime.js";
import {
processReactiveScenarioSchema,
type ProcessReactiveAction,
type ProcessReactiveScenario,
} from "../../../src/domain/processReactiveScenario.js";
const terminalTrigger = (literal = "Ready") => ({
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,
});
const scenarioWith = (
transitions: readonly unknown[],
): ProcessReactiveScenario =>
processReactiveScenarioSchema.parse({
version: 1,
initial_state: "starting",
deadline_ms: 30000,
states: [
{
id: "starting",
max_visits: 4,
deadline_ms: 5000,
on: transitions,
},
],
});
const finish = (
id: string,
when: unknown,
priority = 100,
actions: readonly unknown[] = [],
) => ({
id,
priority,
max_uses: 4,
when,
actions,
target: { kind: "finish", outcome: "passed" },
});
const collectionFor = (source: ProcessObservationSource) => {
switch (source) {
case "terminal_raw":
return "frames" as const;
case "terminal_rendered":
return "rendered_frames" as const;
case "process":
return "process_samples" as const;
case "filesystem":
return "filesystem_checkpoints" as const;
case "shim":
return "shim_events" as const;
case "http":
case "websocket":
return "protocol_events" as const;
case "replay_transition":
return "replay_transitions" as const;
case "interaction":
return "interaction_events" as const;
case "lifecycle":
return "lifecycle" as const;
}
};
const observation = (
source: ProcessObservationSource,
order: number,
payload: unknown,
) =>
createProcessObservation({
source,
source_sequence: order,
captured_at_ms: order,
subject_id: null,
location: {
collection: collectionFor(source),
index: order,
capture_order: order,
},
payload,
});
const succeededEffect = (action: ProcessReactiveAction, order: number) => ({
status: "succeeded" as const,
observation:
action.type === "checkpoint"
? observation("filesystem", order, { name: action.name })
: observation("interaction", order, {
type:
action.type === "send_input"
? "input"
: action.type === "resize"
? "resize"
: action.type === "close_stdin"
? "stdin_close"
: "signal",
data:
action.type === "send_input"
? action.sensitive
? `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`
: action.data
: action.type === "resize"
? `${String(action.columns)}x${String(action.rows)}`
: action.type === "close_stdin"
? ""
: action.signal,
outcome: "dispatched",
}),
});
describe("process reactive runtime lifecycle", () => {
it("does not commit state, checkpoints, consumption, or history before effects succeed", () => {
const scenario = scenarioWith([
finish("ready", { ...terminalTrigger(), consume: true }, 100, [
{ type: "checkpoint", name: "ready" },
{ type: "send_signal", target: { kind: "root" }, signal: "SIGINT" },
]),
]);
const proposed = reduceProcessReactiveScenario(
scenario,
createProcessReactiveSnapshot(scenario),
{
kind: "observation",
observation: observation("terminal_raw", 0, { data: "Ready" }),
},
);
expect(proposed.kind).toBe("proposal");
if (proposed.kind !== "proposal") return;
expect(proposed.snapshot).toMatchObject({
status: "running",
checkpoints: [],
consumed_event_ids: [],
transitions: [],
});
const rejected = commitProcessReactiveProposal(scenario, proposed, [
{
status: "succeeded",
observation: observation("filesystem", 1, { name: "ready" }),
},
{ status: "rejected" },
]);
expect(rejected).toMatchObject({
kind: "finished",
outcome: "action_rejected",
snapshot: {
checkpoints: [],
consumed_event_ids: [],
transitions: [],
},
});
expect(
commitProcessReactiveProposal(scenario, proposed, [
{ status: "target_lost" },
{
status: "succeeded",
observation: observation("interaction", 2, {
type: "signal",
data: "SIGINT",
outcome: "dispatched",
}),
},
]),
).toMatchObject({ kind: "finished", outcome: "target_lost" });
const committed = commitProcessReactiveProposal(scenario, proposed, [
{
status: "succeeded",
observation: observation("filesystem", 1, { name: "ready" }),
},
{
status: "succeeded",
observation: observation("interaction", 2, {
type: "signal",
data: "SIGINT",
outcome: "dispatched",
}),
},
]);
expect(committed.snapshot).toMatchObject({
checkpoints: [
{
name: "ready",
event_id: "obs.filesystem_checkpoints.1",
capture_order: 1,
},
],
});
expect(
commitProcessReactiveProposal(scenario, proposed, [
{
status: "succeeded",
observation: observation("filesystem", 1, { name: "other" }),
},
{
status: "succeeded",
observation: observation("interaction", 2, {
type: "signal",
data: "SIGINT",
outcome: "dispatched",
}),
},
]),
).toMatchObject({ kind: "finished", outcome: "action_rejected" });
const changedScenario = scenarioWith([
finish("ready", { ...terminalTrigger(), consume: true }, 100, [
{ type: "checkpoint", name: "changed" },
{ type: "send_signal", target: { kind: "root" }, signal: "SIGINT" },
]),
]);
expect(
commitProcessReactiveProposal(changedScenario, proposed, [
succeededEffect({ type: "checkpoint", name: "ready" }, 1),
succeededEffect(
{
type: "send_signal",
target: { kind: "root" },
signal: "SIGINT",
},
2,
),
]),
).toMatchObject({ kind: "finished", outcome: "target_lost" });
expect(
commitProcessReactiveProposal(scenario, proposed, [
{
status: "succeeded",
observation: observation("filesystem", 1, { name: "ready" }),
},
{
status: "succeeded",
observation: {
...observation("filesystem", 2, { name: "ready" }),
event_id: "obs.filesystem_checkpoints.1",
},
},
]),
).toMatchObject({ kind: "finished", outcome: "action_rejected" });
});
});
@@ -0,0 +1,226 @@
import { describe, expect, it } from "vitest";
import {
createProcessObservation,
type ProcessObservationSource,
} from "../../../src/domain/processObservation.js";
import {
commitProcessReactiveProposal,
createProcessReactiveSnapshot,
reduceProcessReactiveScenario,
} from "../../../src/domain/processReactiveRuntime.js";
import {
PROCESS_REACTIVE_LIMITS,
processReactiveScenarioSchema,
type ProcessReactiveAction,
type ProcessReactiveScenario,
} from "../../../src/domain/processReactiveScenario.js";
const terminalTrigger = (literal = "Ready") => ({
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,
});
const scenarioWith = (
transitions: readonly unknown[],
): ProcessReactiveScenario =>
processReactiveScenarioSchema.parse({
version: 1,
initial_state: "starting",
deadline_ms: 30_000,
states: [
{
id: "starting",
max_visits: 4,
deadline_ms: 5_000,
on: transitions,
},
],
});
const finish = (
id: string,
when: unknown,
priority = 100,
actions: readonly unknown[] = [],
) => ({
id,
priority,
max_uses: 4,
when,
actions,
target: { kind: "finish", outcome: "passed" },
});
const collectionFor = (source: ProcessObservationSource) => {
switch (source) {
case "terminal_raw":
return "frames" as const;
case "terminal_rendered":
return "rendered_frames" as const;
case "process":
return "process_samples" as const;
case "filesystem":
return "filesystem_checkpoints" as const;
case "shim":
return "shim_events" as const;
case "http":
case "websocket":
return "protocol_events" as const;
case "replay_transition":
return "replay_transitions" as const;
case "interaction":
return "interaction_events" as const;
case "lifecycle":
return "lifecycle" as const;
}
};
const observation = (
source: ProcessObservationSource,
order: number,
payload: unknown,
) =>
createProcessObservation({
source,
source_sequence: order,
captured_at_ms: order,
subject_id: null,
location: {
collection: collectionFor(source),
index: order,
capture_order: order,
},
payload,
});
const succeededEffect = (action: ProcessReactiveAction, order: number) => ({
status: "succeeded" as const,
observation:
action.type === "checkpoint"
? observation("filesystem", order, { name: action.name })
: observation("interaction", order, {
type:
action.type === "send_input"
? "input"
: action.type === "resize"
? "resize"
: action.type === "close_stdin"
? "stdin_close"
: "signal",
data:
action.type === "send_input"
? action.sensitive
? `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`
: action.data
: action.type === "resize"
? `${String(action.columns)}x${String(action.rows)}`
: action.type === "close_stdin"
? ""
: action.signal,
outcome: "dispatched",
}),
});
const offer = (
scenario: ProcessReactiveScenario,
snapshot: ReturnType<typeof createProcessReactiveSnapshot>,
value: ReturnType<typeof observation>,
) => {
const proposed = reduceProcessReactiveScenario(scenario, snapshot, {
kind: "observation",
observation: value,
});
return proposed.kind === "proposal"
? commitProcessReactiveProposal(
scenario,
proposed,
proposed.effects.map((effect, index) => ({
...succeededEffect(
effect,
(proposed.snapshot.observations.at(-1)?.capture_order ?? -1) +
index +
1,
),
})),
)
: proposed;
};
describe("process reactive runtime lifecycle", () => {
it("preserves overflow when no any branch matches", () => {
const scenario = scenarioWith([
finish("bounded_any", {
kind: "any",
triggers: [
terminalTrigger("never"),
{
kind: "event",
source: "shim",
exact: { name: "also-never" },
ignore_fields: [],
since: { kind: "scenario_start" },
consume: false,
cardinality: { min: 1, max: 1 },
},
],
}),
]);
const decision = reduceProcessReactiveScenario(
scenario,
createProcessReactiveSnapshot(scenario),
{
kind: "observation",
observation: observation("terminal_raw", 0, {
data: "x".repeat(PROCESS_REACTIVE_LIMITS.evaluationWork + 1),
}),
},
);
expect(decision).toMatchObject({
kind: "finished",
outcome: "capture_incomplete",
});
});
it("fails closed at the deterministic per-reduction work budget", () => {
const transitions = Array.from(
{ length: PROCESS_REACTIVE_LIMITS.predicates },
(_, index) =>
finish(`event_${String(index)}`, {
kind: "event",
source: "shim",
exact: { name: `expected_${String(index)}` },
ignore_fields: ["sequence"],
since: { kind: "scenario_start" },
consume: false,
cardinality: { min: 1, max: 1 },
}),
);
const scenario = scenarioWith(transitions);
const retained = Array.from({ length: 128 }, (_, order) =>
observation("shim", order, { name: "other", sequence: order }),
);
const snapshot = {
...createProcessReactiveSnapshot(scenario),
observations: retained,
};
const decision = offer(
scenario,
snapshot,
observation("shim", retained.length, {
name: "other",
sequence: retained.length,
}),
);
expect(decision).toMatchObject({
kind: "finished",
outcome: "capture_incomplete",
});
});
});
@@ -0,0 +1,271 @@
import { describe, expect, it } from "vitest";
import {
createProcessObservation,
type ProcessObservationSource,
} from "../../../src/domain/processObservation.js";
import {
commitProcessReactiveProposal,
createProcessReactiveSnapshot,
reduceProcessReactiveScenario,
} from "../../../src/domain/processReactiveRuntime.js";
import {
processReactiveScenarioSchema,
type ProcessReactiveAction,
type ProcessReactiveScenario,
} from "../../../src/domain/processReactiveScenario.js";
const terminalTrigger = (literal = "Ready") => ({
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,
});
const scenarioWith = (
transitions: readonly unknown[],
): ProcessReactiveScenario =>
processReactiveScenarioSchema.parse({
version: 1,
initial_state: "starting",
deadline_ms: 30000,
states: [
{
id: "starting",
max_visits: 4,
deadline_ms: 5000,
on: transitions,
},
],
});
const finish = (
id: string,
when: unknown,
priority = 100,
actions: readonly unknown[] = [],
) => ({
id,
priority,
max_uses: 4,
when,
actions,
target: { kind: "finish", outcome: "passed" },
});
const collectionFor = (source: ProcessObservationSource) => {
switch (source) {
case "terminal_raw":
return "frames" as const;
case "terminal_rendered":
return "rendered_frames" as const;
case "process":
return "process_samples" as const;
case "filesystem":
return "filesystem_checkpoints" as const;
case "shim":
return "shim_events" as const;
case "http":
case "websocket":
return "protocol_events" as const;
case "replay_transition":
return "replay_transitions" as const;
case "interaction":
return "interaction_events" as const;
case "lifecycle":
return "lifecycle" as const;
}
};
const observation = (
source: ProcessObservationSource,
order: number,
payload: unknown,
) =>
createProcessObservation({
source,
source_sequence: order,
captured_at_ms: order,
subject_id: null,
location: {
collection: collectionFor(source),
index: order,
capture_order: order,
},
payload,
});
const succeededEffect = (action: ProcessReactiveAction, order: number) => ({
status: "succeeded" as const,
observation:
action.type === "checkpoint"
? observation("filesystem", order, { name: action.name })
: observation("interaction", order, {
type:
action.type === "send_input"
? "input"
: action.type === "resize"
? "resize"
: action.type === "close_stdin"
? "stdin_close"
: "signal",
data:
action.type === "send_input"
? action.sensitive
? `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`
: action.data
: action.type === "resize"
? `${String(action.columns)}x${String(action.rows)}`
: action.type === "close_stdin"
? ""
: action.signal,
outcome: "dispatched",
}),
});
const offer = (
scenario: ProcessReactiveScenario,
snapshot: ReturnType<typeof createProcessReactiveSnapshot>,
value: ReturnType<typeof observation>,
) => {
const proposed = reduceProcessReactiveScenario(scenario, snapshot, {
kind: "observation",
observation: value,
});
return proposed.kind === "proposal"
? commitProcessReactiveProposal(
scenario,
proposed,
proposed.effects.map((effect, index) => ({
...succeededEffect(
effect,
(proposed.snapshot.observations.at(-1)?.capture_order ?? -1) +
index +
1,
),
})),
)
: proposed;
};
describe("process reactive runtime predicates", () => {
it("selects a unique priority and reports equal-priority ambiguity", () => {
const preferred = scenarioWith([
finish("fallback", terminalTrigger(), 20),
finish("preferred", terminalTrigger(), 10),
]);
const selected = offer(
preferred,
createProcessReactiveSnapshot(preferred),
observation("terminal_raw", 0, { data: "Ready" }),
);
expect(selected.kind).toBe("transition");
if (selected.kind === "transition")
expect(selected.record.transition_id).toBe("preferred");
for (const transitions of [
[finish("one", terminalTrigger()), finish("two", terminalTrigger())],
[finish("two", terminalTrigger()), finish("one", terminalTrigger())],
]) {
const ambiguous = scenarioWith(transitions);
const decision = offer(
ambiguous,
createProcessReactiveSnapshot(ambiguous),
observation("terminal_raw", 0, { data: "Ready" }),
);
expect(decision).toMatchObject({
kind: "finished",
outcome: "ambiguous_match",
});
}
});
it("evaluates ordered and repeated predicates without array-order arbitration", () => {
const event = (name: string) => ({
kind: "event" as const,
source: "shim" as const,
exact: { name },
ignore_fields: ["sequence" as const],
since: { kind: "scenario_start" as const },
consume: true,
cardinality: { min: 1, max: 1 },
});
const scenario = scenarioWith([
finish("sequence", {
kind: "sequence",
triggers: [
event("start"),
{ kind: "repeat", trigger: event("tick"), min: 2, max: 2 },
event("done"),
],
}),
]);
let snapshot = createProcessReactiveSnapshot(scenario);
for (const [order, name] of ["start", "tick", "tick"].entries()) {
const decision = offer(
scenario,
snapshot,
observation("shim", order, { name, sequence: order }),
);
expect(decision.kind).toBe("waiting");
snapshot = decision.snapshot;
}
const decision = offer(
scenario,
snapshot,
observation("shim", 3, { name: "done", sequence: 3 }),
);
expect(decision.kind).toBe("transition");
if (decision.kind === "transition")
expect(decision.record.trigger_event_ids).toEqual([
"obs.shim_events.0",
"obs.shim_events.1",
"obs.shim_events.2",
"obs.shim_events.3",
]);
});
it("applies state-entry frontiers and explicit consumption", () => {
const secondTrigger = {
...terminalTrigger(),
since: { kind: "state_entry" as const },
consume: true,
};
const scenario = processReactiveScenarioSchema.parse({
version: 1,
initial_state: "one",
deadline_ms: 30000,
states: [
{
id: "one",
max_visits: 1,
deadline_ms: 5000,
on: [
{
...finish("advance", terminalTrigger()),
target: { kind: "goto", state: "two" },
},
],
},
{
id: "two",
max_visits: 1,
deadline_ms: 5000,
on: [finish("finish", secondTrigger)],
},
],
});
const advanced = offer(
scenario,
createProcessReactiveSnapshot(scenario),
observation("terminal_raw", 0, { data: "Ready" }),
);
expect(advanced.kind).toBe("transition");
const waiting = offer(
scenario,
advanced.snapshot,
observation("shim", 1, { name: "unrelated" }),
);
expect(waiting.kind).toBe("waiting");
const finished = offer(
scenario,
waiting.snapshot,
observation("terminal_raw", 2, { data: "Ready" }),
);
expect(finished.kind).toBe("transition");
expect(finished.snapshot.consumed_event_ids).toEqual(["obs.frames.2"]);
});
});
@@ -0,0 +1,253 @@
import { describe, expect, it } from "vitest";
import {
createProcessObservation,
type ProcessObservationSource,
} from "../../../src/domain/processObservation.js";
import {
commitProcessReactiveProposal,
createProcessReactiveSnapshot,
reduceProcessReactiveScenario,
} from "../../../src/domain/processReactiveRuntime.js";
import {
processReactiveScenarioSchema,
type ProcessReactiveAction,
type ProcessReactiveScenario,
} from "../../../src/domain/processReactiveScenario.js";
const terminalTrigger = (literal = "Ready") => ({
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,
});
const scenarioWith = (
transitions: readonly unknown[],
): ProcessReactiveScenario =>
processReactiveScenarioSchema.parse({
version: 1,
initial_state: "starting",
deadline_ms: 30000,
states: [
{
id: "starting",
max_visits: 4,
deadline_ms: 5000,
on: transitions,
},
],
});
const finish = (
id: string,
when: unknown,
priority = 100,
actions: readonly unknown[] = [],
) => ({
id,
priority,
max_uses: 4,
when,
actions,
target: { kind: "finish", outcome: "passed" },
});
const collectionFor = (source: ProcessObservationSource) => {
switch (source) {
case "terminal_raw":
return "frames" as const;
case "terminal_rendered":
return "rendered_frames" as const;
case "process":
return "process_samples" as const;
case "filesystem":
return "filesystem_checkpoints" as const;
case "shim":
return "shim_events" as const;
case "http":
case "websocket":
return "protocol_events" as const;
case "replay_transition":
return "replay_transitions" as const;
case "interaction":
return "interaction_events" as const;
case "lifecycle":
return "lifecycle" as const;
}
};
const observation = (
source: ProcessObservationSource,
order: number,
payload: unknown,
) =>
createProcessObservation({
source,
source_sequence: order,
captured_at_ms: order,
subject_id: null,
location: {
collection: collectionFor(source),
index: order,
capture_order: order,
},
payload,
});
const succeededEffect = (action: ProcessReactiveAction, order: number) => ({
status: "succeeded" as const,
observation:
action.type === "checkpoint"
? observation("filesystem", order, { name: action.name })
: observation("interaction", order, {
type:
action.type === "send_input"
? "input"
: action.type === "resize"
? "resize"
: action.type === "close_stdin"
? "stdin_close"
: "signal",
data:
action.type === "send_input"
? action.sensitive
? `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`
: action.data
: action.type === "resize"
? `${String(action.columns)}x${String(action.rows)}`
: action.type === "close_stdin"
? ""
: action.signal,
outcome: "dispatched",
}),
});
const offer = (
scenario: ProcessReactiveScenario,
snapshot: ReturnType<typeof createProcessReactiveSnapshot>,
value: ReturnType<typeof observation>,
) => {
const proposed = reduceProcessReactiveScenario(scenario, snapshot, {
kind: "observation",
observation: value,
});
return proposed.kind === "proposal"
? commitProcessReactiveProposal(
scenario,
proposed,
proposed.effects.map((effect, index) => ({
...succeededEffect(
effect,
(proposed.snapshot.observations.at(-1)?.capture_order ?? -1) +
index +
1,
),
})),
)
: proposed;
};
describe("process reactive runtime predicates", () => {
it("rejects an exhausted state visit before proposing effects", () => {
const scenario = processReactiveScenarioSchema.parse({
version: 1,
initial_state: "loop",
deadline_ms: 30000,
states: [
{
id: "loop",
max_visits: 1,
deadline_ms: 5000,
on: [
{
...finish("again", terminalTrigger(), 100, [
{
type: "send_signal",
target: { kind: "root" },
signal: "SIGKILL",
},
]),
target: { kind: "goto", state: "loop" },
},
],
},
],
});
const decision = reduceProcessReactiveScenario(
scenario,
createProcessReactiveSnapshot(scenario),
{
kind: "observation",
observation: observation("terminal_raw", 0, { data: "Ready" }),
},
);
expect(decision).toMatchObject({
kind: "finished",
outcome: "capture_incomplete",
});
expect(decision).not.toHaveProperty("effects");
});
it("classifies deadlines and non-monotonic observation input", () => {
const scenario = scenarioWith([finish("ready", terminalTrigger())]);
const initial = createProcessReactiveSnapshot(scenario);
expect(
reduceProcessReactiveScenario(scenario, initial, {
kind: "state_deadline",
state_id: "starting",
state_entry_capture_order: 0,
}),
).toMatchObject({ kind: "finished", outcome: "predicate_timeout" });
expect(
reduceProcessReactiveScenario(scenario, initial, {
kind: "state_deadline",
state_id: "previous",
state_entry_capture_order: 0,
}),
).toMatchObject({ kind: "waiting", snapshot: initial });
expect(
reduceProcessReactiveScenario(scenario, initial, {
kind: "scenario_deadline",
}),
).toMatchObject({ kind: "finished", outcome: "scenario_deadline" });
expect(
reduceProcessReactiveScenario(scenario, initial, { kind: "cancelled" }),
).toMatchObject({ kind: "finished", outcome: "cancelled" });
expect(
reduceProcessReactiveScenario(scenario, initial, {
kind: "cleanup_failed",
}),
).toMatchObject({ kind: "finished", outcome: "cleanup_failed" });
const passed = offer(
scenario,
initial,
observation("terminal_raw", 0, { data: "Ready" }),
);
expect(
reduceProcessReactiveScenario(scenario, passed.snapshot, {
kind: "cleanup_failed",
}),
).toMatchObject({ kind: "finished", outcome: "cleanup_failed" });
const first = offer(
scenario,
initial,
observation("shim", 1, { name: "later" }),
);
const invalid = offer(
scenario,
first.snapshot,
observation("shim", 0, { name: "earlier" }),
);
expect(invalid).toMatchObject({
kind: "finished",
outcome: "capture_incomplete",
});
const duplicate = observation("shim", 1, { name: "later" });
expect(offer(scenario, first.snapshot, duplicate)).toMatchObject({
kind: "finished",
outcome: "capture_incomplete",
});
expect(
offer(scenario, first.snapshot, {
...duplicate,
payload: { name: "changed" },
}),
).toMatchObject({ kind: "finished", outcome: "capture_incomplete" });
});
});
@@ -0,0 +1,388 @@
import { describe, expect, it } from "vitest";
import {
PROCESS_REACTIVE_LIMITS,
processReactiveScenarioSchema,
} from "../../../src/domain/processReactiveScenario.js";
const terminalTrigger = () => ({
kind: "terminal_text" as const,
view: "decoded" as const,
encoding: "utf8" as const,
literal: "Ready",
case_sensitive: true,
control_sequences: "include" as const,
occurrence: 1,
since: { kind: "scenario_start" as const },
consume: false,
});
const finishTransition = () => ({
id: "finish",
priority: 100,
max_uses: 1,
when: terminalTrigger(),
actions: [{ type: "checkpoint" as const, name: "ready" }],
target: { kind: "finish" as const, outcome: "passed" as const },
});
const baseScenario = () => ({
version: 1 as const,
initial_state: "starting",
deadline_ms: 30_000,
states: [
{
id: "starting",
max_visits: 1,
deadline_ms: 5_000,
on: [finishTransition()],
},
],
});
describe("process reactive scenario schema", () => {
it("parses the bounded v1 terminal scenario", () => {
expect(processReactiveScenarioSchema.parse(baseScenario())).toMatchObject({
version: 1,
initial_state: "starting",
});
expect(PROCESS_REACTIVE_LIMITS.triggerDepth).toBe(6);
});
it.each([
["unknown major version", { ...baseScenario(), version: 2 }],
[
"missing state bound",
{
...baseScenario(),
states: [
{ id: "starting", deadline_ms: 5_000, on: [finishTransition()] },
],
},
],
[
"missing transition bound",
{
...baseScenario(),
states: [
{
id: "starting",
max_visits: 1,
deadline_ms: 5_000,
on: [{ ...finishTransition(), max_uses: undefined }],
},
],
},
],
[
"unsupported trigger",
{
...baseScenario(),
states: [
{
id: "starting",
max_visits: 1,
deadline_ms: 5_000,
on: [{ ...finishTransition(), when: { kind: "callback" } }],
},
],
},
],
[
"zero-minimum event absence predicate",
{
...baseScenario(),
states: [
{
...baseScenario().states[0],
on: [
{
...finishTransition(),
when: {
kind: "event",
source: "shim",
exact: { name: "missing" },
ignore_fields: [],
since: { kind: "scenario_start" },
consume: false,
cardinality: { min: 0, max: 1 },
},
},
],
},
],
},
],
[
"unsupported terminal interpretation",
{
...baseScenario(),
states: [
{
...baseScenario().states[0],
on: [
{
...finishTransition(),
when: {
...terminalTrigger(),
control_sequences: "strip_ansi",
},
},
],
},
],
},
],
])("rejects %s", (_name, input) => {
expect(processReactiveScenarioSchema.safeParse(input).success).toBe(false);
});
});
describe("process reactive scenario graph validation", () => {
it("rejects unknown targets, unreachable states, and duplicate transition ids", () => {
const input = {
...baseScenario(),
states: [
{
id: "starting",
max_visits: 1,
deadline_ms: 5_000,
on: [
{
...finishTransition(),
target: { kind: "goto" as const, state: "missing" },
},
],
},
{
id: "unreachable",
max_visits: 1,
deadline_ms: 5_000,
on: [finishTransition()],
},
],
};
const result = processReactiveScenarioSchema.safeParse(input);
expect(result.success).toBe(false);
if (!result.success)
expect(result.error.issues.map(({ message }) => message)).toEqual(
expect.arrayContaining([
"transition target state is not declared",
"state is unreachable from the initial state",
"transition ids must be unique",
]),
);
});
it("accepts only explicitly bounded cycles", () => {
const cycle = {
version: 1 as const,
initial_state: "one",
deadline_ms: 10_000,
states: [
{
id: "one",
max_visits: 2,
deadline_ms: 2_000,
on: [
{
...finishTransition(),
id: "to_two",
max_uses: 2,
actions: [],
target: { kind: "goto" as const, state: "two" },
},
],
},
{
id: "two",
max_visits: 2,
deadline_ms: 2_000,
on: [
{
...finishTransition(),
id: "to_one",
max_uses: 2,
actions: [],
target: { kind: "goto" as const, state: "one" },
},
],
},
],
};
expect(processReactiveScenarioSchema.safeParse(cycle).success).toBe(true);
const unbounded = {
...cycle,
states: cycle.states.map((state) => ({
...state,
max_visits: undefined,
})),
};
expect(processReactiveScenarioSchema.safeParse(unbounded).success).toBe(
false,
);
});
});
describe("process reactive scenario checkpoint validation", () => {
it("rejects impossible checkpoint frontiers and volatile exact fields", () => {
const exact = {
kind: "event" as const,
source: "http" as const,
exact: { sequence: 0, path: "/ready" },
ignore_fields: ["sequence" as const],
since: { kind: "checkpoint" as const, name: "missing" },
consume: false,
cardinality: { min: 1, max: 1 },
};
const input = {
...baseScenario(),
states: [
{
...baseScenario().states[0],
on: [{ ...finishTransition(), when: exact, actions: [] }],
},
],
};
const result = processReactiveScenarioSchema.safeParse(input);
expect(result.success).toBe(false);
if (!result.success)
expect(result.error.issues.map(({ message }) => message)).toEqual(
expect.arrayContaining([
"exact payload must omit every ignored field",
"checkpoint frontier is not definitely available before this transition",
]),
);
});
it("rejects checkpoint frontiers produced only by self or later transitions", () => {
const checkpointTrigger = (name: string) => ({
...terminalTrigger(),
since: { kind: "checkpoint" as const, name },
});
const input = {
version: 1 as const,
initial_state: "one",
deadline_ms: 10_000,
states: [
{
id: "one",
max_visits: 1,
deadline_ms: 2_000,
on: [
{
...finishTransition(),
id: "self",
when: checkpointTrigger("self_checkpoint"),
actions: [
{ type: "checkpoint" as const, name: "self_checkpoint" },
],
target: { kind: "goto" as const, state: "two" },
},
],
},
{
id: "two",
max_visits: 1,
deadline_ms: 2_000,
on: [
{
...finishTransition(),
id: "later",
when: checkpointTrigger("later_checkpoint"),
actions: [
{ type: "checkpoint" as const, name: "later_checkpoint" },
],
},
],
},
],
};
const result = processReactiveScenarioSchema.safeParse(input);
expect(result.success).toBe(false);
if (!result.success)
expect(
result.error.issues.filter(({ message }) =>
message.includes("not definitely available"),
),
).toHaveLength(2);
});
});
describe("process reactive scenario nesting validation", () => {
it("rejects trigger trees beyond the declared depth", () => {
let trigger: unknown = terminalTrigger();
for (
let depth = 0;
depth < PROCESS_REACTIVE_LIMITS.triggerDepth;
depth += 1
)
trigger = { kind: "repeat", trigger, min: 1, max: 1 };
const input = {
...baseScenario(),
states: [
{
...baseScenario().states[0],
on: [{ ...finishTransition(), when: trigger }],
},
],
};
const result = processReactiveScenarioSchema.safeParse(input);
expect(result.success).toBe(false);
if (!result.success)
expect(result.error.issues.map(({ message }) => message)).toContain(
"trigger nesting exceeds the v1 limit",
);
let hostile: unknown = terminalTrigger();
for (let depth = 0; depth < 10_000; depth += 1)
hostile = { kind: "repeat", trigger: hostile, min: 1, max: 1 };
const hostileInput = {
...input,
states: [
{
...input.states[0],
on: [{ ...finishTransition(), when: hostile }],
},
],
};
expect(() =>
processReactiveScenarioSchema.safeParse(hostileInput),
).not.toThrow();
expect(processReactiveScenarioSchema.safeParse(hostileInput).success).toBe(
false,
);
let deepJson: unknown = "leaf";
for (let depth = 0; depth < 10_000; depth += 1)
deepJson = { child: deepJson };
const deepJsonInput = {
...input,
states: [
{
...input.states[0],
on: [
{
...finishTransition(),
when: {
kind: "event",
source: "shim",
exact: deepJson,
ignore_fields: [],
since: { kind: "scenario_start" },
consume: false,
cardinality: { min: 1, max: 1 },
},
},
],
},
],
};
expect(() =>
processReactiveScenarioSchema.safeParse(deepJsonInput),
).not.toThrow();
expect(processReactiveScenarioSchema.safeParse(deepJsonInput).success).toBe(
false,
);
});
});
@@ -0,0 +1,313 @@
import { describe, expect, it } from "vitest";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
import {
compareProcessCaptures,
processCaptureSchema,
} from "../../../src/domain/processCapture.js";
import type { ProcessTraceSpecification } from "../../../src/domain/processTraceComparison.js";
const beforeCheckpoint = {
name: "before",
at_ms: 0,
files: [],
effects: [],
truncated: false,
};
const afterCheckpoint = {
name: "after_settlement",
at_ms: 50,
files: [],
effects: [],
truncated: false,
};
const capture = {
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
event_journal: [
{ 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;
const traceSpecification: ProcessTraceSpecification = {
version: 1,
events: [
{
id: "before",
source: "filesystem",
exact: beforeCheckpoint,
cardinality: { kind: "required" },
},
{
id: "exit",
source: "lifecycle",
exact: { event: "exit", ...capture.exit },
cardinality: { kind: "required" },
},
{
id: "settlement",
source: "lifecycle",
exact: { event: "settlement", ...capture.settlement },
cardinality: { kind: "required" },
},
{
id: "after",
source: "filesystem",
exact: afterCheckpoint,
cardinality: { kind: "required" },
},
],
language: {
kind: "finite_traces",
variants: [
{
id: "normal",
trace: ["before", "exit", "settlement", "after"],
},
],
},
};
describe("declared trace comparison adapters", () => {
it("treats only explicitly ignored schedule metadata as reorderable", () => {
const httpPayload = {
protocol: "http" as const,
direction: "request" as const,
method: "GET",
path: "/status",
data: "",
outcome: "unmatched" as const,
};
const websocketPayload = {
protocol: "websocket" as const,
direction: "received" as const,
method: null,
path: "/ws",
data: "done",
outcome: "matched" as const,
};
const scheduledCapture = (order: "http-first" | "websocket-first") => {
const protocolEvents =
order === "http-first"
? [
{ sequence: 0, at_ms: 1, ...httpPayload },
{ sequence: 1, at_ms: 2, ...websocketPayload },
]
: [
{ sequence: 0, at_ms: 1, ...websocketPayload },
{ sequence: 1, at_ms: 2, ...httpPayload },
];
return processCaptureSchema.parse({
...capture,
protocol_events: protocolEvents,
event_journal: [
{
capture_order: 0,
collection: "filesystem_checkpoints",
index: 0,
},
{ capture_order: 1, collection: "protocol_events", index: 0 },
{ capture_order: 2, collection: "protocol_events", index: 1 },
{ capture_order: 3, collection: "lifecycle", index: 0 },
{ capture_order: 4, collection: "lifecycle", index: 1 },
{
capture_order: 5,
collection: "filesystem_checkpoints",
index: 1,
},
],
});
};
const specification: ProcessTraceSpecification = {
version: 1,
events: [
{
id: "status",
source: "http",
exact: httpPayload,
ignore_fields: ["sequence", "at_ms"],
cardinality: { kind: "required" },
},
{
id: "done",
source: "websocket",
exact: websocketPayload,
ignore_fields: ["sequence", "at_ms"],
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [],
not_before: [],
unordered_groups: [{ events: ["status", "done"] }],
prefix: [],
suffix: [],
},
};
expect(
compareProcessCaptures(
scheduledCapture("http-first"),
scheduledCapture("websocket-first"),
{ traceSpecification: specification },
),
).toMatchObject({
status: "unchanged",
protocol: "unchanged",
trace: {
verdict: "equivalent",
left: { raw_trace: [{ event_id: "status" }, { event_id: "done" }] },
right: { raw_trace: [{ event_id: "done" }, { event_id: "status" }] },
},
});
});
});
describe("declared trace comparison coverage", () => {
it("does not mask an unselected source in a covered legacy dimension", () => {
const http = {
sequence: 0,
at_ms: 1,
protocol: "http" as const,
direction: "request" as const,
method: "GET",
path: "/status",
data: "",
outcome: "unmatched" as const,
};
const websocket = (data: string) => ({
sequence: 1,
at_ms: 2,
protocol: "websocket" as const,
direction: "received" as const,
method: null,
path: "/ws",
data,
outcome: "matched" as const,
});
const withProtocol = (data: string) =>
processCaptureSchema.parse({
...capture,
protocol_events: [http, websocket(data)],
event_journal: [
{
capture_order: 0,
collection: "filesystem_checkpoints",
index: 0,
},
{ capture_order: 1, collection: "protocol_events", index: 0 },
{ capture_order: 2, collection: "protocol_events", index: 1 },
{ capture_order: 3, collection: "lifecycle", index: 0 },
{ capture_order: 4, collection: "lifecycle", index: 1 },
{
capture_order: 5,
collection: "filesystem_checkpoints",
index: 1,
},
],
});
const specification: ProcessTraceSpecification = {
version: 1,
events: [
{
id: "status",
source: "http",
exact: http,
cardinality: { kind: "required" },
},
],
language: {
kind: "finite_traces",
variants: [{ id: "status", trace: ["status"] }],
},
};
expect(
compareProcessCaptures(withProtocol("left"), withProtocol("right"), {
traceSpecification: specification,
}),
).toMatchObject({
status: "changed",
protocol: "changed",
trace: { verdict: "equivalent" },
});
});
});
describe("declared trace comparison nonconformance", () => {
it("does not call identical captures changed when both violate the language", () => {
const parsedCapture = processCaptureSchema.parse(capture);
const specification: ProcessTraceSpecification = {
...traceSpecification,
language: {
kind: "finite_traces",
variants: [
{
id: "reversed",
trace: ["after", "settlement", "exit", "before"],
},
],
},
};
expect(
compareProcessCaptures(parsedCapture, parsedCapture, {
traceSpecification: specification,
}),
).toMatchObject({
status: "unchanged",
trace: { verdict: "nonconforming" },
});
});
it("does not mask distinct payloads when both traces are nonconforming", () => {
const withTerminal = (data: string) =>
processCaptureSchema.parse({
...capture,
frames: [{ sequence: 0, at_ms: 1, data }],
event_journal: [
{
capture_order: 0,
collection: "filesystem_checkpoints",
index: 0,
},
{ capture_order: 1, collection: "frames", index: 0 },
{ capture_order: 2, collection: "lifecycle", index: 0 },
{ capture_order: 3, collection: "lifecycle", index: 1 },
{
capture_order: 4,
collection: "filesystem_checkpoints",
index: 1,
},
],
});
const specification: ProcessTraceSpecification = {
version: 1,
events: [
{
id: "expected",
source: "terminal_raw",
exact: { sequence: 0, at_ms: 1, data: "expected" },
cardinality: { kind: "required" },
},
],
language: {
kind: "finite_traces",
variants: [{ id: "expected", trace: ["expected"] }],
},
};
expect(
compareProcessCaptures(withTerminal("left"), withTerminal("right"), {
traceSpecification: specification,
}),
).toMatchObject({
status: "changed",
terminal: "changed",
trace: { verdict: "nonconforming" },
});
});
});
@@ -0,0 +1,294 @@
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 {
compareProcessTraces,
type ProcessTraceSpecification,
} from "../../../src/domain/processTraceComparison.js";
const emptyCapture = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const capture = (
values: Pick<
ProcessCapture,
| "frames"
| "process_samples"
| "filesystem_checkpoints"
| "protocol_events"
| "shim_events"
> & {
readonly event_journal: NonNullable<ProcessCapture["event_journal"]>;
},
options: {
readonly truncated?: boolean;
readonly residualUnknowns?: ProcessCapture["residual_unknowns"];
} = {},
): ProcessCapture => ({
...emptyCapture,
frames: values.frames,
process_samples: values.process_samples,
filesystem_checkpoints: emptyCapture.filesystem_checkpoints,
shim_events: values.shim_events,
protocol_events: values.protocol_events,
event_journal: [
{
capture_order: 0,
collection: "filesystem_checkpoints",
index: 0,
},
...values.event_journal.map((entry) => ({
...entry,
capture_order: entry.capture_order + 1,
})),
{
capture_order: values.event_journal.length + 1,
collection: "lifecycle",
index: 0,
},
{
capture_order: values.event_journal.length + 2,
collection: "lifecycle",
index: 1,
},
{
capture_order: values.event_journal.length + 3,
collection: "filesystem_checkpoints",
index: 1,
},
],
truncated: options.truncated ?? false,
residual_unknowns: options.residualUnknowns ?? [],
});
const terminal = { sequence: 0, at_ms: 900, data: "Ready" };
const processStarted = {
at_ms: 1,
pid: 1,
parent_pid: 0,
command: "worker",
process_group_id: 1,
session_id: 1,
};
const http = {
sequence: 0,
at_ms: 2,
protocol: "http" as const,
direction: "request" as const,
method: "GET",
path: "/status",
data: "",
outcome: "unmatched" as const,
};
const websocket = {
sequence: 1,
at_ms: 3,
protocol: "websocket" as const,
direction: "received" as const,
method: null,
path: "/ws",
data: "done",
outcome: "matched" as const,
};
const values = (
order: readonly ("terminal" | "process" | "http" | "websocket")[],
): Parameters<typeof capture>[0] => ({
frames: [terminal],
process_samples: [processStarted],
filesystem_checkpoints: [],
protocol_events: [http, websocket],
shim_events: [],
event_journal: order.map((event, captureOrder) => ({
capture_order: captureOrder,
collection:
event === "terminal"
? "frames"
: event === "process"
? "process_samples"
: "protocol_events",
index: event === "websocket" ? 1 : 0,
})),
});
const partialSpecification = (): ProcessTraceSpecification => ({
version: 1,
events: [
{
id: "ready",
source: "terminal_raw",
exact: terminal,
cardinality: { kind: "required" },
},
{
id: "worker",
source: "process",
exact: processStarted,
cardinality: { kind: "required" },
},
{
id: "status",
source: "http",
exact: http,
cardinality: { kind: "required" },
},
{
id: "done",
source: "websocket",
exact: websocket,
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [
{ before: "ready", after: "worker" },
{ before: "ready", after: "status" },
{ before: "worker", after: "done" },
{ before: "status", after: "done" },
],
not_before: [{ event: "done", anchor: "ready" }],
unordered_groups: [{ events: ["worker", "status"] }],
prefix: ["ready"],
suffix: ["done"],
},
});
describe("process trace comparison", () => {
it("accepts only explicitly declared concurrent schedules without timestamp causality", () => {
const left = capture(values(["terminal", "process", "http", "websocket"]));
const right = capture(values(["terminal", "http", "process", "websocket"]));
const comparison = compareProcessTraces(
left,
right,
partialSpecification(),
);
expect(comparison.verdict).toBe("equivalent");
expect(comparison.left.raw_trace.map(({ event_id }) => event_id)).toEqual([
"ready",
"worker",
"status",
"done",
]);
expect(comparison.right.raw_trace.map(({ event_id }) => event_id)).toEqual([
"ready",
"status",
"worker",
"done",
]);
expect(comparison.left.satisfied_constraints).toContain(
"unordered:worker:status",
);
});
it("returns the minimal journal slice for a reversed required edge", () => {
const baseline = capture(
values(["terminal", "process", "http", "websocket"]),
);
const reversed = capture(
values(["process", "terminal", "http", "websocket"]),
);
const comparison = compareProcessTraces(
baseline,
reversed,
partialSpecification(),
);
expect(comparison).toMatchObject({
verdict: "different",
diagnostic: {
kind: "edge",
side: "right",
event_ids: ["ready", "worker"],
locations: [{ capture_order: 2 }, { capture_order: 1 }],
},
});
});
it("enforces explicit negative not-before constraints", () => {
const specification: ProcessTraceSpecification = {
version: 1,
events: [
{
id: "ready",
source: "terminal_raw",
exact: terminal,
cardinality: { kind: "required" },
},
{
id: "done",
source: "websocket",
exact: websocket,
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [],
not_before: [{ event: "done", anchor: "ready" }],
unordered_groups: [],
prefix: [],
suffix: [],
},
};
const normal = capture(
values(["terminal", "process", "http", "websocket"]),
);
const invalid = capture(
values(["websocket", "terminal", "process", "http"]),
);
expect(compareProcessTraces(normal, invalid, specification)).toMatchObject({
verdict: "different",
diagnostic: {
kind: "edge",
side: "right",
event_ids: ["done", "ready"],
},
});
});
it("supports declared optional events and bounded duplicates", () => {
const first = { sequence: 0, at_ms: 1, data: "tick" };
const second = { sequence: 1, at_ms: 2, data: "tick" };
const one = capture({
frames: [first],
process_samples: [],
filesystem_checkpoints: [],
protocol_events: [],
shim_events: [],
event_journal: [{ capture_order: 0, collection: "frames", index: 0 }],
});
const two = capture({
frames: [first, second],
process_samples: [],
filesystem_checkpoints: [],
protocol_events: [],
shim_events: [],
event_journal: [
{ capture_order: 0, collection: "frames", index: 0 },
{ capture_order: 1, collection: "frames", index: 1 },
],
});
const specification: ProcessTraceSpecification = {
version: 1,
events: [
{
id: "tick1",
source: "terminal_raw",
exact: first,
cardinality: { kind: "required" },
},
{
id: "tick2",
source: "terminal_raw",
exact: second,
cardinality: { kind: "optional" },
},
],
language: {
kind: "finite_traces",
variants: [
{ id: "one", trace: ["tick1"] },
{ id: "two", trace: ["tick1", "tick2"] },
],
},
};
expect(compareProcessTraces(one, two, specification)).toMatchObject({
verdict: "equivalent",
left: { matched_variant: "one" },
right: { matched_variant: "two" },
});
});
});
@@ -0,0 +1,262 @@
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 {
compareProcessTraces,
type ProcessTraceSpecification,
} from "../../../src/domain/processTraceComparison.js";
const emptyCapture = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const capture = (
values: Pick<
ProcessCapture,
| "frames"
| "process_samples"
| "filesystem_checkpoints"
| "protocol_events"
| "shim_events"
> & {
readonly event_journal: NonNullable<ProcessCapture["event_journal"]>;
},
options: {
readonly truncated?: boolean;
readonly residualUnknowns?: ProcessCapture["residual_unknowns"];
} = {},
): ProcessCapture => ({
...emptyCapture,
frames: values.frames,
process_samples: values.process_samples,
filesystem_checkpoints: emptyCapture.filesystem_checkpoints,
shim_events: values.shim_events,
protocol_events: values.protocol_events,
event_journal: [
{
capture_order: 0,
collection: "filesystem_checkpoints",
index: 0,
},
...values.event_journal.map((entry) => ({
...entry,
capture_order: entry.capture_order + 1,
})),
{
capture_order: values.event_journal.length + 1,
collection: "lifecycle",
index: 0,
},
{
capture_order: values.event_journal.length + 2,
collection: "lifecycle",
index: 1,
},
{
capture_order: values.event_journal.length + 3,
collection: "filesystem_checkpoints",
index: 1,
},
],
truncated: options.truncated ?? false,
residual_unknowns: options.residualUnknowns ?? [],
});
const terminal = { sequence: 0, at_ms: 900, data: "Ready" };
const processStarted = {
at_ms: 1,
pid: 1,
parent_pid: 0,
command: "worker",
process_group_id: 1,
session_id: 1,
};
const http = {
sequence: 0,
at_ms: 2,
protocol: "http" as const,
direction: "request" as const,
method: "GET",
path: "/status",
data: "",
outcome: "unmatched" as const,
};
const websocket = {
sequence: 1,
at_ms: 3,
protocol: "websocket" as const,
direction: "received" as const,
method: null,
path: "/ws",
data: "done",
outcome: "matched" as const,
};
const values = (
order: readonly ("terminal" | "process" | "http" | "websocket")[],
): Parameters<typeof capture>[0] => ({
frames: [terminal],
process_samples: [processStarted],
filesystem_checkpoints: [],
protocol_events: [http, websocket],
shim_events: [],
event_journal: order.map((event, captureOrder) => ({
capture_order: captureOrder,
collection:
event === "terminal"
? "frames"
: event === "process"
? "process_samples"
: "protocol_events",
index: event === "websocket" ? 1 : 0,
})),
});
const partialSpecification = (): ProcessTraceSpecification => ({
version: 1,
events: [
{
id: "ready",
source: "terminal_raw",
exact: terminal,
cardinality: { kind: "required" },
},
{
id: "worker",
source: "process",
exact: processStarted,
cardinality: { kind: "required" },
},
{
id: "status",
source: "http",
exact: http,
cardinality: { kind: "required" },
},
{
id: "done",
source: "websocket",
exact: websocket,
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [
{ before: "ready", after: "worker" },
{ before: "ready", after: "status" },
{ before: "worker", after: "done" },
{ before: "status", after: "done" },
],
not_before: [{ event: "done", anchor: "ready" }],
unordered_groups: [{ events: ["worker", "status"] }],
prefix: ["ready"],
suffix: ["done"],
},
});
describe("process trace comparison", () => {
it("enforces exact and range cardinality for one repeated predicate", () => {
const repeated = (count: number) =>
capture({
frames: Array.from({ length: count }, (_, sequence) => ({
sequence,
at_ms: sequence,
data: "tick",
})),
process_samples: [],
filesystem_checkpoints: [],
protocol_events: [],
shim_events: [],
event_journal: Array.from({ length: count }, (_, index) => ({
capture_order: index,
collection: "frames" as const,
index,
})),
});
const event: Omit<
ProcessTraceSpecification["events"][number],
"cardinality"
> = {
id: "tick",
source: "terminal_raw",
exact: { data: "tick" },
ignore_fields: ["sequence", "at_ms"],
};
const rangeSpecification: ProcessTraceSpecification = {
version: 1,
events: [{ ...event, cardinality: { kind: "range", min: 2, max: 3 } }],
language: {
kind: "partial_order",
happens_before: [],
not_before: [],
unordered_groups: [],
prefix: [],
suffix: [],
},
};
expect(
compareProcessTraces(repeated(2), repeated(3), rangeSpecification),
).toMatchObject({ verdict: "equivalent" });
expect(
compareProcessTraces(repeated(1), repeated(2), rangeSpecification),
).toMatchObject({
verdict: "different",
diagnostic: { kind: "cardinality", side: "left" },
});
expect(
compareProcessTraces(repeated(2), repeated(4), rangeSpecification),
).toMatchObject({
verdict: "different",
diagnostic: { kind: "cardinality", side: "right" },
});
const exactSpecification: ProcessTraceSpecification = {
version: 1,
events: [{ ...event, cardinality: { kind: "exact", count: 2 } }],
language: {
kind: "finite_traces",
variants: [{ id: "two", trace: ["tick", "tick"] }],
},
};
expect(
compareProcessTraces(repeated(2), repeated(2), exactSpecification),
).toMatchObject({ verdict: "equivalent" });
expect(
compareProcessTraces(repeated(3), repeated(2), exactSpecification),
).toMatchObject({
verdict: "different",
diagnostic: { kind: "cardinality", side: "left" },
});
});
it("never proves equivalence from truncated, unknown, or journal-free evidence", () => {
const complete = capture(
values(["terminal", "process", "http", "websocket"]),
);
const truncated = capture(
values(["terminal", "process", "http", "websocket"]),
{ truncated: true },
);
expect(
compareProcessTraces(complete, truncated, partialSpecification()).verdict,
).toBe("unknown");
const unknown = capture(
values(["terminal", "process", "http", "websocket"]),
{ residualUnknowns: [{ scope: "protocol", reason: "gap" }] },
);
expect(
compareProcessTraces(complete, unknown, partialSpecification()).verdict,
).toBe("unknown");
const noJournal = { ...complete, event_journal: [] };
const comparison = compareProcessTraces(
complete,
noJournal,
partialSpecification(),
);
expect(comparison).toMatchObject({
verdict: "unknown",
diagnostic: { kind: "journal", side: "right" },
});
const incompleteJournal = {
...complete,
event_journal: (complete.event_journal ?? []).slice(1),
};
expect(() =>
compareProcessTraces(complete, incompleteJournal, partialSpecification()),
).toThrow("Invalid Process Capture v4: event_journal.0.capture_order");
});
});
@@ -0,0 +1,185 @@
import { describe, expect, it } from "vitest";
import {
processTraceSpecificationSchema,
type ProcessTraceSpecification,
} from "../../../src/domain/processTraceComparison.js";
const terminal = { sequence: 0, at_ms: 900, data: "Ready" };
const processStarted = {
at_ms: 1,
pid: 1,
parent_pid: 0,
command: "worker",
process_group_id: 1,
session_id: 1,
};
const http = {
sequence: 0,
at_ms: 2,
protocol: "http" as const,
direction: "request" as const,
method: "GET",
path: "/status",
data: "",
outcome: "unmatched" as const,
};
const websocket = {
sequence: 1,
at_ms: 3,
protocol: "websocket" as const,
direction: "received" as const,
method: null,
path: "/ws",
data: "done",
outcome: "matched" as const,
};
const partialSpecification = (): ProcessTraceSpecification => ({
version: 1,
events: [
{
id: "ready",
source: "terminal_raw",
exact: terminal,
cardinality: { kind: "required" },
},
{
id: "worker",
source: "process",
exact: processStarted,
cardinality: { kind: "required" },
},
{
id: "status",
source: "http",
exact: http,
cardinality: { kind: "required" },
},
{
id: "done",
source: "websocket",
exact: websocket,
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [
{ before: "ready", after: "worker" },
{ before: "ready", after: "status" },
{ before: "worker", after: "done" },
{ before: "status", after: "done" },
],
not_before: [{ event: "done", anchor: "ready" }],
unordered_groups: [{ events: ["worker", "status"] }],
prefix: ["ready"],
suffix: ["done"],
},
});
describe("process trace specification", () => {
it("rejects cycles, implicit concurrency, overlap, and unsatisfiable variants", () => {
const base = partialSpecification();
expect(
processTraceSpecificationSchema.safeParse({
...base,
language: {
kind: "partial_order",
happens_before: [
{ before: "ready", after: "worker" },
{ before: "worker", after: "ready" },
],
unordered_groups: [{ events: ["status", "done"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
version: 1,
events: base.events.slice(0, 3),
language: {
kind: "partial_order",
happens_before: [{ before: "ready", after: "status" }],
not_before: [{ event: "worker", anchor: "ready" }],
unordered_groups: [],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
version: 1,
events: [
{
id: "invalid-ignore",
source: "terminal_raw",
exact: "ready",
ignore_fields: ["at_ms"],
},
],
language: {
kind: "finite_traces",
variants: [{ id: "one", trace: ["invalid-ignore"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
version: 1,
events: [
{
id: "invalid-ignore",
source: "terminal_raw",
exact: terminal,
ignore_fields: ["at_ms"],
},
],
language: {
kind: "finite_traces",
variants: [{ id: "one", trace: ["invalid-ignore"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
version: 1,
events: base.events.slice(0, 2),
language: { kind: "partial_order" },
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
version: 1,
events: [base.events[0], { ...base.events[0], id: "duplicate" }],
language: {
kind: "partial_order",
unordered_groups: [{ events: ["ready", "duplicate"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
version: 1,
events: [
{
...base.events[0],
cardinality: { kind: "exact", count: 2 },
},
],
language: {
kind: "finite_traces",
variants: [{ id: "once", trace: ["ready"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
version: 1,
events: [base.events[0]],
language: {
kind: "finite_traces",
variants: [
{ id: "first", trace: ["ready"] },
{ id: "duplicate", trace: ["ready"] },
],
},
}).success,
).toBe(false);
});
});
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import {
boundedSensitiveText,
redactSensitiveText,
} from "../../../src/browser/SensitiveTextCapture.js";
describe("sensitive console text", () => {
it("redacts assignments, bearer credentials, and JWT-shaped values", () => {
const jwt = "eyJabcdefghijk.abcdefghijkl.abcdefghijk";
expect(
redactSensitiveText(
`authorization=Bearer abc.def password='hunter2' api_key=key ${jwt}`,
),
).toBe(
"authorization=[REDACTED] password=[REDACTED] api_key=[REDACTED] [REDACTED_JWT]",
);
});
it("bounds UTF-8 after redaction without splitting a code point", () => {
expect(boundedSensitiveText("password=secret 你好", 22)).toEqual({
text: "password=[REDACTED] ",
bytes: 20,
truncated: true,
});
});
});