chore: merge main into persistent workspace branch

This commit is contained in:
N0zoM1z0
2026-07-13 20:19:07 +08:00
47 changed files with 2741 additions and 1277 deletions
+138 -69
View File
@@ -17,6 +17,7 @@ import {
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
import { ZipArtifactReader } from "../artifacts/ZipArtifactReader.js";
import { MachOSliceArtifactReader } from "../artifacts/MachOSliceArtifactReader.js";
import { NativeDmgArtifactReader } from "../artifacts/NativeDmgArtifactReader.js";
import { streamChunkToBuffer } from "../artifacts/StreamBytes.js";
import {
artifactInventoryResultSchema,
@@ -49,6 +50,17 @@ interface InventoryPageInput {
readonly edgeLimit: number;
}
/** Per-request authority combined with operator-owned native mount policy. */
export interface ArtifactNativeMountPolicy {
readonly nativeMountApproved: boolean;
readonly nativeMountEnabled: boolean;
}
const NATIVE_MOUNT_DISABLED: ArtifactNativeMountPolicy = {
nativeMountApproved: false,
nativeMountEnabled: false,
};
/** Immutable inventory produced by one complete artifact scan. */
export interface ArtifactInventorySnapshot {
readonly manifest: ArtifactInventoryResult["manifest"];
@@ -67,9 +79,17 @@ export const inventoryArtifact = async (
inputPath: string,
limits: ArtifactLimits,
page: InventoryPageInput,
signal?: AbortSignal,
options: {
readonly signal?: AbortSignal;
readonly nativeMount?: ArtifactNativeMountPolicy;
} = {},
): Promise<ArtifactInventoryResult> => {
const snapshot = await scanArtifactInventory(inputPath, limits, signal);
const snapshot = await scanArtifactInventory(
inputPath,
limits,
options.signal,
options.nativeMount ?? NATIVE_MOUNT_DISABLED,
);
return paginateArtifactInventory(snapshot, page);
};
@@ -78,6 +98,7 @@ export const scanArtifactInventory = async (
inputPath: string,
limits: ArtifactLimits,
signal?: AbortSignal,
nativeMount: ArtifactNativeMountPolicy = NATIVE_MOUNT_DISABLED,
): Promise<ArtifactInventorySnapshot> => {
abortIfNeeded(signal);
const path = await realpath(inputPath);
@@ -86,7 +107,7 @@ export const scanArtifactInventory = async (
const rootDigest = metadata.isDirectory()
? null
: await hashReadable(createReadStream(path), limits.maxTotalBytes, signal);
const reader = await createReader(path, rootFormat);
const reader = await createReader(path, rootFormat, nativeMount, signal);
try {
const { nodes, occurrences } = await scanReader(reader, limits, signal);
@@ -202,6 +223,8 @@ const inventoryLimitations = (
const createReader = async (
path: string,
format: ArtifactNode["format"],
nativeMount: ArtifactNativeMountPolicy,
signal?: AbortSignal,
): Promise<ArtifactReader | undefined> => {
switch (format) {
case "directory":
@@ -216,11 +239,42 @@ const createReader = async (
return process.platform === "darwin"
? new MachOSliceArtifactReader(path)
: undefined;
case "dmg":
if (!nativeMount.nativeMountApproved) return undefined;
if (!nativeMount.nativeMountEnabled)
throw new ArtifactReaderFailure(
"unavailable",
"Native DMG mounting is disabled by operator policy",
);
return NativeDmgArtifactReader.create(path, signal);
default:
return undefined;
}
};
const visitNestedAsar = async (
adapterKey: string,
logicalPath: string,
visit: (reader: ArtifactReader, prefix: string) => Promise<void>,
): Promise<void> => {
const nested = new AsarArtifactReader(adapterKey);
try {
await visit(nested, logicalPath);
} finally {
await nested.close();
}
};
const isExpandableAsar = (entry: ArtifactEntry, logicalPath: string): boolean =>
entry.kind === "file" &&
logicalPath.toLowerCase().endsWith(".asar") &&
entry.adapterKey.startsWith("/");
const emptyScan = (): {
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
} => ({ nodes: new Map(), occurrences: [] });
const scanReader = async (
reader: ArtifactReader | undefined,
limits: ArtifactLimits,
@@ -229,81 +283,96 @@ const scanReader = async (
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
}> => {
const nodes = new Map<string, ArtifactNode>();
const occurrences: MutableOccurrence[] = [];
const { nodes, occurrences } = emptyScan();
if (reader === undefined) return { nodes, occurrences };
const occurrenceByPath = new Map<string, MutableOccurrence>();
const registry = new ArtifactPathRegistry();
let totalBytes = 0;
for await (const entry of reader.entries(signal)) {
if (occurrences.length >= limits.maxEntries)
throw new ArtifactReaderFailure("limit", "Artifact entry limit exceeded");
const logicalPath = normalizeArtifactPath(entry.path, limits);
registry.add(logicalPath, entry.kind);
preflightEntry(entry, limits);
const parent = nearestParent(logicalPath, occurrenceByPath);
const occurrence = createOccurrence(
entry,
logicalPath,
parent?.occurrence_id ?? null,
);
if ((entry.kind === "file" || entry.kind === "slice") && !entry.encrypted) {
const remainingBytes = limits.maxTotalBytes - totalBytes;
if (remainingBytes <= 0)
throw new ArtifactReaderFailure(
"limit",
"Artifact total byte limit exceeded",
);
if (entry.declaredSize !== null && entry.declaredSize > remainingBytes)
throw new ArtifactReaderFailure(
"limit",
"Declared artifact bytes exceed remaining cumulative limit",
);
const digest = await hashReadable(
await reader.open(entry, signal),
Math.min(limits.maxEntryBytes, remainingBytes),
signal,
const digestEntry = async (
currentReader: ArtifactReader,
entry: ArtifactEntry,
logicalPath: string,
): Promise<ArtifactNode | undefined> => {
if ((entry.kind !== "file" && entry.kind !== "slice") || entry.encrypted)
return undefined;
const remainingBytes = limits.maxTotalBytes - totalBytes;
if (remainingBytes <= 0)
throw new ArtifactReaderFailure(
"limit",
"Artifact total byte limit exceeded",
);
totalBytes += digest.bytes;
if (
entry.declaredSha256 !== null &&
entry.declaredSha256 !== digest.sha256
)
throw new ArtifactReaderFailure(
"integrity",
`Artifact integrity metadata disagrees with content: ${logicalPath}`,
undefined,
{
logicalPath,
declaredSha256: entry.declaredSha256,
calculatedSha256: digest.sha256,
unpacked: entry.unpacked,
},
);
if (totalBytes > limits.maxTotalBytes)
if (entry.declaredSize !== null && entry.declaredSize > remainingBytes)
throw new ArtifactReaderFailure(
"limit",
"Declared artifact bytes exceed remaining cumulative limit",
);
const digest = await hashReadable(
await currentReader.open(entry, signal),
Math.min(limits.maxEntryBytes, remainingBytes),
signal,
);
totalBytes += digest.bytes;
if (entry.declaredSha256 !== null && entry.declaredSha256 !== digest.sha256)
throw new ArtifactReaderFailure(
"integrity",
`Artifact integrity metadata disagrees with content: ${logicalPath}`,
undefined,
{
logicalPath,
declaredSha256: entry.declaredSha256,
calculatedSha256: digest.sha256,
unpacked: entry.unpacked,
},
);
const classified =
entry.kind === "slice"
? ({ kind: "universal-slice", format: "mach-o" } as const)
: classifyArtifactContent(logicalPath, digest.prefix);
return createArtifactNode({
sha256: digest.sha256,
size: digest.bytes,
kind: classified.kind,
format: classified.format,
executable: entry.executable,
contentState: "embedded",
});
};
const visit = async (
currentReader: ArtifactReader,
prefix: string,
): Promise<void> => {
for await (const entry of currentReader.entries(signal)) {
if (occurrences.length >= limits.maxEntries)
throw new ArtifactReaderFailure(
"limit",
"Artifact total byte limit exceeded",
"Artifact entry limit exceeded",
);
const classified =
entry.kind === "slice"
? ({ kind: "universal-slice", format: "mach-o" } as const)
: classifyArtifactContent(logicalPath, digest.prefix);
const node = createArtifactNode({
sha256: digest.sha256,
size: digest.bytes,
kind: classified.kind,
format: classified.format,
executable: entry.executable,
contentState: "embedded",
});
nodes.set(node.artifact_id, node);
occurrence.artifact_id = node.artifact_id;
occurrence.hash_status = "verified";
const logicalPath = normalizeArtifactPath(
prefix.length === 0 ? entry.path : `${prefix}/${entry.path}`,
limits,
);
const expandableAsar = isExpandableAsar(entry, logicalPath);
registry.add(logicalPath, expandableAsar ? "directory" : entry.kind);
preflightEntry(entry, limits);
const parent = nearestParent(logicalPath, occurrenceByPath);
const occurrence = createOccurrence(
entry,
logicalPath,
parent?.occurrence_id ?? null,
);
const node = await digestEntry(currentReader, entry, logicalPath);
if (node !== undefined) {
nodes.set(node.artifact_id, node);
occurrence.artifact_id = node.artifact_id;
occurrence.hash_status = "verified";
}
occurrences.push(occurrence);
occurrenceByPath.set(logicalPath, occurrence);
if (expandableAsar)
await visitNestedAsar(entry.adapterKey, logicalPath, visit);
}
occurrences.push(occurrence);
occurrenceByPath.set(logicalPath, occurrence);
}
};
await visit(reader, "");
return { nodes, occurrences };
};
+2
View File
@@ -99,6 +99,8 @@ export const startCommandShimReplay = async (
sequence: events.length,
at_ms: Math.max(0, Date.now() - started),
command: invocation.command,
route_index:
routeIndex !== undefined && routeIndex >= 0 ? routeIndex : null,
arguments: invocation.arguments,
working_directory: invocation.working_directory,
outcome,
+12 -1
View File
@@ -11,6 +11,10 @@ import {
} from "../domain/evidenceBundle.js";
import { EvidenceFileError, EvidenceIntegrityError } from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import {
LEGACY_PROCESS_CAPTURE_MESSAGE,
parseProcessCapture,
} from "../domain/processCapture.js";
type EvidenceReadFailure = EvidenceFileError | EvidenceIntegrityError;
type EvidenceWriteFailure = EvidenceFileError | EvidenceIntegrityError;
@@ -42,7 +46,14 @@ export const readEvidenceBundle = async (
const limits = validateJsonLimits(decoded, policy);
if (!limits.ok) return limits;
try {
return ok(parseEvidenceBundle(decoded));
const bundle = parseEvidenceBundle(decoded);
for (const record of bundle.records) {
if (record.predicate_type === "rea.process-capture/v3")
throw new TypeError(LEGACY_PROCESS_CAPTURE_MESSAGE);
if (record.predicate_type === "rea.process-capture/v4")
parseProcessCapture(record.normalized_result);
}
return ok(bundle);
} catch (cause: unknown) {
return err(
new EvidenceIntegrityError("Evidence bundle validation failed", {
@@ -0,0 +1,48 @@
import { realpath } from "node:fs/promises";
import type {
ProcessExecutionPolicy,
ProcessScenario,
} from "../domain/processCapture.js";
import { ProcessCaptureError } from "./ProcessCaptureError.js";
const isWithin = (candidate: string, root: string): boolean =>
candidate === root ||
candidate.startsWith(`${root.endsWith("/") ? root.slice(0, -1) : root}/`);
export const assertRealPathAuthority = async (
scenario: ProcessScenario,
policy: ProcessExecutionPolicy,
): Promise<void> => {
const executable = await realpath(scenario.executable);
const executableRoots = await Promise.all(
policy.executableRoots.map((root) => realpath(root)),
);
if (!executableRoots.some((root) => isWithin(executable, root)))
throw new ProcessCaptureError(
"resolved executable is outside approved roots",
);
const workingDirectory = await realpath(scenario.working_directory);
const workingRoots = await Promise.all(
policy.workingRoots.map((root) => realpath(root)),
);
if (!workingRoots.some((root) => isWithin(workingDirectory, root)))
throw new ProcessCaptureError(
"resolved working directory is outside approved roots",
);
for (const root of scenario.filesystem_roots) {
const resolvedRoot = await realpath(root);
if (!workingRoots.some((approved) => isWithin(resolvedRoot, approved)))
throw new ProcessCaptureError(
"resolved filesystem root is outside approved roots",
);
}
};
/** Expected refusal or runtime failure from the process capture adapter. */
export const assertNotCancelled = (signal: AbortSignal | undefined): void => {
if (signal?.aborted === true)
throw new ProcessCaptureError("process capture was cancelled");
};
/** Runtime availability of the native PTY adapter on this host. */
@@ -0,0 +1,38 @@
import { tmpdir } from "node:os";
import { spawn } from "node-pty";
export type ProcessCaptureCapability =
| { readonly available: true; readonly backend: "node-pty" }
| {
readonly available: false;
readonly backend: "node-pty";
readonly reason: string;
};
/** Probe the actual native PTY seam instead of inferring support from the OS name. */
export const probeProcessCaptureCapability =
async (): Promise<ProcessCaptureCapability> => {
try {
const terminal = spawn(
process.platform === "win32" ? "cmd.exe" : "/bin/sh",
process.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 {
return {
available: false,
backend: "node-pty",
reason: "the native PTY backend could not start a probe process",
};
}
};
+6
View File
@@ -0,0 +1,6 @@
import { AnalysisError } from "../domain/errors.js";
/** Typed application failure produced by controlled process capture. */
export class ProcessCaptureError extends AnalysisError {
readonly _tag = "ProcessCaptureError";
}
+417
View File
@@ -0,0 +1,417 @@
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 "node-pty";
import type {
FilesystemCheckpoint,
InteractionEvent,
ProcessCapture,
ProcessExecutionPolicy,
ProcessSample,
ProcessScenario,
TerminalFrame,
} from "../domain/processCapture.js";
import {
authorizeProcessScenario,
digestProcessCommitment,
processComparisonContract,
processScenarioCommitment,
} from "../domain/processCapture.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import type { SnapshotResult } from "./FilesystemSnapshot.js";
import { snapshotRoots } from "./FilesystemSnapshot.js";
import type { LoopbackReplay } from "./LoopbackReplay.js";
import {
cleanupOwnedProcessGroup,
observeOwnedProcessGroup,
} from "./ProcessOwnership.js";
import {
classifyFilesystemEffects,
ProcessCheckpoints,
} from "./ProcessCheckpoints.js";
import { ProcessCaptureError } from "./ProcessCaptureError.js";
import {
assertNotCancelled,
assertRealPathAuthority,
} from "./ProcessCaptureAuthority.js";
import {
normalizeProcessSamples,
normalizeProcessText,
redactProtocolEvents,
} from "./ProcessNormalization.js";
import type { CommandShimReplay } from "./CommandShimReplay.js";
import { PROCESS_PROVIDER } from "./ProcessEvidence.js";
import { TerminalRenderer } from "./TerminalRenderer.js";
interface TerminalExitOptions {
readonly terminal: IPty;
readonly scenario: ProcessScenario;
readonly started: number;
readonly lastOutput: () => number;
readonly signal: AbortSignal | undefined;
readonly timers: Set<NodeJS.Timeout>;
readonly interactions: InteractionEvent[];
readonly dispatchedEventIndexes: ReadonlySet<number>;
}
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 replay: LoopbackReplay;
readonly before: SnapshotResult;
readonly after: SnapshotResult;
readonly truncated: boolean;
readonly scenario: ProcessScenario;
readonly rootPid: number;
readonly samplingPartial: boolean;
readonly renderedFrames: ProcessCapture["rendered_frames"];
readonly interactions: readonly InteractionEvent[];
readonly checkpoints: readonly FilesystemCheckpoint[];
readonly shimEvents: ProcessCapture["shim_events"];
readonly settlement: ProcessCapture["settlement"];
readonly manifest: ProcessCapture["manifest"];
}
export const buildCaptureResult = (
options: CaptureResultOptions,
): ProcessCapture => ({
schema_version: 4,
manifest: options.manifest,
normalization: options.scenario.normalization,
frames: options.frames,
rendered_frames: [...options.renderedFrames]
.sort(
(left, right) =>
left.at_ms - right.at_ms || left.sequence - right.sequence,
)
.map((frame, sequence) => ({ ...frame, sequence })),
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,
shim_events: options.shimEvents,
protocol_events: redactProtocolEvents(
options.replay.events,
options.scenario,
),
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.",
"The harness does not enforce external network isolation.",
],
residual_unknowns: [
{
scope: "process",
reason: "Process trees are sampled and may omit short-lived descendants.",
},
{
scope: "network",
reason: "External network isolation is not enforced by this adapter.",
},
],
cleanup: {
owned_process_group: "verified",
temporary_root: "removed",
},
});
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,
): Promise<ProcessCapture["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: process.platform,
architecture: process.arch,
pty_backend: "node-pty",
started_at: startedAt.toISOString(),
completed_at: completedAt.toISOString(),
scenario: scenarioCommitment,
comparison_contract: comparisonContract,
shim_plan: scenario.command_shims,
replay_plan: scenario.replay,
full_scenario_sha256: digestProcessCommitment(scenarioCommitment),
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
executable_sha256: executableSha256,
normalization_sha256: digestProcessCommitment(scenario.normalization),
shim_plan_sha256: digestProcessCommitment(scenario.command_shims),
replay_plan_sha256: digestProcessCommitment(scenario.replay),
};
};
export const observeSettlement = async (
runId: string,
processGroupIds: readonly number[],
settleMs: number,
): Promise<Omit<ProcessCapture["settlement"], "cleanup_outcome">> => {
if (process.platform === "win32")
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"))
return { state: "unverifiable", elapsed_ms: Date.now() - started };
if (observations.every(({ state }) => state === "empty")) {
consecutiveEmpty += 1;
if (consecutiveEmpty >= 2)
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));
}
return { state: "alive_at_deadline", elapsed_ms: Date.now() - started };
};
export const awaitTerminalExit = async ({
terminal,
scenario,
started,
lastOutput,
signal,
timers,
interactions,
dispatchedEventIndexes,
}: 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) => {
for (const [eventIndex, event] of scenario.events.entries()) {
if (dispatchedEventIndexes.has(eventIndex)) continue;
interactions.push({
sequence: interactions.length,
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",
});
}
for (const timer of timers) {
clearTimeout(timer);
clearInterval(timer);
}
timers.clear();
resolveExit({ ...exit, reason });
});
const timeout = setInterval(() => {
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);
});
export const releaseProcessResources = async (options: {
readonly timers: ReadonlySet<NodeJS.Timeout>;
readonly replay: LoopbackReplay | undefined;
readonly terminal: IPty | undefined;
readonly renderer: TerminalRenderer | undefined;
readonly shimReplay: CommandShimReplay | undefined;
readonly checkpoints: ProcessCheckpoints | undefined;
readonly runId: string;
readonly temporaryRoot: string;
readonly sampledProcessGroupIds: readonly number[];
}): Promise<string | undefined> => {
for (const timer of options.timers) clearTimeout(timer);
let failure: string | undefined;
try {
await options.replay?.close();
} catch {
failure = "loopback replay cleanup failed";
}
try {
await options.shimReplay?.close();
} catch {
failure ??= "command shim replay cleanup failed";
}
try {
await options.renderer?.dispose();
} catch {
failure ??= "terminal renderer cleanup failed";
}
try {
await options.checkpoints?.dispose();
} catch {
failure ??= "filesystem checkpoint cleanup failed";
}
if (options.terminal !== undefined && process.platform !== "win32") {
const processGroupIds = new Set([
options.terminal.pid,
...options.sampledProcessGroupIds,
]);
for (const processGroupId of processGroupIds) {
const cleaned = await cleanupOwnedProcessGroup({
runId: options.runId,
leaderPid: processGroupId,
processGroupId,
});
if (!cleaned.cleaned) failure ??= cleaned.reason;
}
}
try {
await rm(options.temporaryRoot, { recursive: true, force: true });
} catch {
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 onFirstOutput: () => void;
readonly renderer: TerminalRenderer;
readonly checkpoints: ProcessCheckpoints;
}): (() => boolean) => {
let outputBytes = 0;
let truncated = false;
options.terminal.onData((data) => {
options.onFirstOutput();
options.onOutput();
const bytes = Buffer.byteLength(data);
if (
options.frames.length >= options.scenario.limits.frames ||
outputBytes + bytes > options.scenario.limits.output_bytes
) {
truncated = true;
return;
}
outputBytes += bytes;
const atMs =
Math.floor(
(Date.now() - options.started) /
options.scenario.normalization.time_bucket_ms,
) * options.scenario.normalization.time_bucket_ms;
const normalized = normalizeProcessText(
data,
options.scenario,
options.temporaryRoot,
options.terminal.pid,
);
options.frames.push({
sequence: options.frames.length,
at_ms: atMs,
data: normalized,
});
options.renderer.write(data, atMs);
options.checkpoints.observeTerminal(normalized);
});
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);
if (capture === undefined)
throw new ProcessCaptureError("process capture produced no result");
return capture;
};
export const prepareProcessCapture = async (
scenario: ProcessScenario,
policy: ProcessExecutionPolicy,
signal: AbortSignal | undefined,
): Promise<{
readonly temporaryRoot: string;
readonly runId: string;
readonly home: string;
readonly before: SnapshotResult;
}> => {
const decision = authorizeProcessScenario(scenario, policy);
if (!decision.allowed) throw new ProcessCaptureError(decision.reason);
await assertRealPathAuthority(scenario, policy);
assertNotCancelled(signal);
const before = await snapshotRoots(scenario, signal);
const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-process-"));
const runId = randomUUID();
const home = join(temporaryRoot, "home");
await import("node:fs/promises").then(({ mkdir }) => mkdir(home));
return { temporaryRoot, runId, home, before };
};
+10 -6
View File
@@ -5,8 +5,9 @@ import { createEvidence, parseEvidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import {
compareProcessCaptures,
LEGACY_PROCESS_CAPTURE_MESSAGE,
parseProcessScenario,
processCaptureSchema,
parseProcessCapture,
} from "../domain/processCapture.js";
import { captureProcessScenario } from "./ProcessHarness.js";
import {
@@ -38,7 +39,7 @@ export const compareProcessEvidenceFiles = async (
const right = parseCaptureEvidence(await readJson(rightPath));
const comparison = compareProcessCaptures(left.capture, right.capture);
return createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-comparison/v2",
predicateType: "rea.process-comparison/v3",
operation: "compare_process_captures",
parameters: {
left_evidence_id: left.id,
@@ -58,14 +59,17 @@ const parseCaptureEvidence = (input: unknown) => {
const evidence = parseEvidence(input);
if (
evidence.operation !== "capture_process_scenario" ||
evidence.predicate_type !== "rea.process-capture/v3" ||
evidence.predicate_type !== "rea.process-capture/v4" ||
evidence.provider.id !== PROCESS_PROVIDER.id ||
evidence.provider.version !== PROCESS_PROVIDER.version
)
throw new TypeError("Expected REA Process Capture v3 Evidence");
) {
if (evidence.predicate_type === "rea.process-capture/v3")
throw new TypeError(LEGACY_PROCESS_CAPTURE_MESSAGE);
throw new TypeError("Expected REA Process Capture v4 Evidence");
}
return {
id: evidence.evidence_id,
capture: processCaptureSchema.parse(evidence.normalized_result),
capture: parseProcessCapture(evidence.normalized_result),
};
};
+11 -8
View File
@@ -5,12 +5,13 @@ import type {
ProcessCapture,
ProcessScenario,
} from "../domain/processCapture.js";
import { parseProcessCapture } from "../domain/processCapture.js";
/** Provider identity for controlled Process Capture v3 evidence. */
/** Provider identity for controlled Process Capture v4 evidence. */
export const PROCESS_PROVIDER = {
id: "rea-process",
name: "REA deterministic process harness",
version: "2",
version: "3",
} as const;
/** Project one process scenario into secret-free Evidence parameters. */
@@ -26,16 +27,17 @@ const processEvidenceParameters = (
normalization: scenario.normalization,
});
/** Create one canonical observed Process Capture v3 Evidence record. */
/** Create one canonical observed Process Capture v4 Evidence record. */
export const createProcessCaptureEvidence = (
scenario: ProcessScenario,
capture: ProcessCapture,
) =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture/v3",
) => {
const validatedCapture = parseProcessCapture(capture);
return createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture/v4",
operation: "capture_process_scenario",
parameters: processEvidenceParameters(scenario),
result: jsonValueSchema.parse(capture),
result: jsonValueSchema.parse(validatedCapture),
confidence: "observed",
authority: "controlled-replay",
environment: {
@@ -44,5 +46,6 @@ export const createProcessCaptureEvidence = (
architecture: process.arch,
isolation: "process",
},
limitations: capture.limitations,
limitations: validatedCapture.limitations,
});
};
+314 -486
View File
@@ -1,10 +1,5 @@
import { randomUUID } from "node:crypto";
import { mkdtemp, realpath, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawn, type IPty } from "node-pty";
import type {
FilesystemCheckpoint,
InteractionEvent,
ProcessCapture,
ProcessExecutionPolicy,
@@ -12,107 +7,34 @@ import type {
ProcessScenario,
TerminalFrame,
} from "../domain/processCapture.js";
import { authorizeProcessScenario } from "../domain/processCapture.js";
import { validateProcessCapture } from "../domain/processCapture.js";
import { err, ok, type Result } from "../domain/result.js";
import { AnalysisError } from "../domain/errors.js";
import { ProcessCaptureError } from "./ProcessCaptureError.js";
export { ProcessCaptureError } from "./ProcessCaptureError.js";
import { startLoopbackReplay, type LoopbackReplay } from "./LoopbackReplay.js";
import { cleanupOwnedProcessGroup } from "./ProcessOwnership.js";
import { startProcessSampler } from "./ProcessSampling.js";
import { snapshotRoots, type SnapshotResult } from "./FilesystemSnapshot.js";
import {
classifyFilesystemEffects,
ProcessCheckpoints,
} from "./ProcessCheckpoints.js";
import { snapshotRoots } from "./FilesystemSnapshot.js";
import { ProcessCheckpoints } from "./ProcessCheckpoints.js";
import { TerminalRenderer } from "./TerminalRenderer.js";
import {
startCommandShimReplay,
type CommandShimReplay,
} from "./CommandShimReplay.js";
import { normalizeProcessText } from "./ProcessNormalization.js";
import {
normalizeProcessSamples,
normalizeProcessText,
redactProtocolEvents,
} from "./ProcessNormalization.js";
awaitTerminalExit,
buildCaptureResult,
captureTerminalFrames,
createRunManifest,
observeSettlement,
prepareProcessCapture,
releaseProcessResources,
resolveProcessResult,
} from "./ProcessCaptureLifecycle.js";
import { assertNotCancelled } from "./ProcessCaptureAuthority.js";
const isWithin = (candidate: string, root: string): boolean =>
candidate === root ||
candidate.startsWith(`${root.endsWith("/") ? root.slice(0, -1) : root}/`);
const assertRealPathAuthority = async (
scenario: ProcessScenario,
policy: ProcessExecutionPolicy,
): Promise<void> => {
const executable = await realpath(scenario.executable);
const executableRoots = await Promise.all(
policy.executableRoots.map((root) => realpath(root)),
);
if (!executableRoots.some((root) => isWithin(executable, root)))
throw new ProcessCaptureError(
"resolved executable is outside approved roots",
);
const workingDirectory = await realpath(scenario.working_directory);
const workingRoots = await Promise.all(
policy.workingRoots.map((root) => realpath(root)),
);
if (!workingRoots.some((root) => isWithin(workingDirectory, root)))
throw new ProcessCaptureError(
"resolved working directory is outside approved roots",
);
for (const root of scenario.filesystem_roots) {
const resolvedRoot = await realpath(root);
if (!workingRoots.some((approved) => isWithin(resolvedRoot, approved)))
throw new ProcessCaptureError(
"resolved filesystem root is outside approved roots",
);
}
};
/** Expected refusal or runtime failure from the process capture adapter. */
export class ProcessCaptureError extends AnalysisError {
readonly _tag = "ProcessCaptureError";
}
const assertNotCancelled = (signal: AbortSignal | undefined): void => {
if (signal?.aborted === true)
throw new ProcessCaptureError("process capture was cancelled");
};
/** Runtime availability of the native PTY adapter on this host. */
export type ProcessCaptureCapability =
| { readonly available: true; readonly backend: "node-pty" }
| {
readonly available: false;
readonly backend: "node-pty";
readonly reason: string;
};
/** Probe the actual native PTY seam instead of inferring support from the OS name. */
export const probeProcessCaptureCapability =
async (): Promise<ProcessCaptureCapability> => {
try {
const terminal = spawn(
process.platform === "win32" ? "cmd.exe" : "/bin/sh",
process.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 {
return {
available: false,
backend: "node-pty",
reason: "the native PTY backend could not start a probe process",
};
}
};
export { probeProcessCaptureCapability } from "./ProcessCaptureCapability.js";
interface EnvironmentOptions {
readonly scenario: ProcessScenario;
@@ -219,151 +141,22 @@ const eventsRequireReadiness = (scenario: ProcessScenario): boolean =>
(event) => event.type === "input" || event.type === "resize",
);
interface TerminalExitOptions {
readonly terminal: IPty;
readonly scenario: ProcessScenario;
readonly started: number;
readonly lastOutput: () => number;
readonly signal: AbortSignal | undefined;
readonly timers: Set<NodeJS.Timeout>;
readonly interactions: InteractionEvent[];
readonly dispatchedEventIndexes: ReadonlySet<number>;
}
interface CaptureResultOptions {
readonly frames: readonly TerminalFrame[];
readonly exit: {
readonly exitCode: number;
readonly signal?: number;
readonly reason: "exited" | "timeout" | "idle_timeout";
};
readonly samples: readonly ProcessSample[];
interface StartedCaptureRuntime {
readonly replay: LoopbackReplay;
readonly before: SnapshotResult;
readonly after: SnapshotResult;
readonly truncated: boolean;
readonly scenario: ProcessScenario;
readonly rootPid: number;
readonly samplingPartial: boolean;
readonly renderedFrames: ProcessCapture["rendered_frames"];
readonly interactions: readonly InteractionEvent[];
readonly checkpoints: readonly FilesystemCheckpoint[];
readonly shimEvents: ProcessCapture["shim_events"];
readonly renderer: TerminalRenderer;
readonly checkpoints: ProcessCheckpoints;
readonly shimReplay: CommandShimReplay;
readonly terminal: IPty;
readonly started: number;
readonly startedAt: Date;
readonly lastOutput: () => number;
readonly framesTruncated: () => boolean;
readonly stopSampler: () => Promise<{ readonly partial: boolean }>;
}
const buildCaptureResult = (options: CaptureResultOptions): ProcessCapture => ({
schema_version: 3,
normalization: options.scenario.normalization,
frames: options.frames,
rendered_frames: options.renderedFrames,
interaction_events: options.interactions,
exit: {
code: options.exit.exitCode < 0 ? null : options.exit.exitCode,
signal: options.exit.signal ?? null,
reason: options.exit.reason,
},
process_samples: normalizeProcessSamples(
options.samples,
options.scenario,
options.rootPid,
),
filesystem_checkpoints: options.checkpoints,
shim_events: options.shimEvents,
protocol_events: redactProtocolEvents(
options.replay.events,
options.scenario,
),
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.",
"The harness does not enforce external network isolation.",
],
residual_unknowns: [
{
scope: "process",
reason: "Process trees are sampled and may omit short-lived descendants.",
},
{
scope: "network",
reason: "External network isolation is not enforced by this adapter.",
},
],
cleanup: {
owned_process_group: "verified",
temporary_root: "removed",
},
});
const awaitTerminalExit = async ({
terminal,
scenario,
started,
lastOutput,
signal,
timers,
interactions,
dispatchedEventIndexes,
}: 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) => {
for (const [eventIndex, event] of scenario.events.entries()) {
if (dispatchedEventIndexes.has(eventIndex)) continue;
interactions.push({
sequence: interactions.length,
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",
});
}
for (const timer of timers) {
clearTimeout(timer);
clearInterval(timer);
}
timers.clear();
resolveExit({ ...exit, reason });
});
const timeout = setInterval(() => {
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);
});
const releaseProcessResources = async (options: {
readonly timers: ReadonlySet<NodeJS.Timeout>;
const cleanupFailedStartup = async (options: {
readonly cause: unknown;
readonly timers: Set<NodeJS.Timeout>;
readonly replay: LoopbackReplay | undefined;
readonly terminal: IPty | undefined;
readonly renderer: TerminalRenderer | undefined;
@@ -371,136 +164,264 @@ const releaseProcessResources = async (options: {
readonly checkpoints: ProcessCheckpoints | undefined;
readonly runId: string;
readonly temporaryRoot: string;
readonly sampledProcessGroupIds: readonly number[];
}): Promise<string | undefined> => {
for (const timer of options.timers) clearTimeout(timer);
let failure: string | undefined;
try {
await options.replay?.close();
} catch {
failure = "loopback replay cleanup failed";
}
try {
await options.shimReplay?.close();
} catch {
failure ??= "command shim replay cleanup failed";
}
try {
await options.renderer?.dispose();
} catch {
failure ??= "terminal renderer cleanup failed";
}
try {
await options.checkpoints?.dispose();
} catch {
failure ??= "filesystem checkpoint cleanup failed";
}
if (options.terminal !== undefined && process.platform !== "win32") {
const processGroupIds = new Set([
options.terminal.pid,
...options.sampledProcessGroupIds,
]);
for (const processGroupId of processGroupIds) {
const cleaned = await cleanupOwnedProcessGroup({
runId: options.runId,
leaderPid: processGroupId,
processGroupId,
});
if (!cleaned.cleaned) failure ??= cleaned.reason;
}
}
try {
await rm(options.temporaryRoot, { recursive: true, force: true });
} catch {
failure ??= "temporary process root cleanup failed";
}
return failure;
};
const captureTerminalFrames = (options: {
readonly terminal: IPty;
readonly scenario: ProcessScenario;
readonly frames: TerminalFrame[];
readonly started: number;
readonly temporaryRoot: string;
readonly onOutput: () => void;
readonly onFirstOutput: () => void;
readonly renderer: TerminalRenderer;
readonly checkpoints: ProcessCheckpoints;
}): (() => boolean) => {
let outputBytes = 0;
let truncated = false;
options.terminal.onData((data) => {
options.onFirstOutput();
options.onOutput();
const bytes = Buffer.byteLength(data);
if (
options.frames.length >= options.scenario.limits.frames ||
outputBytes + bytes > options.scenario.limits.output_bytes
) {
truncated = true;
return;
}
outputBytes += bytes;
const atMs =
Math.floor(
(Date.now() - options.started) /
options.scenario.normalization.time_bucket_ms,
) * options.scenario.normalization.time_bucket_ms;
const normalized = normalizeProcessText(
data,
options.scenario,
options.temporaryRoot,
options.terminal.pid,
);
options.frames.push({
sequence: options.frames.length,
at_ms: atMs,
data: normalized,
});
options.renderer.write(data, atMs);
options.checkpoints.observeTerminal(normalized);
}): Promise<never> => {
options.terminal?.kill("SIGKILL");
const cleanupFailure = await releaseProcessResources({
...options,
sampledProcessGroupIds: [],
});
return () => truncated;
};
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);
if (capture === undefined)
throw new ProcessCaptureError("process capture produced no result");
return capture;
throw new ProcessCaptureError(cleanupFailure, { cause: options.cause });
throw options.cause;
};
const prepareProcessCapture = async (
const createTerminalRenderer = (
scenario: ProcessScenario,
policy: ProcessExecutionPolicy,
signal: AbortSignal | undefined,
): Promise<{
temporaryRoot: string,
terminalPid: () => number,
): TerminalRenderer =>
new TerminalRenderer({
columns: scenario.terminal.columns,
rows: scenario.terminal.rows,
scrollback: scenario.terminal.scrollback,
maxFrames: scenario.limits.frames,
maxBytes: scenario.limits.output_bytes,
normalize: (value) =>
normalizeProcessText(value, scenario, temporaryRoot, terminalPid()),
});
const startCaptureRuntime = async (options: {
readonly scenario: ProcessScenario;
readonly home: string;
readonly temporaryRoot: string;
readonly runId: string;
readonly home: string;
readonly before: SnapshotResult;
}> => {
const decision = authorizeProcessScenario(scenario, policy);
if (!decision.allowed) throw new ProcessCaptureError(decision.reason);
await assertRealPathAuthority(scenario, policy);
assertNotCancelled(signal);
const before = await snapshotRoots(scenario, signal);
const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-process-"));
const runId = randomUUID();
const home = join(temporaryRoot, "home");
await import("node:fs/promises").then(({ mkdir }) => mkdir(home));
return { temporaryRoot, runId, home, before };
readonly before: Awaited<ReturnType<typeof snapshotRoots>>;
readonly frames: TerminalFrame[];
readonly samples: ProcessSample[];
readonly interactions: InteractionEvent[];
readonly timers: Set<NodeJS.Timeout>;
readonly dispatchedEventIndexes: Set<number>;
readonly signal?: AbortSignal;
}): Promise<StartedCaptureRuntime> => {
const { scenario } = options;
let replay: LoopbackReplay | undefined;
let renderer: TerminalRenderer | undefined;
let checkpoints: ProcessCheckpoints | undefined;
let shimReplay: CommandShimReplay | undefined;
let terminal: IPty | undefined;
try {
replay = await startLoopbackReplay(scenario);
const startedAt = new Date();
const started = Date.now();
let lastOutput = started;
renderer = createTerminalRenderer(
scenario,
options.temporaryRoot,
() => terminal?.pid ?? -1,
);
checkpoints = new ProcessCheckpoints(
scenario,
started,
options.before,
options.signal,
);
shimReplay = await startCommandShimReplay(
scenario,
options.temporaryRoot,
started,
);
terminal = spawn(scenario.executable, [...scenario.arguments], {
cwd: scenario.working_directory,
env: makeEnvironment({ ...options, replay, shimReplay }),
cols: scenario.terminal.columns,
rows: scenario.terminal.rows,
name: "xterm-256color",
});
const startEvents = startScenarioEvents({
...options,
getTerminal: () => terminal,
renderer,
started,
});
if (!eventsRequireReadiness(scenario)) startEvents();
const framesTruncated = captureTerminalFrames({
...options,
terminal,
started,
onOutput: () => (lastOutput = Date.now()),
onFirstOutput: startEvents,
renderer,
checkpoints,
});
const stopSampler = startProcessSampler(
terminal.pid,
started,
scenario.limits.processes,
options.samples,
);
return {
replay,
renderer,
checkpoints,
shimReplay,
terminal,
started,
startedAt,
lastOutput: () => lastOutput,
framesTruncated,
stopSampler,
};
} catch (cause: unknown) {
return cleanupFailedStartup({
cause,
timers: options.timers,
replay,
terminal,
renderer,
shimReplay,
checkpoints,
runId: options.runId,
temporaryRoot: options.temporaryRoot,
});
}
};
const normalizedShimEvents = (
runtime: StartedCaptureRuntime,
scenario: ProcessScenario,
temporaryRoot: string,
): ProcessCapture["shim_events"] =>
runtime.shimReplay.events.map((event) => ({
...event,
arguments: event.arguments.map((argument) =>
normalizeProcessText(
argument,
scenario,
temporaryRoot,
runtime.terminal.pid,
),
),
working_directory: normalizeProcessText(
event.working_directory,
scenario,
temporaryRoot,
runtime.terminal.pid,
),
}));
const finishProcessRun = async (options: {
readonly runtime: StartedCaptureRuntime | undefined;
readonly timers: Set<NodeJS.Timeout>;
readonly runId: string;
readonly temporaryRoot: string;
readonly samples: readonly ProcessSample[];
readonly stopSampler: () => Promise<{ readonly partial: boolean }>;
readonly capture: ProcessCapture | undefined;
readonly executionFailure: unknown;
}): Promise<ProcessCapture> => {
await options.stopSampler();
const cleanupFailure = await releaseProcessResources({
timers: options.timers,
replay: options.runtime?.replay,
terminal: options.runtime?.terminal,
renderer: options.runtime?.renderer,
shimReplay: options.runtime?.shimReplay,
checkpoints: options.runtime?.checkpoints,
runId: options.runId,
temporaryRoot: options.temporaryRoot,
sampledProcessGroupIds: options.samples.flatMap(({ process_group_id }) =>
process_group_id === null ? [] : [process_group_id],
),
});
let { capture, executionFailure } = options;
if (capture !== undefined) {
capture = {
...capture,
settlement: {
...capture.settlement,
cleanup_outcome:
capture.settlement.state === "quiesced"
? "not_required"
: cleanupFailure === undefined
? "cleaned"
: "failed",
},
};
const issue = validateProcessCapture(capture)[0];
if (issue !== undefined)
executionFailure = new ProcessCaptureError(
`process capture validation failed: ${issue.path}: ${issue.message}`,
);
}
return resolveProcessResult(capture, executionFailure, cleanupFailure);
};
const completeCapture = async (options: {
readonly scenario: ProcessScenario;
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 initiallyTruncated: boolean;
}): Promise<ProcessCapture> => {
const { runtime, scenario } = options;
runtime.checkpoints.trigger("root_exit");
const { reason } = options.exit;
if (reason === "cancelled")
throw new ProcessCaptureError("process capture was cancelled");
const settlement = await observeSettlement(
options.runId,
[
runtime.terminal.pid,
...options.samples.flatMap(({ process_group_id }) =>
process_group_id === null ? [] : [process_group_id],
),
],
scenario.settle_ms,
);
runtime.checkpoints.trigger("settled");
const samplingPartial = (await runtime.stopSampler()).partial;
assertNotCancelled(options.signal);
const after = await snapshotRoots(scenario, options.signal);
const renderedFrames = await runtime.renderer.frames();
const checkpoints = await runtime.checkpoints.finish(after);
const manifest = await createRunManifest(
scenario,
runtime.startedAt,
new Date(),
);
const truncated =
options.initiallyTruncated ||
after.truncated ||
runtime.replay.truncated ||
runtime.shimReplay.truncated ||
runtime.framesTruncated() ||
checkpoints.some(({ truncated: partial }) => partial) ||
samplingPartial ||
runtime.renderer.truncated();
return buildCaptureResult({
frames: options.frames,
exit: { ...options.exit, reason },
samples: options.samples,
replay: runtime.replay,
before: options.before,
after,
truncated,
scenario,
rootPid: runtime.terminal.pid,
samplingPartial,
renderedFrames,
interactions: options.interactions,
checkpoints,
shimEvents: normalizedShimEvents(runtime, scenario, options.temporaryRoot),
settlement: { ...settlement, cleanup_outcome: "not_required" },
manifest,
});
};
/** Execute one authorized scenario and return bounded observations. */
@@ -516,159 +437,66 @@ const runProcessScenario = async (
);
const frames: TerminalFrame[] = [];
const samples: ProcessSample[] = [];
let truncated = before.truncated;
let terminal: IPty | undefined;
let replay: LoopbackReplay | undefined;
let renderer: TerminalRenderer | undefined;
let checkpoints: ProcessCheckpoints | undefined;
let shimReplay: CommandShimReplay | undefined;
let started = 0;
let lastOutput = 0;
let runtime: StartedCaptureRuntime | undefined;
const timers = new Set<NodeJS.Timeout>();
let capture: ProcessCapture | undefined;
let executionFailure: unknown;
let framesTruncated = (): boolean => false;
let stopSampler = async () => ({ partial: false });
let samplingPartial = false;
const interactions: InteractionEvent[] = [];
const dispatchedEventIndexes = new Set<number>();
try {
replay = await startLoopbackReplay(scenario);
started = Date.now();
lastOutput = started;
renderer = new TerminalRenderer({
columns: scenario.terminal.columns,
rows: scenario.terminal.rows,
scrollback: scenario.terminal.scrollback,
maxFrames: scenario.limits.frames,
maxBytes: scenario.limits.output_bytes,
normalize: (value) =>
normalizeProcessText(
value,
scenario,
temporaryRoot,
terminal?.pid ?? -1,
),
});
checkpoints = new ProcessCheckpoints(scenario, started, before, signal);
shimReplay = await startCommandShimReplay(scenario, temporaryRoot, started);
terminal = spawn(scenario.executable, [...scenario.arguments], {
cwd: scenario.working_directory,
env: makeEnvironment({ scenario, home, replay, shimReplay, runId }),
cols: scenario.terminal.columns,
rows: scenario.terminal.rows,
name: "xterm-256color",
});
const startEvents = startScenarioEvents({
runtime = await startCaptureRuntime({
scenario,
getTerminal: () => terminal,
timers,
interactions,
renderer,
started,
dispatchedEventIndexes,
});
if (!eventsRequireReadiness(scenario)) startEvents();
framesTruncated = captureTerminalFrames({
terminal,
scenario,
frames,
started,
home,
temporaryRoot,
onOutput: () => (lastOutput = Date.now()),
onFirstOutput: startEvents,
renderer,
checkpoints,
});
stopSampler = startProcessSampler(
terminal.pid,
started,
scenario.limits.processes,
runId,
before,
frames,
samples,
);
interactions,
timers,
dispatchedEventIndexes,
...(signal === undefined ? {} : { signal }),
});
stopSampler = runtime.stopSampler;
const exit = await awaitTerminalExit({
terminal,
terminal: runtime.terminal,
scenario,
started,
lastOutput: () => lastOutput,
started: runtime.started,
lastOutput: runtime.lastOutput,
signal,
timers,
interactions,
dispatchedEventIndexes,
});
const exitReason = exit.reason;
checkpoints.trigger("root_exit");
if (exitReason === "cancelled")
throw new ProcessCaptureError("process capture was cancelled");
await new Promise((resolveSettle) =>
setTimeout(resolveSettle, scenario.settle_ms),
);
checkpoints.trigger("settled");
samplingPartial = (await stopSampler()).partial;
assertNotCancelled(signal);
const after = await snapshotRoots(scenario, signal);
const renderedFrames = await renderer.frames();
const filesystemCheckpoints = await checkpoints.finish(after);
truncated ||=
after.truncated ||
replay.truncated ||
shimReplay.truncated ||
framesTruncated() ||
filesystemCheckpoints.some(({ truncated: partial }) => partial) ||
samplingPartial;
truncated ||= renderer.truncated();
capture = buildCaptureResult({
frames,
exit: { ...exit, reason: exitReason },
samples,
replay,
before,
after,
truncated,
capture = await completeCapture({
scenario,
rootPid: terminal.pid,
samplingPartial,
renderedFrames,
runtime,
runId,
temporaryRoot,
before,
frames,
samples,
interactions,
checkpoints: filesystemCheckpoints,
shimEvents: shimReplay.events.map((event) => ({
...event,
arguments: event.arguments.map((argument) =>
normalizeProcessText(
argument,
scenario,
temporaryRoot,
terminal?.pid ?? -1,
),
),
working_directory: normalizeProcessText(
event.working_directory,
scenario,
temporaryRoot,
terminal?.pid ?? -1,
),
})),
exit,
initiallyTruncated: before.truncated,
...(signal === undefined ? {} : { signal }),
});
} catch (cause: unknown) {
terminal?.kill("SIGKILL");
runtime?.terminal.kill("SIGKILL");
executionFailure = cause;
}
samplingPartial ||= (await stopSampler()).partial;
const cleanupFailure = await releaseProcessResources({
return finishProcessRun({
runtime,
timers,
replay,
terminal,
renderer,
shimReplay,
checkpoints,
runId,
temporaryRoot,
sampledProcessGroupIds: samples.flatMap(({ process_group_id }) =>
process_group_id === null ? [] : [process_group_id],
),
samples,
stopSampler,
capture,
executionFailure,
});
return resolveProcessResult(capture, executionFailure, cleanupFailure);
};
/** Execute one scenario through a typed expected-failure channel. */
+41
View File
@@ -34,6 +34,12 @@ export type ProcessCleanupResult =
| { readonly cleaned: true; readonly signaled: boolean }
| { readonly cleaned: false; readonly reason: string };
/** Token-verified liveness result used by post-root-exit settlement. */
export type ProcessGroupObservation =
| { readonly state: "empty" }
| { readonly state: "alive" }
| { readonly state: "unverifiable"; readonly reason: string };
const parseEnvironment = (value: string): Readonly<Record<string, string>> =>
Object.fromEntries(
value
@@ -146,6 +152,41 @@ export const cleanupOwnedProcessGroup = async (
return { cleaned: true, signaled: true };
};
/** Observe one group without signaling it, failing closed on identity doubt. */
export const observeOwnedProcessGroup = async (
ownership: OwnedProcessGroup,
host: ProcessOwnershipHost = systemHost,
): Promise<ProcessGroupObservation> => {
let members: readonly ProcessGroupMember[];
try {
members = await host.listMembers(ownership.processGroupId);
} catch {
return {
state: "unverifiable",
reason: "process group could not be inspected",
};
}
if (members.length === 0) return { state: "empty" };
for (const member of members) {
try {
if (
(await host.environment(member.pid)).REA_PROCESS_RUN_ID !==
ownership.runId
)
return {
state: "unverifiable",
reason: "process ownership did not match",
};
} catch {
return {
state: "unverifiable",
reason: "process ownership could not be revalidated",
};
}
}
return { state: "alive" };
};
const commandMatches = (actual: string, expected: string): boolean => {
const normalizedActual = actual.trim();
const normalizedExpected = expected.trim();
+71 -96
View File
@@ -22,6 +22,9 @@ import {
type LinuxDistribution,
} from "./LinuxHopper.js";
import { installMacHopper } from "./MacHopper.js";
import { installCanonicalSkill } from "./SetupSkill.js";
export { installCanonicalSkill } from "./SetupSkill.js";
const registrationCommand = (): readonly string[] =>
process.env.npm_command === "exec"
@@ -100,6 +103,65 @@ export type SetupConfirmation = (
actions: readonly SetupAction[],
) => Promise<boolean>;
const setupPlan = (
platform: NodeJS.Platform,
hopperPath: string | undefined,
clients: readonly SetupClient[],
): readonly SetupAction[] => [
...(hopperPath === undefined
? [
{
kind: "install_hopper" as const,
target:
platform === "darwin"
? "~/Applications/Hopper Disassembler.app"
: "system package manager",
detail:
"Download the official Hopper package, verify it, install it, and open Hopper for activation.",
external: true,
},
]
: []),
...clients
.filter(({ format }) => format !== "unsupported")
.map(
(client): SetupAction => ({
kind: "configure_client",
target: client.configPath,
detail: `Add the REA MCP registration for ${client.name}; preserve unrelated configuration.`,
external: false,
}),
),
{
kind: "install_skill",
target: "~/.agents/skills/rea-analysis/SKILL.md",
detail: "Install or update the bundled REA analysis skill.",
external: false,
},
];
const configureDetectedClients = async (options: {
readonly host: SetupHost;
readonly detectedClients: readonly SetupClient[];
readonly hopperPath: string | undefined;
readonly clients: Record<string, ClientConfigurationResult>;
readonly appliedActions: string[];
}): Promise<string | undefined> => {
for (const client of options.detectedClients) {
const result = await options.host.configureClient(
client,
options.hopperPath,
registrationCommand(),
);
options.clients[client.name] = result;
if (result.status === "failed")
return `${client.name} configuration ${result.reason} verification failed; no successful configuration was reported.`;
if (result.status === "configured")
options.appliedActions.push(`configured_${client.name}`);
}
return undefined;
};
/**
* Install prerequisites and configure detected clients idempotently.
* Discovery always precedes mutation. Interactive confirmation or explicit
@@ -125,38 +187,7 @@ export const runSetup = async (
if (unsupported !== undefined) return fail(unsupported);
let hopperPath = await host.hopperPath();
const detectedClients = await host.detectedClients();
plannedActions = [
...(hopperPath === undefined
? [
{
kind: "install_hopper" as const,
target:
host.platform === "darwin"
? "~/Applications/Hopper Disassembler.app"
: "system package manager",
detail:
"Download the official Hopper package, verify it, install it, and open Hopper for activation.",
external: true,
},
]
: []),
...detectedClients
.filter(({ format }) => format !== "unsupported")
.map(
(client): SetupAction => ({
kind: "configure_client",
target: client.configPath,
detail: `Add the REA MCP registration for ${client.name}; preserve unrelated configuration.`,
external: false,
}),
),
{
kind: "install_skill",
target: "~/.agents/skills/rea-analysis/SKILL.md",
detail: "Install or update the bundled REA analysis skill.",
external: false,
},
];
plannedActions = setupPlan(host.platform, hopperPath, detectedClients);
let approved = options.approved;
let interactiveApproval = false;
if (!approved && confirm !== undefined && !options.structured) {
@@ -191,20 +222,14 @@ export const runSetup = async (
};
appliedActions.push("installed_hopper");
}
for (const client of detectedClients) {
const result = await host.configureClient(
client,
hopperPath,
registrationCommand(),
);
clients[client.name] = result;
if (result.status === "failed")
return fail(
`${client.name} configuration ${result.reason} verification failed; no successful configuration was reported.`,
);
if (result.status === "configured")
appliedActions.push(`configured_${client.name}`);
}
const clientFailure = await configureDetectedClients({
host,
detectedClients,
hopperPath,
clients,
appliedActions,
});
if (clientFailure !== undefined) return fail(clientFailure);
const skill = await host.installSkill();
if (skill === "failed")
return fail("Agent skill installation or readback failed.");
@@ -485,56 +510,6 @@ export const configureTomlClient = async (
};
};
/** Transactionally install or upgrade the versioned canonical REA skill. */
export const installCanonicalSkill = async (
home: string,
): Promise<"installed" | "unchanged" | "failed"> => {
const destination = join(
home,
".agents/skills",
PRODUCT_IDENTITY.skillName,
"SKILL.md",
);
const backup = `${destination}.rea.backup`;
let original: string | undefined;
try {
const content = await readFile(
new URL(
`../../skills/${PRODUCT_IDENTITY.skillName}/SKILL.md`,
import.meta.url,
),
"utf8",
);
original = await readFile(destination, "utf8").catch(() => undefined);
if (original === content) return "unchanged";
await mkdir(dirname(destination), { recursive: true });
if (original !== undefined)
await writeFileAtomic(backup, original, {
encoding: "utf8",
mode: 0o600,
});
await writeFileAtomic(destination, content, {
encoding: "utf8",
mode: 0o600,
});
if ((await readFile(destination, "utf8")) !== content)
throw new Error("skill readback mismatch");
return "installed";
} catch {
try {
if (original === undefined) await rm(destination, { force: true });
else
await writeFileAtomic(destination, original, {
encoding: "utf8",
mode: 0o600,
});
} catch {
// The backup remains beside the skill for explicit operator recovery.
}
return "failed";
}
};
const major = (version: string): number =>
Number.parseInt(version.split(".")[0] ?? "0", 10);
const exists = async (path: string): Promise<boolean> => {
+55
View File
@@ -0,0 +1,55 @@
import { mkdir, readFile, rm } from "node:fs/promises";
import { dirname, join } from "node:path";
import writeFileAtomic from "write-file-atomic";
import { PRODUCT_IDENTITY } from "../identity.js";
/** Transactionally install or upgrade the versioned canonical REA skill. */
export const installCanonicalSkill = async (
home: string,
): Promise<"installed" | "unchanged" | "failed"> => {
const destination = join(
home,
".agents/skills",
PRODUCT_IDENTITY.skillName,
"SKILL.md",
);
const backup = `${destination}.rea.backup`;
let original: string | undefined;
try {
const content = await readFile(
new URL(
`../../skills/${PRODUCT_IDENTITY.skillName}/SKILL.md`,
import.meta.url,
),
"utf8",
);
original = await readFile(destination, "utf8").catch(() => undefined);
if (original === content) return "unchanged";
await mkdir(dirname(destination), { recursive: true });
if (original !== undefined)
await writeFileAtomic(backup, original, {
encoding: "utf8",
mode: 0o600,
});
await writeFileAtomic(destination, content, {
encoding: "utf8",
mode: 0o600,
});
if ((await readFile(destination, "utf8")) !== content)
throw new Error("skill readback mismatch");
return "installed";
} catch {
try {
if (original === undefined) await rm(destination, { force: true });
else
await writeFileAtomic(destination, original, {
encoding: "utf8",
mode: 0o600,
});
} catch {
// The backup remains beside the skill for explicit operator recovery.
}
return "failed";
}
};
+1 -1
View File
@@ -17,7 +17,7 @@ export const createBinarySession = (
): BinarySession => {
return new BinarySession(
new CompositeProvider([
new ArtifactProvider(),
new ArtifactProvider(config.artifactNativeMountEnabled),
new NativeMacOSProvider(),
new HopperProvider(config, logger),
]),