refactor(process): separate capture implementation from analyst workflows (#988)
* refactor(process): separate capture implementation from analyst workflows * fix(ci): generate source catalog before shard tests
This commit is contained in:
@@ -0,0 +1,127 @@
|
||||
import { fstatSync } from "node:fs";
|
||||
import {
|
||||
mkdtemp,
|
||||
lstat,
|
||||
open,
|
||||
readdir,
|
||||
rm,
|
||||
utimes,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { hashFile } from "./FilesystemSnapshot.js";
|
||||
|
||||
const countOpenDescriptorsFor = async (path: string): Promise<number> => {
|
||||
const directory = process.platform === "linux" ? "/proc/self/fd" : "/dev/fd";
|
||||
const expected = await lstat(path);
|
||||
const descriptors = await readdir(directory);
|
||||
const matches = await Promise.all(
|
||||
descriptors.map(async (descriptor) => {
|
||||
if (!/^\d+$/u.test(descriptor)) return false;
|
||||
try {
|
||||
const stats = fstatSync(Number(descriptor));
|
||||
return stats.dev === expected.dev && stats.ino === expected.ino;
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "EBADF")
|
||||
return false;
|
||||
throw cause;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return matches.filter(Boolean).length;
|
||||
};
|
||||
|
||||
it("does not hash a replacement file using the earlier path metadata", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-identity-"));
|
||||
const path = join(directory, "observed-file");
|
||||
try {
|
||||
await writeFile(path, "captured file\n");
|
||||
const expected = await lstat(path);
|
||||
await rm(path);
|
||||
await writeFile(path, "replacement with a different identity and size\n");
|
||||
|
||||
await expect(hashFile(path, expected, 1_000)).resolves.toBeNull();
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a same-size rewrite even when its modification time is restored", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-ctime-"));
|
||||
const path = join(directory, "observed-file");
|
||||
try {
|
||||
const fixedMtime = new Date("2020-01-02T03:04:05.000Z");
|
||||
await writeFile(path, "before\n");
|
||||
await utimes(path, fixedMtime, fixedMtime);
|
||||
const expected = await lstat(path);
|
||||
await expect
|
||||
.poll(async () => {
|
||||
await writeFile(path, "after!\n");
|
||||
await utimes(path, fixedMtime, fixedMtime);
|
||||
return (await lstat(path)).ctimeMs;
|
||||
})
|
||||
.not.toBe(expected.ctimeMs);
|
||||
const rewritten = await lstat(path);
|
||||
|
||||
expect(rewritten).toMatchObject({
|
||||
dev: expected.dev,
|
||||
ino: expected.ino,
|
||||
mode: expected.mode,
|
||||
size: expected.size,
|
||||
mtimeMs: expected.mtimeMs,
|
||||
});
|
||||
expect(rewritten.ctimeMs).not.toBe(expected.ctimeMs);
|
||||
|
||||
await expect(hashFile(path, expected, 1_000)).resolves.toBeNull();
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects cancellation for an empty file before returning its digest", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-empty-cancel-"));
|
||||
const path = join(directory, "observed-file");
|
||||
try {
|
||||
await writeFile(path, "");
|
||||
const expected = await lstat(path);
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
|
||||
await expect(
|
||||
hashFile(path, expected, 1_000, controller.signal),
|
||||
).rejects.toMatchObject({ name: "AbortError" });
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"closes the opened file when cancellation arrives during open",
|
||||
async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-cancel-"));
|
||||
const path = join(directory, "observed-file");
|
||||
try {
|
||||
await writeFile(path, "captured file\n");
|
||||
const expected = await lstat(path);
|
||||
const controller = new AbortController();
|
||||
const held = await open(path, "r");
|
||||
expect(await countOpenDescriptorsFor(path)).toBe(1);
|
||||
await held.close();
|
||||
expect(await countOpenDescriptorsFor(path)).toBe(0);
|
||||
const hashing = hashFile(path, expected, 1_000, controller.signal);
|
||||
// hashFile reaches `open` synchronously before its first suspension, so
|
||||
// this abort is observed after the descriptor is acquired and is handled
|
||||
// by the `finally` close path.
|
||||
controller.abort();
|
||||
|
||||
await expect(hashing).rejects.toMatchObject({ name: "AbortError" });
|
||||
expect(await countOpenDescriptorsFor(path)).toBe(0);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,175 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { lstat, open, readdir, readlink } from "node:fs/promises";
|
||||
import { dirname, join, relative, resolve } from "node:path";
|
||||
import type {
|
||||
FileState,
|
||||
ProcessScenario,
|
||||
} from "../../domain/process/processCapture.js";
|
||||
import type { Stats } from "node:fs";
|
||||
|
||||
export interface SnapshotResult {
|
||||
readonly files: readonly FileState[];
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
const hasSameIdentity = (
|
||||
before: Stats,
|
||||
after: Stats,
|
||||
expected: "directory" | "symlink",
|
||||
): boolean =>
|
||||
before.dev === after.dev &&
|
||||
before.ino === after.ino &&
|
||||
(expected === "directory" ? after.isDirectory() : after.isSymbolicLink());
|
||||
|
||||
const hasSameFileState = (before: Stats, after: Stats): boolean =>
|
||||
before.dev === after.dev &&
|
||||
before.ino === after.ino &&
|
||||
before.isFile() &&
|
||||
after.isFile() &&
|
||||
before.mode === after.mode &&
|
||||
before.size === after.size &&
|
||||
before.mtimeMs === after.mtimeMs &&
|
||||
before.ctimeMs === after.ctimeMs;
|
||||
|
||||
const lstatIfPresent = async (path: string): Promise<Stats | undefined> => {
|
||||
try {
|
||||
return await lstat(path);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
||||
return undefined;
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
/** Hash a file only when its opened descriptor still matches the captured path state. */
|
||||
export const hashFile = async (
|
||||
path: string,
|
||||
expected: Stats,
|
||||
maxBytes: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string | null> => {
|
||||
signal?.throwIfAborted();
|
||||
const handle = await open(
|
||||
path,
|
||||
fsConstants.O_RDONLY |
|
||||
(fsConstants.O_NOFOLLOW ?? 0) |
|
||||
(fsConstants.O_NONBLOCK ?? 0),
|
||||
);
|
||||
try {
|
||||
signal?.throwIfAborted();
|
||||
const stats = await handle.stat();
|
||||
signal?.throwIfAborted();
|
||||
if (!hasSameFileState(expected, stats) || stats.size > maxBytes)
|
||||
return null;
|
||||
const hash = createHash("sha256");
|
||||
const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes));
|
||||
let position = 0;
|
||||
while (position < stats.size) {
|
||||
signal?.throwIfAborted();
|
||||
const { bytesRead } = await handle.read(
|
||||
buffer,
|
||||
0,
|
||||
Math.min(buffer.length, stats.size - position),
|
||||
position,
|
||||
);
|
||||
if (bytesRead === 0) return null;
|
||||
hash.update(buffer.subarray(0, bytesRead));
|
||||
position += bytesRead;
|
||||
}
|
||||
const after = await handle.stat();
|
||||
signal?.throwIfAborted();
|
||||
if (!hasSameFileState(stats, after)) return null;
|
||||
return hash.digest("hex");
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
};
|
||||
|
||||
/** Capture bounded, root-aliased filesystem state without following symlinks. */
|
||||
export const snapshotRoots = async (
|
||||
scenario: ProcessScenario,
|
||||
signal?: AbortSignal,
|
||||
): Promise<SnapshotResult> => {
|
||||
const entries: FileState[] = [];
|
||||
let remainingBytes = scenario.limits.file_bytes;
|
||||
let truncated = false;
|
||||
const visit = async (
|
||||
root: string,
|
||||
rootAlias: string,
|
||||
path: string,
|
||||
depth: number,
|
||||
): Promise<void> => {
|
||||
signal?.throwIfAborted();
|
||||
if (
|
||||
entries.length >= scenario.limits.files ||
|
||||
depth > scenario.limits.filesystem_depth
|
||||
) {
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
const stats = await lstatIfPresent(path);
|
||||
if (stats === undefined) return;
|
||||
const relativePath = relative(root, path) || ".";
|
||||
if (stats.isSymbolicLink()) {
|
||||
const target = resolve(dirname(path), await readlink(path));
|
||||
const afterRead = await lstat(path);
|
||||
if (!hasSameIdentity(stats, afterRead, "symlink")) {
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
entries.push({
|
||||
path: `${rootAlias}:${relativePath}`,
|
||||
type: "symlink",
|
||||
mode: stats.mode,
|
||||
size: stats.size,
|
||||
sha256: null,
|
||||
symlink_target: target,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (stats.isFile()) {
|
||||
const sha256 =
|
||||
remainingBytes >= stats.size
|
||||
? await hashFile(path, stats, remainingBytes, signal)
|
||||
: null;
|
||||
remainingBytes -= sha256 === null ? 0 : stats.size;
|
||||
if (sha256 === null) truncated = true;
|
||||
entries.push({
|
||||
path: `${rootAlias}:${relativePath}`,
|
||||
type: "file",
|
||||
mode: stats.mode,
|
||||
size: stats.size,
|
||||
sha256,
|
||||
symlink_target: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const type = stats.isDirectory() ? "directory" : "other";
|
||||
entries.push({
|
||||
path: `${rootAlias}:${relativePath}`,
|
||||
type,
|
||||
mode: stats.mode,
|
||||
size: stats.size,
|
||||
sha256: null,
|
||||
symlink_target: null,
|
||||
});
|
||||
if (type !== "directory") return;
|
||||
const children = await readdir(path);
|
||||
const afterRead = await lstat(path);
|
||||
if (!hasSameIdentity(stats, afterRead, "directory")) {
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
for (const child of children.sort())
|
||||
await visit(root, rootAlias, join(path, child), depth + 1);
|
||||
};
|
||||
for (const [index, root] of scenario.filesystem_observation_paths.entries()) {
|
||||
if ((await lstatIfPresent(root)) === undefined) {
|
||||
truncated = true;
|
||||
continue;
|
||||
}
|
||||
await visit(root, `root_${String(index)}`, root, 0);
|
||||
}
|
||||
return { files: entries, truncated };
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
export type ProcessCaptureCapability =
|
||||
| { readonly available: true; readonly backend: "node-pty" }
|
||||
| {
|
||||
readonly available: false;
|
||||
readonly backend: "node-pty";
|
||||
readonly reason: string;
|
||||
};
|
||||
|
||||
/** Explain why process capture cannot claim owned-process cleanup on a host. */
|
||||
export const processCaptureOwnershipUnavailableReason = (
|
||||
platform: NodeJS.Platform,
|
||||
): string | undefined =>
|
||||
platform === "win32"
|
||||
? "Windows PTY process capture is unavailable because this adapter does not yet verify descendant cleanup. Use Linux (including WSL for Linux commands) or macOS. Reinstalling the PTY backend does not enable native Windows capture."
|
||||
: undefined;
|
||||
|
||||
/** Dependencies that make the native PTY probe's host boundary testable. */
|
||||
export interface ProcessCaptureProbeOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly loadPty?: () => Promise<typeof import("@lydell/node-pty")>;
|
||||
}
|
||||
|
||||
/** Probe the native PTY seam and explain loader failures at their source. */
|
||||
export const processCaptureProbeFailureReason = (cause: unknown): string => {
|
||||
const error = cause instanceof Error ? cause : new Error(String(cause));
|
||||
const code = "code" in error ? String(error.code) : "";
|
||||
const diagnostic = error.message;
|
||||
if (
|
||||
code === "ERR_MODULE_NOT_FOUND" ||
|
||||
code === "MODULE_NOT_FOUND" ||
|
||||
/cannot find module|cannot find package/iu.test(diagnostic)
|
||||
)
|
||||
return `the native PTY module is missing (${diagnostic}); reinstall REA for this host with optional dependencies enabled (for a source checkout, run npm ci)`;
|
||||
if (
|
||||
/NODE_MODULE_VERSION|compiled against a different Node\.js version|module version mismatch/iu.test(
|
||||
diagnostic,
|
||||
)
|
||||
)
|
||||
return `the native PTY module is incompatible with this Node.js runtime (${diagnostic}); reinstall REA for this host and active Node.js version with optional dependencies enabled (for a source checkout, run npm ci after selecting that Node.js version)`;
|
||||
if (code === "ERR_DLOPEN_FAILED")
|
||||
return `the native PTY library failed to load (${diagnostic}); check the loader error, then reinstall REA for this host with optional dependencies enabled (for a source checkout, run npm ci)`;
|
||||
return `the native PTY probe failed (${diagnostic}); check the reported operating-system or process-startup error and reinstall REA for this host with optional dependencies enabled if the native binary is missing`;
|
||||
};
|
||||
|
||||
/** Probe the actual native PTY seam instead of inferring support from the OS name. */
|
||||
export const probeProcessCaptureCapability = async (
|
||||
options: ProcessCaptureProbeOptions = {},
|
||||
): Promise<ProcessCaptureCapability> => {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const ownershipReason = processCaptureOwnershipUnavailableReason(platform);
|
||||
if (ownershipReason !== undefined)
|
||||
return {
|
||||
available: false,
|
||||
backend: "node-pty",
|
||||
reason: ownershipReason,
|
||||
};
|
||||
try {
|
||||
const { spawn } = await (
|
||||
options.loadPty ?? (() => import("@lydell/node-pty"))
|
||||
)();
|
||||
const terminal = spawn(
|
||||
platform === "win32" ? "cmd.exe" : "/bin/sh",
|
||||
platform === "win32" ? ["/c", "exit", "0"] : ["-c", "exit 0"],
|
||||
{
|
||||
cwd: tmpdir(),
|
||||
env: { HOME: tmpdir(), TERM: "xterm-256color" },
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
name: "xterm-256color",
|
||||
},
|
||||
);
|
||||
await new Promise<void>((resolveExit) =>
|
||||
terminal.onExit(() => resolveExit()),
|
||||
);
|
||||
return { available: true, backend: "node-pty" };
|
||||
} catch (cause: unknown) {
|
||||
return {
|
||||
available: false,
|
||||
backend: "node-pty",
|
||||
reason: processCaptureProbeFailureReason(cause),
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { ProcessScenario } from "../../domain/process/processCapture.js";
|
||||
|
||||
interface ProcessCaptureEnvironmentOptions {
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly runId: string;
|
||||
readonly hostEnvironment: Readonly<Record<string, string | undefined>>;
|
||||
}
|
||||
|
||||
/** Build the child environment from the host plus caller-selected overrides. */
|
||||
export const makeProcessCaptureEnvironment = (
|
||||
options: ProcessCaptureEnvironmentOptions,
|
||||
): Record<string, string> => ({
|
||||
...Object.fromEntries(
|
||||
Object.entries(options.hostEnvironment).filter(
|
||||
(entry): entry is [string, string] => entry[1] !== undefined,
|
||||
),
|
||||
),
|
||||
...options.scenario.environment,
|
||||
TERM:
|
||||
options.scenario.environment.TERM ??
|
||||
options.hostEnvironment.TERM ??
|
||||
"xterm-256color",
|
||||
REA_PROCESS_RUN_ID: options.runId,
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
import {
|
||||
ProcessCaptureError,
|
||||
processCaptureCancelled,
|
||||
} from "./ProcessCaptureError.js";
|
||||
|
||||
describe("process capture error projection", () => {
|
||||
it("reports incomplete cleanup resources without exposing its cause", () => {
|
||||
const projected = projectAnalysisError(
|
||||
new ProcessCaptureError("terminal cleanup failed", {
|
||||
cause: new Error("secret-token"),
|
||||
reason: "cleanup_incomplete",
|
||||
cleanupResources: ["process_group"],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(projected).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: { cleanup: "incomplete", resources: ["process_group"] },
|
||||
});
|
||||
expect(JSON.stringify(projected)).not.toContain("secret-token");
|
||||
});
|
||||
|
||||
it("projects caller cancellation as completed cleanup", () => {
|
||||
expect(projectAnalysisError(processCaptureCancelled())).toMatchObject({
|
||||
code: "cancelled",
|
||||
category: "cancelled",
|
||||
details: { operation: "process_capture", cleanup: "complete" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
|
||||
interface ProcessCaptureErrorOptions extends ErrorOptions {
|
||||
readonly userMessage?: string;
|
||||
readonly userCategory?: "cancelled";
|
||||
readonly reason?: "capture_failed" | "cleanup_incomplete" | "cancelled";
|
||||
readonly cleanupResources?: readonly string[];
|
||||
}
|
||||
|
||||
/** Typed application failure produced by controlled process capture. */
|
||||
export class ProcessCaptureError extends AnalysisError {
|
||||
readonly _tag = "ProcessCaptureError";
|
||||
|
||||
override readonly userMessage: string | undefined;
|
||||
override readonly userCategory: "cancelled" | undefined;
|
||||
readonly reason: NonNullable<ProcessCaptureErrorOptions["reason"]>;
|
||||
override readonly cleanupIncomplete: boolean;
|
||||
override readonly cleanupResources: readonly string[];
|
||||
|
||||
constructor(message: string, options?: ProcessCaptureErrorOptions) {
|
||||
super(message, options);
|
||||
this.userMessage = options?.userMessage;
|
||||
this.userCategory = options?.userCategory;
|
||||
this.reason =
|
||||
options?.reason ??
|
||||
(options?.userCategory === "cancelled" ? "cancelled" : "capture_failed");
|
||||
this.cleanupIncomplete = this.reason === "cleanup_incomplete";
|
||||
this.cleanupResources = options?.cleanupResources ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Caller-visible cancellation without exposing capture implementation state. */
|
||||
export const processCaptureCancelled = (): ProcessCaptureError =>
|
||||
new ProcessCaptureError("process capture was cancelled", {
|
||||
userCategory: "cancelled",
|
||||
reason: "cancelled",
|
||||
userMessage: "Process capture was cancelled. Start it again when ready.",
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createProcessCaptureJournal } from "./ProcessCaptureJournal.js";
|
||||
|
||||
it("records capture events in monotonic observation order", () => {
|
||||
const journal = createProcessCaptureJournal();
|
||||
journal.recordEvent("filesystem_checkpoints", 0);
|
||||
journal.recordEvent("lifecycle", 0);
|
||||
journal.recordEvent("frames", 0);
|
||||
journal.recordEvent("filesystem_checkpoints", 1);
|
||||
|
||||
expect(journal.entries).toEqual([
|
||||
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
|
||||
{ capture_order: 1, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 2, collection: "frames", index: 0 },
|
||||
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import type { IPty } from "@lydell/node-pty";
|
||||
|
||||
import type {
|
||||
InteractionEvent,
|
||||
ProcessCaptureEventJournalEntry,
|
||||
ProcessScenario,
|
||||
RecordProcessCaptureEvent,
|
||||
} from "../../domain/process/processCapture.js";
|
||||
import {
|
||||
normalizeProcessElapsedTime,
|
||||
normalizeProcessText,
|
||||
} from "./ProcessNormalization.js";
|
||||
import type { TerminalRenderer } from "./TerminalRenderer.js";
|
||||
import { scheduleProcessDelay, type ProcessTimer } from "./ProcessTimer.js";
|
||||
|
||||
/** Mutable observation-order ledger whose writer is shared by capture producers. */
|
||||
export interface ProcessCaptureJournal {
|
||||
readonly entries: readonly ProcessCaptureEventJournalEntry[];
|
||||
readonly recordEvent: RecordProcessCaptureEvent;
|
||||
}
|
||||
|
||||
/** Create one monotonic event journal for a process capture. */
|
||||
export const createProcessCaptureJournal = (): ProcessCaptureJournal => {
|
||||
const entries: ProcessCaptureEventJournalEntry[] = [];
|
||||
const recordEvent: RecordProcessCaptureEvent = (
|
||||
collection: ProcessCaptureEventJournalEntry["collection"],
|
||||
index: number,
|
||||
): void => {
|
||||
entries.push({ capture_order: entries.length, collection, index });
|
||||
};
|
||||
return {
|
||||
entries,
|
||||
recordEvent,
|
||||
};
|
||||
};
|
||||
|
||||
interface ScenarioInteractionOptions {
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly getTerminal: () => IPty | undefined;
|
||||
readonly timers: Set<ProcessTimer>;
|
||||
readonly interactions: InteractionEvent[];
|
||||
readonly renderer: TerminalRenderer;
|
||||
readonly started: number;
|
||||
readonly dispatchedEventIndexes: Set<number>;
|
||||
readonly recordEvent: RecordProcessCaptureEvent;
|
||||
}
|
||||
|
||||
/** Schedule scenario interactions and record each observed dispatch atomically. */
|
||||
export const scheduleScenarioInteractions = (
|
||||
options: ScenarioInteractionOptions,
|
||||
): void => {
|
||||
const { scenario, getTerminal, timers, interactions, renderer, started } =
|
||||
options;
|
||||
for (const [eventIndex, event] of scenario.events.entries()) {
|
||||
const timer = scheduleProcessDelay(event.at_ms, () => {
|
||||
options.dispatchedEventIndexes.add(eventIndex);
|
||||
const terminal = getTerminal();
|
||||
const dispatchedAt = Math.max(0, Date.now() - started);
|
||||
let outcome: InteractionEvent["outcome"] = "dispatched";
|
||||
if (terminal === undefined) outcome = "target_exited";
|
||||
else {
|
||||
try {
|
||||
if (event.type === "input") terminal.write(event.data);
|
||||
else if (event.type === "resize") {
|
||||
terminal.resize(event.columns, event.rows);
|
||||
renderer.resize(
|
||||
event.columns,
|
||||
event.rows,
|
||||
normalizeProcessElapsedTime(
|
||||
dispatchedAt,
|
||||
scenario.normalization.time_bucket_ms,
|
||||
),
|
||||
);
|
||||
} else terminal.kill(event.signal);
|
||||
} catch (cause: unknown) {
|
||||
// Terminal dispatch failures are recorded as failed outcomes.
|
||||
void cause;
|
||||
outcome = "failed";
|
||||
}
|
||||
}
|
||||
const sequence = interactions.length;
|
||||
interactions.push({
|
||||
sequence,
|
||||
scheduled_at_ms: event.at_ms,
|
||||
dispatched_at_ms: dispatchedAt,
|
||||
type: event.type,
|
||||
data:
|
||||
event.type === "input"
|
||||
? event.sensitive
|
||||
? `<redacted-input:${String(Buffer.byteLength(event.data))}-bytes>`
|
||||
: normalizeProcessText(
|
||||
event.data,
|
||||
scenario,
|
||||
"<no-temporary-root>",
|
||||
-1,
|
||||
)
|
||||
: event.type === "resize"
|
||||
? `${String(event.columns)}x${String(event.rows)}`
|
||||
: event.signal,
|
||||
outcome,
|
||||
});
|
||||
options.recordEvent("interaction_events", sequence);
|
||||
});
|
||||
timers.add(timer);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,480 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { IPty } from "@lydell/node-pty";
|
||||
|
||||
import type {
|
||||
FilesystemCheckpoint,
|
||||
InteractionEvent,
|
||||
ProcessCapture,
|
||||
UnverifiedProcessCapture,
|
||||
ProcessSample,
|
||||
ProcessSettlement,
|
||||
ProcessScenario,
|
||||
ProcessCaptureEventJournalEntry,
|
||||
RecordProcessCaptureEvent,
|
||||
TerminalFrame,
|
||||
} from "../../domain/process/processCapture.js";
|
||||
import {
|
||||
digestProcessCommitment,
|
||||
processComparisonContract,
|
||||
processScenarioCommitment,
|
||||
} from "../../domain/process/processCapture.js";
|
||||
import { PRODUCT_IDENTITY } from "../../identity.js";
|
||||
import type { SnapshotResult } from "./FilesystemSnapshot.js";
|
||||
import { snapshotRoots } from "./FilesystemSnapshot.js";
|
||||
import { classifyFilesystemEffects } from "./ProcessFilesystemEffects.js";
|
||||
import { cleanupOwnedProcessGroup } from "../ProcessOwnership.js";
|
||||
import { observeOwnedProcessGroup } from "../ProcessOwnershipObservation.js";
|
||||
import { ProcessCaptureError } from "./ProcessCaptureError.js";
|
||||
import { assertNotCancelled } from "./ProcessScenarioRuntimeValidation.js";
|
||||
import {
|
||||
normalizeProcessElapsedTime,
|
||||
normalizeProcessSamples,
|
||||
normalizeProcessText,
|
||||
} from "./ProcessNormalization.js";
|
||||
import { PROCESS_PROVIDER } from "../../domain/process/processEvidenceProvider.js";
|
||||
import { TerminalRenderer } from "./TerminalRenderer.js";
|
||||
import { scheduleProcessInterval, type ProcessTimer } from "./ProcessTimer.js";
|
||||
|
||||
interface TerminalExitOptions {
|
||||
readonly terminal: IPty;
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly started: number;
|
||||
readonly lastOutput: () => number;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
readonly timers: Set<ProcessTimer>;
|
||||
readonly interactions: InteractionEvent[];
|
||||
readonly dispatchedEventIndexes: ReadonlySet<number>;
|
||||
readonly recordEvent: RecordProcessCaptureEvent;
|
||||
}
|
||||
|
||||
interface CaptureResultOptions {
|
||||
readonly frames: readonly TerminalFrame[];
|
||||
readonly exit: {
|
||||
readonly exitCode: number;
|
||||
readonly signal?: number;
|
||||
readonly reason: "exited" | "timeout" | "idle_timeout";
|
||||
};
|
||||
readonly samples: readonly ProcessSample[];
|
||||
readonly before: SnapshotResult;
|
||||
readonly after: SnapshotResult;
|
||||
readonly truncated: boolean;
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly rootPid: number;
|
||||
readonly samplingPartial: boolean;
|
||||
readonly renderedFrames: UnverifiedProcessCapture["rendered_frames"];
|
||||
readonly interactions: readonly InteractionEvent[];
|
||||
readonly checkpoints: readonly FilesystemCheckpoint[];
|
||||
readonly settlement: ObservedProcessSettlement;
|
||||
readonly manifest: UnverifiedProcessCapture["manifest"];
|
||||
readonly eventJournal: readonly ProcessCaptureEventJournalEntry[];
|
||||
}
|
||||
|
||||
/** Settlement observation before process-resource cleanup has completed. */
|
||||
export type ObservedProcessSettlement =
|
||||
| Pick<
|
||||
Extract<ProcessSettlement, { readonly state: "quiesced" }>,
|
||||
"state" | "elapsed_ms"
|
||||
>
|
||||
| Pick<
|
||||
Exclude<ProcessSettlement, { readonly state: "quiesced" }>,
|
||||
"state" | "elapsed_ms"
|
||||
>;
|
||||
|
||||
/** Capture observations before owned-resource cleanup has been verified. */
|
||||
export type PendingProcessCapture = Omit<
|
||||
UnverifiedProcessCapture,
|
||||
"cleanup" | "settlement"
|
||||
> & {
|
||||
readonly settlement: ObservedProcessSettlement;
|
||||
};
|
||||
|
||||
/** Wait for trailing PTY callbacks before the capture becomes immutable. */
|
||||
export const settleProcessCaptureJournal = async (
|
||||
journal: readonly ProcessCaptureEventJournalEntry[],
|
||||
quietMs = 25,
|
||||
maxWaitMs = 500,
|
||||
): Promise<void> => {
|
||||
const deadline = Date.now() + maxWaitMs;
|
||||
let observed = journal.length;
|
||||
let lastChangeAt = Date.now();
|
||||
while (Date.now() < deadline) {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 4));
|
||||
if (journal.length !== observed) {
|
||||
observed = journal.length;
|
||||
lastChangeAt = Date.now();
|
||||
} else if (Date.now() - lastChangeAt >= quietMs) return;
|
||||
}
|
||||
};
|
||||
|
||||
export const buildCaptureResult = (
|
||||
options: CaptureResultOptions,
|
||||
): PendingProcessCapture => {
|
||||
const hasSensitiveScriptedInput = options.scenario.events.some(
|
||||
(event) => event.type === "input" && event.sensitive,
|
||||
);
|
||||
const sensitiveInputUnknown =
|
||||
"Sensitive scripted input values are redacted from process capture Evidence.";
|
||||
const filesystemObservationUnknown =
|
||||
"No filesystem observation paths were selected; filesystem effects remain unknown.";
|
||||
const hasFilesystemObservations =
|
||||
options.scenario.filesystem_observation_paths.length > 0;
|
||||
return {
|
||||
manifest: options.manifest,
|
||||
normalization: options.scenario.normalization,
|
||||
frames: options.frames,
|
||||
rendered_frames: options.renderedFrames,
|
||||
interaction_events: options.interactions,
|
||||
exit: {
|
||||
code:
|
||||
options.exit.reason === "exited" && options.exit.exitCode >= 0
|
||||
? options.exit.exitCode
|
||||
: null,
|
||||
signal: options.exit.signal ?? null,
|
||||
reason: options.exit.reason,
|
||||
},
|
||||
settlement: options.settlement,
|
||||
process_samples: normalizeProcessSamples(
|
||||
options.samples,
|
||||
options.scenario,
|
||||
options.rootPid,
|
||||
),
|
||||
filesystem_checkpoints: options.checkpoints,
|
||||
event_journal: options.eventJournal,
|
||||
files_before: options.before.files,
|
||||
files_after: options.after.files,
|
||||
filesystem_effects: classifyFilesystemEffects(
|
||||
options.before.files,
|
||||
options.after.files,
|
||||
),
|
||||
truncated: options.truncated,
|
||||
limitations: [
|
||||
"Process trees are sampled and may omit short-lived descendants.",
|
||||
...(options.samplingPartial
|
||||
? ["Process-tree sampling ended with an incomplete observation."]
|
||||
: []),
|
||||
"Filesystem observations are before/after snapshots, not syscall traces.",
|
||||
"Inherited host environment variables are not recorded and may affect results.",
|
||||
...(!hasFilesystemObservations ? [filesystemObservationUnknown] : []),
|
||||
...(hasSensitiveScriptedInput ? [sensitiveInputUnknown] : []),
|
||||
],
|
||||
residual_unknowns: [
|
||||
{
|
||||
scope: "process",
|
||||
reason:
|
||||
"Process trees are sampled and may omit short-lived descendants.",
|
||||
},
|
||||
{
|
||||
scope: "environment",
|
||||
reason: "Inherited host environment variables are not recorded.",
|
||||
},
|
||||
{
|
||||
scope: "network",
|
||||
reason: "Network activity is not observed by this capture.",
|
||||
},
|
||||
...(!hasFilesystemObservations
|
||||
? [
|
||||
{
|
||||
scope: "filesystem" as const,
|
||||
reason: filesystemObservationUnknown,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasSensitiveScriptedInput
|
||||
? [{ scope: "interaction" as const, reason: sensitiveInputUnknown }]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const hashFile = async (path: string): Promise<string> => {
|
||||
const hash = createHash("sha256");
|
||||
for await (const chunk of createReadStream(path)) hash.update(chunk);
|
||||
return hash.digest("hex");
|
||||
};
|
||||
|
||||
export const createRunManifest = async (
|
||||
scenario: ProcessScenario,
|
||||
startedAt: Date,
|
||||
completedAt: Date,
|
||||
host: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly architecture: NodeJS.Architecture;
|
||||
} = {
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
},
|
||||
): Promise<UnverifiedProcessCapture["manifest"]> => {
|
||||
const executableSha256 = await hashFile(scenario.executable);
|
||||
const scenarioCommitment = processScenarioCommitment(
|
||||
scenario,
|
||||
executableSha256,
|
||||
);
|
||||
const comparisonContract = processComparisonContract(scenario);
|
||||
return {
|
||||
rea_version: PRODUCT_IDENTITY.packageVersion,
|
||||
provider_version: PROCESS_PROVIDER.version,
|
||||
platform: host.platform,
|
||||
architecture: host.architecture,
|
||||
pty_backend: "node-pty",
|
||||
started_at: startedAt.toISOString(),
|
||||
completed_at: completedAt.toISOString(),
|
||||
scenario: scenarioCommitment,
|
||||
comparison_contract: comparisonContract,
|
||||
full_scenario_sha256: digestProcessCommitment(scenarioCommitment),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: executableSha256,
|
||||
normalization_sha256: digestProcessCommitment(scenario.normalization),
|
||||
};
|
||||
};
|
||||
|
||||
export const observeSettlement = async (
|
||||
runId: string,
|
||||
processGroupIds: readonly number[],
|
||||
settleMs: number,
|
||||
recordEvent: RecordProcessCaptureEvent = () => undefined,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): Promise<ObservedProcessSettlement> => {
|
||||
if (platform === "win32") {
|
||||
recordEvent("lifecycle", 1);
|
||||
return { state: "unverifiable", elapsed_ms: 0 };
|
||||
}
|
||||
const started = Date.now();
|
||||
let consecutiveEmpty = 0;
|
||||
let deadlineReached = false;
|
||||
while (!deadlineReached) {
|
||||
const observations = await Promise.all(
|
||||
[...new Set(processGroupIds)].map((processGroupId) =>
|
||||
observeOwnedProcessGroup({
|
||||
runId,
|
||||
leaderPid: processGroupId,
|
||||
processGroupId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (observations.some(({ state }) => state === "unverifiable")) {
|
||||
recordEvent("lifecycle", 1);
|
||||
return { state: "unverifiable", elapsed_ms: Date.now() - started };
|
||||
}
|
||||
if (observations.every(({ state }) => state === "empty")) {
|
||||
consecutiveEmpty += 1;
|
||||
if (consecutiveEmpty >= 2) {
|
||||
recordEvent("lifecycle", 1);
|
||||
return { state: "quiesced", elapsed_ms: Date.now() - started };
|
||||
}
|
||||
} else consecutiveEmpty = 0;
|
||||
deadlineReached = Date.now() - started >= settleMs;
|
||||
if (deadlineReached) break;
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
recordEvent("lifecycle", 1);
|
||||
return { state: "alive_at_deadline", elapsed_ms: Date.now() - started };
|
||||
};
|
||||
|
||||
export const awaitTerminalExit = async ({
|
||||
terminal,
|
||||
scenario,
|
||||
started,
|
||||
lastOutput,
|
||||
signal,
|
||||
timers,
|
||||
interactions,
|
||||
dispatchedEventIndexes,
|
||||
recordEvent,
|
||||
}: TerminalExitOptions): Promise<{
|
||||
exitCode: number;
|
||||
signal?: number;
|
||||
reason: "exited" | "timeout" | "idle_timeout" | "cancelled";
|
||||
}> =>
|
||||
new Promise((resolveExit) => {
|
||||
// The kill caused by a deadline is observed later as an ordinary PTY exit.
|
||||
// Keep the initiating lifecycle reason so comparisons distinguish a target
|
||||
// exit from harness-owned timeout, idle-timeout, and cancellation cleanup.
|
||||
let reason: "exited" | "timeout" | "idle_timeout" | "cancelled" = "exited";
|
||||
terminal.onExit((exit) => {
|
||||
recordEvent("lifecycle", 0);
|
||||
for (const [eventIndex, event] of scenario.events.entries()) {
|
||||
if (dispatchedEventIndexes.has(eventIndex)) continue;
|
||||
const sequence = interactions.length;
|
||||
interactions.push({
|
||||
sequence,
|
||||
scheduled_at_ms: event.at_ms,
|
||||
dispatched_at_ms: Math.max(0, Date.now() - started),
|
||||
type: event.type,
|
||||
data:
|
||||
event.type === "input"
|
||||
? "<not-dispatched>"
|
||||
: event.type === "resize"
|
||||
? `${String(event.columns)}x${String(event.rows)}`
|
||||
: event.signal,
|
||||
outcome: "target_exited",
|
||||
});
|
||||
recordEvent("interaction_events", sequence);
|
||||
}
|
||||
for (const timer of timers) {
|
||||
timer.cancel();
|
||||
}
|
||||
timers.clear();
|
||||
resolveExit({ ...exit, reason });
|
||||
});
|
||||
const timeout = scheduleProcessInterval(() => {
|
||||
if (signal?.aborted === true) {
|
||||
reason = "cancelled";
|
||||
terminal.kill("SIGKILL");
|
||||
} else if (Date.now() - started >= scenario.timeout_ms) {
|
||||
reason = "timeout";
|
||||
terminal.kill("SIGKILL");
|
||||
} else if (Date.now() - lastOutput() >= scenario.idle_timeout_ms) {
|
||||
reason = "idle_timeout";
|
||||
terminal.kill("SIGKILL");
|
||||
}
|
||||
}, 20);
|
||||
timers.add(timeout);
|
||||
});
|
||||
|
||||
/** Host operations used when releasing one captured process run. */
|
||||
export interface ProcessCaptureCleanupHost {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly cleanupProcessGroup: typeof cleanupOwnedProcessGroup;
|
||||
readonly removeTemporaryRoot: (path: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const processCaptureCleanupHost: ProcessCaptureCleanupHost = {
|
||||
platform: process.platform,
|
||||
cleanupProcessGroup: cleanupOwnedProcessGroup,
|
||||
removeTemporaryRoot: (path) => rm(path, { recursive: true, force: true }),
|
||||
};
|
||||
|
||||
export const releaseProcessResources = async (options: {
|
||||
readonly timers: ReadonlySet<ProcessTimer>;
|
||||
readonly terminal: IPty | undefined;
|
||||
readonly renderer: TerminalRenderer | undefined;
|
||||
readonly runId: string;
|
||||
readonly temporaryRoot: string;
|
||||
readonly capturedProcessGroupIds: readonly number[];
|
||||
readonly host?: ProcessCaptureCleanupHost;
|
||||
}): Promise<string | undefined> => {
|
||||
const host = options.host ?? processCaptureCleanupHost;
|
||||
for (const timer of options.timers) timer.cancel();
|
||||
let failure: string | undefined;
|
||||
try {
|
||||
await options.renderer?.dispose();
|
||||
} catch (cause: unknown) {
|
||||
void cause;
|
||||
failure ??= "terminal renderer cleanup failed";
|
||||
}
|
||||
if (options.terminal !== undefined && host.platform !== "win32") {
|
||||
for (const processGroupId of new Set(options.capturedProcessGroupIds)) {
|
||||
const cleaned = await host.cleanupProcessGroup({
|
||||
runId: options.runId,
|
||||
leaderPid: processGroupId,
|
||||
processGroupId,
|
||||
});
|
||||
if (!cleaned.cleaned) failure ??= cleaned.reason;
|
||||
}
|
||||
}
|
||||
try {
|
||||
await host.removeTemporaryRoot(options.temporaryRoot);
|
||||
} catch (cause: unknown) {
|
||||
void cause;
|
||||
failure ??= "temporary process root cleanup failed";
|
||||
}
|
||||
return failure;
|
||||
};
|
||||
|
||||
export const captureTerminalFrames = (options: {
|
||||
readonly terminal: IPty;
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly frames: TerminalFrame[];
|
||||
readonly started: number;
|
||||
readonly temporaryRoot: string;
|
||||
readonly onOutput: () => void;
|
||||
readonly renderer: TerminalRenderer;
|
||||
readonly recordEvent: RecordProcessCaptureEvent;
|
||||
}): (() => boolean) => {
|
||||
let outputBytes = 0;
|
||||
let truncated = false;
|
||||
options.terminal.onData((data) => {
|
||||
options.onOutput();
|
||||
const bytes = Buffer.byteLength(data);
|
||||
if (outputBytes + bytes > options.scenario.limits.output_bytes) {
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
outputBytes += bytes;
|
||||
const atMs = normalizeProcessElapsedTime(
|
||||
Date.now() - options.started,
|
||||
options.scenario.normalization.time_bucket_ms,
|
||||
);
|
||||
const normalized = normalizeProcessText(
|
||||
data,
|
||||
options.scenario,
|
||||
options.temporaryRoot,
|
||||
options.terminal.pid,
|
||||
);
|
||||
const sequence = options.frames.length;
|
||||
options.frames.push({
|
||||
sequence,
|
||||
at_ms: atMs,
|
||||
data: normalized,
|
||||
});
|
||||
options.renderer.write(data, atMs);
|
||||
options.recordEvent("frames", sequence);
|
||||
});
|
||||
return () => truncated;
|
||||
};
|
||||
|
||||
export const resolveProcessResult = (
|
||||
capture: ProcessCapture | undefined,
|
||||
executionFailure: unknown,
|
||||
cleanupFailure: string | undefined,
|
||||
): ProcessCapture => {
|
||||
if (executionFailure instanceof ProcessCaptureError) throw executionFailure;
|
||||
if (executionFailure !== undefined)
|
||||
throw new ProcessCaptureError("process capture failed", {
|
||||
cause: executionFailure,
|
||||
});
|
||||
if (cleanupFailure !== undefined)
|
||||
throw new ProcessCaptureError(cleanupFailure, {
|
||||
reason: "cleanup_incomplete",
|
||||
});
|
||||
if (capture === undefined)
|
||||
throw new ProcessCaptureError("process capture produced no result");
|
||||
return capture;
|
||||
};
|
||||
|
||||
export const prepareProcessCapture = async (
|
||||
scenario: ProcessScenario,
|
||||
signal: AbortSignal | undefined,
|
||||
captureSnapshot: typeof snapshotRoots = snapshotRoots,
|
||||
host: ProcessPreparationHost = systemProcessPreparationHost,
|
||||
): Promise<{
|
||||
readonly temporaryRoot: string;
|
||||
readonly runId: string;
|
||||
readonly before: SnapshotResult;
|
||||
}> => {
|
||||
assertNotCancelled(signal);
|
||||
const before = await captureSnapshot(scenario, signal);
|
||||
const temporaryRoot = await host.createTemporaryRoot();
|
||||
try {
|
||||
const runId = randomUUID();
|
||||
return { temporaryRoot, runId, before };
|
||||
} catch (cause: unknown) {
|
||||
await host.cleanup(temporaryRoot);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
/** Filesystem seam for allocating and cleaning a capture's temporary root. */
|
||||
export interface ProcessPreparationHost {
|
||||
createTemporaryRoot(): Promise<string>;
|
||||
cleanup(path: string): Promise<void>;
|
||||
}
|
||||
|
||||
const systemProcessPreparationHost: ProcessPreparationHost = {
|
||||
createTemporaryRoot: () => mkdtemp(join(tmpdir(), "rea-process-")),
|
||||
cleanup: (path) => rm(path, { recursive: true, force: true }),
|
||||
};
|
||||
@@ -0,0 +1,294 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { snapshotRoots } from "./FilesystemSnapshot.js";
|
||||
import { buildCaptureResult } from "./ProcessCaptureLifecycle.js";
|
||||
import { normalizeProcessSamples } from "./ProcessNormalization.js";
|
||||
import { isInitializedPtyRoot, readLinuxChildren } from "./ProcessSampling.js";
|
||||
import { TerminalRenderer } from "./TerminalRenderer.js";
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
parseProcessCapture,
|
||||
parseProcessScenario,
|
||||
type ProcessCapture,
|
||||
} from "../../domain/process/processCapture.js";
|
||||
import { emptyProcessCapture as emptyCapture } from "../../domain/process/processCapture.fixture.js";
|
||||
|
||||
const base = {
|
||||
executable: "/bin/sh",
|
||||
working_directory: "/tmp",
|
||||
};
|
||||
|
||||
it("returns detached terminal observations", async () => {
|
||||
const observed: string[] = [];
|
||||
const renderer = new TerminalRenderer({
|
||||
columns: 40,
|
||||
rows: 12,
|
||||
scrollback: 100,
|
||||
maxBytes: 100_000,
|
||||
normalize: (value) => value,
|
||||
recordEvent: (collection, index) =>
|
||||
observed.push(`${collection}:${String(index)}`),
|
||||
});
|
||||
renderer.write("A", 20);
|
||||
renderer.resize(40, 12, 10);
|
||||
for (let index = 0; index < 20; index += 1)
|
||||
renderer.resize(40, 12, 11 + index);
|
||||
const frames = await renderer.frames();
|
||||
expect(frames).toHaveLength(22);
|
||||
expect(frames.slice(0, 2).map(({ at_ms }) => at_ms)).toEqual([20, 10]);
|
||||
expect(observed).toHaveLength(22);
|
||||
const frame = frames[0];
|
||||
if (frame === undefined) throw new Error("expected observed frame");
|
||||
const originalCursor = frame.cursor_x;
|
||||
Reflect.set(frame, "cursor_x", 999);
|
||||
const reread = await renderer.frames();
|
||||
expect(reread).toHaveLength(frames.length);
|
||||
expect(reread[0]?.cursor_x).toBe(originalCursor);
|
||||
await renderer.dispose();
|
||||
});
|
||||
|
||||
it("preserves rendered observation order instead of timestamp sorting", () => {
|
||||
const capture = emptyCapture();
|
||||
const renderedFrames: ProcessCapture["rendered_frames"] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 20,
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["first"],
|
||||
serialized_state: "first",
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["second"],
|
||||
serialized_state: "second",
|
||||
},
|
||||
];
|
||||
const result = buildCaptureResult({
|
||||
frames: [],
|
||||
exit: { exitCode: 0, reason: "exited" },
|
||||
samples: [],
|
||||
before: { files: [], truncated: false },
|
||||
after: { files: [], truncated: false },
|
||||
truncated: false,
|
||||
scenario: parseProcessScenario(base),
|
||||
rootPid: 1,
|
||||
samplingPartial: false,
|
||||
renderedFrames,
|
||||
interactions: [],
|
||||
checkpoints: capture.filesystem_checkpoints,
|
||||
settlement: {
|
||||
state: capture.settlement.state,
|
||||
elapsed_ms: capture.settlement.elapsed_ms,
|
||||
},
|
||||
manifest: capture.manifest,
|
||||
eventJournal: [],
|
||||
});
|
||||
|
||||
expect(result.rendered_frames).toEqual(renderedFrames);
|
||||
});
|
||||
|
||||
it("marks redacted scripted input as an interaction unknown", () => {
|
||||
const capture = emptyCapture();
|
||||
const result = buildCaptureResult({
|
||||
frames: [],
|
||||
exit: { exitCode: 0, reason: "exited" },
|
||||
samples: [],
|
||||
before: { files: [], truncated: false },
|
||||
after: { files: [], truncated: false },
|
||||
truncated: false,
|
||||
scenario: parseProcessScenario({
|
||||
...base,
|
||||
events: [{ type: "input", at_ms: 0, data: "secret", sensitive: true }],
|
||||
}),
|
||||
rootPid: 1,
|
||||
samplingPartial: false,
|
||||
renderedFrames: [],
|
||||
interactions: [
|
||||
{
|
||||
sequence: 0,
|
||||
scheduled_at_ms: 0,
|
||||
dispatched_at_ms: 0,
|
||||
type: "input",
|
||||
data: "<redacted-input:6-bytes>",
|
||||
outcome: "dispatched",
|
||||
},
|
||||
],
|
||||
checkpoints: capture.filesystem_checkpoints,
|
||||
settlement: {
|
||||
state: capture.settlement.state,
|
||||
elapsed_ms: capture.settlement.elapsed_ms,
|
||||
},
|
||||
manifest: capture.manifest,
|
||||
eventJournal: [],
|
||||
});
|
||||
|
||||
expect(result.residual_unknowns).toContainEqual({
|
||||
scope: "interaction",
|
||||
reason:
|
||||
"Sensitive scripted input values are redacted from process capture Evidence.",
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes every sampled process identifier in command text", () => {
|
||||
const samples = normalizeProcessSamples(
|
||||
[
|
||||
{
|
||||
at_ms: 0,
|
||||
pid: 101,
|
||||
parent_pid: 0,
|
||||
process_group_id: 101,
|
||||
session_id: 101,
|
||||
command: "root 101",
|
||||
},
|
||||
{
|
||||
at_ms: 10,
|
||||
pid: 202,
|
||||
parent_pid: 101,
|
||||
process_group_id: 101,
|
||||
session_id: 101,
|
||||
command: "child 202 peer=101 unrelated 1202",
|
||||
},
|
||||
],
|
||||
parseProcessScenario(base),
|
||||
101,
|
||||
);
|
||||
|
||||
expect(samples[1]?.command).toBe("child <pid> peer=<pid> unrelated 1202");
|
||||
});
|
||||
|
||||
it("collects and deduplicates children from every Linux thread", async () => {
|
||||
const signal = new AbortController().signal;
|
||||
expect(
|
||||
await readLinuxChildren(100, signal, {
|
||||
taskIds: () => Promise.resolve([100, 101, 102]),
|
||||
children: (_pid, taskId) =>
|
||||
Promise.resolve(
|
||||
taskId === 100 ? "201 202" : taskId === 101 ? "202 203" : "",
|
||||
),
|
||||
}),
|
||||
).toEqual([201, 202, 203]);
|
||||
});
|
||||
|
||||
it("admits PTY samples only after stable session and token setup", () => {
|
||||
const initialized = {
|
||||
pid: 100,
|
||||
parent_pid: 10,
|
||||
process_group_id: 100,
|
||||
session_id: 100,
|
||||
startTime: "200",
|
||||
};
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: { ...initialized, process_group_id: 10, session_id: 10 },
|
||||
observedRunId: undefined,
|
||||
after: initialized,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: initialized,
|
||||
observedRunId: "run-token",
|
||||
after: { ...initialized, startTime: "201" },
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: initialized,
|
||||
observedRunId: "run-token",
|
||||
after: initialized,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: { ...initialized, session_id: null },
|
||||
observedRunId: "run-token",
|
||||
after: { ...initialized, session_id: null },
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps interaction and process residual uncertainty in separate scopes", () => {
|
||||
const baseCapture = emptyCapture();
|
||||
const interaction = parseProcessCapture({
|
||||
...baseCapture,
|
||||
residual_unknowns: [
|
||||
{ scope: "interaction", reason: "Interaction capture was partial." },
|
||||
],
|
||||
});
|
||||
const process = parseProcessCapture({
|
||||
...baseCapture,
|
||||
residual_unknowns: [
|
||||
{ scope: "process", reason: "Process sampling was partial." },
|
||||
],
|
||||
});
|
||||
|
||||
expect(compareProcessCaptures(interaction, baseCapture)).toMatchObject({
|
||||
status: "unknown",
|
||||
terminal: "unchanged",
|
||||
interaction: "unknown",
|
||||
process: "unchanged",
|
||||
});
|
||||
expect(compareProcessCaptures(process, baseCapture)).toMatchObject({
|
||||
status: "unknown",
|
||||
terminal: "unchanged",
|
||||
interaction: "unchanged",
|
||||
process: "unknown",
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels filesystem snapshots before traversing declared roots", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(
|
||||
snapshotRoots(
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
filesystem_observation_paths: ["/tmp"],
|
||||
}),
|
||||
controller.signal,
|
||||
),
|
||||
).rejects.toMatchObject({ name: "AbortError" });
|
||||
});
|
||||
|
||||
it("parses bounded scenarios and rejects unordered events", () => {
|
||||
const timeoutMs = parseProcessScenario(base).timeout_ms;
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
events: [
|
||||
{ type: "input", at_ms: 2, data: "a" },
|
||||
{ type: "input", at_ms: 1, data: "b" },
|
||||
],
|
||||
}),
|
||||
).toThrow(/ordered/);
|
||||
expect(
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
environment: { HOME: "/caller-selected-home" },
|
||||
}).environment.HOME,
|
||||
).toBe("/caller-selected-home");
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
events: [{ type: "input", at_ms: timeoutMs + 1, data: "late" }],
|
||||
}),
|
||||
).toThrow(/after the scenario timeout/);
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import type {
|
||||
FileState,
|
||||
FilesystemCheckpoint,
|
||||
} from "../../domain/process/processCapture.js";
|
||||
|
||||
/** Classify path-stable filesystem effects between two bounded states. */
|
||||
export const classifyFilesystemEffects = (
|
||||
before: readonly FileState[],
|
||||
after: readonly FileState[],
|
||||
): FilesystemCheckpoint["effects"] => {
|
||||
const beforeByPath = new Map(before.map((file) => [file.path, file]));
|
||||
const afterByPath = new Map(after.map((file) => [file.path, file]));
|
||||
return [...new Set([...beforeByPath.keys(), ...afterByPath.keys()])]
|
||||
.sort()
|
||||
.map((path) => {
|
||||
const beforeFile = beforeByPath.get(path) ?? null;
|
||||
const afterFile = afterByPath.get(path) ?? null;
|
||||
if (beforeFile === null) {
|
||||
if (afterFile === null)
|
||||
throw new TypeError(`Filesystem effect ${path} has no file state`);
|
||||
return {
|
||||
path,
|
||||
status: "created",
|
||||
before: null,
|
||||
after: afterFile,
|
||||
} as const;
|
||||
}
|
||||
if (afterFile === null)
|
||||
return {
|
||||
path,
|
||||
status: "deleted",
|
||||
before: beforeFile,
|
||||
after: null,
|
||||
} as const;
|
||||
return {
|
||||
path,
|
||||
status:
|
||||
JSON.stringify(beforeFile) === JSON.stringify(afterFile)
|
||||
? "unchanged"
|
||||
: "modified",
|
||||
before: beforeFile,
|
||||
after: afterFile,
|
||||
} as const;
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { processScenarioSchema } from "../../domain/process/processScenario.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
|
||||
import { captureProcessScenario } from "./ProcessHarness.js";
|
||||
import { settleProcessCaptureJournal } from "./ProcessCaptureLifecycle.js";
|
||||
import { processCaptureSchema } from "../../domain/process/processCapture.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../domain/process/processCapture.fixture.js";
|
||||
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
|
||||
it("rejects legacy replay output instead of silently discarding it", () => {
|
||||
expect(
|
||||
processCaptureSchema.safeParse({
|
||||
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
protocol_events: [],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("waits for terminal observations delivered after the exit callback", async () => {
|
||||
const journal: Array<{
|
||||
capture_order: number;
|
||||
collection: "frames";
|
||||
index: number;
|
||||
}> = [{ capture_order: 0, collection: "frames", index: 0 }];
|
||||
const lateFrame = new Promise<void>((resolve) => {
|
||||
setTimeout(() => {
|
||||
journal.push({ capture_order: 1, collection: "frames", index: 1 });
|
||||
resolve();
|
||||
}, 12);
|
||||
});
|
||||
|
||||
let settled = false;
|
||||
const wait = settleProcessCaptureJournal(journal, 20, 200).then(() => {
|
||||
settled = true;
|
||||
});
|
||||
await lateFrame;
|
||||
expect(settled).toBe(false);
|
||||
await wait;
|
||||
|
||||
expect(journal).toHaveLength(2);
|
||||
expect(journal[1]).toMatchObject({ collection: "frames", index: 1 });
|
||||
});
|
||||
|
||||
it("fails closed on Windows before resolving or launching scenario paths", async () => {
|
||||
const scenario = processScenarioSchema.parse({
|
||||
executable: "Z:/missing/should-never-be-resolved.exe",
|
||||
working_directory: "Z:/missing/working-directory",
|
||||
});
|
||||
const result = await captureProcessScenario(scenario, undefined, "win32");
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected Windows ownership refusal");
|
||||
if (!(result.error instanceof AnalysisCapabilityUnavailableError))
|
||||
throw new Error("expected a capability-unavailable outcome");
|
||||
expect(result.error).toMatchObject({
|
||||
operation: "capture_process_scenario",
|
||||
reason: expect.stringContaining("Windows PTY process capture"),
|
||||
});
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "capability_unavailable",
|
||||
category: "unsupported_provider",
|
||||
message: expect.stringContaining("does not yet verify descendant cleanup"),
|
||||
details: {
|
||||
operation: "capture_process_scenario",
|
||||
reason: result.error.reason,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,457 @@
|
||||
import type { IPty } from "@lydell/node-pty";
|
||||
import type {
|
||||
InteractionEvent,
|
||||
ProcessCapture,
|
||||
UnverifiedProcessCapture,
|
||||
ProcessCaptureEventJournalEntry,
|
||||
ProcessSample,
|
||||
ProcessScenario,
|
||||
RecordProcessCaptureEvent,
|
||||
TerminalFrame,
|
||||
} from "../../domain/process/processCapture.js";
|
||||
import { parseProcessCapture } from "../../domain/process/processCapture.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
|
||||
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
ProcessCaptureError,
|
||||
processCaptureCancelled,
|
||||
} from "./ProcessCaptureError.js";
|
||||
export { ProcessCaptureError } from "./ProcessCaptureError.js";
|
||||
import { startProcessSampler } from "./ProcessSampling.js";
|
||||
import { snapshotRoots } from "./FilesystemSnapshot.js";
|
||||
import { TerminalRenderer } from "./TerminalRenderer.js";
|
||||
import type { ProcessTimer } from "./ProcessTimer.js";
|
||||
import { normalizeProcessText } from "./ProcessNormalization.js";
|
||||
import { selectCapturedProcessGroupIds } from "../ProcessOwnershipProcessTree.js";
|
||||
import {
|
||||
awaitTerminalExit,
|
||||
buildCaptureResult,
|
||||
captureTerminalFrames,
|
||||
createRunManifest,
|
||||
observeSettlement,
|
||||
prepareProcessCapture,
|
||||
releaseProcessResources,
|
||||
resolveProcessResult,
|
||||
settleProcessCaptureJournal,
|
||||
type PendingProcessCapture,
|
||||
} from "./ProcessCaptureLifecycle.js";
|
||||
import {
|
||||
assertNotCancelled,
|
||||
resolveProcessScenarioRuntimePaths,
|
||||
} from "./ProcessScenarioRuntimeValidation.js";
|
||||
import {
|
||||
createProcessCaptureJournal,
|
||||
scheduleScenarioInteractions,
|
||||
} from "./ProcessCaptureJournal.js";
|
||||
import { makeProcessCaptureEnvironment } from "./ProcessCaptureEnvironment.js";
|
||||
import { classifyFilesystemEffects } from "./ProcessFilesystemEffects.js";
|
||||
import { processCaptureOwnershipUnavailableReason } from "./ProcessCaptureCapability.js";
|
||||
export { probeProcessCaptureCapability } from "./ProcessCaptureCapability.js";
|
||||
|
||||
interface StartedCaptureRuntime {
|
||||
readonly renderer: TerminalRenderer;
|
||||
readonly terminal: IPty;
|
||||
readonly started: number;
|
||||
readonly startedAt: Date;
|
||||
readonly lastOutput: () => number;
|
||||
readonly framesTruncated: () => boolean;
|
||||
readonly stopSampler: () => Promise<{ readonly partial: boolean }>;
|
||||
}
|
||||
|
||||
const cleanupFailedStartup = async (options: {
|
||||
readonly cause: unknown;
|
||||
readonly timers: Set<ProcessTimer>;
|
||||
readonly terminal: IPty | undefined;
|
||||
readonly renderer: TerminalRenderer | undefined;
|
||||
readonly runId: string;
|
||||
readonly temporaryRoot: string;
|
||||
}): Promise<never> => {
|
||||
options.terminal?.kill("SIGKILL");
|
||||
const cleanupFailure = await releaseProcessResources({
|
||||
...options,
|
||||
capturedProcessGroupIds:
|
||||
options.terminal === undefined ? [] : [options.terminal.pid],
|
||||
});
|
||||
if (cleanupFailure !== undefined)
|
||||
throw new ProcessCaptureError(cleanupFailure, {
|
||||
cause: options.cause,
|
||||
reason: "cleanup_incomplete",
|
||||
});
|
||||
throw options.cause;
|
||||
};
|
||||
|
||||
const createTerminalRenderer = (
|
||||
scenario: ProcessScenario,
|
||||
temporaryRoot: string,
|
||||
terminalPid: () => number,
|
||||
recordEvent: RecordProcessCaptureEvent,
|
||||
): TerminalRenderer =>
|
||||
new TerminalRenderer({
|
||||
columns: scenario.terminal.columns,
|
||||
rows: scenario.terminal.rows,
|
||||
scrollback: scenario.terminal.scrollback,
|
||||
maxBytes: scenario.limits.output_bytes,
|
||||
normalize: (value) =>
|
||||
normalizeProcessText(value, scenario, temporaryRoot, terminalPid()),
|
||||
recordEvent,
|
||||
});
|
||||
|
||||
interface StartCaptureRuntimeOptions {
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly hostEnvironment: Readonly<Record<string, string | undefined>>;
|
||||
readonly temporaryRoot: string;
|
||||
readonly runId: string;
|
||||
readonly frames: TerminalFrame[];
|
||||
readonly samples: ProcessSample[];
|
||||
readonly interactions: InteractionEvent[];
|
||||
readonly timers: Set<ProcessTimer>;
|
||||
readonly dispatchedEventIndexes: Set<number>;
|
||||
readonly recordEvent: RecordProcessCaptureEvent;
|
||||
readonly signal?: AbortSignal;
|
||||
}
|
||||
|
||||
const startCaptureRuntime = async (
|
||||
options: StartCaptureRuntimeOptions,
|
||||
): Promise<StartedCaptureRuntime> => {
|
||||
const { scenario } = options;
|
||||
let renderer: TerminalRenderer | undefined;
|
||||
let terminal: IPty | undefined;
|
||||
try {
|
||||
const { spawn } = await import("@lydell/node-pty");
|
||||
const startedAt = new Date();
|
||||
const started = Date.now();
|
||||
let lastOutput = started;
|
||||
renderer = createTerminalRenderer(
|
||||
scenario,
|
||||
options.temporaryRoot,
|
||||
() => terminal?.pid ?? -1,
|
||||
options.recordEvent,
|
||||
);
|
||||
terminal = spawn(scenario.executable, [...scenario.arguments], {
|
||||
cwd: scenario.working_directory,
|
||||
env: makeProcessCaptureEnvironment(options),
|
||||
cols: scenario.terminal.columns,
|
||||
rows: scenario.terminal.rows,
|
||||
name: "xterm-256color",
|
||||
});
|
||||
const framesTruncated = captureTerminalFrames({
|
||||
...options,
|
||||
terminal,
|
||||
started,
|
||||
onOutput: () => (lastOutput = Date.now()),
|
||||
renderer,
|
||||
});
|
||||
scheduleScenarioInteractions({
|
||||
...options,
|
||||
getTerminal: () => terminal,
|
||||
renderer,
|
||||
started,
|
||||
});
|
||||
const stopSampler = startProcessSampler({
|
||||
rootPid: terminal.pid,
|
||||
runId: options.runId,
|
||||
started,
|
||||
limit: scenario.limits.processes,
|
||||
samples: options.samples,
|
||||
recordEvent: options.recordEvent,
|
||||
});
|
||||
return {
|
||||
renderer,
|
||||
terminal,
|
||||
started,
|
||||
startedAt,
|
||||
lastOutput: () => lastOutput,
|
||||
framesTruncated,
|
||||
stopSampler,
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
return cleanupFailedStartup({
|
||||
cause,
|
||||
timers: options.timers,
|
||||
terminal,
|
||||
renderer,
|
||||
runId: options.runId,
|
||||
temporaryRoot: options.temporaryRoot,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const finishProcessRun = async (options: {
|
||||
readonly runtime: StartedCaptureRuntime | undefined;
|
||||
readonly timers: Set<ProcessTimer>;
|
||||
readonly runId: string;
|
||||
readonly temporaryRoot: string;
|
||||
readonly samples: readonly ProcessSample[];
|
||||
readonly stopSampler: () => Promise<{ readonly partial: boolean }>;
|
||||
readonly capture: PendingProcessCapture | undefined;
|
||||
readonly executionFailure: unknown;
|
||||
}): Promise<ProcessCapture> => {
|
||||
await options.stopSampler();
|
||||
const cleanupFailure = await releaseProcessResources({
|
||||
timers: options.timers,
|
||||
terminal: options.runtime?.terminal,
|
||||
renderer: options.runtime?.renderer,
|
||||
runId: options.runId,
|
||||
temporaryRoot: options.temporaryRoot,
|
||||
capturedProcessGroupIds:
|
||||
options.runtime === undefined
|
||||
? []
|
||||
: selectCapturedProcessGroupIds(
|
||||
options.runtime.terminal.pid,
|
||||
options.samples,
|
||||
),
|
||||
});
|
||||
let { capture, executionFailure } = options;
|
||||
let verifiedCapture: ProcessCapture | undefined;
|
||||
if (capture !== undefined && cleanupFailure === undefined) {
|
||||
const settlement: UnverifiedProcessCapture["settlement"] =
|
||||
capture.settlement.state === "quiesced"
|
||||
? { ...capture.settlement, cleanup_outcome: "not_required" }
|
||||
: { ...capture.settlement, cleanup_outcome: "cleaned" };
|
||||
const completedCapture: UnverifiedProcessCapture = {
|
||||
...capture,
|
||||
settlement,
|
||||
cleanup: {
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
},
|
||||
};
|
||||
try {
|
||||
verifiedCapture = parseProcessCapture(completedCapture);
|
||||
} catch (cause: unknown) {
|
||||
executionFailure = new ProcessCaptureError(
|
||||
`process capture validation failed${cause instanceof Error ? `: ${cause.message}` : ""}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
return resolveProcessResult(
|
||||
verifiedCapture,
|
||||
executionFailure,
|
||||
cleanupFailure,
|
||||
);
|
||||
};
|
||||
|
||||
const normalizeCaptureFailure = (
|
||||
cause: unknown,
|
||||
signal: AbortSignal | undefined,
|
||||
): unknown => {
|
||||
if (cause instanceof ProcessCaptureError) return cause;
|
||||
if (
|
||||
signal?.aborted === true &&
|
||||
(cause === signal.reason ||
|
||||
(cause instanceof Error && cause.name === "AbortError"))
|
||||
)
|
||||
return processCaptureCancelled();
|
||||
return cause;
|
||||
};
|
||||
|
||||
const completeCapture = async (options: {
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly hostPlatform: NodeJS.Platform;
|
||||
readonly runtime: StartedCaptureRuntime;
|
||||
readonly runId: string;
|
||||
readonly temporaryRoot: string;
|
||||
readonly before: Awaited<ReturnType<typeof snapshotRoots>>;
|
||||
readonly frames: readonly TerminalFrame[];
|
||||
readonly samples: readonly ProcessSample[];
|
||||
readonly interactions: readonly InteractionEvent[];
|
||||
readonly exit: Awaited<ReturnType<typeof awaitTerminalExit>>;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly captureSnapshot: typeof snapshotRoots;
|
||||
readonly initiallyTruncated: boolean;
|
||||
readonly eventJournal: readonly ProcessCaptureEventJournalEntry[];
|
||||
readonly recordEvent: RecordProcessCaptureEvent;
|
||||
}): Promise<PendingProcessCapture> => {
|
||||
const { runtime, scenario } = options;
|
||||
const { reason } = options.exit;
|
||||
if (reason === "cancelled") throw processCaptureCancelled();
|
||||
const settlement = await observeSettlement(
|
||||
options.runId,
|
||||
selectCapturedProcessGroupIds(runtime.terminal.pid, options.samples),
|
||||
scenario.settle_ms,
|
||||
options.recordEvent,
|
||||
options.hostPlatform,
|
||||
);
|
||||
const samplingPartial = (await runtime.stopSampler()).partial;
|
||||
await settleProcessCaptureJournal(options.eventJournal);
|
||||
assertNotCancelled(options.signal);
|
||||
const after = await options.captureSnapshot(scenario, options.signal);
|
||||
options.recordEvent("filesystem_checkpoints", 1);
|
||||
const renderedFrames = await runtime.renderer.frames();
|
||||
const checkpoints: UnverifiedProcessCapture["filesystem_checkpoints"] = [
|
||||
{
|
||||
name: "before",
|
||||
at_ms: 0,
|
||||
files: options.before.files,
|
||||
effects: [],
|
||||
truncated: options.before.truncated,
|
||||
},
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: Math.max(0, Date.now() - runtime.started),
|
||||
files: after.files,
|
||||
effects: classifyFilesystemEffects(options.before.files, after.files),
|
||||
truncated: after.truncated,
|
||||
},
|
||||
];
|
||||
const manifest = await createRunManifest(
|
||||
scenario,
|
||||
runtime.startedAt,
|
||||
new Date(),
|
||||
{ platform: options.hostPlatform, architecture: process.arch },
|
||||
);
|
||||
const truncated =
|
||||
options.initiallyTruncated ||
|
||||
after.truncated ||
|
||||
runtime.framesTruncated() ||
|
||||
checkpoints.some(({ truncated: partial }) => partial) ||
|
||||
samplingPartial ||
|
||||
runtime.renderer.truncated();
|
||||
return buildCaptureResult({
|
||||
frames: options.frames,
|
||||
exit: { ...options.exit, reason },
|
||||
samples: options.samples,
|
||||
before: options.before,
|
||||
after,
|
||||
truncated,
|
||||
scenario,
|
||||
rootPid: runtime.terminal.pid,
|
||||
samplingPartial,
|
||||
renderedFrames,
|
||||
interactions: options.interactions,
|
||||
checkpoints,
|
||||
settlement,
|
||||
manifest,
|
||||
eventJournal: options.eventJournal,
|
||||
});
|
||||
};
|
||||
|
||||
/** Execute one caller-selected scenario and return bounded observations. */
|
||||
const runProcessScenario = async (
|
||||
scenario: ProcessScenario,
|
||||
signal?: AbortSignal,
|
||||
hostEnvironment: Readonly<Record<string, string | undefined>> = process.env,
|
||||
hostPlatform: NodeJS.Platform = process.platform,
|
||||
captureSnapshot: typeof snapshotRoots = snapshotRoots,
|
||||
): Promise<ProcessCapture> => {
|
||||
const { temporaryRoot, runId, before } = await prepareProcessCapture(
|
||||
scenario,
|
||||
signal,
|
||||
captureSnapshot,
|
||||
);
|
||||
const frames: TerminalFrame[] = [];
|
||||
const samples: ProcessSample[] = [];
|
||||
const journal = createProcessCaptureJournal();
|
||||
const { entries: eventJournal, recordEvent } = journal;
|
||||
recordEvent("filesystem_checkpoints", 0);
|
||||
let runtime: StartedCaptureRuntime | undefined;
|
||||
const timers = new Set<ProcessTimer>();
|
||||
let capture: PendingProcessCapture | undefined;
|
||||
let executionFailure: unknown;
|
||||
let stopSampler = async () => ({ partial: false });
|
||||
const interactions: InteractionEvent[] = [];
|
||||
const dispatchedEventIndexes = new Set<number>();
|
||||
|
||||
try {
|
||||
runtime = await startCaptureRuntime({
|
||||
scenario,
|
||||
hostEnvironment,
|
||||
temporaryRoot,
|
||||
runId,
|
||||
frames,
|
||||
samples,
|
||||
interactions,
|
||||
timers,
|
||||
dispatchedEventIndexes,
|
||||
recordEvent,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
});
|
||||
stopSampler = runtime.stopSampler;
|
||||
const exit = await awaitTerminalExit({
|
||||
terminal: runtime.terminal,
|
||||
scenario,
|
||||
started: runtime.started,
|
||||
lastOutput: runtime.lastOutput,
|
||||
signal,
|
||||
timers,
|
||||
interactions,
|
||||
dispatchedEventIndexes,
|
||||
recordEvent,
|
||||
});
|
||||
capture = await completeCapture({
|
||||
scenario,
|
||||
hostPlatform,
|
||||
runtime,
|
||||
runId,
|
||||
temporaryRoot,
|
||||
before,
|
||||
frames,
|
||||
samples,
|
||||
interactions,
|
||||
exit,
|
||||
initiallyTruncated: before.truncated,
|
||||
eventJournal,
|
||||
recordEvent,
|
||||
captureSnapshot,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
runtime?.terminal.kill("SIGKILL");
|
||||
executionFailure = normalizeCaptureFailure(cause, signal);
|
||||
}
|
||||
return finishProcessRun({
|
||||
runtime,
|
||||
timers,
|
||||
runId,
|
||||
temporaryRoot,
|
||||
samples,
|
||||
stopSampler,
|
||||
capture,
|
||||
executionFailure,
|
||||
});
|
||||
};
|
||||
|
||||
/** Execute one scenario through a typed expected-failure channel. */
|
||||
export const captureProcessScenario = async (
|
||||
scenario: ProcessScenario,
|
||||
signal?: AbortSignal,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
environment: Readonly<Record<string, string | undefined>> = process.env,
|
||||
captureSnapshot: typeof snapshotRoots = snapshotRoots,
|
||||
): Promise<Result<ProcessCapture, ProcessCaptureError | AnalysisError>> => {
|
||||
const ownershipReason = processCaptureOwnershipUnavailableReason(platform);
|
||||
if (ownershipReason !== undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-process",
|
||||
"capture_process_scenario",
|
||||
ownershipReason,
|
||||
{ userMessage: ownershipReason },
|
||||
),
|
||||
);
|
||||
try {
|
||||
assertNotCancelled(signal);
|
||||
const resolvedScenario = await resolveProcessScenarioRuntimePaths(
|
||||
scenario,
|
||||
environment,
|
||||
);
|
||||
return ok(
|
||||
await runProcessScenario(
|
||||
resolvedScenario,
|
||||
signal,
|
||||
environment,
|
||||
platform,
|
||||
captureSnapshot,
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
const failure = normalizeCaptureFailure(cause, signal);
|
||||
return err(
|
||||
failure instanceof ProcessCaptureError
|
||||
? failure
|
||||
: new ProcessCaptureError("process capture failed", { cause }),
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,167 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { normalizeProcessSamples } from "./ProcessNormalization.js";
|
||||
import {
|
||||
parseProcessScenario,
|
||||
type ProcessSample,
|
||||
} from "../../domain/process/processCapture.js";
|
||||
|
||||
const rootPid = 41_010;
|
||||
const samples = Object.freeze(
|
||||
[
|
||||
{
|
||||
at_ms: 17,
|
||||
pid: rootPid,
|
||||
parent_pid: 40_000,
|
||||
process_group_id: rootPid,
|
||||
session_id: rootPid,
|
||||
command: " root 41010 ",
|
||||
},
|
||||
{
|
||||
at_ms: 28,
|
||||
pid: 42_020,
|
||||
parent_pid: rootPid,
|
||||
process_group_id: 43_030,
|
||||
session_id: 44_040,
|
||||
command: "child 42020 parent 41010 group 43030 session 44040",
|
||||
},
|
||||
{
|
||||
at_ms: 39,
|
||||
pid: 45_050,
|
||||
parent_pid: 42_020,
|
||||
process_group_id: 43_030,
|
||||
session_id: 44_040,
|
||||
command: "peer 45050 unrelated 145050",
|
||||
},
|
||||
{
|
||||
at_ms: 41,
|
||||
pid: 46_060,
|
||||
parent_pid: 0,
|
||||
process_group_id: null,
|
||||
session_id: 0,
|
||||
command: "unknown 46060",
|
||||
},
|
||||
{
|
||||
at_ms: 52,
|
||||
pid: 47_070,
|
||||
parent_pid: 0,
|
||||
process_group_id: 0,
|
||||
session_id: null,
|
||||
command: "unavailable 47070",
|
||||
},
|
||||
].map((sample) =>
|
||||
Object.freeze({ ...sample, runtime_metadata: "must not be serialized" }),
|
||||
),
|
||||
);
|
||||
|
||||
it.each([false, true, undefined])(
|
||||
"projects only declared sample fields without mutating inputs when pids is %s",
|
||||
(pids) => {
|
||||
const scenario = parseProcessScenario({
|
||||
executable: "/usr/bin/node",
|
||||
...(pids === undefined ? {} : { normalization: { pids } }),
|
||||
});
|
||||
const before = JSON.stringify(samples);
|
||||
const normalized = normalizeProcessSamples(samples, scenario, rootPid);
|
||||
const identities =
|
||||
pids === false
|
||||
? [
|
||||
[rootPid, 40_000, rootPid, rootPid],
|
||||
[42_020, rootPid, 43_030, 44_040],
|
||||
[45_050, 42_020, 43_030, 44_040],
|
||||
[46_060, 0, null, 0],
|
||||
[47_070, 0, 0, null],
|
||||
]
|
||||
: [
|
||||
[1, 2, 1, 1],
|
||||
[3, 1, 4, 5],
|
||||
[6, 3, 4, 5],
|
||||
[7, 0, null, 0],
|
||||
[8, 0, 0, null],
|
||||
];
|
||||
const commands =
|
||||
pids === false
|
||||
? samples.map(({ command }) => command.trim())
|
||||
: [
|
||||
"root <pid>",
|
||||
"child <pid> parent <pid> group <pid> session <pid>",
|
||||
"peer <pid> unrelated 145050",
|
||||
"unknown <pid>",
|
||||
"unavailable <pid>",
|
||||
];
|
||||
|
||||
expect(scenario.normalization.pids).toBe(pids ?? true);
|
||||
expect(normalized).toEqual(
|
||||
identities.map(
|
||||
([pid, parent_pid, process_group_id, session_id], index) => ({
|
||||
at_ms: (index + 1) * 10,
|
||||
pid,
|
||||
parent_pid,
|
||||
process_group_id,
|
||||
session_id,
|
||||
command: commands[index],
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(normalized).not.toBe(samples);
|
||||
for (const [index, sample] of normalized.entries()) {
|
||||
expect(sample).not.toBe(samples[index]);
|
||||
expect(Object.keys(sample).sort()).toEqual(
|
||||
[
|
||||
"at_ms",
|
||||
"pid",
|
||||
"parent_pid",
|
||||
"process_group_id",
|
||||
"session_id",
|
||||
"command",
|
||||
].sort(),
|
||||
);
|
||||
}
|
||||
expect(JSON.stringify(samples)).toBe(before);
|
||||
},
|
||||
);
|
||||
|
||||
for (const pids of [false, true]) {
|
||||
for (const paths of [false, true]) {
|
||||
it.each([false, true])(
|
||||
`keeps time, patterns, paths=${String(paths)}, and ports=%s independent of pids=${String(pids)}`,
|
||||
(ports) => {
|
||||
const sample: ProcessSample = Object.freeze({
|
||||
at_ms: 29,
|
||||
pid: 42_020,
|
||||
parent_pid: rootPid,
|
||||
process_group_id: 43_030,
|
||||
session_id: 44_040,
|
||||
command:
|
||||
" /workspace/program child 42020 parent 41010 group 43030 session 44040 listen:8080 marker ",
|
||||
});
|
||||
const scenario = parseProcessScenario({
|
||||
executable: "/usr/bin/node",
|
||||
working_directory: "/workspace",
|
||||
normalization: {
|
||||
pids,
|
||||
paths,
|
||||
ports,
|
||||
time_bucket_ms: 25,
|
||||
patterns: [{ pattern: "marker", replacement: "selected" }],
|
||||
},
|
||||
});
|
||||
const normalized = normalizeProcessSamples([sample], scenario, rootPid);
|
||||
const directory = paths ? "<working-directory>" : "/workspace";
|
||||
const identifiers = pids
|
||||
? "child <pid> parent <pid> group <pid> session <pid>"
|
||||
: "child 42020 parent 41010 group 43030 session 44040";
|
||||
expect(normalized).toEqual([
|
||||
{
|
||||
at_ms: 25,
|
||||
pid: pids ? 2 : 42_020,
|
||||
parent_pid: pids ? 1 : rootPid,
|
||||
process_group_id: pids ? 3 : 43_030,
|
||||
session_id: pids ? 4 : 44_040,
|
||||
command: `${directory}/program ${identifiers} listen:${ports ? "<port>" : "8080"} selected`,
|
||||
},
|
||||
]);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import type {
|
||||
ProcessSample,
|
||||
ProcessScenario,
|
||||
} from "../../domain/process/processCapture.js";
|
||||
|
||||
/** Bucket one elapsed process-capture timestamp under scenario normalization. */
|
||||
export const normalizeProcessElapsedTime = (
|
||||
elapsedMs: number,
|
||||
timeBucketMs: number,
|
||||
): number => Math.floor(elapsedMs / timeBucketMs) * timeBucketMs;
|
||||
|
||||
/** Normalize one terminal/protocol payload under explicitly selected scenario rules. */
|
||||
export const normalizeProcessText = (
|
||||
value: string,
|
||||
scenario: ProcessScenario,
|
||||
temporaryRoot: string,
|
||||
pid: number,
|
||||
): string => {
|
||||
let normalized = value;
|
||||
if (scenario.normalization.paths) {
|
||||
normalized = normalized.replaceAll(temporaryRoot, "<temporary-root>");
|
||||
normalized = normalized.replaceAll(
|
||||
scenario.working_directory,
|
||||
"<working-directory>",
|
||||
);
|
||||
normalized = normalized.replaceAll(scenario.executable, "<executable>");
|
||||
for (const [index, root] of scenario.filesystem_observation_paths.entries())
|
||||
normalized = normalized.replaceAll(
|
||||
root,
|
||||
`<filesystem-root-${String(index)}>`,
|
||||
);
|
||||
}
|
||||
if (scenario.normalization.pids)
|
||||
normalized = normalizePidTokens(normalized, [pid]);
|
||||
if (scenario.normalization.ports)
|
||||
normalized = normalized.replaceAll(/(?<=[:=])\d{2,5}\b/g, "<port>");
|
||||
for (const pattern of scenario.normalization.patterns)
|
||||
normalized = normalized.replaceAll(pattern.pattern, pattern.replacement);
|
||||
return normalized;
|
||||
};
|
||||
|
||||
/** Project sampled observations under the caller-selected normalization rules. */
|
||||
export const normalizeProcessSamples = (
|
||||
samples: readonly ProcessSample[],
|
||||
scenario: ProcessScenario,
|
||||
rootPid: number,
|
||||
): readonly ProcessSample[] => {
|
||||
const identifiers = [
|
||||
rootPid,
|
||||
...samples.flatMap((sample) => [
|
||||
sample.pid,
|
||||
sample.parent_pid,
|
||||
sample.process_group_id ?? 0,
|
||||
sample.session_id ?? 0,
|
||||
]),
|
||||
];
|
||||
const mapping = new Map<number, number>();
|
||||
for (const identifier of identifiers)
|
||||
if (identifier > 0 && !mapping.has(identifier))
|
||||
mapping.set(identifier, mapping.size + 1);
|
||||
const normalizeCommand = (command: string): string => {
|
||||
const normalized = normalizeProcessText(
|
||||
command,
|
||||
scenario,
|
||||
"<no-temporary-root>",
|
||||
rootPid,
|
||||
);
|
||||
const withNormalizedPids = scenario.normalization.pids
|
||||
? normalizePidTokens(normalized, identifiers)
|
||||
: normalized;
|
||||
return withNormalizedPids.trim();
|
||||
};
|
||||
return samples.map((sample) => ({
|
||||
at_ms: normalizeProcessElapsedTime(
|
||||
sample.at_ms,
|
||||
scenario.normalization.time_bucket_ms,
|
||||
),
|
||||
pid: scenario.normalization.pids
|
||||
? (mapping.get(sample.pid) ?? 1)
|
||||
: sample.pid,
|
||||
parent_pid: scenario.normalization.pids
|
||||
? (mapping.get(sample.parent_pid) ?? 0)
|
||||
: sample.parent_pid,
|
||||
process_group_id:
|
||||
!scenario.normalization.pids || sample.process_group_id === null
|
||||
? sample.process_group_id
|
||||
: (mapping.get(sample.process_group_id) ?? 0),
|
||||
session_id:
|
||||
!scenario.normalization.pids || sample.session_id === null
|
||||
? sample.session_id
|
||||
: (mapping.get(sample.session_id) ?? 0),
|
||||
command: normalizeCommand(sample.command),
|
||||
}));
|
||||
};
|
||||
|
||||
const normalizePidTokens = (
|
||||
value: string,
|
||||
identifiers: readonly number[],
|
||||
): string => {
|
||||
const tokens = [...new Set(identifiers)]
|
||||
.filter((identifier) => Number.isSafeInteger(identifier) && identifier > 0)
|
||||
.sort((left, right) => right - left)
|
||||
.map(String);
|
||||
if (tokens.length === 0) return value;
|
||||
return value.replace(
|
||||
new RegExp(`(?<!\\d)(?:${tokens.join("|")})(?!\\d)`, "gu"),
|
||||
"<pid>",
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,532 @@
|
||||
import { readFile, readdir } from "node:fs/promises";
|
||||
import type {
|
||||
ProcessSample,
|
||||
RecordProcessCaptureEvent,
|
||||
} from "../../domain/process/processCapture.js";
|
||||
import { execFileOutput } from "../ExecFileOutput.js";
|
||||
import { readProcessRunId } from "../ProcessOwnership.js";
|
||||
const PROC_READ_CONCURRENCY = 64;
|
||||
|
||||
interface ProcessRow {
|
||||
readonly pid: number;
|
||||
readonly parent_pid: number;
|
||||
readonly process_group_id: number | null;
|
||||
readonly session_id: number | null;
|
||||
readonly command: string;
|
||||
readonly startTime: string | undefined;
|
||||
}
|
||||
|
||||
interface ProcessNode extends ProcessRow {
|
||||
readonly children: readonly number[];
|
||||
}
|
||||
|
||||
interface SampleProcessContext {
|
||||
readonly rootPid: number;
|
||||
readonly elapsedMs: number;
|
||||
readonly limit: number;
|
||||
readonly identities: Map<number, string>;
|
||||
readonly signal: AbortSignal;
|
||||
}
|
||||
|
||||
type ProcessIdentitySnapshot = Pick<
|
||||
ProcessRow,
|
||||
"pid" | "parent_pid" | "process_group_id" | "session_id" | "startTime"
|
||||
>;
|
||||
|
||||
/** Prove that forkpty completed session setup and installed the run token. */
|
||||
export const isInitializedPtyRoot = (options: {
|
||||
readonly rootPid: number;
|
||||
readonly expectedRunId: string;
|
||||
readonly before: ProcessIdentitySnapshot;
|
||||
readonly observedRunId: string | undefined;
|
||||
readonly after: ProcessIdentitySnapshot;
|
||||
}): boolean => {
|
||||
const sessionIdentityMatches =
|
||||
(options.before.session_id === options.rootPid &&
|
||||
options.after.session_id === options.rootPid) ||
|
||||
(options.before.session_id === null && options.after.session_id === null);
|
||||
return (
|
||||
options.before.pid === options.rootPid &&
|
||||
options.before.process_group_id === options.rootPid &&
|
||||
sessionIdentityMatches &&
|
||||
options.after.pid === options.rootPid &&
|
||||
options.after.parent_pid === options.before.parent_pid &&
|
||||
options.after.process_group_id === options.rootPid &&
|
||||
options.after.startTime === options.before.startTime &&
|
||||
options.observedRunId === options.expectedRunId
|
||||
);
|
||||
};
|
||||
|
||||
const isExpectedProcReadFailure = (cause: unknown): boolean =>
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause.code === "ENOENT" ||
|
||||
cause.code === "ESRCH" ||
|
||||
cause.code === "EACCES" ||
|
||||
cause.code === "EPERM");
|
||||
|
||||
const handleProcReadFailure = (cause: unknown): undefined => {
|
||||
if (isExpectedProcReadFailure(cause)) return undefined;
|
||||
throw cause;
|
||||
};
|
||||
|
||||
const parseProcStat = (
|
||||
identifier: string,
|
||||
stat: string,
|
||||
): ProcessRow | undefined => {
|
||||
const commandEnd = stat.lastIndexOf(")");
|
||||
if (commandEnd < 0) return undefined;
|
||||
const fields = stat
|
||||
.slice(commandEnd + 2)
|
||||
.trim()
|
||||
.split(/\s+/);
|
||||
const pid = Number(identifier);
|
||||
const parentPid = Number(fields[1]);
|
||||
const processGroupId = Number(fields[2]);
|
||||
const sessionId = Number(fields[3]);
|
||||
const startTime = fields[19];
|
||||
if (
|
||||
!Number.isSafeInteger(pid) ||
|
||||
pid <= 0 ||
|
||||
!Number.isSafeInteger(parentPid) ||
|
||||
parentPid < 0 ||
|
||||
!Number.isSafeInteger(processGroupId) ||
|
||||
processGroupId <= 0 ||
|
||||
!Number.isSafeInteger(sessionId) ||
|
||||
sessionId <= 0 ||
|
||||
startTime === undefined ||
|
||||
!/^\d+$/.test(startTime)
|
||||
)
|
||||
return undefined;
|
||||
return {
|
||||
pid,
|
||||
parent_pid: parentPid,
|
||||
process_group_id: processGroupId,
|
||||
session_id: sessionId,
|
||||
command: "",
|
||||
startTime,
|
||||
};
|
||||
};
|
||||
|
||||
const readProcessStat = async (
|
||||
pid: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<ProcessRow | undefined> => {
|
||||
try {
|
||||
const stat = await readFile(`/proc/${String(pid)}/stat`, {
|
||||
encoding: "utf8",
|
||||
signal,
|
||||
});
|
||||
return parseProcStat(String(pid), stat);
|
||||
} catch (cause: unknown) {
|
||||
return handleProcReadFailure(cause);
|
||||
}
|
||||
};
|
||||
|
||||
const readProcessCommand = async (
|
||||
pid: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<Buffer | undefined> => {
|
||||
try {
|
||||
return await readFile(`/proc/${String(pid)}/cmdline`, { signal });
|
||||
} catch (cause: unknown) {
|
||||
return handleProcReadFailure(cause);
|
||||
}
|
||||
};
|
||||
|
||||
/** Procfs reads used to enumerate children created by every process thread. */
|
||||
export interface LinuxChildrenHost {
|
||||
taskIds(
|
||||
pid: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<readonly number[] | undefined>;
|
||||
children(
|
||||
pid: number,
|
||||
taskId: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<string | undefined>;
|
||||
}
|
||||
|
||||
const systemLinuxChildrenHost: LinuxChildrenHost = {
|
||||
async taskIds(pid, signal) {
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
const entries = await readdir(`/proc/${String(pid)}/task`);
|
||||
signal.throwIfAborted();
|
||||
return entries
|
||||
.filter((entry) => /^\d+$/.test(entry))
|
||||
.map(Number)
|
||||
.filter((taskId) => Number.isSafeInteger(taskId) && taskId > 0)
|
||||
.sort((left, right) => left - right);
|
||||
} catch (cause: unknown) {
|
||||
return handleProcReadFailure(cause);
|
||||
}
|
||||
},
|
||||
async children(pid, taskId, signal) {
|
||||
try {
|
||||
return await readFile(
|
||||
`/proc/${String(pid)}/task/${String(taskId)}/children`,
|
||||
{ encoding: "utf8", signal },
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return handleProcReadFailure(cause);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/** Read the deduplicated children created by every thread in a Linux process. */
|
||||
export const readLinuxChildren = async (
|
||||
pid: number,
|
||||
signal: AbortSignal,
|
||||
host: LinuxChildrenHost = systemLinuxChildrenHost,
|
||||
): Promise<readonly number[] | undefined> => {
|
||||
const taskIds = await host.taskIds(pid, signal);
|
||||
if (taskIds === undefined) return undefined;
|
||||
const children = new Set<number>();
|
||||
let successfulReads = 0;
|
||||
for (
|
||||
let offset = 0;
|
||||
offset < taskIds.length;
|
||||
offset += PROC_READ_CONCURRENCY
|
||||
) {
|
||||
const texts = await Promise.all(
|
||||
taskIds
|
||||
.slice(offset, offset + PROC_READ_CONCURRENCY)
|
||||
.map((taskId) => host.children(pid, taskId, signal)),
|
||||
);
|
||||
for (const text of texts) {
|
||||
if (text === undefined) continue;
|
||||
successfulReads += 1;
|
||||
for (const value of text.trim().split(/\s+/)) {
|
||||
if (!/^\d+$/.test(value)) continue;
|
||||
const child = Number(value);
|
||||
if (Number.isSafeInteger(child) && child > 0) children.add(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
return successfulReads === 0
|
||||
? undefined
|
||||
: [...children].sort((left, right) => left - right);
|
||||
};
|
||||
|
||||
const inspectProcess = async (
|
||||
pid: number,
|
||||
expectedParent: number | undefined,
|
||||
signal: AbortSignal,
|
||||
identities: Map<number, string>,
|
||||
): Promise<ProcessNode | undefined> => {
|
||||
const before = await readProcessStat(pid, signal);
|
||||
if (before === undefined || before.startTime === undefined) return undefined;
|
||||
|
||||
const existing = identities.get(pid);
|
||||
if (existing !== undefined && existing !== before.startTime) return undefined;
|
||||
if (expectedParent !== undefined && before.parent_pid !== expectedParent)
|
||||
return undefined;
|
||||
|
||||
const [commandBuffer, children] = await Promise.all([
|
||||
readProcessCommand(pid, signal),
|
||||
readLinuxChildren(pid, signal),
|
||||
]);
|
||||
|
||||
const after = await readProcessStat(pid, signal);
|
||||
if (after === undefined || after.startTime === undefined) return undefined;
|
||||
if (
|
||||
before.startTime !== after.startTime ||
|
||||
before.parent_pid !== after.parent_pid
|
||||
)
|
||||
return undefined;
|
||||
if (expectedParent !== undefined && after.parent_pid !== expectedParent)
|
||||
return undefined;
|
||||
|
||||
const command =
|
||||
commandBuffer === undefined
|
||||
? ""
|
||||
: commandBuffer.toString().replaceAll("\0", " ").trim();
|
||||
|
||||
return {
|
||||
pid: before.pid,
|
||||
parent_pid: before.parent_pid,
|
||||
process_group_id: before.process_group_id,
|
||||
session_id: before.session_id,
|
||||
startTime: before.startTime,
|
||||
command,
|
||||
children: children ?? [],
|
||||
};
|
||||
};
|
||||
|
||||
const sampleLinux = async (
|
||||
context: SampleProcessContext,
|
||||
): Promise<readonly ProcessRow[]> => {
|
||||
const { rootPid, limit, signal, identities } = context;
|
||||
if (limit <= 0) return [];
|
||||
|
||||
const rootStat = await readProcessStat(rootPid, signal);
|
||||
if (rootStat === undefined) return [];
|
||||
const rootChildren = await readLinuxChildren(rootPid, signal);
|
||||
if (rootChildren === undefined) return samplePs(context);
|
||||
|
||||
const rows: ProcessRow[] = [];
|
||||
const visited = new Set<number>([rootPid]);
|
||||
let level: Array<{
|
||||
readonly pid: number;
|
||||
readonly expectedParent: number | undefined;
|
||||
}> = [{ pid: rootPid, expectedParent: undefined }];
|
||||
|
||||
while (level.length > 0 && rows.length < limit) {
|
||||
const batchSize = Math.min(level.length, PROC_READ_CONCURRENCY);
|
||||
const batch = level.slice(0, batchSize);
|
||||
level = level.slice(batchSize);
|
||||
|
||||
const batchResults = await Promise.all(
|
||||
batch.map((item) =>
|
||||
inspectProcess(item.pid, item.expectedParent, signal, identities),
|
||||
),
|
||||
);
|
||||
|
||||
const nextLevel: typeof batch = [];
|
||||
for (const node of batchResults) {
|
||||
if (node === undefined) continue;
|
||||
|
||||
if (rows.length >= limit) break;
|
||||
rows.push(node);
|
||||
if (rows.length >= limit) break;
|
||||
|
||||
for (const child of node.children) {
|
||||
if (visited.has(child)) continue;
|
||||
visited.add(child);
|
||||
nextLevel.push({ pid: child, expectedParent: node.pid });
|
||||
}
|
||||
if (rows.length >= limit) break;
|
||||
}
|
||||
|
||||
level.push(...nextLevel);
|
||||
}
|
||||
|
||||
return rows;
|
||||
};
|
||||
|
||||
const readPsRows = async (
|
||||
signal: AbortSignal,
|
||||
): Promise<readonly ProcessRow[]> => {
|
||||
const { stdout } = await execFileOutput(
|
||||
"ps",
|
||||
["-axo", "pid=,ppid=,pgid=,sess=,command="],
|
||||
{ signal },
|
||||
);
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => /\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(.*)/u.exec(line))
|
||||
.filter((match): match is RegExpExecArray => match !== null)
|
||||
.map((match) => ({
|
||||
pid: Number(match[1]),
|
||||
parent_pid: Number(match[2]),
|
||||
process_group_id: Number(match[3]),
|
||||
session_id: Number(match[4]) || null,
|
||||
command: match[5] ?? "",
|
||||
startTime: undefined,
|
||||
}))
|
||||
.filter(
|
||||
(row) =>
|
||||
Number.isSafeInteger(row.pid) &&
|
||||
row.pid > 0 &&
|
||||
Number.isSafeInteger(row.parent_pid) &&
|
||||
row.parent_pid >= 0,
|
||||
)
|
||||
.sort((left, right) => left.pid - right.pid);
|
||||
};
|
||||
|
||||
const readRootIdentity = async (
|
||||
rootPid: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<ProcessRow | undefined> =>
|
||||
process.platform === "linux"
|
||||
? readProcessStat(rootPid, signal)
|
||||
: (await readPsRows(signal)).find(({ pid }) => pid === rootPid);
|
||||
|
||||
const inspectInitializedPtyRoot = async (
|
||||
rootPid: number,
|
||||
runId: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<{ readonly startTime: string | undefined } | undefined> => {
|
||||
const before = await readRootIdentity(rootPid, signal);
|
||||
if (
|
||||
before === undefined ||
|
||||
before.process_group_id !== rootPid ||
|
||||
(before.session_id !== rootPid && before.session_id !== null)
|
||||
)
|
||||
return undefined;
|
||||
let observedRunId: string | undefined;
|
||||
try {
|
||||
observedRunId = await readProcessRunId(rootPid);
|
||||
} catch (cause: unknown) {
|
||||
// Unreadable run identity means the root cannot be attributed.
|
||||
void cause;
|
||||
return undefined;
|
||||
}
|
||||
const after = await readRootIdentity(rootPid, signal);
|
||||
if (
|
||||
after === undefined ||
|
||||
!isInitializedPtyRoot({
|
||||
rootPid,
|
||||
expectedRunId: runId,
|
||||
before,
|
||||
observedRunId,
|
||||
after,
|
||||
})
|
||||
)
|
||||
return undefined;
|
||||
return { startTime: after.startTime };
|
||||
};
|
||||
|
||||
const samplePs = async (
|
||||
context: SampleProcessContext,
|
||||
): Promise<readonly ProcessRow[]> => {
|
||||
const { rootPid, limit, signal } = context;
|
||||
if (limit <= 0) return [];
|
||||
|
||||
const rows = await readPsRows(signal);
|
||||
const rowByPid = new Map(rows.map((row) => [row.pid, row]));
|
||||
const childrenByParent = new Map<number, ProcessRow[]>();
|
||||
for (const row of rows) {
|
||||
const siblings = childrenByParent.get(row.parent_pid) ?? [];
|
||||
siblings.push(row);
|
||||
childrenByParent.set(row.parent_pid, siblings);
|
||||
}
|
||||
|
||||
const result: ProcessRow[] = [];
|
||||
const visited = new Set<number>();
|
||||
const queue: number[] = [rootPid];
|
||||
let index = 0;
|
||||
|
||||
while (index < queue.length && result.length < limit) {
|
||||
const pid = queue[index];
|
||||
if (pid === undefined) break;
|
||||
index += 1;
|
||||
if (visited.has(pid)) continue;
|
||||
visited.add(pid);
|
||||
|
||||
const row = rowByPid.get(pid);
|
||||
if (row !== undefined) result.push(row);
|
||||
if (result.length >= limit) break;
|
||||
|
||||
for (const child of childrenByParent.get(pid) ?? []) {
|
||||
if (!visited.has(child.pid)) queue.push(child.pid);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const sampleProcesses = async (
|
||||
context: SampleProcessContext,
|
||||
): Promise<readonly ProcessSample[]> => {
|
||||
if (process.platform === "win32" || context.limit <= 0) return [];
|
||||
|
||||
const rows =
|
||||
process.platform === "linux"
|
||||
? await sampleLinux(context)
|
||||
: await samplePs(context);
|
||||
|
||||
const { elapsedMs, identities } = context;
|
||||
const samples: ProcessSample[] = [];
|
||||
for (const row of rows) {
|
||||
if (row.startTime !== undefined) {
|
||||
const existing = identities.get(row.pid);
|
||||
if (existing !== undefined && existing !== row.startTime) continue;
|
||||
identities.set(row.pid, row.startTime);
|
||||
}
|
||||
samples.push({
|
||||
at_ms: elapsedMs,
|
||||
pid: row.pid,
|
||||
parent_pid: row.parent_pid,
|
||||
command: row.command,
|
||||
process_group_id: row.process_group_id,
|
||||
session_id: row.session_id,
|
||||
});
|
||||
}
|
||||
return samples;
|
||||
};
|
||||
|
||||
/** Start bounded process-tree sampling and expose an awaited stop. */
|
||||
export const startProcessSampler = (options: {
|
||||
readonly rootPid: number;
|
||||
readonly runId: string;
|
||||
readonly started: number;
|
||||
readonly limit: number;
|
||||
readonly samples: ProcessSample[];
|
||||
readonly recordEvent?: RecordProcessCaptureEvent;
|
||||
}): (() => Promise<{ readonly partial: boolean }>) => {
|
||||
const { rootPid, runId, started, limit, samples } = options;
|
||||
const identities = new Map<number, string>();
|
||||
const lastObservations = new Map<number, string>();
|
||||
let pending: Promise<void> | undefined;
|
||||
let stopped = false;
|
||||
let abortCurrent: (() => void) | undefined;
|
||||
let partial = false;
|
||||
let rootInitialized = false;
|
||||
|
||||
const sample = (): void => {
|
||||
if (stopped || pending !== undefined) return;
|
||||
|
||||
const controller = new AbortController();
|
||||
abortCurrent = () => controller.abort();
|
||||
pending = (async () => {
|
||||
if (!rootInitialized) {
|
||||
const identity = await inspectInitializedPtyRoot(
|
||||
rootPid,
|
||||
runId,
|
||||
controller.signal,
|
||||
);
|
||||
if (identity === undefined) return [];
|
||||
if (identity.startTime !== undefined)
|
||||
identities.set(rootPid, identity.startTime);
|
||||
rootInitialized = true;
|
||||
}
|
||||
return sampleProcesses({
|
||||
rootPid,
|
||||
elapsedMs: Date.now() - started,
|
||||
limit: limit + 1,
|
||||
identities,
|
||||
signal: controller.signal,
|
||||
});
|
||||
})()
|
||||
.then((values) => {
|
||||
for (const value of values) {
|
||||
const observation = JSON.stringify({
|
||||
parent_pid: value.parent_pid,
|
||||
command: value.command,
|
||||
process_group_id: value.process_group_id,
|
||||
session_id: value.session_id,
|
||||
});
|
||||
if (lastObservations.get(value.pid) === observation) continue;
|
||||
if (samples.length >= limit) {
|
||||
partial = true;
|
||||
continue;
|
||||
}
|
||||
lastObservations.set(value.pid, observation);
|
||||
const index = samples.length;
|
||||
samples.push(value);
|
||||
options.recordEvent?.("process_samples", index);
|
||||
}
|
||||
})
|
||||
.catch((cause: unknown) => {
|
||||
if (!(cause instanceof Error && cause.name === "AbortError"))
|
||||
partial = true;
|
||||
})
|
||||
.then(() => {
|
||||
abortCurrent = undefined;
|
||||
pending = undefined;
|
||||
});
|
||||
};
|
||||
|
||||
const timer = setInterval(sample, 50);
|
||||
sample();
|
||||
|
||||
return async () => {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
abortCurrent?.();
|
||||
await pending;
|
||||
return { partial };
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
import { mkdtemp, rm, symlink } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolveExecutable,
|
||||
resolveProcessScenarioRuntimePaths,
|
||||
} from "./ProcessScenarioRuntimeValidation.js";
|
||||
import { parseProcessScenario } from "../../domain/process/processCapture.js";
|
||||
|
||||
it("preserves the caller-selected executable symlink for process invocation", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-process-executable-alias-"));
|
||||
try {
|
||||
const alias = join(root, "chosen-node");
|
||||
await symlink(process.execPath, alias);
|
||||
|
||||
await expect(resolveExecutable(alias, root, "")).resolves.toBe(alias);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("retains the selected missing working directory and OS reason", async () => {
|
||||
const selected = join(tmpdir(), "rea-process-missing-cwd-unique");
|
||||
const scenario = parseProcessScenario({
|
||||
executable: process.execPath,
|
||||
working_directory: selected,
|
||||
});
|
||||
|
||||
await expect(resolveProcessScenarioRuntimePaths(scenario)).rejects.toThrow(
|
||||
`working directory could not be resolved: ${selected} (ENOENT)`,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { access, realpath, stat } from "node:fs/promises";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { delimiter, isAbsolute, join, resolve } from "node:path";
|
||||
|
||||
import type { ProcessScenario } from "../../domain/process/processCapture.js";
|
||||
import {
|
||||
ProcessCaptureError,
|
||||
processCaptureCancelled,
|
||||
} from "./ProcessCaptureError.js";
|
||||
|
||||
/** Resolve caller-selected executable and observation paths for this execution. */
|
||||
export const resolveProcessScenarioRuntimePaths = async (
|
||||
scenario: ProcessScenario,
|
||||
environment: Readonly<Record<string, string | undefined>> = process.env,
|
||||
): Promise<ProcessScenario> => {
|
||||
const selectedWorkingDirectory = resolve(scenario.working_directory);
|
||||
let workingDirectory: string;
|
||||
try {
|
||||
workingDirectory = await realpath(selectedWorkingDirectory);
|
||||
} catch (cause: unknown) {
|
||||
throw new ProcessCaptureError(
|
||||
`working directory could not be resolved: ${selectedWorkingDirectory}${osFailure(cause)}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
let workingDirectoryStat;
|
||||
try {
|
||||
workingDirectoryStat = await stat(workingDirectory);
|
||||
} catch (cause: unknown) {
|
||||
throw new ProcessCaptureError(
|
||||
`working directory could not be inspected: ${workingDirectory}${osFailure(cause)}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
if (!workingDirectoryStat.isDirectory())
|
||||
throw new ProcessCaptureError(
|
||||
`working directory is not a directory: ${workingDirectory}`,
|
||||
);
|
||||
const executable = await resolveExecutable(
|
||||
scenario.executable,
|
||||
workingDirectory,
|
||||
scenario.environment.PATH ?? environment.PATH ?? "",
|
||||
);
|
||||
const observationPaths = scenario.filesystem_observation_paths.map((path) =>
|
||||
resolve(workingDirectory, path),
|
||||
);
|
||||
return {
|
||||
...scenario,
|
||||
executable,
|
||||
working_directory: workingDirectory,
|
||||
filesystem_observation_paths: observationPaths,
|
||||
};
|
||||
};
|
||||
|
||||
/** Resolve a selected executable through the caller's effective PATH. */
|
||||
export const resolveExecutable = async (
|
||||
command: string,
|
||||
workingDirectory: string,
|
||||
searchPath: string,
|
||||
): Promise<string> => {
|
||||
const directories = searchPath
|
||||
.split(delimiter)
|
||||
.map((directory) =>
|
||||
directory === ""
|
||||
? workingDirectory
|
||||
: resolve(workingDirectory, directory),
|
||||
);
|
||||
const candidates =
|
||||
isAbsolute(command) || command.includes("/") || command.includes("\\")
|
||||
? [resolve(workingDirectory, command)]
|
||||
: directories.map((directory) => join(directory, command));
|
||||
const failures: string[] = [];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
await access(candidate, fsConstants.X_OK);
|
||||
if ((await stat(candidate)).isFile()) return candidate;
|
||||
failures.push(`${candidate} (not a regular file)`);
|
||||
} catch (cause: unknown) {
|
||||
const code = osErrorCode(cause);
|
||||
if (code !== "ENOENT" && code !== "ENOTDIR")
|
||||
failures.push(`${candidate}${osFailure(cause)}`);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
throw new ProcessCaptureError(
|
||||
failures.length === 0
|
||||
? `executable could not be resolved: ${command}`
|
||||
: `executable could not be resolved: ${command}; checked ${failures.join("; ")}`,
|
||||
);
|
||||
};
|
||||
|
||||
const osErrorCode = (cause: unknown): string | undefined =>
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
typeof cause.code === "string"
|
||||
? cause.code
|
||||
: undefined;
|
||||
|
||||
const osFailure = (cause: unknown): string => {
|
||||
const code = osErrorCode(cause);
|
||||
return code === undefined ? "" : ` (${code})`;
|
||||
};
|
||||
|
||||
/** Reject cancellation before a process capture operation begins. */
|
||||
export const assertNotCancelled = (signal: AbortSignal | undefined): void => {
|
||||
if (signal?.aborted === true) throw processCaptureCancelled();
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { scheduleProcessDelay } from "./ProcessTimer.js";
|
||||
|
||||
describe("process delay scheduling", () => {
|
||||
it("splits long delays into timer-sized chunks and can cancel the next chunk", () => {
|
||||
const scheduled: Array<{
|
||||
readonly delayMs: number;
|
||||
readonly callback: () => void;
|
||||
cancelled: boolean;
|
||||
}> = [];
|
||||
const schedule = (callback: () => void, delayMs: number) => {
|
||||
const entry = { delayMs, callback, cancelled: false };
|
||||
scheduled.push(entry);
|
||||
return { cancel: () => (entry.cancelled = true) };
|
||||
};
|
||||
let fired = false;
|
||||
const timer = scheduleProcessDelay(
|
||||
2_147_483_647 + 25,
|
||||
() => {
|
||||
fired = true;
|
||||
},
|
||||
schedule,
|
||||
);
|
||||
|
||||
expect(scheduled.map(({ delayMs }) => delayMs)).toEqual([2_147_483_647]);
|
||||
scheduled[0]?.callback();
|
||||
expect(scheduled.map(({ delayMs }) => delayMs)).toEqual([
|
||||
2_147_483_647, 25,
|
||||
]);
|
||||
expect(fired).toBe(false);
|
||||
|
||||
timer.cancel();
|
||||
expect(scheduled[1]?.cancelled).toBe(true);
|
||||
scheduled[1]?.callback();
|
||||
expect(fired).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
/** A timer owned by one process capture or replay endpoint. */
|
||||
export interface ProcessTimer {
|
||||
cancel(): void;
|
||||
}
|
||||
|
||||
/** Injectable timer primitive for deterministic long-delay tests. */
|
||||
export type ProcessTimerScheduler = (
|
||||
callback: () => void,
|
||||
delayMs: number,
|
||||
) => ProcessTimer;
|
||||
|
||||
const systemTimerScheduler: ProcessTimerScheduler = (callback, delayMs) => {
|
||||
const timer = setTimeout(callback, delayMs);
|
||||
return { cancel: () => clearTimeout(timer) };
|
||||
};
|
||||
|
||||
/** Schedule a delay using consecutive Node timers without shortening long waits. */
|
||||
export const scheduleProcessDelay = (
|
||||
delayMs: number,
|
||||
callback: () => void,
|
||||
schedule: ProcessTimerScheduler = systemTimerScheduler,
|
||||
): ProcessTimer => {
|
||||
if (!Number.isSafeInteger(delayMs) || delayMs < 0)
|
||||
throw new RangeError("Process delay must be a nonnegative safe integer");
|
||||
const maximumTimerDelay = 2_147_483_647;
|
||||
let remaining = delayMs;
|
||||
let timer: ProcessTimer | undefined;
|
||||
let cancelled = false;
|
||||
|
||||
const scheduleNext = (): void => {
|
||||
if (cancelled) return;
|
||||
const interval = Math.min(remaining, maximumTimerDelay);
|
||||
timer = schedule(() => {
|
||||
if (cancelled) return;
|
||||
remaining -= interval;
|
||||
if (remaining === 0) callback();
|
||||
else scheduleNext();
|
||||
}, interval);
|
||||
};
|
||||
|
||||
scheduleNext();
|
||||
return {
|
||||
cancel: () => {
|
||||
cancelled = true;
|
||||
timer?.cancel();
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Create an owned interval that shares process-capture cancellation handling. */
|
||||
export const scheduleProcessInterval = (
|
||||
callback: () => void,
|
||||
intervalMs: number,
|
||||
): ProcessTimer => {
|
||||
const timer = setInterval(callback, intervalMs);
|
||||
return { cancel: () => clearInterval(timer) };
|
||||
};
|
||||
@@ -0,0 +1,129 @@
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
import type {
|
||||
RecordProcessCaptureEvent,
|
||||
RenderedTerminalFrame,
|
||||
} from "../../domain/process/processCapture.js";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
// SAFETY: both pinned xterm packages publish CommonJS at runtime and matching declarations.
|
||||
const HeadlessPackage =
|
||||
require("@xterm/headless") as typeof import("@xterm/headless");
|
||||
// SAFETY: the addon package is pinned with the compatible headless xterm release.
|
||||
const SerializePackage =
|
||||
require("@xterm/addon-serialize") as typeof import("@xterm/addon-serialize");
|
||||
|
||||
interface TerminalRendererOptions {
|
||||
readonly columns: number;
|
||||
readonly rows: number;
|
||||
readonly scrollback: number;
|
||||
readonly maxBytes: number;
|
||||
readonly normalize: (value: string) => string;
|
||||
readonly recordEvent?: RecordProcessCaptureEvent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns one headless terminal and serializes writes into deterministic frames.
|
||||
* Reconstructs bounded terminal states while raw PTY chunks remain authoritative.
|
||||
*
|
||||
* Rendered frames answer what an operator saw after control-sequence handling;
|
||||
* raw frames preserve byte/chunk differences that can render identically.
|
||||
* Comparisons retain both because neither representation subsumes the other.
|
||||
*/
|
||||
export class TerminalRenderer {
|
||||
readonly #terminal: InstanceType<typeof HeadlessPackage.Terminal>;
|
||||
readonly #serializeAddon = new SerializePackage.SerializeAddon();
|
||||
readonly #frames: RenderedTerminalFrame[] = [];
|
||||
#pending: Promise<void> = Promise.resolve();
|
||||
#capturedBytes = 0;
|
||||
#truncated = false;
|
||||
|
||||
constructor(private readonly options: TerminalRendererOptions) {
|
||||
this.#terminal = new HeadlessPackage.Terminal({
|
||||
allowProposedApi: true,
|
||||
cols: options.columns,
|
||||
rows: options.rows,
|
||||
scrollback: options.scrollback,
|
||||
});
|
||||
this.#terminal.loadAddon(this.#serializeAddon);
|
||||
}
|
||||
|
||||
/** Queue one PTY chunk and capture state only after xterm has parsed it. */
|
||||
write(data: string, atMs: number): void {
|
||||
this.#pending = this.#pending.then(
|
||||
() =>
|
||||
new Promise<void>((resolveWrite) => {
|
||||
this.#terminal.write(data, () => {
|
||||
this.#capture(atMs);
|
||||
resolveWrite();
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Queue a terminal resize after every preceding write. */
|
||||
resize(columns: number, rows: number, atMs: number): void {
|
||||
this.#pending = this.#pending.then(() => {
|
||||
this.#terminal.resize(columns, rows);
|
||||
this.#capture(atMs);
|
||||
});
|
||||
}
|
||||
|
||||
/** Await all queued parsing and return immutable rendered observations. */
|
||||
async frames(): Promise<readonly RenderedTerminalFrame[]> {
|
||||
await this.#pending;
|
||||
return structuredClone(this.#frames);
|
||||
}
|
||||
|
||||
/** Whether a rendered observation exceeded its independent capture budget. */
|
||||
truncated(): boolean {
|
||||
return this.#truncated;
|
||||
}
|
||||
|
||||
/** Release addon and terminal resources after all writes settle. */
|
||||
async dispose(): Promise<void> {
|
||||
await this.#pending;
|
||||
this.#serializeAddon.dispose();
|
||||
this.#terminal.dispose();
|
||||
}
|
||||
|
||||
#capture(atMs: number): void {
|
||||
const buffer = this.#terminal.buffer.active;
|
||||
const lines: string[] = [];
|
||||
for (let row = 0; row < this.#terminal.rows; row += 1) {
|
||||
const line = buffer.getLine(buffer.viewportY + row);
|
||||
lines.push(
|
||||
this.options.normalize(
|
||||
(line?.translateToString(false, 0, this.#terminal.cols) ?? "").padEnd(
|
||||
this.#terminal.cols,
|
||||
" ",
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
const serializedState = this.options.normalize(
|
||||
this.#serializeAddon.serialize(),
|
||||
);
|
||||
const bytes =
|
||||
Buffer.byteLength(serializedState) +
|
||||
lines.reduce((total, line) => total + Buffer.byteLength(line), 0);
|
||||
if (this.#capturedBytes + bytes > this.options.maxBytes) {
|
||||
this.#truncated = true;
|
||||
return;
|
||||
}
|
||||
this.#capturedBytes += bytes;
|
||||
const sequence = this.#frames.length;
|
||||
this.#frames.push({
|
||||
sequence,
|
||||
at_ms: atMs,
|
||||
columns: this.#terminal.cols,
|
||||
rows: this.#terminal.rows,
|
||||
cursor_x: buffer.cursorX,
|
||||
cursor_y: buffer.cursorY,
|
||||
active_buffer: buffer.type,
|
||||
lines,
|
||||
serialized_state: serializedState,
|
||||
});
|
||||
this.options.recordEvent?.("rendered_frames", sequence);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user