From db9a83190b841c8195da0b3036644831770ba369 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 23 Jul 2026 01:32:58 +0000 Subject: [PATCH] feat(process): coordinate reactive capture effects --- src/application/ProcessCaptureJournal.ts | 51 +- src/application/ProcessCheckpoints.ts | 32 +- src/application/ProcessReactiveCoordinator.ts | 284 ++++++++++ src/application/ProcessReactiveEffects.ts | 226 ++++++++ .../ProcessReactiveObservations.ts | 35 ++ tests/processCapture.test.ts | 22 +- tests/processReactiveCoordinator.test.ts | 501 ++++++++++++++++++ 7 files changed, 1147 insertions(+), 4 deletions(-) create mode 100644 src/application/ProcessReactiveCoordinator.ts create mode 100644 src/application/ProcessReactiveEffects.ts create mode 100644 src/application/ProcessReactiveObservations.ts create mode 100644 tests/processReactiveCoordinator.test.ts diff --git a/src/application/ProcessCaptureJournal.ts b/src/application/ProcessCaptureJournal.ts index b3696e435..bbddfbca3 100644 --- a/src/application/ProcessCaptureJournal.ts +++ b/src/application/ProcessCaptureJournal.ts @@ -16,15 +16,62 @@ import type { TerminalRenderer } from "./TerminalRenderer.js"; export interface ProcessCaptureJournal { readonly entries: readonly ProcessCaptureEventJournalEntry[]; readonly recordEvent: RecordProcessCaptureEvent; + readonly record: ( + collection: ProcessCaptureEventJournalEntry["collection"], + index: number, + ) => ProcessCaptureEventJournalEntry; + readonly subscribe: ( + listener: (entry: ProcessCaptureEventJournalEntry) => void, + ) => () => void; } /** Create one monotonic event journal for a process capture. */ export const createProcessCaptureJournal = (): ProcessCaptureJournal => { const entries: ProcessCaptureEventJournalEntry[] = []; + const listeners = new Set<(entry: ProcessCaptureEventJournalEntry) => void>(); + const notifications: ProcessCaptureEventJournalEntry[] = []; + let delivering = false; + const deliverNotifications = (): void => { + if (delivering) return; + delivering = true; + const failures: unknown[] = []; + try { + for (;;) { + const notification = notifications.shift(); + if (notification === undefined) break; + for (const listener of Array.from(listeners)) + try { + listener(notification); + } catch (cause: unknown) { + failures.push(cause); + } + } + } finally { + delivering = false; + } + if (failures.length > 0) + throw new AggregateError( + failures, + "process capture journal subscriber failed", + ); + }; + const record = ( + collection: ProcessCaptureEventJournalEntry["collection"], + index: number, + ): ProcessCaptureEventJournalEntry => { + const entry = { capture_order: entries.length, collection, index }; + entries.push(entry); + notifications.push(entry); + deliverNotifications(); + return entry; + }; return { entries, - recordEvent: (collection, index) => { - entries.push({ capture_order: entries.length, collection, index }); + record, + recordEvent: (collection, index) => void record(collection, index), + subscribe: (listener) => { + listeners.add(listener); + return () => listeners.delete(listener); }, }; }; diff --git a/src/application/ProcessCheckpoints.ts b/src/application/ProcessCheckpoints.ts index c693cc2d0..3996869f4 100644 --- a/src/application/ProcessCheckpoints.ts +++ b/src/application/ProcessCheckpoints.ts @@ -103,13 +103,17 @@ export class ProcessCheckpoints { /** Queue one idempotent named snapshot. */ capture(name: string): void { + this.#scheduleCapture(name, this.#signal); + } + + #scheduleCapture(name: string, signal: AbortSignal | undefined): void { if (this.#captured.has(name)) return; this.#captured.add(name); // Serialize scans even when time, terminal, and lifecycle triggers fire // together. Each effect set is intentionally relative to the immediately // preceding checkpoint, which preserves transient create/delete behavior. this.#pending = this.#pending.then(async () => { - const snapshot = await snapshotRoots(this.scenario, this.#signal); + const snapshot = await snapshotRoots(this.scenario, signal); const previous = this.#captures.at(-1)?.files ?? []; const index = this.#captures.length; this.#captures.push({ @@ -123,6 +127,32 @@ export class ProcessCheckpoints { }); } + /** Queue one named snapshot and return its exact captured record. */ + async captureAndRead( + name: string, + signal?: AbortSignal, + ): Promise<{ + readonly index: number; + readonly checkpoint: FilesystemCheckpoint; + }> { + const captureSignal = + signal === undefined + ? this.#signal + : this.#signal === undefined + ? signal + : AbortSignal.any([this.#signal, signal]); + this.#scheduleCapture(name, captureSignal); + const scheduled = this.#pending; + await scheduled; + const index = this.#captures.findIndex( + ({ name: capturedName }) => capturedName === name, + ); + const checkpoint = this.#captures[index]; + if (index < 0 || checkpoint === undefined) + throw new Error(`filesystem checkpoint was not captured: ${name}`); + return { index, checkpoint: structuredClone(checkpoint) }; + } + /** Finish pending snapshots and return them in observation order. */ async finish( after: SnapshotResult, diff --git a/src/application/ProcessReactiveCoordinator.ts b/src/application/ProcessReactiveCoordinator.ts new file mode 100644 index 000000000..04d83fd30 --- /dev/null +++ b/src/application/ProcessReactiveCoordinator.ts @@ -0,0 +1,284 @@ +import { + commitProcessReactiveProposal, + createProcessReactiveSnapshot, + reduceProcessReactiveScenario, + type ProcessReactiveDecision, + type ProcessReactiveEffectResult, + type ProcessReactiveInput, + type ProcessReactiveSnapshot, +} from "../domain/processReactiveRuntime.js"; +import type { + ProcessReactiveAction, + ProcessReactiveScenario, +} from "../domain/processReactiveScenario.js"; + +/** Effect boundary owned by the serialized reactive coordinator. */ +export interface ProcessReactiveExecutor { + execute( + actions: readonly ProcessReactiveAction[], + signal: AbortSignal, + ): Promise; +} + +/** Cancel handle for one coordinator-owned deadline. */ +export interface ProcessReactiveTimer { + cancel(): void; +} + +/** Injectable deadline scheduler used by deterministic coordinator tests. */ +export interface ProcessReactiveTimerHost { + readonly schedule: ( + callback: () => void, + delayMs: number, + ) => ProcessReactiveTimer; +} + +const systemTimerHost: ProcessReactiveTimerHost = { + schedule: (callback, delayMs) => { + const timer = setTimeout(callback, delayMs); + return { cancel: () => clearTimeout(timer) }; + }, +}; + +/** + * Serializes live observations, deadlines, and effect commits for one run. + * Producer callbacks enqueue work without awaiting it, preventing reentrancy. + */ +export class ProcessReactiveCoordinator { + readonly #scenario: ProcessReactiveScenario; + readonly #executor: ProcessReactiveExecutor; + readonly #timerHost: ProcessReactiveTimerHost; + readonly #now: () => number; + readonly #scenarioDeadlineAt: number; + readonly #onDecision: + | ((decision: ProcessReactiveDecision) => void) + | undefined; + #snapshot: ProcessReactiveSnapshot; + readonly #pendingInputs: ProcessReactiveInput[] = []; + #tail: Promise = Promise.resolve(); + #running = false; + #failure: unknown; + #stateTimer: ProcessReactiveTimer | undefined; + #scenarioTimer: ProcessReactiveTimer | undefined; + #stateDeadlineAt = 0; + #effectAbort: AbortController | undefined; + #accepting = true; + #closed = false; + + constructor(options: { + readonly scenario: ProcessReactiveScenario; + readonly executor: ProcessReactiveExecutor; + readonly timerHost?: ProcessReactiveTimerHost; + readonly now?: () => number; + readonly onDecision?: (decision: ProcessReactiveDecision) => void; + }) { + this.#scenario = options.scenario; + this.#executor = options.executor; + this.#timerHost = options.timerHost ?? systemTimerHost; + this.#now = options.now ?? Date.now; + this.#scenarioDeadlineAt = this.#now() + options.scenario.deadline_ms; + this.#onDecision = options.onDecision; + this.#snapshot = createProcessReactiveSnapshot(options.scenario); + this.#scheduleScenarioDeadline(); + this.#scheduleStateDeadline(); + } + + /** Current immutable reducer snapshot after all completed turns. */ + get snapshot(): ProcessReactiveSnapshot { + return this.#snapshot; + } + + /** Enqueue producer work without creating a floating promise. */ + enqueue(input: ProcessReactiveInput): void { + if (!this.#accepting) return; + if (this.#interruptsEffects(input)) this.#effectAbort?.abort(); + this.#enqueueOwned(input); + } + + /** Submit one input and wait until every turn queued before it completes. */ + async submit(input: ProcessReactiveInput): Promise { + this.enqueue(input); + await this.drain(); + return this.#snapshot; + } + + /** Wait for currently queued reducer/effect work and surface host failures. */ + async drain(): Promise { + for (;;) { + const observedTail = this.#tail; + await observedTail; + if (observedTail === this.#tail) break; + } + if (this.#failure !== undefined) throw this.#failure; + } + + /** Stop owned deadlines after queued work settles. */ + async close(): Promise { + this.#accepting = false; + this.#clearTimers(); + await this.drain(); + this.#closed = true; + } + + #enqueueOwned(input: ProcessReactiveInput): void { + if (this.#closed || this.#failure !== undefined) return; + this.#pendingInputs.push(input); + this.#startWorker(); + } + + #startWorker(): void { + if (this.#running || this.#pendingInputs.length === 0) return; + this.#running = true; + this.#tail = this.#runQueue() + .catch((cause: unknown) => this.#fail(cause)) + .finally(() => { + this.#running = false; + if (this.#pendingInputs.length > 0) this.#startWorker(); + }); + } + + async #runQueue(): Promise { + for (;;) { + const input = this.#nextInput(); + if (input === undefined) return; + await this.#advance(input); + } + } + + #nextInput(): ProcessReactiveInput | undefined { + const terminalIndex = this.#pendingInputs.findIndex( + ({ kind }) => kind === "cancelled" || kind === "cleanup_failed", + ); + if (terminalIndex >= 0) + return this.#pendingInputs.splice(terminalIndex, 1)[0]; + let observationIndex = -1; + let captureOrder = Number.POSITIVE_INFINITY; + for (const [index, input] of this.#pendingInputs.entries()) + if ( + input.kind === "observation" && + input.observation.capture_order < captureOrder + ) { + observationIndex = index; + captureOrder = input.observation.capture_order; + } + return observationIndex >= 0 + ? this.#pendingInputs.splice(observationIndex, 1)[0] + : this.#pendingInputs.shift(); + } + + #fail(cause: unknown): void { + this.#failure ??= cause; + this.#accepting = false; + this.#closed = true; + this.#effectAbort?.abort(); + this.#pendingInputs.length = 0; + this.#clearTimers(); + } + + async #advance(input: ProcessReactiveInput): Promise { + const before = this.#snapshot; + let decision = reduceProcessReactiveScenario(this.#scenario, before, input); + let effectResults: readonly ProcessReactiveEffectResult[] = []; + if (decision.kind === "proposal") { + const effectAbort = new AbortController(); + this.#effectAbort = effectAbort; + try { + effectResults = await this.#executor.execute( + decision.effects, + effectAbort.signal, + ); + } catch (cause: unknown) { + if (effectAbort.signal.aborted) return; + throw cause; + } finally { + if (this.#effectAbort === effectAbort) this.#effectAbort = undefined; + } + if (effectAbort.signal.aborted) return; + const expired = this.#expiredDeadlineInput(); + if (expired !== undefined) { + this.#enqueueOwned(expired); + return; + } + decision = commitProcessReactiveProposal( + this.#scenario, + decision, + effectResults, + ); + } + this.#snapshot = decision.snapshot; + this.#onDecision?.(decision); + if (this.#snapshot.status === "finished") this.#clearTimers(); + else if ( + this.#accepting && + (before.active_state !== this.#snapshot.active_state || + before.state_entry_capture_order !== + this.#snapshot.state_entry_capture_order) + ) + this.#scheduleStateDeadline(); + for (const result of effectResults) + if (result.status === "succeeded") + this.#enqueueOwned({ + kind: "observation", + observation: result.observation, + }); + } + + #interruptsEffects(input: ProcessReactiveInput): boolean { + if ( + input.kind === "cancelled" || + input.kind === "cleanup_failed" || + input.kind === "scenario_deadline" + ) + return true; + return ( + input.kind === "state_deadline" && + input.state_id === this.#snapshot.active_state && + input.state_entry_capture_order === + this.#snapshot.state_entry_capture_order + ); + } + + #expiredDeadlineInput(): ProcessReactiveInput | undefined { + const now = this.#now(); + if (now >= this.#scenarioDeadlineAt) return { kind: "scenario_deadline" }; + if (now < this.#stateDeadlineAt) return undefined; + return { + kind: "state_deadline", + state_id: this.#snapshot.active_state, + state_entry_capture_order: this.#snapshot.state_entry_capture_order, + }; + } + + #scheduleScenarioDeadline(): void { + if (!this.#accepting) return; + this.#scenarioTimer = this.#timerHost.schedule( + () => this.enqueue({ kind: "scenario_deadline" }), + this.#scenario.deadline_ms, + ); + } + + #scheduleStateDeadline(): void { + if (!this.#accepting) return; + this.#stateTimer?.cancel(); + const state = this.#scenario.states.find( + ({ id }) => id === this.#snapshot.active_state, + ); + if (state === undefined) return; + this.#stateDeadlineAt = this.#now() + state.deadline_ms; + const identity = { + state_id: state.id, + state_entry_capture_order: this.#snapshot.state_entry_capture_order, + }; + this.#stateTimer = this.#timerHost.schedule( + () => this.enqueue({ kind: "state_deadline", ...identity }), + state.deadline_ms, + ); + } + + #clearTimers(): void { + this.#stateTimer?.cancel(); + this.#scenarioTimer?.cancel(); + this.#stateTimer = undefined; + this.#scenarioTimer = undefined; + } +} diff --git a/src/application/ProcessReactiveEffects.ts b/src/application/ProcessReactiveEffects.ts new file mode 100644 index 000000000..725673233 --- /dev/null +++ b/src/application/ProcessReactiveEffects.ts @@ -0,0 +1,226 @@ +import type { + FilesystemCheckpoint, + InteractionEvent, +} from "../domain/processCapture.js"; +import { createProcessObservation } from "../domain/processObservation.js"; +import type { ProcessReactiveEffectResult } from "../domain/processReactiveRuntime.js"; +import type { + ProcessReactiveAction, + ProcessReactiveScenario, +} from "../domain/processReactiveScenario.js"; +import type { ProcessCaptureJournal } from "./ProcessCaptureJournal.js"; + +/** Minimal PTY authority used by the admitted reactive action slice. */ +export interface ProcessReactiveTerminal { + write(data: string): void; + resize(columns: number, rows: number): void; + kill(signal: "SIGINT" | "SIGTERM" | "SIGKILL"): void; +} + +/** Rendered-terminal resize seam kept in lockstep with the PTY. */ +export interface ProcessReactiveRenderer { + resize(columns: number, rows: number, atMs: number): void; +} + +/** Awaited filesystem checkpoint seam used by reactive effects. */ +export interface ProcessReactiveCheckpoints { + captureAndRead( + name: string, + signal?: AbortSignal, + ): Promise<{ + readonly index: number; + readonly checkpoint: FilesystemCheckpoint; + }>; +} + +/** Host dependencies for journal-backed reactive process actions. */ +export interface ProcessReactiveEffectHost { + readonly terminal: () => ProcessReactiveTerminal | undefined; + readonly renderer: ProcessReactiveRenderer; + readonly checkpoints: ProcessReactiveCheckpoints; + readonly interactions: InteractionEvent[]; + readonly journal: ProcessCaptureJournal; + readonly startedAtMs: number; + readonly now: () => number; +} + +const elapsed = (host: ProcessReactiveEffectHost): number => + Math.max(0, host.now() - host.startedAtMs); + +const interactionData = ( + action: Exclude, +): string => { + if (action.type === "send_input") + return action.sensitive + ? `` + : action.data; + if (action.type === "resize") + return `${String(action.columns)}x${String(action.rows)}`; + return action.signal; +}; + +const interactionType = ( + action: Exclude, +): InteractionEvent["type"] => { + if (action.type === "send_input") return "input"; + if (action.type === "resize") return "resize"; + return "signal"; +}; + +const performTerminalAction = ( + terminal: ProcessReactiveTerminal, + renderer: ProcessReactiveRenderer, + action: Exclude, + atMs: number, +): void => { + if (action.type === "send_input") terminal.write(action.data); + else if (action.type === "resize") { + terminal.resize(action.columns, action.rows); + renderer.resize(action.columns, action.rows, atMs); + } else terminal.kill(action.signal); +}; + +const recordInteraction = ( + host: ProcessReactiveEffectHost, + action: Exclude, + atMs: number, + outcome: InteractionEvent["outcome"], +): ProcessReactiveEffectResult => { + const index = host.interactions.length; + const event: InteractionEvent = { + sequence: index, + scheduled_at_ms: atMs, + dispatched_at_ms: atMs, + type: interactionType(action), + data: interactionData(action), + outcome, + }; + host.interactions.push(event); + const location = host.journal.record("interaction_events", index); + if (outcome !== "dispatched") return { status: "rejected" }; + return { + status: "succeeded", + observation: createProcessObservation({ + source: "interaction", + source_sequence: index, + captured_at_ms: atMs, + subject_id: null, + location, + payload: event, + }), + }; +}; + +const executeTerminalAction = ( + host: ProcessReactiveEffectHost, + action: Exclude, +): ProcessReactiveEffectResult => { + if (action.type === "send_signal" && action.target.kind !== "root") + return { status: "rejected" }; + const terminal = host.terminal(); + if (terminal === undefined) return { status: "target_lost" }; + const atMs = elapsed(host); + let outcome: InteractionEvent["outcome"] = "dispatched"; + try { + performTerminalAction(terminal, host.renderer, action, atMs); + } catch { + outcome = "failed"; + } + return recordInteraction(host, action, atMs, outcome); +}; + +const executeCheckpoint = async ( + host: ProcessReactiveEffectHost, + action: Extract, + signal: AbortSignal, +): Promise => { + try { + const { index, checkpoint } = await host.checkpoints.captureAndRead( + action.name, + signal, + ); + const location = host.journal.entries.findLast( + (entry) => + entry.collection === "filesystem_checkpoints" && entry.index === index, + ); + if (location === undefined) return { status: "rejected" }; + return { + status: "succeeded", + observation: createProcessObservation({ + source: "filesystem", + source_sequence: index, + captured_at_ms: checkpoint.at_ms, + subject_id: `checkpoint:${checkpoint.name}`, + location, + payload: checkpoint, + }), + }; + } catch { + return { status: "rejected" }; + } +}; + +/** Execute proposed effects in order and stop after the first failure. */ +export const executeProcessReactiveEffects = async ( + host: ProcessReactiveEffectHost, + actions: readonly ProcessReactiveAction[], + signal: AbortSignal, +): Promise => { + const results: ProcessReactiveEffectResult[] = []; + for (const action of actions) { + if (signal.aborted) return results; + const result = + action.type === "checkpoint" + ? await executeCheckpoint(host, action, signal) + : executeTerminalAction(host, action); + results.push(result); + if (result.status !== "succeeded") break; + } + return results; +}; + +const triggerSources = ( + trigger: ProcessReactiveScenario["states"][number]["on"][number]["when"], +): readonly string[] => { + if (trigger.kind === "terminal_text") return []; + if (trigger.kind === "event") + return ["terminal_raw", "interaction", "filesystem"].includes( + trigger.source, + ) + ? [] + : [trigger.source]; + return trigger.kind === "repeat" + ? triggerSources(trigger.trigger) + : trigger.triggers.flatMap(triggerSources); +}; + +/** Return unsupported sources, selectors, and checkpoint collisions pre-launch. */ +export const unsupportedProcessReactiveFeatures = ( + scenario: ProcessReactiveScenario, + reservedCheckpointNames: ReadonlySet = new Set([ + "before", + "after_settlement", + ]), +): readonly string[] => [ + ...scenario.states.flatMap((state) => + state.on.flatMap((transition) => + triggerSources(transition.when).map( + (source) => `${transition.id}:source:${source}`, + ), + ), + ), + ...scenario.states.flatMap((state) => + state.on.flatMap((transition) => + transition.actions.flatMap((action) => { + if (action.type === "send_signal" && action.target.kind !== "root") + return [`${transition.id}:target:${action.target.kind}`]; + if ( + action.type === "checkpoint" && + reservedCheckpointNames.has(action.name) + ) + return [`${transition.id}:checkpoint:${action.name}`]; + return []; + }), + ), + ), +]; diff --git a/src/application/ProcessReactiveObservations.ts b/src/application/ProcessReactiveObservations.ts new file mode 100644 index 000000000..affd4853b --- /dev/null +++ b/src/application/ProcessReactiveObservations.ts @@ -0,0 +1,35 @@ +import type { + ProcessCaptureEventJournalEntry, + TerminalFrame, +} from "../domain/processCapture.js"; +import { createProcessObservation } from "../domain/processObservation.js"; +import type { ProcessReactiveInput } from "../domain/processReactiveRuntime.js"; +import type { ProcessCaptureJournal } from "./ProcessCaptureJournal.js"; + +/** Non-blocking input seam implemented by the reactive coordinator. */ +export interface ProcessReactiveObservationSink { + enqueue(input: ProcessReactiveInput): void; +} + +/** Subscribe a reactive coordinator to normalized raw PTY journal records. */ +export const subscribeProcessReactiveTerminalObservations = (options: { + readonly journal: ProcessCaptureJournal; + readonly frames: readonly TerminalFrame[]; + readonly sink: ProcessReactiveObservationSink; +}): (() => void) => + options.journal.subscribe((entry: ProcessCaptureEventJournalEntry) => { + if (entry.collection !== "frames") return; + const frame = options.frames[entry.index]; + if (frame === undefined) return; + options.sink.enqueue({ + kind: "observation", + observation: createProcessObservation({ + source: "terminal_raw", + source_sequence: frame.sequence, + captured_at_ms: frame.at_ms, + subject_id: null, + location: entry, + payload: frame, + }), + }); + }); diff --git a/tests/processCapture.test.ts b/tests/processCapture.test.ts index 009667ec2..63d4e44ff 100644 --- a/tests/processCapture.test.ts +++ b/tests/processCapture.test.ts @@ -37,6 +37,7 @@ import { processCaptureSchema, validateProcessCapture, type ProcessCapture, + type ProcessCaptureEventJournalEntry, type ProcessExecutionPolicy, } from "../src/domain/processCapture.js"; @@ -493,12 +494,31 @@ describe("process capture domain", () => { 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); - journal.recordEvent("lifecycle", 1); + 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; diff --git a/tests/processReactiveCoordinator.test.ts b/tests/processReactiveCoordinator.test.ts new file mode 100644 index 000000000..b54b84b9b --- /dev/null +++ b/tests/processReactiveCoordinator.test.ts @@ -0,0 +1,501 @@ +import { describe, expect, it } from "vitest"; + +import { + ProcessReactiveCoordinator, + type ProcessReactiveTimerHost, +} from "../src/application/ProcessReactiveCoordinator.js"; +import { + executeProcessReactiveEffects, + unsupportedProcessReactiveFeatures, +} from "../src/application/ProcessReactiveEffects.js"; +import { createProcessCaptureJournal } from "../src/application/ProcessCaptureJournal.js"; +import { subscribeProcessReactiveTerminalObservations } from "../src/application/ProcessReactiveObservations.js"; +import type { + FilesystemCheckpoint, + InteractionEvent, + TerminalFrame, +} from "../src/domain/processCapture.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: 30_000, + states: [ + { + id: "starting", + max_visits: 1, + deadline_ms: 5_000, + 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: 5_000, + 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)}`), + 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 = subscribeProcessReactiveTerminalObservations({ + journal, + frames, + sink: coordinator, + }); + return { + coordinator, + frames, + interactions, + checkpoints, + journal, + terminalCalls, + timers: timers.scheduled, + setNow: (value: number) => (now = value), + unsubscribe, + }; +}; + +describe("process reactive coordinator", () => { + 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: 30_000, + states: [ + { + id: "ready", + max_visits: 1, + deadline_ms: 5_000, + 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: "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", + "kill:SIGINT", + ]); + expect(harness.interactions.map(({ data }) => data)).toEqual([ + "", + "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.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(5_000); + 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(); + }); + + 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( + (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); + }); + + 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(); + }); +});