docs(process): preserve capture invariants

This commit is contained in:
morluto
2026-07-13 17:15:22 +08:00
parent ba15d16c58
commit 841990bde1
33 changed files with 214 additions and 128 deletions
+7 -1
View File
@@ -41,7 +41,13 @@ else process.exit(route.termination.code);
const shellQuote = (value: string): string =>
`'${value.replaceAll("'", `'\\''`)}'`;
/** Start bounded executable replay wrappers and their private invocation ledger. */
/**
* Start bounded executable replay wrappers and their private invocation ledger.
*
* Exact argument matching is deliberate: a fallback to the host executable
* would make an unmatched dependency call look authoritative. Unmatched and
* exhausted routes therefore fail visibly and remain part of the capture.
*/
export const startCommandShimReplay = async (
scenario: ProcessScenario,
temporaryRoot: string,
+3
View File
@@ -96,6 +96,9 @@ export class ProcessCheckpoints {
capture(name: string): void {
if (this.#captured.has(name)) return;
this.#captured.add(name);
// Serialize scans even when time, terminal, and lifecycle triggers fire
// together. Each effect set is intentionally relative to the immediately
// preceding checkpoint, which preserves transient create/delete behavior.
this.#pending = this.#pending.then(async () => {
const snapshot = await snapshotRoots(this.scenario, this.signal);
const previous = this.#captures.at(-1)?.files ?? [];
+8 -1
View File
@@ -1,7 +1,7 @@
import { randomUUID } from "node:crypto";
import { mkdtemp, realpath, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { join } from "node:path";
import { spawn, type IPty } from "node-pty";
import type {
FilesystemCheckpoint,
@@ -139,6 +139,10 @@ const makeEnvironment = (
environment.REA_REPLAY_HTTP_URL = replay.httpUrl;
environment.REA_REPLAY_WEBSOCKET_URL = replay.websocketUrl;
environment.REA_SHIM_LEDGER_URL = shimReplay.url;
// PATH is evidence-producing input. Inheriting the host PATH here would let
// the authority and reconstruction probe different tools without recording
// that difference. Scenarios must opt in through environment or
// inherit_environment; deterministic shims always take precedence.
environment.PATH = [shimReplay.binPath, environment.PATH ?? ""]
.filter((part) => part.length > 0)
.join(":");
@@ -315,6 +319,9 @@ const awaitTerminalExit = async ({
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()) {
+10 -1
View File
@@ -4,6 +4,7 @@ import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
/** Identity proof required before REA may signal a captured process group. */
export interface OwnedProcessGroup {
readonly runId: string;
readonly leaderPid: number;
@@ -21,12 +22,14 @@ interface ProcessGroupMember {
readonly command: string;
}
/** Narrow operating-system seam used to inspect and signal process groups. */
export interface ProcessOwnershipHost {
listMembers(processGroupId: number): Promise<readonly ProcessGroupMember[]>;
environment(pid: number): Promise<Readonly<Record<string, string>>>;
signalGroup(processGroupId: number, signal: NodeJS.Signals): void;
}
/** Cleanup succeeds only when the group is absent or every member is owned. */
export type ProcessCleanupResult =
| { readonly cleaned: true; readonly signaled: boolean }
| { readonly cleaned: false; readonly reason: string };
@@ -78,7 +81,13 @@ const systemHost: ProcessOwnershipHost = {
},
};
/** Verify run-token ownership before signaling a POSIX process group. */
/**
* Verify run-token ownership before signaling a POSIX process group.
*
* Process IDs and group IDs can be reused. REA therefore re-reads every live
* member's environment immediately before signaling and fails closed if any
* member cannot be inspected or lacks the per-capture run token.
*/
export const cleanupOwnedProcessGroup = async (
ownership: OwnedProcessGroup,
host: ProcessOwnershipHost = systemHost,
+7
View File
@@ -20,6 +20,13 @@ interface TerminalRendererOptions {
}
/** 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();
+7 -1
View File
@@ -8,7 +8,13 @@ import {
type ArtifactReader,
} from "./ArtifactReader.js";
/** Official Electron ASAR adapter. Individual files remain caller-bounded. */
/**
* Official Electron ASAR adapter. Individual files remain caller-bounded.
*
* An entry marked `unpacked` is metadata, not an integrity exemption: Electron
* stores its bytes beside the archive in `<archive>.unpacked`, and callers must
* hash those companion bytes against the archive's declared integrity value.
*/
export class AsarArtifactReader implements ArtifactReader {
readonly format = "asar" as const;
+20
View File
@@ -37,6 +37,10 @@ const outputChunkSchema = z.object({
});
/** Exact boundary schema for bounded dynamic process scenarios. */
/**
* Boundary schema for one explicitly approved, bounded process experiment.
* Defaults are part of the evidence contract and must remain deterministic.
*/
export const processScenarioSchema = z
.object({
approved: z
@@ -310,6 +314,7 @@ export const processScenarioSchema = z
});
/** A parsed, bounded dynamic process observation scenario. */
/** Parsed instructions and resource bounds for one process experiment. */
export type ProcessScenario = z.infer<typeof processScenarioSchema>;
/** Parse untrusted process scenario input and apply safe default budgets. */
@@ -317,6 +322,7 @@ export const parseProcessScenario = (input: unknown): ProcessScenario =>
processScenarioSchema.parse(input);
/** Operator-owned policy for process capture. */
/** Operator-owned ceiling applied in addition to per-scenario approval. */
export interface ProcessExecutionPolicy {
readonly enabled: boolean;
readonly executableRoots: readonly string[];
@@ -326,6 +332,7 @@ export interface ProcessExecutionPolicy {
}
/** A safe, caller-visible process-policy decision. */
/** Explicit authorization result; denial reasons are safe to show callers. */
export type ProcessPolicyDecision =
| { readonly allowed: true }
| { readonly allowed: false; readonly reason: string };
@@ -389,6 +396,7 @@ export const authorizeProcessScenario = (
};
/** One bounded terminal observation. */
/** Normalized raw PTY chunk, preserving transport-level output differences. */
export interface TerminalFrame {
readonly sequence: number;
readonly at_ms: number;
@@ -396,6 +404,7 @@ export interface TerminalFrame {
}
/** One rendered terminal state after xterm has parsed a PTY chunk or resize. */
/** Serialized terminal state after interpreting control and resize sequences. */
export interface RenderedTerminalFrame {
readonly sequence: number;
readonly at_ms: number;
@@ -409,6 +418,7 @@ export interface RenderedTerminalFrame {
}
/** One attempted scripted interaction with the PTY. */
/** Scheduled input, resize, or signal with its observed dispatch outcome. */
export interface InteractionEvent {
readonly sequence: number;
readonly scheduled_at_ms: number;
@@ -446,6 +456,9 @@ export interface ProcessSample {
}
/** A named filesystem observation captured during a process lifecycle. */
/**
* Named filesystem state whose effects are relative to the prior checkpoint.
*/
export interface FilesystemCheckpoint {
readonly name: string;
readonly at_ms: number;
@@ -455,6 +468,7 @@ export interface FilesystemCheckpoint {
}
/** One invocation observed by the declarative command-shim replay adapter. */
/** Recorded deterministic dependency invocation and route-match outcome. */
export interface ShimEvent {
readonly sequence: number;
readonly at_ms: number;
@@ -481,6 +495,12 @@ export interface ProtocolEvent {
}
/** A bounded process observation with explicit incompleteness metadata. */
/**
* Process Capture v3 observation set.
*
* `truncated` and `residual_unknowns` are semantic evidence: consumers must not
* infer equivalence from matching bounded observations when either is present.
*/
export interface ProcessCapture {
readonly schema_version: 3;
readonly normalization: z.infer<typeof normalizationSchema>;
+6
View File
@@ -197,6 +197,12 @@ const chooseFirstDivergence = (
};
/** Compare bounded captures without equating missing or incompatible evidence. */
/**
* Compare two Process Capture v3 observations without treating absence as proof.
*
* Observed differences outrank residual unknowns. A capture may therefore be
* definitively changed in one dimension while completeness remains unknown.
*/
export const compareProcessCaptures = (
left: ProcessCapture,
right: ProcessCapture,