feat(process): coordinate reactive capture effects
This commit is contained in:
@@ -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);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<readonly ProcessReactiveEffectResult[]>;
|
||||
}
|
||||
|
||||
/** 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<void> = 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<ProcessReactiveSnapshot> {
|
||||
this.enqueue(input);
|
||||
await this.drain();
|
||||
return this.#snapshot;
|
||||
}
|
||||
|
||||
/** Wait for currently queued reducer/effect work and surface host failures. */
|
||||
async drain(): Promise<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<ProcessReactiveAction, { readonly type: "checkpoint" }>,
|
||||
): string => {
|
||||
if (action.type === "send_input")
|
||||
return action.sensitive
|
||||
? `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`
|
||||
: action.data;
|
||||
if (action.type === "resize")
|
||||
return `${String(action.columns)}x${String(action.rows)}`;
|
||||
return action.signal;
|
||||
};
|
||||
|
||||
const interactionType = (
|
||||
action: Exclude<ProcessReactiveAction, { readonly type: "checkpoint" }>,
|
||||
): 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<ProcessReactiveAction, { readonly type: "checkpoint" }>,
|
||||
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<ProcessReactiveAction, { readonly type: "checkpoint" }>,
|
||||
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<ProcessReactiveAction, { readonly type: "checkpoint" }>,
|
||||
): 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<ProcessReactiveAction, { readonly type: "checkpoint" }>,
|
||||
signal: AbortSignal,
|
||||
): Promise<ProcessReactiveEffectResult> => {
|
||||
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<readonly ProcessReactiveEffectResult[]> => {
|
||||
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<string> = 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 [];
|
||||
}),
|
||||
),
|
||||
),
|
||||
];
|
||||
@@ -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,
|
||||
}),
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user