feat(process): add reactive capture scenarios
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import type { ProcessScenario } from "../domain/processCapture.js";
|
||||
import type { LoopbackReplay } from "./LoopbackReplay.js";
|
||||
import type { CommandShimReplay } from "./CommandShimReplay.js";
|
||||
|
||||
interface ProcessCaptureEnvironmentOptions {
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly home: string;
|
||||
readonly replay: LoopbackReplay;
|
||||
readonly shimReplay: CommandShimReplay;
|
||||
readonly runId: string;
|
||||
}
|
||||
|
||||
/** Build the explicitly admitted environment for a captured process. */
|
||||
export const makeProcessCaptureEnvironment = (
|
||||
options: ProcessCaptureEnvironmentOptions,
|
||||
): Record<string, string> => {
|
||||
const { scenario, home, replay, shimReplay, runId } = options;
|
||||
const environment: Record<string, string> = {
|
||||
...scenario.environment,
|
||||
HOME: home,
|
||||
TERM: "xterm-256color",
|
||||
REA_PROCESS_RUN_ID: runId,
|
||||
};
|
||||
for (const name of scenario.inherit_environment) {
|
||||
const value = process.env[name];
|
||||
if (value !== undefined) environment[name] = value;
|
||||
}
|
||||
environment.REA_REPLAY_HTTP_URL = replay.httpUrl;
|
||||
environment.REA_REPLAY_WEBSOCKET_URL = replay.websocketUrl;
|
||||
environment.REA_SHIM_LEDGER_URL = shimReplay.url;
|
||||
// PATH is evidence-producing input. Inheriting the host PATH here would let
|
||||
// the authority and reconstruction probe different tools without recording
|
||||
// that difference. Scenarios must opt in through environment or
|
||||
// inherit_environment; deterministic shims always take precedence.
|
||||
environment.PATH = [shimReplay.binPath, environment.PATH ?? ""]
|
||||
.filter((part) => part.length > 0)
|
||||
.join(":");
|
||||
return environment;
|
||||
};
|
||||
@@ -71,6 +71,7 @@ interface CaptureResultOptions {
|
||||
};
|
||||
readonly samples: readonly ProcessSample[];
|
||||
readonly replay: LoopbackReplay;
|
||||
readonly reactiveRun: ProcessCapture["reactive_run"];
|
||||
readonly before: SnapshotResult;
|
||||
readonly after: SnapshotResult;
|
||||
readonly truncated: boolean;
|
||||
@@ -116,6 +117,7 @@ export const buildCaptureResult = (
|
||||
options.scenario,
|
||||
),
|
||||
replay_transitions: options.replay.transitions,
|
||||
reactive_run: options.reactiveRun,
|
||||
event_journal: options.eventJournal,
|
||||
files_before: options.before.files,
|
||||
files_after: options.after.files,
|
||||
|
||||
@@ -106,6 +106,12 @@ export class ProcessCheckpoints {
|
||||
this.#scheduleCapture(name, this.#signal);
|
||||
}
|
||||
|
||||
/** Read one committed checkpoint for synchronous journal projection. */
|
||||
at(index: number): FilesystemCheckpoint | undefined {
|
||||
const checkpoint = this.#captures[index];
|
||||
return checkpoint === undefined ? undefined : structuredClone(checkpoint);
|
||||
}
|
||||
|
||||
#scheduleCapture(name: string, signal: AbortSignal | undefined): void {
|
||||
if (this.#captured.has(name)) return;
|
||||
this.#captured.add(name);
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
ProcessCaptureError,
|
||||
processCaptureCancelled,
|
||||
} from "./ProcessCaptureError.js";
|
||||
|
||||
export { ProcessCaptureError } from "./ProcessCaptureError.js";
|
||||
import { startLoopbackReplay, type LoopbackReplay } from "./LoopbackReplay.js";
|
||||
import { startProcessSampler } from "./ProcessSampling.js";
|
||||
@@ -26,7 +25,10 @@ import {
|
||||
startCommandShimReplay,
|
||||
type CommandShimReplay,
|
||||
} from "./CommandShimReplay.js";
|
||||
import { normalizeProcessText } from "./ProcessNormalization.js";
|
||||
import {
|
||||
normalizeProcessShimEvent,
|
||||
normalizeProcessText,
|
||||
} from "./ProcessNormalization.js";
|
||||
import { selectCapturedProcessGroupIds } from "../process/ProcessOwnership.js";
|
||||
import {
|
||||
awaitTerminalExit,
|
||||
@@ -42,45 +44,17 @@ import { assertNotCancelled } from "./ProcessCaptureAuthority.js";
|
||||
import {
|
||||
createProcessCaptureJournal,
|
||||
scheduleScenarioInteractions,
|
||||
type ProcessCaptureJournal,
|
||||
} from "./ProcessCaptureJournal.js";
|
||||
|
||||
import {
|
||||
assertSupportedReactiveScenario,
|
||||
projectProcessReactiveRun,
|
||||
startProcessReactiveHarness,
|
||||
type ProcessReactiveHarness,
|
||||
} from "./ProcessReactiveHarness.js";
|
||||
import { makeProcessCaptureEnvironment } from "./ProcessCaptureEnvironment.js";
|
||||
export { probeProcessCaptureCapability } from "./ProcessCaptureCapability.js";
|
||||
|
||||
interface EnvironmentOptions {
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly home: string;
|
||||
readonly replay: LoopbackReplay;
|
||||
readonly shimReplay: CommandShimReplay;
|
||||
readonly runId: string;
|
||||
}
|
||||
|
||||
const makeEnvironment = (
|
||||
options: EnvironmentOptions,
|
||||
): Record<string, string> => {
|
||||
const { scenario, home, replay, shimReplay, runId } = options;
|
||||
const environment: Record<string, string> = {
|
||||
...scenario.environment,
|
||||
HOME: home,
|
||||
TERM: "xterm-256color",
|
||||
REA_PROCESS_RUN_ID: runId,
|
||||
};
|
||||
for (const name of scenario.inherit_environment) {
|
||||
const value = process.env[name];
|
||||
if (value !== undefined) environment[name] = value;
|
||||
}
|
||||
environment.REA_REPLAY_HTTP_URL = replay.httpUrl;
|
||||
environment.REA_REPLAY_WEBSOCKET_URL = replay.websocketUrl;
|
||||
environment.REA_SHIM_LEDGER_URL = shimReplay.url;
|
||||
// PATH is evidence-producing input. Inheriting the host PATH here would let
|
||||
// the authority and reconstruction probe different tools without recording
|
||||
// that difference. Scenarios must opt in through environment or
|
||||
// inherit_environment; deterministic shims always take precedence.
|
||||
environment.PATH = [shimReplay.binPath, environment.PATH ?? ""]
|
||||
.filter((part) => part.length > 0)
|
||||
.join(":");
|
||||
return environment;
|
||||
};
|
||||
|
||||
interface StartedCaptureRuntime {
|
||||
readonly replay: LoopbackReplay;
|
||||
readonly renderer: TerminalRenderer;
|
||||
@@ -92,6 +66,7 @@ interface StartedCaptureRuntime {
|
||||
readonly lastOutput: () => number;
|
||||
readonly framesTruncated: () => boolean;
|
||||
readonly stopSampler: () => Promise<{ readonly partial: boolean }>;
|
||||
readonly reactive: ProcessReactiveHarness | undefined;
|
||||
}
|
||||
|
||||
const cleanupFailedStartup = async (options: {
|
||||
@@ -136,7 +111,7 @@ const createTerminalRenderer = (
|
||||
recordEvent,
|
||||
});
|
||||
|
||||
const startCaptureRuntime = async (options: {
|
||||
interface StartCaptureRuntimeOptions {
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly home: string;
|
||||
readonly temporaryRoot: string;
|
||||
@@ -148,14 +123,29 @@ const startCaptureRuntime = async (options: {
|
||||
readonly timers: Set<NodeJS.Timeout>;
|
||||
readonly dispatchedEventIndexes: Set<number>;
|
||||
readonly recordEvent: RecordProcessCaptureEvent;
|
||||
readonly journal: ProcessCaptureJournal;
|
||||
readonly signal?: AbortSignal;
|
||||
}): Promise<StartedCaptureRuntime> => {
|
||||
}
|
||||
|
||||
const reactiveCapture = (
|
||||
options: StartCaptureRuntimeOptions,
|
||||
protocolEvents: () => LoopbackReplay["events"],
|
||||
): Parameters<typeof startProcessReactiveHarness>[0]["capture"] => ({
|
||||
...options,
|
||||
processSamples: options.samples,
|
||||
protocolEvents,
|
||||
});
|
||||
|
||||
const startCaptureRuntime = async (
|
||||
options: StartCaptureRuntimeOptions,
|
||||
): Promise<StartedCaptureRuntime> => {
|
||||
const { scenario } = options;
|
||||
let replay: LoopbackReplay | undefined;
|
||||
let renderer: TerminalRenderer | undefined;
|
||||
let checkpoints: ProcessCheckpoints | undefined;
|
||||
let shimReplay: CommandShimReplay | undefined;
|
||||
let terminal: IPty | undefined;
|
||||
let reactive: ProcessReactiveHarness | undefined;
|
||||
try {
|
||||
const { spawn } = await import("@lydell/node-pty");
|
||||
replay = await startLoopbackReplay(scenario, options.recordEvent);
|
||||
@@ -180,7 +170,7 @@ const startCaptureRuntime = async (options: {
|
||||
);
|
||||
terminal = spawn(scenario.executable, [...scenario.arguments], {
|
||||
cwd: scenario.working_directory,
|
||||
env: makeEnvironment({ ...options, replay, shimReplay }),
|
||||
env: makeProcessCaptureEnvironment({ ...options, replay, shimReplay }),
|
||||
cols: scenario.terminal.columns,
|
||||
rows: scenario.terminal.rows,
|
||||
name: "xterm-256color",
|
||||
@@ -193,6 +183,15 @@ const startCaptureRuntime = async (options: {
|
||||
renderer,
|
||||
checkpoints,
|
||||
});
|
||||
reactive = startProcessReactiveHarness({
|
||||
capture: reactiveCapture(options, () => replay?.events ?? []),
|
||||
scenario,
|
||||
terminal: () => terminal,
|
||||
renderer,
|
||||
checkpoints,
|
||||
shimReplay,
|
||||
started,
|
||||
});
|
||||
scheduleScenarioInteractions({
|
||||
...options,
|
||||
getTerminal: () => terminal,
|
||||
@@ -218,8 +217,11 @@ const startCaptureRuntime = async (options: {
|
||||
lastOutput: () => lastOutput,
|
||||
framesTruncated,
|
||||
stopSampler,
|
||||
reactive,
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
reactive?.unsubscribe();
|
||||
await reactive?.coordinator.close();
|
||||
return cleanupFailedStartup({
|
||||
cause,
|
||||
timers: options.timers,
|
||||
@@ -239,23 +241,14 @@ const normalizedShimEvents = (
|
||||
scenario: ProcessScenario,
|
||||
temporaryRoot: string,
|
||||
): ProcessCapture["shim_events"] =>
|
||||
runtime.shimReplay.events.map((event) => ({
|
||||
...event,
|
||||
arguments: event.arguments.map((argument) =>
|
||||
normalizeProcessText(
|
||||
argument,
|
||||
scenario,
|
||||
temporaryRoot,
|
||||
runtime.terminal.pid,
|
||||
),
|
||||
),
|
||||
working_directory: normalizeProcessText(
|
||||
event.working_directory,
|
||||
runtime.shimReplay.events.map((event) =>
|
||||
normalizeProcessShimEvent(
|
||||
event,
|
||||
scenario,
|
||||
temporaryRoot,
|
||||
runtime.terminal.pid,
|
||||
),
|
||||
}));
|
||||
);
|
||||
|
||||
const finishProcessRun = async (options: {
|
||||
readonly runtime: StartedCaptureRuntime | undefined;
|
||||
@@ -267,6 +260,7 @@ const finishProcessRun = async (options: {
|
||||
readonly capture: ProcessCapture | undefined;
|
||||
readonly executionFailure: unknown;
|
||||
}): Promise<ProcessCapture> => {
|
||||
options.runtime?.reactive?.unsubscribe();
|
||||
await options.stopSampler();
|
||||
const cleanupFailure = await releaseProcessResources({
|
||||
timers: options.timers,
|
||||
@@ -285,10 +279,16 @@ const finishProcessRun = async (options: {
|
||||
options.samples,
|
||||
),
|
||||
});
|
||||
if (cleanupFailure !== undefined)
|
||||
await options.runtime?.reactive?.coordinator.submit({
|
||||
kind: "cleanup_failed",
|
||||
});
|
||||
await options.runtime?.reactive?.coordinator.close();
|
||||
let { capture, executionFailure } = options;
|
||||
if (capture !== undefined) {
|
||||
capture = {
|
||||
...capture,
|
||||
reactive_run: projectProcessReactiveRun(options.runtime?.reactive),
|
||||
settlement: {
|
||||
...capture.settlement,
|
||||
cleanup_outcome:
|
||||
@@ -326,7 +326,17 @@ const completeCapture = async (options: {
|
||||
const { runtime, scenario } = options;
|
||||
runtime.checkpoints.trigger("root_exit");
|
||||
const { reason } = options.exit;
|
||||
if (reason === "cancelled") throw processCaptureCancelled();
|
||||
if (reason === "cancelled") {
|
||||
if (runtime.reactive !== undefined) {
|
||||
await runtime.reactive.coordinator.submit({ kind: "cancelled" });
|
||||
runtime.reactive.unsubscribe();
|
||||
}
|
||||
throw processCaptureCancelled();
|
||||
}
|
||||
if (runtime.reactive !== undefined) {
|
||||
await runtime.reactive.coordinator.submit({ kind: "target_lost" });
|
||||
runtime.reactive.unsubscribe();
|
||||
}
|
||||
const settlement = await observeSettlement(
|
||||
options.runId,
|
||||
selectCapturedProcessGroupIds(runtime.terminal.pid, options.samples),
|
||||
@@ -359,6 +369,7 @@ const completeCapture = async (options: {
|
||||
exit: { ...options.exit, reason },
|
||||
samples: options.samples,
|
||||
replay: runtime.replay,
|
||||
reactiveRun: projectProcessReactiveRun(runtime.reactive),
|
||||
before: options.before,
|
||||
after,
|
||||
truncated,
|
||||
@@ -381,6 +392,7 @@ const runProcessScenario = async (
|
||||
policy: ProcessExecutionPolicy,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ProcessCapture> => {
|
||||
assertSupportedReactiveScenario(scenario);
|
||||
const { temporaryRoot, runId, home, before } = await prepareProcessCapture(
|
||||
scenario,
|
||||
policy,
|
||||
@@ -388,7 +400,8 @@ const runProcessScenario = async (
|
||||
);
|
||||
const frames: TerminalFrame[] = [];
|
||||
const samples: ProcessSample[] = [];
|
||||
const { entries: eventJournal, recordEvent } = createProcessCaptureJournal();
|
||||
const journal = createProcessCaptureJournal();
|
||||
const { entries: eventJournal, recordEvent } = journal;
|
||||
let runtime: StartedCaptureRuntime | undefined;
|
||||
const timers = new Set<NodeJS.Timeout>();
|
||||
let capture: ProcessCapture | undefined;
|
||||
@@ -410,6 +423,7 @@ const runProcessScenario = async (
|
||||
timers,
|
||||
dispatchedEventIndexes,
|
||||
recordEvent,
|
||||
journal,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
});
|
||||
stopSampler = runtime.stopSampler;
|
||||
|
||||
@@ -2,6 +2,7 @@ import type {
|
||||
ProcessCapture,
|
||||
ProcessSample,
|
||||
ProcessScenario,
|
||||
ShimEvent,
|
||||
} from "../domain/processCapture.js";
|
||||
|
||||
/** Bucket one elapsed process-capture timestamp under scenario normalization. */
|
||||
@@ -91,6 +92,25 @@ export const normalizeProcessSamples = (
|
||||
}));
|
||||
};
|
||||
|
||||
/** Normalize one shim observation identically for live matching and capture. */
|
||||
export const normalizeProcessShimEvent = (
|
||||
event: ShimEvent,
|
||||
scenario: ProcessScenario,
|
||||
temporaryRoot: string,
|
||||
rootPid: number,
|
||||
): ShimEvent => ({
|
||||
...event,
|
||||
arguments: event.arguments.map((argument) =>
|
||||
normalizeProcessText(argument, scenario, temporaryRoot, rootPid),
|
||||
),
|
||||
working_directory: normalizeProcessText(
|
||||
event.working_directory,
|
||||
scenario,
|
||||
temporaryRoot,
|
||||
rootPid,
|
||||
),
|
||||
});
|
||||
|
||||
const normalizePidTokens = (
|
||||
value: string,
|
||||
identifiers: readonly number[],
|
||||
|
||||
@@ -51,7 +51,7 @@ export class ProcessReactiveCoordinator {
|
||||
readonly #now: () => number;
|
||||
readonly #scenarioDeadlineAt: number;
|
||||
readonly #onDecision:
|
||||
| ((decision: ProcessReactiveDecision) => void)
|
||||
| ((decision: ProcessReactiveDecision, input: ProcessReactiveInput) => void)
|
||||
| undefined;
|
||||
#snapshot: ProcessReactiveSnapshot;
|
||||
readonly #pendingInputs: ProcessReactiveInput[] = [];
|
||||
@@ -70,7 +70,10 @@ export class ProcessReactiveCoordinator {
|
||||
readonly executor: ProcessReactiveExecutor;
|
||||
readonly timerHost?: ProcessReactiveTimerHost;
|
||||
readonly now?: () => number;
|
||||
readonly onDecision?: (decision: ProcessReactiveDecision) => void;
|
||||
readonly onDecision?: (
|
||||
decision: ProcessReactiveDecision,
|
||||
input: ProcessReactiveInput,
|
||||
) => void;
|
||||
}) {
|
||||
this.#scenario = options.scenario;
|
||||
this.#executor = options.executor;
|
||||
@@ -206,7 +209,7 @@ export class ProcessReactiveCoordinator {
|
||||
);
|
||||
}
|
||||
this.#snapshot = decision.snapshot;
|
||||
this.#onDecision?.(decision);
|
||||
this.#onDecision?.(decision, input);
|
||||
if (this.#snapshot.status === "finished") this.#clearTimers();
|
||||
else if (
|
||||
this.#accepting &&
|
||||
@@ -216,18 +219,35 @@ export class ProcessReactiveCoordinator {
|
||||
)
|
||||
this.#scheduleStateDeadline();
|
||||
for (const result of effectResults)
|
||||
if (result.status === "succeeded")
|
||||
if (
|
||||
result.status === "succeeded" &&
|
||||
!this.#hasObservation(result.observation.event_id)
|
||||
)
|
||||
this.#enqueueOwned({
|
||||
kind: "observation",
|
||||
observation: result.observation,
|
||||
});
|
||||
}
|
||||
|
||||
#hasObservation(eventId: string): boolean {
|
||||
return (
|
||||
this.#snapshot.observations.some(
|
||||
(observation) => observation.event_id === eventId,
|
||||
) ||
|
||||
this.#pendingInputs.some(
|
||||
(input) =>
|
||||
input.kind === "observation" &&
|
||||
input.observation.event_id === eventId,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#interruptsEffects(input: ProcessReactiveInput): boolean {
|
||||
if (
|
||||
input.kind === "cancelled" ||
|
||||
input.kind === "cleanup_failed" ||
|
||||
input.kind === "scenario_deadline"
|
||||
input.kind === "scenario_deadline" ||
|
||||
input.kind === "target_lost"
|
||||
)
|
||||
return true;
|
||||
return (
|
||||
|
||||
@@ -184,9 +184,15 @@ const triggerSources = (
|
||||
): readonly string[] => {
|
||||
if (trigger.kind === "terminal_text") return [];
|
||||
if (trigger.kind === "event")
|
||||
return ["terminal_raw", "interaction", "filesystem"].includes(
|
||||
trigger.source,
|
||||
)
|
||||
return [
|
||||
"terminal_raw",
|
||||
"interaction",
|
||||
"process",
|
||||
"filesystem",
|
||||
"http",
|
||||
"websocket",
|
||||
"shim",
|
||||
].includes(trigger.source)
|
||||
? []
|
||||
: [trigger.source];
|
||||
return trigger.kind === "repeat"
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import type { IPty } from "@lydell/node-pty";
|
||||
|
||||
import type {
|
||||
InteractionEvent,
|
||||
ProcessCapture,
|
||||
ProcessReactiveControlRecord,
|
||||
ProcessSample,
|
||||
ProcessScenario,
|
||||
ProtocolEvent,
|
||||
TerminalFrame,
|
||||
} from "../domain/processCapture.js";
|
||||
import type { ProcessReactiveInput } from "../domain/processReactiveRuntime.js";
|
||||
import { ProcessCaptureError } from "./ProcessCaptureError.js";
|
||||
import type { ProcessCaptureJournal } from "./ProcessCaptureJournal.js";
|
||||
import type { ProcessCheckpoints } from "./ProcessCheckpoints.js";
|
||||
import type { CommandShimReplay } from "./CommandShimReplay.js";
|
||||
import { ProcessReactiveCoordinator } from "./ProcessReactiveCoordinator.js";
|
||||
import {
|
||||
executeProcessReactiveEffects,
|
||||
unsupportedProcessReactiveFeatures,
|
||||
} from "./ProcessReactiveEffects.js";
|
||||
import { subscribeProcessReactiveObservations } from "./ProcessReactiveObservations.js";
|
||||
import {
|
||||
normalizeProcessSamples,
|
||||
normalizeProcessShimEvent,
|
||||
redactProtocolEvents,
|
||||
} from "./ProcessNormalization.js";
|
||||
import type { TerminalRenderer } from "./TerminalRenderer.js";
|
||||
|
||||
/** Coordinator and subscription owned by one live process capture. */
|
||||
export interface ProcessReactiveHarness {
|
||||
readonly coordinator: ProcessReactiveCoordinator;
|
||||
readonly controls: readonly ProcessReactiveControlRecord[];
|
||||
readonly unsubscribe: () => void;
|
||||
}
|
||||
|
||||
const controlKind = (
|
||||
input: ProcessReactiveInput,
|
||||
): ProcessReactiveControlRecord["kind"] | undefined =>
|
||||
input.kind === "observation" ? undefined : input.kind;
|
||||
|
||||
/** Reject reactive declarations the current process adapter cannot execute. */
|
||||
export const assertSupportedReactiveScenario = (
|
||||
scenario: ProcessScenario,
|
||||
): void => {
|
||||
if (scenario.reactive === null) return;
|
||||
const unsupported = unsupportedProcessReactiveFeatures(scenario.reactive);
|
||||
if (unsupported.length === 0) return;
|
||||
throw new ProcessCaptureError(
|
||||
`reactive scenario requests unsupported features: ${unsupported.join(", ")}`,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Attach the serialized reactive runtime once the target PID is available.
|
||||
*
|
||||
* Subscription replays journal entries admitted during launcher startup before
|
||||
* observing new records, so PID-dependent normalization cannot drop them.
|
||||
*/
|
||||
export const startProcessReactiveHarness = (options: {
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly terminal: () => IPty | undefined;
|
||||
readonly renderer: TerminalRenderer;
|
||||
readonly checkpoints: ProcessCheckpoints;
|
||||
readonly shimReplay: CommandShimReplay;
|
||||
readonly started: number;
|
||||
readonly capture: {
|
||||
readonly interactions: InteractionEvent[];
|
||||
readonly journal: ProcessCaptureJournal;
|
||||
readonly frames: readonly TerminalFrame[];
|
||||
readonly processSamples: readonly ProcessSample[];
|
||||
readonly protocolEvents: () => readonly ProtocolEvent[];
|
||||
readonly temporaryRoot: string;
|
||||
};
|
||||
}): ProcessReactiveHarness | undefined => {
|
||||
if (options.scenario.reactive === null) return undefined;
|
||||
const controls: ProcessReactiveControlRecord[] = [];
|
||||
const coordinator = new ProcessReactiveCoordinator({
|
||||
scenario: options.scenario.reactive,
|
||||
executor: {
|
||||
execute: (actions, signal) =>
|
||||
executeProcessReactiveEffects(
|
||||
{
|
||||
terminal: options.terminal,
|
||||
renderer: options.renderer,
|
||||
checkpoints: options.checkpoints,
|
||||
interactions: options.capture.interactions,
|
||||
journal: options.capture.journal,
|
||||
startedAtMs: options.started,
|
||||
now: Date.now,
|
||||
},
|
||||
actions,
|
||||
signal,
|
||||
),
|
||||
},
|
||||
onDecision: (decision, input) => {
|
||||
const kind = controlKind(input);
|
||||
if (kind === undefined || decision.kind !== "finished") return;
|
||||
controls.push({
|
||||
sequence: controls.length,
|
||||
kind,
|
||||
after_capture_order:
|
||||
decision.snapshot.observations.at(-1)?.capture_order ?? -1,
|
||||
});
|
||||
},
|
||||
});
|
||||
return {
|
||||
coordinator,
|
||||
controls,
|
||||
unsubscribe: subscribeProcessReactiveObservations({
|
||||
journal: options.capture.journal,
|
||||
frames: options.capture.frames,
|
||||
interactions: options.capture.interactions,
|
||||
checkpointAt: (index) => options.checkpoints.at(index),
|
||||
processSampleAt: (index) => {
|
||||
const rootPid = options.terminal()?.pid;
|
||||
return rootPid === undefined
|
||||
? undefined
|
||||
: normalizeProcessSamples(
|
||||
options.capture.processSamples,
|
||||
options.scenario,
|
||||
rootPid,
|
||||
)[index];
|
||||
},
|
||||
protocolEventAt: (index) =>
|
||||
redactProtocolEvents(
|
||||
options.capture.protocolEvents().slice(index, index + 1),
|
||||
options.scenario,
|
||||
)[0],
|
||||
shimEventAt: (index) => {
|
||||
const event = options.shimReplay.events[index];
|
||||
const rootPid = options.terminal()?.pid;
|
||||
return event === undefined || rootPid === undefined
|
||||
? undefined
|
||||
: normalizeProcessShimEvent(
|
||||
event,
|
||||
options.scenario,
|
||||
options.capture.temporaryRoot,
|
||||
rootPid,
|
||||
);
|
||||
},
|
||||
sink: coordinator,
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
/** Project internal reducer state into the stable Process Capture shape. */
|
||||
export const projectProcessReactiveRun = (
|
||||
harness: ProcessReactiveHarness | undefined,
|
||||
): ProcessCapture["reactive_run"] =>
|
||||
harness === undefined
|
||||
? null
|
||||
: {
|
||||
status: harness.coordinator.snapshot.status,
|
||||
outcome: harness.coordinator.snapshot.outcome,
|
||||
active_state: harness.coordinator.snapshot.active_state,
|
||||
transitions: harness.coordinator.snapshot.transitions,
|
||||
controls: harness.controls,
|
||||
};
|
||||
@@ -1,8 +1,17 @@
|
||||
import type {
|
||||
InteractionEvent,
|
||||
FilesystemCheckpoint,
|
||||
ProcessCaptureEventJournalEntry,
|
||||
ProcessSample,
|
||||
ProtocolEvent,
|
||||
ShimEvent,
|
||||
TerminalFrame,
|
||||
} from "../domain/processCapture.js";
|
||||
import { createProcessObservation } from "../domain/processObservation.js";
|
||||
import {
|
||||
createProcessObservation,
|
||||
processObservationSubject,
|
||||
type ProcessObservation,
|
||||
} from "../domain/processObservation.js";
|
||||
import type { ProcessReactiveInput } from "../domain/processReactiveRuntime.js";
|
||||
import type { ProcessCaptureJournal } from "./ProcessCaptureJournal.js";
|
||||
|
||||
@@ -11,25 +20,145 @@ export interface ProcessReactiveObservationSink {
|
||||
enqueue(input: ProcessReactiveInput): void;
|
||||
}
|
||||
|
||||
/** Subscribe a reactive coordinator to normalized raw PTY journal records. */
|
||||
export const subscribeProcessReactiveTerminalObservations = (options: {
|
||||
interface ProcessReactiveObservationOptions {
|
||||
readonly journal: ProcessCaptureJournal;
|
||||
readonly frames: readonly TerminalFrame[];
|
||||
readonly interactions: readonly InteractionEvent[];
|
||||
readonly checkpointAt: (index: number) => FilesystemCheckpoint | undefined;
|
||||
readonly processSampleAt: (index: number) => ProcessSample | undefined;
|
||||
readonly protocolEventAt: (index: number) => ProtocolEvent | undefined;
|
||||
readonly shimEventAt: (index: number) => ShimEvent | undefined;
|
||||
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({
|
||||
}
|
||||
|
||||
const terminalObservation = (
|
||||
options: ProcessReactiveObservationOptions,
|
||||
entry: ProcessCaptureEventJournalEntry,
|
||||
): ProcessObservation | undefined => {
|
||||
const value = options.frames[entry.index];
|
||||
return value === undefined
|
||||
? undefined
|
||||
: createProcessObservation({
|
||||
source: "terminal_raw",
|
||||
source_sequence: frame.sequence,
|
||||
captured_at_ms: frame.at_ms,
|
||||
source_sequence: value.sequence,
|
||||
captured_at_ms: value.at_ms,
|
||||
subject_id: null,
|
||||
location: entry,
|
||||
payload: frame,
|
||||
}),
|
||||
});
|
||||
payload: value,
|
||||
});
|
||||
};
|
||||
|
||||
const interactionObservation = (
|
||||
options: ProcessReactiveObservationOptions,
|
||||
entry: ProcessCaptureEventJournalEntry,
|
||||
): ProcessObservation | undefined => {
|
||||
const value = options.interactions[entry.index];
|
||||
return value === undefined
|
||||
? undefined
|
||||
: createProcessObservation({
|
||||
source: "interaction",
|
||||
source_sequence: value.sequence,
|
||||
captured_at_ms: value.dispatched_at_ms,
|
||||
subject_id: null,
|
||||
location: entry,
|
||||
payload: value,
|
||||
});
|
||||
};
|
||||
|
||||
const filesystemObservation = (
|
||||
options: ProcessReactiveObservationOptions,
|
||||
entry: ProcessCaptureEventJournalEntry,
|
||||
): ProcessObservation | undefined => {
|
||||
const value = options.checkpointAt(entry.index);
|
||||
return value === undefined
|
||||
? undefined
|
||||
: createProcessObservation({
|
||||
source: "filesystem",
|
||||
source_sequence: entry.index,
|
||||
captured_at_ms: value.at_ms,
|
||||
subject_id: processObservationSubject("filesystem", value),
|
||||
location: entry,
|
||||
payload: value,
|
||||
});
|
||||
};
|
||||
|
||||
const processObservation = (
|
||||
options: ProcessReactiveObservationOptions,
|
||||
entry: ProcessCaptureEventJournalEntry,
|
||||
): ProcessObservation | undefined => {
|
||||
const value = options.processSampleAt(entry.index);
|
||||
return value === undefined
|
||||
? undefined
|
||||
: createProcessObservation({
|
||||
source: "process",
|
||||
source_sequence: entry.index,
|
||||
captured_at_ms: value.at_ms,
|
||||
subject_id: processObservationSubject("process", value),
|
||||
location: entry,
|
||||
payload: value,
|
||||
});
|
||||
};
|
||||
|
||||
const protocolObservation = (
|
||||
options: ProcessReactiveObservationOptions,
|
||||
entry: ProcessCaptureEventJournalEntry,
|
||||
): ProcessObservation | undefined => {
|
||||
const value = options.protocolEventAt(entry.index);
|
||||
return value === undefined
|
||||
? undefined
|
||||
: createProcessObservation({
|
||||
source: value.protocol,
|
||||
source_sequence: value.sequence,
|
||||
captured_at_ms: value.at_ms,
|
||||
subject_id: processObservationSubject(value.protocol, value),
|
||||
location: entry,
|
||||
payload: value,
|
||||
});
|
||||
};
|
||||
|
||||
const shimObservation = (
|
||||
options: ProcessReactiveObservationOptions,
|
||||
entry: ProcessCaptureEventJournalEntry,
|
||||
): ProcessObservation | undefined => {
|
||||
const normalized = options.shimEventAt(entry.index);
|
||||
if (normalized === undefined) return undefined;
|
||||
return createProcessObservation({
|
||||
source: "shim",
|
||||
source_sequence: normalized.sequence,
|
||||
captured_at_ms: normalized.at_ms,
|
||||
subject_id: processObservationSubject("shim", normalized),
|
||||
location: entry,
|
||||
payload: normalized,
|
||||
});
|
||||
};
|
||||
|
||||
const observationFor = (
|
||||
options: ProcessReactiveObservationOptions,
|
||||
entry: ProcessCaptureEventJournalEntry,
|
||||
): ProcessObservation | undefined => {
|
||||
if (entry.collection === "frames") return terminalObservation(options, entry);
|
||||
if (entry.collection === "interaction_events")
|
||||
return interactionObservation(options, entry);
|
||||
if (entry.collection === "filesystem_checkpoints")
|
||||
return filesystemObservation(options, entry);
|
||||
if (entry.collection === "process_samples")
|
||||
return processObservation(options, entry);
|
||||
if (entry.collection === "protocol_events")
|
||||
return protocolObservation(options, entry);
|
||||
if (entry.collection === "shim_events")
|
||||
return shimObservation(options, entry);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Subscribe the reactive coordinator to admitted normalized journal records. */
|
||||
export const subscribeProcessReactiveObservations = (
|
||||
options: ProcessReactiveObservationOptions,
|
||||
): (() => void) => {
|
||||
const enqueue = (entry: ProcessCaptureEventJournalEntry): void => {
|
||||
const observation = observationFor(options, entry);
|
||||
if (observation !== undefined)
|
||||
options.sink.enqueue({ kind: "observation", observation });
|
||||
};
|
||||
for (const entry of options.journal.entries) enqueue(entry);
|
||||
return options.journal.subscribe(enqueue);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user