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:
Ysopwnable
2026-10-08 00:46:21 +08:00
committed by GitHub
parent 5b172b1042
commit 6aa9afb549
98 changed files with 214 additions and 141 deletions
@@ -0,0 +1,112 @@
import type { ProcessNode, ProcessTreeEvent } from "./eventProcessTree.js";
/**
* Defaults shared by every fixture event. Tests vary only the fields they are
* actually asserting on, so a tree reads as the sequence of transitions under
* test rather than thirteen repeated literal fields per event.
*/
const eventDefaults: {
arguments: string[];
previous_pid: number | null;
previous_ppid: number | null;
exit_code: number | null;
signal: number | null;
tid: number | null;
} = {
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
};
/** One `spawn` event, numbering itself from the sequence given. */
export const spawnEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number;
process_name: string;
executable?: string | null;
arguments?: string[];
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "spawn",
executable: event.executable ?? `/${event.process_name}`,
...event,
});
/** One `exit` event. */
export const exitEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number | null;
process_name: string | null;
exit_code?: number;
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "exit",
executable: null,
exit_code: 0,
...event,
});
/** One `re_exec` event, which keeps the pid and replaces the executable. */
export const reExecEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number;
process_name: string;
executable: string;
arguments?: string[];
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "re_exec",
previous_pid: null,
...event,
});
/** One `reparent` event, which records the pid the process was adopted from. */
export const reparentEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number;
process_name: string;
previous_ppid: number;
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "reparent",
executable: null,
...event,
});
/** A reconstructed node, defaulting to a childless process with no lifecycle. */
export const processNode = (node: {
pid: number;
ppid: number | null;
process_name: string;
children?: number[];
}): ProcessNode => ({
executable: null,
arguments: [],
spawn_time_ms: null,
exit_time_ms: null,
exit_code: null,
is_re_exec: false,
is_reparented: false,
previous_ppid: null,
...node,
children: node.children ?? [],
});
/** The common `spawn` of a root process at pid 1. */
export const rootSpawn = (sequence = 0): ProcessTreeEvent =>
spawnEvent({ sequence, pid: 1, ppid: 0, process_name: "root" });
+214
View File
@@ -0,0 +1,214 @@
import { describe, expect, it } from "vitest";
import {
containsProcess,
getDescendants,
maxTreeDepth,
reconstructProcessTree,
type ProcessTreeEvent,
} from "./eventProcessTree.js";
import {
exitEvent,
processNode,
reExecEvent,
reparentEvent,
rootSpawn,
spawnEvent,
} from "./eventProcessTree.fixture.js";
describe("event-backed process tree reconstruction", () => {
it("walks trees larger than ten thousand nodes", () => {
const childPids = Array.from({ length: 10_001 }, (_, index) => index + 2);
const root = processNode({
pid: 1,
ppid: null,
process_name: "root",
children: childPids,
});
const children = childPids.map((pid) =>
processNode({ pid, ppid: 1, process_name: "root" }),
);
expect(maxTreeDepth([root, ...children], 1)).toBe(1);
expect(getDescendants([root, ...children], 1)).toHaveLength(
childPids.length,
);
});
it("reconstructs a simple process tree", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child",
executable: "/child",
}),
exitEvent({
sequence: 2,
at_ms: 20,
pid: 2,
ppid: 1,
process_name: "child",
}),
exitEvent({
sequence: 3,
at_ms: 30,
pid: 1,
ppid: 0,
process_name: "root",
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.processes).toHaveLength(2);
expect(result.events_consumed).toBe(4);
expect(result.events_unmatched).toBe(0);
expect(result.short_lived_descendants).toBe(2);
});
});
describe("short-lived process descendants", () => {
it("detects short-lived descendants", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "short",
executable: "/short",
}),
exitEvent({
sequence: 2,
at_ms: 11,
pid: 2,
ppid: 1,
process_name: "short",
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.short_lived_descendants).toBe(1);
});
});
describe("event-backed process tree transitions", () => {
it("detects re-exec", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
reExecEvent({
sequence: 1,
pid: 1,
ppid: 0,
process_name: "root",
executable: "/newroot",
arguments: ["--new"],
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.has_re_exec).toBe(true);
const root = result.processes.find((p) => p.pid === 1);
expect(root?.is_re_exec).toBe(true);
expect(root?.executable).toBe("/newroot");
});
it("detects reparenting", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child",
executable: "/child",
}),
reparentEvent({
sequence: 2,
pid: 2,
ppid: 0,
process_name: "child",
previous_ppid: 1,
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.has_reparenting).toBe(true);
const child = result.processes.find((p) => p.pid === 2);
expect(child?.is_reparented).toBe(true);
expect(child?.previous_ppid).toBe(1);
expect(child?.ppid).toBe(0);
});
it("reports unmatched events for unknown exits", () => {
const events: ProcessTreeEvent[] = [
exitEvent({
sequence: 0,
at_ms: 0,
pid: 999,
ppid: null,
process_name: null,
exit_code: 1,
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.events_unmatched).toBe(1);
expect(result.processes).toHaveLength(0);
});
});
describe("event-backed process tree queries", () => {
it("gets descendants", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child1",
executable: "/c1",
}),
spawnEvent({
sequence: 2,
pid: 3,
ppid: 2,
process_name: "grandchild",
executable: "/gc",
}),
];
const result = reconstructProcessTree(events, 1);
const descendants = getDescendants(result.processes, 1);
expect(descendants).toHaveLength(2);
expect(descendants).toContain(2);
expect(descendants).toContain(3);
});
it("checks process containment", () => {
const events: ProcessTreeEvent[] = [rootSpawn(0)];
const result = reconstructProcessTree(events, 1);
expect(containsProcess(result.processes, 1)).toBe(true);
expect(containsProcess(result.processes, 999)).toBe(false);
});
});
describe("event-backed process tree depth and types", () => {
it("computes max tree depth", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child",
executable: "/c",
}),
spawnEvent({
sequence: 2,
pid: 3,
ppid: 2,
process_name: "gc",
executable: "/gc",
}),
];
const result = reconstructProcessTree(events, 1);
expect(maxTreeDepth(result.processes, 1)).toBe(2);
});
});
+262
View File
@@ -0,0 +1,262 @@
import { z } from "zod";
/** Event types for event-backed process-tree capture. */
export const processEventTypeSchema = z.enum([
"spawn",
"exit",
"re_exec",
"reparent",
"signal",
"name_change",
"thread_create",
"thread_exit",
]);
/** A single event-backed process-tree event. */
export const processTreeEventSchema = z.strictObject({
/** Monotonic event sequence number. */
sequence: z.number().int().nonnegative(),
/** Event timestamp in milliseconds. */
at_ms: z.number().int().nonnegative(),
/** Event type. */
type: processEventTypeSchema,
/** Process ID. */
pid: z.number().int().positive(),
/** Parent process ID. */
ppid: z.number().int().nullable(),
/** Process name if known. */
process_name: z.string().nullable(),
/** Executable path if known. */
executable: z.string().nullable(),
/** Command line arguments. */
arguments: z.array(z.string()).default([]),
/** Previous PID (for reparent events). */
previous_pid: z.number().int().nullable(),
/** Previous PPID (for reparent events). */
previous_ppid: z.number().int().nullable(),
/** Exit code (for exit events). */
exit_code: z.number().int().nullable(),
/** Signal number (for signal events). */
signal: z.number().int().nullable(),
/** Thread ID (for thread events). */
tid: z.number().int().nullable(),
});
export type ProcessTreeEvent = z.infer<typeof processTreeEventSchema>;
/** Process node in a reconstructed tree. */
export const processNodeSchema = z.strictObject({
pid: z.number().int().positive(),
ppid: z.number().int().nullable(),
process_name: z.string().nullable(),
executable: z.string().nullable(),
arguments: z.array(z.string()).default([]),
children: z.array(z.number().int()).default([]),
spawn_time_ms: z.number().int().nullable(),
exit_time_ms: z.number().int().nullable(),
exit_code: z.number().int().nullable(),
is_re_exec: z.boolean().default(false),
is_reparented: z.boolean().default(false),
previous_ppid: z.number().int().nullable(),
});
export type ProcessNode = z.infer<typeof processNodeSchema>;
/** Result of event-backed process-tree reconstruction. */
export const processTreeReconstructionSchema = z.strictObject({
/** Root PID of the process tree. */
root_pid: z.number().int().positive(),
/** All reconstructed process nodes. */
processes: z.array(processNodeSchema).min(0),
/** Events that were consumed. */
events_consumed: z.number().int().nonnegative(),
/** Events that could not be matched. */
events_unmatched: z.number().int().nonnegative(),
/** Short-lived descendants that were missed by sampling. */
short_lived_descendants: z.number().int().nonnegative(),
/** Whether any re-exec was detected. */
has_re_exec: z.boolean().default(false),
/** Whether any reparenting was detected. */
has_reparenting: z.boolean().default(false),
});
export type ProcessTreeReconstruction = z.infer<
typeof processTreeReconstructionSchema
>;
type ProcessTreeAccumulator = {
readonly nodes: Map<number, ProcessNode>;
readonly children: Map<number, number[]>;
eventsUnmatched: number;
hasReExec: boolean;
hasReparenting: boolean;
shortLivedDescendants: number;
};
const applyProcessTreeEvent = (
event: ProcessTreeEvent,
state: ProcessTreeAccumulator,
): void => {
let node = state.nodes.get(event.pid);
switch (event.type) {
case "spawn": {
if (!node) {
node = {
pid: event.pid,
ppid: event.ppid,
process_name: event.process_name,
executable: event.executable,
arguments: event.arguments,
children: [],
spawn_time_ms: event.at_ms,
exit_time_ms: null,
exit_code: null,
is_re_exec: false,
is_reparented: false,
previous_ppid: null,
};
state.nodes.set(event.pid, node);
}
if (event.ppid !== null) {
const parentChildren = state.children.get(event.ppid) ?? [];
parentChildren.push(event.pid);
state.children.set(event.ppid, parentChildren);
}
break;
}
case "exit":
if (node) {
node.exit_time_ms = event.at_ms;
node.exit_code = event.exit_code;
if (
node.spawn_time_ms !== null &&
event.at_ms - node.spawn_time_ms < 100
)
state.shortLivedDescendants++;
} else state.eventsUnmatched++;
break;
case "re_exec":
if (node) {
node.is_re_exec = true;
node.executable = event.executable ?? node.executable;
node.arguments = event.arguments;
state.hasReExec = true;
} else state.eventsUnmatched++;
break;
case "reparent":
if (node) {
node.previous_ppid = node.ppid;
node.ppid = event.ppid;
node.is_reparented = true;
state.hasReparenting = true;
} else state.eventsUnmatched++;
break;
case "signal":
case "name_change":
case "thread_create":
case "thread_exit":
// These events are recorded but don't modify the tree structure.
break;
}
};
/** Reconstruct a process tree from event-backed capture. */
export function reconstructProcessTree(
events: readonly ProcessTreeEvent[],
rootPid: number,
): ProcessTreeReconstruction {
const nodes = new Map<number, ProcessNode>();
const children = new Map<number, number[]>();
let eventsConsumed = 0;
const state: ProcessTreeAccumulator = {
nodes,
children,
eventsUnmatched: 0,
hasReExec: false,
hasReparenting: false,
shortLivedDescendants: 0,
};
const sorted = [...events].sort((a, b) => a.at_ms - b.at_ms);
for (const event of sorted) {
eventsConsumed++;
applyProcessTreeEvent(event, state);
}
// Attach children to nodes
for (const [pid, childPids] of children) {
const node = nodes.get(pid);
if (node) node.children = childPids;
}
return {
root_pid: rootPid,
processes: [...nodes.values()],
events_consumed: eventsConsumed,
events_unmatched: state.eventsUnmatched,
short_lived_descendants: state.shortLivedDescendants,
has_re_exec: state.hasReExec,
has_reparenting: state.hasReparenting,
};
}
/** Get all descendant PIDs of a given root PID. */
export function getDescendants(
processes: readonly ProcessNode[],
rootPid: number,
): number[] {
const byPid = new Map(processes.map((p) => [p.pid, p]));
const visited = new Set<number>();
const result: number[] = [];
const queue: number[] = [rootPid];
for (let head = 0; head < queue.length; head += 1) {
const pid = queue[head];
if (pid === undefined) continue;
if (visited.has(pid)) continue;
visited.add(pid);
const node = byPid.get(pid);
if (node) {
for (const child of node.children) {
if (!visited.has(child)) {
result.push(child);
queue.push(child);
}
}
}
}
return result;
}
/** Check if a process tree contains a specific PID. */
export function containsProcess(
processes: readonly ProcessNode[],
pid: number,
): boolean {
return processes.some((p) => p.pid === pid);
}
/** Get the maximum tree depth from the root. */
export function maxTreeDepth(
processes: readonly ProcessNode[],
rootPid: number,
): number {
const byPid = new Map(processes.map((p) => [p.pid, p]));
const pending = [{ pid: rootPid, depth: 0 }];
const visited = new Set<number>();
let maximumDepth = 0;
while (pending.length > 0) {
const current = pending.pop();
if (!current || visited.has(current.pid)) continue;
visited.add(current.pid);
const node = byPid.get(current.pid);
if (!node || node.children.length === 0) continue;
const childDepth = current.depth + 1;
maximumDepth = Math.max(maximumDepth, childDepth);
for (const childPid of node.children)
if (!visited.has(childPid))
pending.push({ pid: childPid, depth: childDepth });
}
return maximumDepth;
}
@@ -0,0 +1,198 @@
import { expect, it } from "vitest";
import {
compareUnverifiedProcessCaptures as compareProcessCaptures,
emptyProcessCapture as emptyCapture,
} from "./processCapture.fixture.js";
it("classifies missing observations as unknown and one-sided evidence as added", () => {
const base = {
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: [],
rendered_frames: [],
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: false,
limitations: [],
residual_unknowns: [],
cleanup: {
owned_process_group: "verified" as const,
temporary_root: "removed" as const,
},
};
const added = compareProcessCaptures(base, {
...base,
frames: [{ sequence: 0, at_ms: 0, data: "new" }],
rendered_frames: [
{
sequence: 0,
at_ms: 0,
columns: 3,
rows: 1,
cursor_x: 3,
cursor_y: 0,
active_buffer: "normal",
lines: ["new"],
serialized_state: "new",
},
],
});
expect(added.terminal).toBe("added");
expect(added.status).toBe("changed");
const unknown = compareProcessCaptures(
{ ...base, residual_unknowns: [{ scope: "process", reason: "sampled" }] },
base,
);
expect(unknown.process).toBe("unknown");
expect(unknown.status).toBe("unknown");
});
it("treats equivalent normalization records as equal regardless of member order", () => {
const capture = emptyCapture();
expect(
compareProcessCaptures(capture, {
...capture,
normalization: {
patterns: [],
time_bucket_ms: 10,
ports: true,
pids: true,
paths: true,
},
}),
).toMatchObject({
status: "unchanged",
first_divergence: { status: "none" },
});
});
it("compares raw terminal chunks even when rendered states agree", () => {
const capture = {
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: [{ sequence: 0, at_ms: 0, data: "bar" }],
rendered_frames: [],
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: false,
limitations: [],
residual_unknowns: [],
cleanup: {
owned_process_group: "verified" as const,
temporary_root: "removed" as const,
},
};
const comparison = compareProcessCaptures(capture, {
...capture,
frames: [{ sequence: 0, at_ms: 0, data: "foo\rbar" }],
});
expect(comparison.terminal).toBe("changed");
expect(comparison.first_divergence).toMatchObject({
status: "found",
dimension: "terminal",
});
});
it("keeps filesystem evidence unknown when stable snapshots match", () => {
const capture = {
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: [],
rendered_frames: [],
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: false,
limitations: [],
residual_unknowns: [
{ scope: "filesystem" as const, reason: "watcher unavailable" },
],
cleanup: {
owned_process_group: "verified" as const,
temporary_root: "removed" as const,
},
};
const comparison = compareProcessCaptures(capture, capture);
expect(comparison.filesystem).toBe("unknown");
expect(comparison.status).toBe("unknown");
const complete = { ...capture, residual_unknowns: [] };
const finalFile = {
path: "root_0:created.txt",
type: "file" as const,
mode: 0o644,
size: 4,
sha256: "a".repeat(64),
symlink_target: null,
};
const changed = compareProcessCaptures(complete, {
...complete,
filesystem_checkpoints: [
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
{
name: "after_settlement",
at_ms: 10,
files: [finalFile],
effects: [
{
path: finalFile.path,
status: "created",
before: null,
after: finalFile,
},
],
truncated: false,
},
],
files_after: [finalFile],
filesystem_effects: [
{
path: finalFile.path,
status: "created",
before: null,
after: finalFile,
},
],
});
expect(changed.filesystem).toBe("changed");
expect(changed.status).toBe("changed");
});
@@ -0,0 +1,42 @@
import {
compareProcessCaptures,
parseProcessCapture,
processCaptureSchema,
type UnverifiedProcessCapture,
} from "./processCapture.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCaptureExample.js";
export { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCaptureExample.js";
/** Parse a detached valid empty capture for tests that need trusted evidence. */
export const emptyProcessCapture = () =>
parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
/** Parse a mutable unverified capture for boundary-validation tests. */
export const emptyUnverifiedProcessCapture = (): UnverifiedProcessCapture =>
processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
/** Project validation failures without coupling tests to Zod internals. */
export const processCaptureIssues = (
capture: UnverifiedProcessCapture,
): readonly { readonly path: string; readonly message: string }[] => {
const parsed = processCaptureSchema.safeParse(capture);
return parsed.success
? []
: parsed.error.issues.map((issue) => ({
path: issue.path.join("."),
message: issue.message,
}));
};
/** Compare unverified fixture values through the production parser. */
export const compareUnverifiedProcessCaptures = (
left: UnverifiedProcessCapture,
right: UnverifiedProcessCapture,
options?: Parameters<typeof compareProcessCaptures>[2],
): ReturnType<typeof compareProcessCaptures> =>
compareProcessCaptures(
parseProcessCapture(left),
parseProcessCapture(right),
options,
);
@@ -0,0 +1,62 @@
import { expect, it } from "vitest";
import {
compareUnverifiedProcessCaptures as compareProcessCaptures,
emptyProcessCapture as emptyCapture,
} from "./processCapture.fixture.js";
it("detects changes in normalized process sample metadata", () => {
const capture = {
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: [],
rendered_frames: [],
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [
{
at_ms: 10,
pid: 1,
parent_pid: 0,
process_group_id: 1,
session_id: 1,
command: "worker",
},
],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: false,
limitations: [],
residual_unknowns: [],
cleanup: {
owned_process_group: "verified" as const,
temporary_root: "removed" as const,
},
};
const changed = {
...capture,
process_samples: [
{
at_ms: 20,
pid: 1,
parent_pid: 2,
process_group_id: 1,
session_id: 1,
command: "worker",
},
],
};
const comparison = compareProcessCaptures(capture, changed);
expect(comparison.process).toBe("changed");
expect(comparison.status).toBe("changed");
});
+400
View File
@@ -0,0 +1,400 @@
import { z } from "zod";
import { jsonValueSchema } from "../jsonValue.js";
import { normalizationSchema } from "./processScenario.js";
import { collectProcessCaptureIssues } from "./processCaptureValidation.js";
export * from "./processScenario.js";
/** Normalized raw PTY chunk, preserving transport-level output differences. */
export interface TerminalFrame {
readonly sequence: number;
readonly at_ms: number;
readonly data: string;
}
/** Serialized terminal state after interpreting control and resize sequences. */
export interface RenderedTerminalFrame {
readonly sequence: number;
readonly at_ms: number;
readonly columns: number;
readonly rows: number;
readonly cursor_x: number;
readonly cursor_y: number;
readonly active_buffer: "normal" | "alternate";
readonly lines: readonly string[];
readonly serialized_state: string;
}
/** Scheduled terminal interaction with its observed dispatch outcome. */
export interface InteractionEvent {
readonly sequence: number;
readonly scheduled_at_ms: number;
readonly dispatched_at_ms: number;
readonly type: "input" | "resize" | "signal";
readonly data: string;
readonly outcome: "dispatched" | "target_exited" | "failed";
}
/** One filesystem state used for before/after comparison. */
interface FileStateIdentity {
readonly path: string;
readonly mode: number;
readonly size: number;
}
export type FileState = FileStateIdentity &
(
| {
readonly type: "file";
readonly sha256: string | null;
readonly symlink_target: null;
}
| {
readonly type: "symlink";
readonly sha256: null;
readonly symlink_target: string;
}
| {
readonly type: "directory" | "other";
readonly sha256: null;
readonly symlink_target: null;
}
);
interface FileEffectIdentity {
readonly path: string;
}
type FileEffect = FileEffectIdentity &
(
| {
readonly status: "created";
readonly before: null;
readonly after: FileState;
}
| {
readonly status: "deleted";
readonly before: FileState;
readonly after: null;
}
| {
readonly status: "modified" | "unchanged";
readonly before: FileState;
readonly after: FileState;
}
);
/** A sampled owned-process observation; sampling cannot prove syscall completeness. */
export interface ProcessSample {
readonly at_ms: number;
readonly pid: number;
readonly parent_pid: number;
readonly command: string;
readonly process_group_id: number | null;
readonly session_id: number | null;
}
/** Initial or final filesystem snapshot selected for observation. */
export interface FilesystemCheckpoint {
readonly name: string;
readonly at_ms: number;
readonly files: readonly FileState[];
readonly effects: readonly FileEffect[];
readonly truncated: boolean;
}
/** Capture collection whose members participate in global observation order. */
export const PROCESS_CAPTURE_EVENT_COLLECTIONS = [
"frames",
"rendered_frames",
"interaction_events",
"lifecycle",
"process_samples",
"filesystem_checkpoints",
] as const;
export type ProcessCaptureEventCollection =
(typeof PROCESS_CAPTURE_EVENT_COLLECTIONS)[number];
/** One reference from global observation order into a capture collection. */
export interface ProcessCaptureEventJournalEntry {
readonly capture_order: number;
readonly collection: ProcessCaptureEventCollection;
readonly index: number;
}
/** Shared observation callback used by every process-capture producer. */
export type RecordProcessCaptureEvent = (
collection: ProcessCaptureEventCollection,
index: number,
) => void;
/** Observed process-tree settlement and the cleanup required by that state. */
export type ProcessSettlement =
| {
readonly state: "quiesced";
readonly elapsed_ms: number;
readonly cleanup_outcome: "not_required";
}
| {
readonly state: "alive_at_deadline" | "unverifiable";
readonly elapsed_ms: number;
readonly cleanup_outcome: "cleaned" | "failed";
};
/**
* Process capture observation set.
*
* `truncated` and `residual_unknowns` are semantic evidence: consumers must not
* infer equivalence from matching bounded observations when either is present.
*/
export interface UnverifiedProcessCapture {
readonly manifest: {
readonly rea_version: string;
readonly provider_version: string;
readonly platform: string;
readonly architecture: string;
readonly pty_backend: "node-pty";
readonly started_at: string;
readonly completed_at: string;
readonly scenario: Readonly<Record<string, unknown>>;
readonly comparison_contract: Readonly<Record<string, unknown>>;
readonly full_scenario_sha256: string;
readonly comparison_contract_sha256: string;
readonly executable_sha256: string;
readonly normalization_sha256: string;
};
readonly normalization: z.infer<typeof normalizationSchema>;
readonly frames: readonly TerminalFrame[];
readonly rendered_frames: readonly RenderedTerminalFrame[];
readonly interaction_events: readonly InteractionEvent[];
readonly exit: {
readonly code: number | null;
readonly signal: number | null;
readonly reason: "exited" | "timeout" | "idle_timeout";
};
readonly settlement: ProcessSettlement;
readonly process_samples: readonly ProcessSample[];
readonly filesystem_checkpoints: readonly FilesystemCheckpoint[];
/**
* Global observation order across independently recorded collections.
*
* Absence is accepted for captures written before this journal existed.
*/
readonly event_journal?: readonly ProcessCaptureEventJournalEntry[];
readonly files_before: readonly FileState[];
readonly files_after: readonly FileState[];
readonly filesystem_effects: readonly FileEffect[];
readonly truncated: boolean;
readonly limitations: readonly string[];
readonly residual_unknowns: readonly {
readonly scope:
| "terminal"
| "interaction"
| "exit"
| "process"
| "filesystem"
| "cleanup"
| "network"
| "environment";
readonly reason: string;
}[];
readonly cleanup: {
readonly owned_process_group: "verified";
readonly temporary_root: "removed";
};
}
const fileStateShape = {
path: z.string(),
mode: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
};
const fileStateSchema = z.discriminatedUnion("type", [
z.object({
...fileStateShape,
type: z.literal("file"),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
symlink_target: z.null(),
}),
z.object({
...fileStateShape,
type: z.literal("symlink"),
sha256: z.null(),
symlink_target: z.string(),
}),
z.object({
...fileStateShape,
type: z.enum(["directory", "other"]),
sha256: z.null(),
symlink_target: z.null(),
}),
]);
const fileEffectSchema = z.discriminatedUnion("status", [
z.object({
path: z.string(),
status: z.literal("created"),
before: z.null(),
after: fileStateSchema,
}),
z.object({
path: z.string(),
status: z.literal("deleted"),
before: fileStateSchema,
after: z.null(),
}),
z.object({
path: z.string(),
status: z.enum(["modified", "unchanged"]),
before: fileStateSchema,
after: fileStateSchema,
}),
]);
/** Exact serialized shape of a process capture. */
const processCaptureShapeSchema: z.ZodType<UnverifiedProcessCapture> =
z.strictObject({
manifest: z.strictObject({
rea_version: z.string().min(1),
provider_version: z.string().min(1),
platform: z.string().min(1),
architecture: z.string().min(1),
pty_backend: z.literal("node-pty"),
started_at: z.iso.datetime(),
completed_at: z.iso.datetime(),
scenario: z.record(z.string(), jsonValueSchema),
comparison_contract: z.record(z.string(), jsonValueSchema),
full_scenario_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
comparison_contract_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
executable_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
normalization_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
}),
normalization: normalizationSchema,
frames: z.array(
z.object({
sequence: z.number().int().nonnegative(),
at_ms: z.number().int().nonnegative(),
data: z.string(),
}),
),
rendered_frames: z.array(
z.object({
sequence: z.number().int().nonnegative(),
at_ms: z.number().int().nonnegative(),
columns: z.number().int().positive(),
rows: z.number().int().positive(),
cursor_x: z.number().int().nonnegative(),
cursor_y: z.number().int().nonnegative(),
active_buffer: z.enum(["normal", "alternate"]),
lines: z.array(z.string()),
serialized_state: z.string(),
}),
),
interaction_events: z.array(
z.object({
sequence: z.number().int().nonnegative(),
scheduled_at_ms: z.number().int().nonnegative(),
dispatched_at_ms: z.number().int().nonnegative(),
type: z.enum(["input", "resize", "signal"]),
data: z.string(),
outcome: z.enum(["dispatched", "target_exited", "failed"]),
}),
),
exit: z.object({
code: z.number().int().nullable(),
signal: z.number().int().nullable(),
reason: z.enum(["exited", "timeout", "idle_timeout"]),
}),
settlement: z.discriminatedUnion("state", [
z.object({
state: z.literal("quiesced"),
elapsed_ms: z.number().int().nonnegative(),
cleanup_outcome: z.literal("not_required"),
}),
z.object({
state: z.enum(["alive_at_deadline", "unverifiable"]),
elapsed_ms: z.number().int().nonnegative(),
cleanup_outcome: z.enum(["cleaned", "failed"]),
}),
]),
process_samples: z.array(
z.object({
at_ms: z.number().int().nonnegative(),
pid: z.number().int().positive(),
parent_pid: z.number().int().nonnegative(),
command: z.string(),
process_group_id: z.number().int().positive().nullable(),
session_id: z.number().int().nonnegative().nullable(),
}),
),
filesystem_checkpoints: z.array(
z.object({
name: z.enum(["before", "after_settlement"]),
at_ms: z.number().int().nonnegative(),
files: z.array(fileStateSchema),
effects: z.array(fileEffectSchema),
truncated: z.boolean(),
}),
),
event_journal: z
.array(
z.object({
capture_order: z.number().int().nonnegative(),
collection: z.enum(PROCESS_CAPTURE_EVENT_COLLECTIONS),
index: z.number().int().nonnegative(),
}),
)
.default([]),
files_before: z.array(fileStateSchema),
files_after: z.array(fileStateSchema),
filesystem_effects: z.array(fileEffectSchema),
truncated: z.boolean(),
limitations: z.array(z.string()),
residual_unknowns: z.array(
z.object({
scope: z.enum([
"terminal",
"interaction",
"exit",
"process",
"filesystem",
"cleanup",
"network",
"environment",
]),
reason: z.string(),
}),
),
cleanup: z.object({
owned_process_group: z.literal("verified"),
temporary_root: z.literal("removed"),
}),
});
/** Exact serialized shape plus all process-capture semantic invariants. */
export const processCaptureSchema = processCaptureShapeSchema
.superRefine((capture, context) => {
for (const issue of collectProcessCaptureIssues(capture))
context.addIssue({
code: "custom",
path: issue.path.split("."),
message: issue.message,
});
})
.describe(
"The capture must preserve its canonical scenario, comparison, and normalization SHA-256 commitments; ordered capture timestamps and contiguous sequence numbers; before and final filesystem snapshots with truncation propagated; and exit-code consistency with deadline termination. When parsing older input without an event journal, REA supplies an empty journal; empty journals are valid. A non-empty journal must reference every captured observation exactly once with unique in-range references. These cross-field invariants are checked by REA after capture.",
);
export { parseProcessCapture } from "./processCaptureParsing.js";
export type { ProcessCapture } from "./processCaptureParsing.js";
export {
compareProcessCaptures,
comparisonStatusSchema,
deriveProcessComparisonStatus,
PROCESS_COMPARISON_DIMENSIONS,
processCaptureComparisonSchema,
} from "./processComparison.js";
@@ -0,0 +1,165 @@
import { expect, it } from "vitest";
import {
digestProcessCommitment,
parseProcessCapture,
type UnverifiedProcessCapture,
} from "./processCapture.js";
import {
compareUnverifiedProcessCaptures as compareProcessCaptures,
emptyUnverifiedProcessCapture as emptyCapture,
processCaptureIssues,
} from "./processCapture.fixture.js";
it("never considers truncated captures equivalent", () => {
const capture = {
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: [],
rendered_frames: [],
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: true,
limitations: [],
residual_unknowns: [],
cleanup: {
owned_process_group: "verified" as const,
temporary_root: "removed" as const,
},
};
expect(compareProcessCaptures(capture, capture).status).toBe("truncated");
});
it("rejects altered v4 commitments and accepts canonical key reordering", () => {
const capture = emptyCapture();
expect(parseProcessCapture(capture)).toEqual(capture);
expect(digestProcessCommitment({ second: 2, first: 1 })).toBe(
digestProcessCommitment({ first: 1, second: 2 }),
);
expect(() =>
parseProcessCapture({
...capture,
manifest: {
...capture.manifest,
normalization_sha256: "f".repeat(64),
},
}),
).toThrow("normalization_sha256");
expect(() =>
parseProcessCapture({
...capture,
manifest: {
...capture.manifest,
executable_sha256: "f".repeat(64),
},
}),
).toThrow("executable_sha256");
});
it("rejects settlement and cleanup combinations that cannot occur", () => {
const capture = emptyCapture();
expect(() =>
parseProcessCapture({
...capture,
settlement: {
state: "quiesced",
elapsed_ms: 0,
cleanup_outcome: "cleaned",
},
}),
).toThrow("cleanup_outcome");
expect(() =>
parseProcessCapture({
...capture,
settlement: {
state: "alive_at_deadline",
elapsed_ms: 1,
cleanup_outcome: "not_required",
},
}),
).toThrow("cleanup_outcome");
});
it("accepts old captures without a journal and validates complete journals", () => {
const capture = emptyCapture();
const { event_journal: _eventJournal, ...oldCapture } = capture;
expect(parseProcessCapture(oldCapture).event_journal).toEqual([]);
const eventJournal = [
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
{ capture_order: 1, collection: "lifecycle", index: 0 },
{ capture_order: 2, collection: "lifecycle", index: 1 },
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
] as const;
expect(
processCaptureIssues({ ...capture, event_journal: eventJournal }),
).toEqual([]);
for (const [candidate, message] of [
[
eventJournal.map((entry, index) =>
index === 1 ? { ...entry, capture_order: 2 } : entry,
),
"contiguous",
],
[
eventJournal.map((entry, index) =>
index === 3
? { ...entry, collection: "lifecycle" as const, index: 1 }
: entry,
),
"unique",
],
[eventJournal.slice(0, 3), "every captured observation"],
[
eventJournal.map((entry, index) =>
index === 3 ? { ...entry, index: 2 } : entry,
),
"outside",
],
] as const) {
expect(
processCaptureIssues({ ...capture, event_journal: candidate }),
).toEqual(
expect.arrayContaining([
expect.objectContaining({
message: expect.stringContaining(message),
}),
]),
);
}
});
it("requires compatible contracts and enforces capture age through a clock seam", () => {
const capture = emptyCapture();
expect(() =>
compareProcessCaptures(capture, {
...capture,
manifest: {
...capture.manifest,
comparison_contract: { changed: true },
comparison_contract_sha256: digestProcessCommitment({
changed: true,
}),
},
}),
).toThrow("incompatible comparison contracts");
expect(() =>
compareProcessCaptures(capture, capture, {
maxCaptureAgeMs: 1,
now: () => Date.parse("2026-01-01T00:00:01.000Z"),
}),
).toThrow("max_capture_age_ms");
});
@@ -0,0 +1,62 @@
import type { JsonValue } from "../jsonValue.js";
import { digestProcessCommitment } from "./processCapture.js";
const normalization = {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
};
const scenario = { executable_sha256: "0".repeat(64) };
const comparisonContract = {};
/** Minimal valid process capture retained as a public contract example. */
export const EMPTY_PROCESS_CAPTURE_EXAMPLE = {
manifest: {
rea_version: "1.1.0",
provider_version: "3",
platform: "fixture",
architecture: "fixture",
pty_backend: "node-pty",
started_at: "2026-01-01T00:00:00.000Z",
completed_at: "2026-01-01T00:00:00.001Z",
scenario,
comparison_contract: comparisonContract,
full_scenario_sha256: digestProcessCommitment(scenario),
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
executable_sha256: "0".repeat(64),
normalization_sha256: digestProcessCommitment(normalization),
},
normalization,
frames: [],
rendered_frames: [],
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" },
settlement: {
state: "quiesced",
elapsed_ms: 50,
cleanup_outcome: "not_required",
},
process_samples: [],
filesystem_checkpoints: [
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
{
name: "after_settlement",
at_ms: 50,
files: [],
effects: [],
truncated: false,
},
],
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: false,
limitations: [],
residual_unknowns: [],
cleanup: {
owned_process_group: "verified",
temporary_root: "removed",
},
} satisfies JsonValue;
@@ -0,0 +1,39 @@
import {
processCaptureSchema,
type UnverifiedProcessCapture,
} from "./processCapture.js";
declare class ProcessCaptureProof {
private readonly verified: never;
}
/** Semantically verified process capture value. */
export type ProcessCapture = UnverifiedProcessCapture & ProcessCaptureProof;
const verifiedCaptures = new WeakSet<UnverifiedProcessCapture>();
const isVerifiedCapture = (
capture: UnverifiedProcessCapture,
): capture is ProcessCapture => verifiedCaptures.has(capture);
const attachProof = (capture: UnverifiedProcessCapture): ProcessCapture => {
verifiedCaptures.add(capture);
if (isVerifiedCapture(capture)) return capture;
throw new TypeError("Process Capture proof ownership failed");
};
/** Parse unknown input and reject invalid commitments or semantics. */
export const parseProcessCapture = (input: unknown): ProcessCapture => {
const parsed = processCaptureSchema.safeParse(input);
if (parsed.success) return attachProof(parsed.data);
const issues = parsed.error.issues.flatMap((issue) =>
issue.code === "custom"
? [{ path: issue.path.join("."), message: issue.message }]
: [],
);
if (issues.length > 0)
throw new TypeError(
`Invalid process capture: ${issues.map(({ path, message }) => `${path}: ${message}`).join("; ")}`,
);
throw parsed.error;
};
@@ -0,0 +1,131 @@
import type { UnverifiedProcessCapture } from "./processCapture.js";
import { digestProcessCommitment } from "./processScenario.js";
/** One pure semantic validation failure in a shaped process capture. */
export interface ProcessCaptureValidationIssue {
readonly path: string;
readonly message: string;
}
type RequireInvariant = (
condition: boolean,
path: string,
message: string,
) => void;
const orderedTimestamps = (
values: readonly { readonly at_ms: number }[],
): boolean =>
values.every((value, index) => {
const previous = values[index - 1];
return previous === undefined || value.at_ms >= previous.at_ms;
});
const validateCommitments = (
capture: UnverifiedProcessCapture,
require: RequireInvariant,
): void => {
const { manifest } = capture;
require(manifest.scenario.executable_sha256 ===
manifest.executable_sha256, "manifest.executable_sha256", "executable commitment does not match the scenario projection");
for (const [field, value] of [
["full_scenario_sha256", manifest.scenario],
["comparison_contract_sha256", manifest.comparison_contract],
["normalization_sha256", capture.normalization],
] as const)
require(manifest[field] ===
digestProcessCommitment(
value,
), `manifest.${field}`, "commitment does not match its canonical value");
require(Date.parse(manifest.started_at) <=
Date.parse(
manifest.completed_at,
), "manifest.completed_at", "completion precedes start");
};
const validateOrdering = (
capture: UnverifiedProcessCapture,
require: RequireInvariant,
): void => {
for (const [name, values] of [
["frames", capture.frames],
["rendered_frames", capture.rendered_frames],
["interaction_events", capture.interaction_events],
] as const)
require(values.every(
({ sequence }, index) => sequence === index,
), name, "sequence values must be contiguous from zero");
for (const [name, values] of [
["frames", capture.frames],
["rendered_frames", capture.rendered_frames],
["process_samples", capture.process_samples],
] as const)
require(orderedTimestamps(values), name, "timestamps must be ordered");
};
const validateEventJournal = (
capture: UnverifiedProcessCapture,
require: RequireInvariant,
): void => {
const journal = capture.event_journal ?? [];
if (journal.length === 0) return;
const sizes = {
frames: capture.frames.length,
rendered_frames: capture.rendered_frames.length,
interaction_events: capture.interaction_events.length,
lifecycle: 2,
process_samples: capture.process_samples.length,
filesystem_checkpoints: capture.filesystem_checkpoints.length,
};
const references = new Set<string>();
for (const [position, entry] of journal.entries()) {
require(entry.capture_order ===
position, `event_journal.${String(position)}.capture_order`, "capture order must be contiguous from zero");
require(entry.index <
sizes[
entry.collection
], `event_journal.${String(position)}.index`, "journal reference is outside its capture collection");
const reference = `${entry.collection}:${String(entry.index)}`;
require(!references.has(
reference,
), `event_journal.${String(position)}`, "journal references must be unique");
references.add(reference);
}
const expectedSize = Object.values(sizes).reduce(
(total, size) => total + size,
0,
);
require(journal.length ===
expectedSize, "event_journal", "nonempty journal must reference every captured observation");
};
const validateLifecycle = (
capture: UnverifiedProcessCapture,
require: RequireInvariant,
): void => {
require(capture.filesystem_checkpoints.map(({ name }) => name).join(",") ===
"before,after_settlement", "filesystem_checkpoints", "capture must include initial and final filesystem snapshots");
require(orderedTimestamps(
capture.filesystem_checkpoints,
), "filesystem_checkpoints", "filesystem snapshot times must be ordered");
require(!capture.filesystem_checkpoints.some(({ truncated }) => truncated) ||
capture.truncated, "truncated", "filesystem snapshot truncation must propagate to the capture");
require(capture.exit.reason === "exited" ||
capture.exit.code ===
null, "exit", "deadline termination cannot declare a normal exit code");
};
/** Recompute commitments and cross-field invariants without side effects. */
export const collectProcessCaptureIssues = (
capture: UnverifiedProcessCapture,
): readonly ProcessCaptureValidationIssue[] => {
const issues: ProcessCaptureValidationIssue[] = [];
const require: RequireInvariant = (condition, path, message) => {
if (!condition) issues.push({ path, message });
};
validateCommitments(capture, require);
validateOrdering(capture, require);
validateEventJournal(capture, require);
validateLifecycle(capture, require);
return issues;
};
+444
View File
@@ -0,0 +1,444 @@
import canonicalize from "canonicalize";
import { z } from "zod";
import type { ProcessCapture } from "./processCapture.js";
import { jsonValueSchema } from "../jsonValue.js";
import {
compareProcessTraces,
processTraceOutcomesDiffer,
processTraceComparisonResultSchema,
type ProcessTraceSpecification,
} from "./processTraceComparison.js";
import {
dimensionsForTraceSources,
traceCoversObservedDimension,
} from "./processTraceDimensionProjection.js";
/** Comparison classification that never equates incomplete evidence. */
export const comparisonStatusSchema = z.enum([
"unchanged",
"added",
"removed",
"changed",
"truncated",
"unknown",
"contradiction",
]);
type ComparisonStatus = z.infer<typeof comparisonStatusSchema>;
/** Canonical ordered dimensions that contribute to an overall process status. */
export const PROCESS_COMPARISON_DIMENSIONS = [
"terminal",
"interaction",
"exit",
"filesystem",
"process",
] as const;
/** Derive the overall comparison status from every process dimension. */
export const deriveProcessComparisonStatus = (
dimensions: readonly ComparisonStatus[],
): ComparisonStatus => {
if (dimensions.includes("truncated")) return "truncated";
if (
dimensions.some((status) =>
["changed", "added", "removed"].includes(status),
)
)
return "changed";
return dimensions.includes("unknown") ? "unknown" : "unchanged";
};
/** Pure normalized comparison between two captures. */
export const processCaptureComparisonSchema = z
.object({
status: comparisonStatusSchema,
terminal: comparisonStatusSchema,
interaction: comparisonStatusSchema,
exit: comparisonStatusSchema,
filesystem: comparisonStatusSchema,
process: comparisonStatusSchema,
first_divergence: z.discriminatedUnion("status", [
z.object({ status: z.literal("none") }),
z.object({ status: z.literal("unknown"), reason: z.string() }),
z.object({
status: z.literal("found"),
dimension: z.enum([
"terminal",
"interaction",
"exit",
"filesystem",
"process",
]),
index: z.number().int().nonnegative(),
left_at_ms: z.number().int().nonnegative().nullable(),
right_at_ms: z.number().int().nonnegative().nullable(),
left: jsonValueSchema.nullable(),
right: jsonValueSchema.nullable(),
}),
]),
trace: processTraceComparisonResultSchema.optional(),
limitations: z.array(z.string()),
})
.superRefine((comparison, context) => {
const expected = deriveProcessComparisonStatus(
PROCESS_COMPARISON_DIMENSIONS.map((dimension) => comparison[dimension]),
);
if (comparison.status !== expected)
context.addIssue({
code: "custom",
message: "Process comparison status contradicts its dimensions",
path: ["status"],
});
});
export type ProcessCaptureComparison = z.infer<
typeof processCaptureComparisonSchema
>;
const terminalObservations = (capture: ProcessCapture): readonly unknown[] =>
[
...capture.frames.map((frame) => ({ kind: "raw" as const, ...frame })),
...capture.rendered_frames.map((frame) => ({
kind: "rendered" as const,
...frame,
})),
].sort((left, right) => {
const time = left.at_ms - right.at_ms;
if (time !== 0) return time;
if (left.kind !== right.kind) return left.kind === "raw" ? -1 : 1;
return left.sequence - right.sequence;
});
const filesystemObservations = (capture: ProcessCapture): readonly unknown[] =>
capture.filesystem_checkpoints;
const sameJsonValue = (left: unknown, right: unknown): boolean => {
const encodedLeft = canonicalize(left);
return encodedLeft !== undefined && encodedLeft === canonicalize(right);
};
/** Canonical observations for one process-comparison dimension. */
export const processDimensionObservations = (
capture: ProcessCapture,
dimension: (typeof PROCESS_COMPARISON_DIMENSIONS)[number],
): readonly unknown[] => {
switch (dimension) {
case "terminal":
return terminalObservations(capture);
case "interaction":
return capture.interaction_events;
case "exit":
return [{ ...capture.exit, settlement: capture.settlement }];
case "filesystem":
return filesystemObservations(capture);
case "process":
return capture.process_samples;
}
};
const classifyCollection = (
left: readonly unknown[],
right: readonly unknown[],
): ComparisonStatus => {
if (sameJsonValue(left, right)) return "unchanged";
if (left.length === 0) return "added";
if (right.length === 0) return "removed";
return "changed";
};
const hasUnknown = (
capture: ProcessCapture,
scope: ProcessCapture["residual_unknowns"][number]["scope"],
): boolean => capture.residual_unknowns.some((item) => item.scope === scope);
type DivergenceDimension = Exclude<
ProcessCaptureComparison["first_divergence"],
{ readonly status: "none" | "unknown" }
>["dimension"];
const eventTime = (value: unknown): number | null => {
if (
typeof value === "object" &&
value !== null &&
"at_ms" in value &&
typeof value.at_ms === "number" &&
Number.isSafeInteger(value.at_ms) &&
value.at_ms >= 0
)
return value.at_ms;
return null;
};
const firstCollectionDivergence = (
dimension: DivergenceDimension,
left: readonly unknown[],
right: readonly unknown[],
): Extract<
ProcessCaptureComparison["first_divergence"],
{ readonly status: "found" }
> | null => {
const length = Math.max(left.length, right.length);
for (let index = 0; index < length; index += 1) {
const leftValue = left[index] ?? null;
const rightValue = right[index] ?? null;
if (sameJsonValue(leftValue, rightValue)) continue;
return {
status: "found",
dimension,
index,
left_at_ms: eventTime(leftValue),
right_at_ms: eventTime(rightValue),
left: jsonValueSchema.parse(leftValue),
right: jsonValueSchema.parse(rightValue),
};
}
return null;
};
const chooseFirstDivergence = (
candidates: ReadonlyArray<Extract<
ProcessCaptureComparison["first_divergence"],
{ readonly status: "found" }
> | null>,
): ProcessCaptureComparison["first_divergence"] => {
const found = candidates.filter(
(candidate): candidate is NonNullable<typeof candidate> =>
candidate !== null,
);
return (
found.sort((left, right) => {
const leftTime = Math.min(
left.left_at_ms ?? Number.MAX_SAFE_INTEGER,
left.right_at_ms ?? Number.MAX_SAFE_INTEGER,
);
const rightTime = Math.min(
right.left_at_ms ?? Number.MAX_SAFE_INTEGER,
right.right_at_ms ?? Number.MAX_SAFE_INTEGER,
);
return leftTime - rightTime;
})[0] ?? { status: "none" }
);
};
const assertComparable = (
left: ProcessCapture,
right: ProcessCapture,
options: { readonly maxCaptureAgeMs?: number; readonly now?: () => number },
): void => {
if (
left.manifest.comparison_contract_sha256 !==
right.manifest.comparison_contract_sha256
)
throw new TypeError(
"Process captures have incompatible comparison contracts",
);
if (options.maxCaptureAgeMs === undefined) return;
const maxCaptureAgeMs = options.maxCaptureAgeMs;
const now = (options.now ?? Date.now)();
if (
[left, right].some(
({ manifest }) =>
now - Date.parse(manifest.completed_at) > maxCaptureAgeMs,
)
)
throw new TypeError("Process capture exceeds max_capture_age_ms");
};
const truncatedComparison = (): ProcessCaptureComparison => ({
status: "truncated",
terminal: "truncated",
interaction: "truncated",
exit: "truncated",
filesystem: "truncated",
process: "truncated",
first_divergence: {
status: "unknown",
reason: "At least one capture is truncated.",
},
limitations: ["At least one capture is truncated."],
});
const applyTraceVerdict = (
dimensions: ComparisonDimensions,
specification: ProcessTraceSpecification,
trace: ReturnType<typeof compareProcessTraces>,
captures: readonly [left: ProcessCapture, right: ProcessCapture],
): ComparisonDimensions => {
const traceShowsDifference = processTraceOutcomesDiffer(trace);
const traceStatus =
trace.verdict === "unknown"
? "unknown"
: trace.verdict === "equivalent" || !traceShowsDifference
? "unchanged"
: "changed";
const sources = new Set(specification.events.map(({ source }) => source));
const covered = dimensionsForTraceSources(sources);
const statusFor = (
dimension: (typeof PROCESS_COMPARISON_DIMENSIONS)[number],
): ComparisonStatus => {
const exact = dimensions[dimension];
if (!covered.has(dimension)) return exact;
if (trace.verdict === "nonconforming") return exact;
if (trace.verdict === "different")
return traceShowsDifference ? "changed" : exact;
if (
trace.verdict === "unknown" &&
["changed", "added", "removed"].includes(exact)
)
return exact;
return traceCoversObservedDimension(
dimension,
sources,
captures[0],
captures[1],
)
? traceStatus
: exact;
};
return {
terminal: statusFor("terminal"),
interaction: statusFor("interaction"),
exit: statusFor("exit"),
filesystem: statusFor("filesystem"),
process: statusFor("process"),
};
};
type ComparisonDimensions = Pick<
ProcessCaptureComparison,
"terminal" | "interaction" | "exit" | "filesystem" | "process"
>;
const compareDimensions = (
left: ProcessCapture,
right: ProcessCapture,
sameNormalization: boolean,
): ComparisonDimensions => {
const classify = (
scope: ProcessCapture["residual_unknowns"][number]["scope"],
leftValues: readonly unknown[],
rightValues: readonly unknown[],
): ComparisonStatus =>
!sameNormalization || hasUnknown(left, scope) || hasUnknown(right, scope)
? "unknown"
: classifyCollection(leftValues, rightValues);
return {
terminal: classify(
"terminal",
terminalObservations(left),
terminalObservations(right),
),
interaction: classify(
"interaction",
left.interaction_events,
right.interaction_events,
),
exit:
hasUnknown(left, "exit") || hasUnknown(right, "exit")
? "unknown"
: sameJsonValue(
{ exit: left.exit, settlement: left.settlement },
{ exit: right.exit, settlement: right.settlement },
)
? "unchanged"
: "changed",
filesystem: classify(
"filesystem",
filesystemObservations(left),
filesystemObservations(right),
),
process: classify("process", left.process_samples, right.process_samples),
};
};
/**
* Compare two process capture 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,
options: {
readonly maxCaptureAgeMs?: number;
readonly now?: () => number;
readonly traceSpecification?: ProcessTraceSpecification;
} = {},
): ProcessCaptureComparison => {
assertComparable(left, right, options);
if (left.truncated || right.truncated) {
const truncated = truncatedComparison();
return options.traceSpecification === undefined
? truncated
: {
...truncated,
trace: compareProcessTraces(left, right, options.traceSpecification),
};
}
const sameNormalization = sameJsonValue(
left.normalization,
right.normalization,
);
const exactDimensions = compareDimensions(left, right, sameNormalization);
const trace =
options.traceSpecification === undefined
? undefined
: compareProcessTraces(left, right, options.traceSpecification);
const dimensions =
trace === undefined || options.traceSpecification === undefined
? exactDimensions
: applyTraceVerdict(exactDimensions, options.traceSpecification, trace, [
left,
right,
]);
const divergenceCandidates = PROCESS_COMPARISON_DIMENSIONS.map((dimension) =>
firstCollectionDivergence(
dimension,
processDimensionObservations(left, dimension),
processDimensionObservations(right, dimension),
),
);
const observedFirstDivergence = chooseFirstDivergence(
divergenceCandidates.map((candidate) =>
candidate !== null &&
trace?.verdict === "equivalent" &&
dimensions[candidate.dimension] === "unchanged"
? null
: candidate,
),
);
const firstDivergence =
trace?.verdict === "equivalent" &&
deriveProcessComparisonStatus(
PROCESS_COMPARISON_DIMENSIONS.map((dimension) => dimensions[dimension]),
) === "unchanged"
? ({ status: "none" } as const)
: observedFirstDivergence.status === "found"
? observedFirstDivergence
: !sameNormalization ||
left.residual_unknowns.length > 0 ||
right.residual_unknowns.length > 0
? ({
status: "unknown",
reason:
"Residual unknowns prevent proving that no divergence occurred.",
} as const)
: observedFirstDivergence;
const observedStatus = deriveProcessComparisonStatus(
PROCESS_COMPARISON_DIMENSIONS.map((dimension) => dimensions[dimension]),
);
return {
status: observedStatus,
...dimensions,
first_divergence: firstDivergence,
...(trace === undefined ? {} : { trace }),
limitations: [
...left.limitations,
...right.limitations,
...left.residual_unknowns.map(({ reason }) => reason),
...right.residual_unknowns.map(({ reason }) => reason),
...(sameNormalization ? [] : ["Capture normalization rules differ."]),
],
};
};
@@ -0,0 +1,32 @@
import { expect, it } from "vitest";
import {
PROCESS_PROVIDER,
isProcessEvidenceProvider,
} from "./processEvidenceProvider.js";
it.each(["REA process capture", "REA deterministic process harness"])(
"accepts the exact v3 process provider name %s",
(name) => {
expect(isProcessEvidenceProvider({ ...PROCESS_PROVIDER, name })).toBe(true);
},
);
it.each([
{ name: "REA process capture extra" },
{ name: "REA deterministic process harness extra" },
{ name: "rea process capture" },
{ name: "REA Process Capture" },
{ name: " REA process capture" },
{ name: "REA process capture " },
{ name: "REA deterministic process harness " },
{ name: "Fixture process provider" },
{ id: "fixture-process" },
{ version: "2" },
{ version: "4" },
{ version: null },
])("rejects other process identities: %j", (change) => {
expect(isProcessEvidenceProvider({ ...PROCESS_PROVIDER, ...change })).toBe(
false,
);
});
@@ -0,0 +1,17 @@
import type { EvidenceProvider } from "../evidence.js";
/** Canonical provider identity for controlled process capture Evidence. */
export const PROCESS_PROVIDER = {
id: "rea-process",
name: "REA process capture",
version: "3",
} as const;
/** Admit current and previously emitted names for the same v3 process provider. */
export const isProcessEvidenceProvider = (
provider: EvidenceProvider,
): boolean =>
provider.id === PROCESS_PROVIDER.id &&
provider.version === PROCESS_PROVIDER.version &&
(provider.name === PROCESS_PROVIDER.name ||
provider.name === "REA deterministic process harness");
@@ -0,0 +1,116 @@
import { describe, expect, it } from "vitest";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
import {
processCaptureSchema,
type UnverifiedProcessCapture,
} from "./processCapture.js";
import {
createProcessObservation,
projectProcessObservation,
} from "./processObservation.js";
const emptyCapture = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const capture: UnverifiedProcessCapture = {
...emptyCapture,
frames: [{ sequence: 0, at_ms: 1, data: "Ready" }],
rendered_frames: [
{
sequence: 0,
at_ms: 2,
columns: 80,
rows: 24,
cursor_x: 0,
cursor_y: 0,
active_buffer: "normal",
lines: ["Ready"],
serialized_state: "Ready",
},
],
interaction_events: [
{
sequence: 0,
scheduled_at_ms: 2,
dispatched_at_ms: 3,
type: "signal",
data: "SIGINT",
outcome: "dispatched",
},
],
process_samples: [
{
at_ms: 4,
pid: 2,
parent_pid: 1,
command: "worker",
process_group_id: 1,
session_id: 1,
},
],
};
describe("process observation vocabulary", () => {
it("projects capture collections without timestamp sorting", () => {
const locations = [
{ collection: "frames", index: 0, capture_order: 4 },
{ collection: "rendered_frames", index: 0, capture_order: 3 },
{ collection: "interaction_events", index: 0, capture_order: 2 },
{ collection: "lifecycle", index: 0, capture_order: 8 },
{ collection: "lifecycle", index: 1, capture_order: 9 },
{ collection: "process_samples", index: 0, capture_order: 1 },
{ collection: "filesystem_checkpoints", index: 0, capture_order: 0 },
] as const;
const observations = locations.map((location) =>
projectProcessObservation(capture, location),
);
expect(observations.map((value) => value?.source)).toEqual([
"terminal_raw",
"terminal_rendered",
"interaction",
"lifecycle",
"lifecycle",
"process",
"filesystem",
]);
expect(observations.map((value) => value?.capture_order)).toEqual(
locations.map(({ capture_order }) => capture_order),
);
expect(observations[5]).toMatchObject({
event_id: "obs.process_samples.0",
source_sequence: 0,
captured_at_ms: 4,
subject_id: "process:2",
});
expect(observations[3]?.captured_at_ms).toBeNull();
expect(observations[4]?.captured_at_ms).toBeNull();
});
it("uses the same constructor for live and post-hoc observations", () => {
const location = {
collection: "frames" as const,
index: 0,
capture_order: 4,
};
const projected = projectProcessObservation(capture, location);
const live = createProcessObservation({
source: "terminal_raw",
source_sequence: 0,
captured_at_ms: 1,
subject_id: null,
location,
payload: capture.frames[0],
});
expect(live).toEqual(projected);
});
it("returns no observation for a missing raw record", () => {
expect(
projectProcessObservation(capture, {
collection: "frames",
index: 1,
capture_order: 10,
}),
).toBeNull();
});
});
+193
View File
@@ -0,0 +1,193 @@
import { z } from "zod";
import { jsonValueSchema, type JsonValue } from "../jsonValue.js";
import type { UnverifiedProcessCapture } from "./processCapture.js";
/** Process-capture observation families shared by live drivers and trace assertions. */
export const processObservationSourceSchema = z.enum([
"terminal_raw",
"terminal_rendered",
"interaction",
"lifecycle",
"process",
"filesystem",
]);
export type ProcessObservationSource = z.infer<
typeof processObservationSourceSchema
>;
/** Stable raw-record location within one Process Capture observation journal. */
export const processObservationLocationSchema = z.strictObject({
collection: z.enum([
"frames",
"rendered_frames",
"interaction_events",
"lifecycle",
"process_samples",
"filesystem_checkpoints",
]),
index: z.number().int().nonnegative(),
capture_order: z.number().int().nonnegative(),
});
export type ProcessObservationLocation = z.infer<
typeof processObservationLocationSchema
>;
/** Provider-neutral event projected into an offline trace assertion. */
export interface ProcessObservation {
readonly event_id: string;
readonly source: ProcessObservationSource;
readonly source_sequence: number;
readonly capture_order: number;
readonly captured_at_ms: number | null;
readonly subject_id: string | null;
readonly location: ProcessObservationLocation;
readonly payload: JsonValue;
}
/** Input used by live producers to construct the same observation shape. */
export interface ProcessObservationInput {
readonly source: ProcessObservationSource;
readonly source_sequence: number;
readonly captured_at_ms: number | null;
readonly subject_id: string | null;
readonly location: ProcessObservationLocation;
readonly payload: unknown;
}
/** Remove only explicitly declared top-level volatile fields before matching. */
export const comparableProcessObservationPayload = (
value: unknown,
ignoredFields: readonly string[] = [],
): unknown => {
if (
ignoredFields.length === 0 ||
typeof value !== "object" ||
value === null ||
Array.isArray(value)
)
return value;
return Object.fromEntries(
Object.entries(value).filter(([name]) => !ignoredFields.includes(name)),
);
};
/** Construct a validated observation from one live producer record. */
export const createProcessObservation = (
input: ProcessObservationInput,
): ProcessObservation => ({
event_id: `obs.${input.location.collection}.${String(input.location.index)}`,
source: input.source,
source_sequence: input.source_sequence,
capture_order: input.location.capture_order,
captured_at_ms: input.captured_at_ms,
subject_id: input.subject_id,
location: input.location,
payload: jsonValueSchema.parse(input.payload),
});
type ProjectedRecord = Omit<
ProcessObservation,
"event_id" | "source_sequence" | "capture_order" | "location"
>;
const atMilliseconds = (value: unknown): number | null => {
if (typeof value !== "object" || value === null) return null;
if ("at_ms" in value && isSafeMillisecond(value.at_ms)) return value.at_ms;
if ("dispatched_at_ms" in value && isSafeMillisecond(value.dispatched_at_ms))
return value.dispatched_at_ms;
return null;
};
const isSafeMillisecond = (value: unknown): value is number =>
typeof value === "number" && Number.isSafeInteger(value);
/** Derive the stable capture-local identity for one normalized observation. */
export const processObservationSubject = (
source: ProcessObservationSource,
value: unknown,
): string | null => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return null;
if (source === "process" && "pid" in value && typeof value.pid === "number")
return `process:${String(value.pid)}`;
if (
source === "filesystem" &&
"name" in value &&
typeof value.name === "string"
)
return `checkpoint:${value.name}`;
return null;
};
const projectedRecord = (
capture: UnverifiedProcessCapture,
location: ProcessObservationLocation,
): ProjectedRecord | null => {
const projected = (() => {
switch (location.collection) {
case "frames":
return {
source: "terminal_raw" as const,
value: capture.frames[location.index],
};
case "rendered_frames":
return {
source: "terminal_rendered" as const,
value: capture.rendered_frames[location.index],
};
case "interaction_events":
return {
source: "interaction" as const,
value: capture.interaction_events[location.index],
};
case "lifecycle":
return location.index === 0
? {
source: "lifecycle" as const,
value: { event: "exit", ...capture.exit },
}
: location.index === 1
? {
source: "lifecycle" as const,
value: { event: "settlement", ...capture.settlement },
}
: null;
case "process_samples":
return {
source: "process" as const,
value: capture.process_samples[location.index],
};
case "filesystem_checkpoints":
return {
source: "filesystem" as const,
value: capture.filesystem_checkpoints[location.index],
};
}
})();
if (projected === null || projected.value === undefined) return null;
const payload = jsonValueSchema.parse(projected.value);
return {
source: projected.source,
captured_at_ms: atMilliseconds(payload),
subject_id: processObservationSubject(projected.source, payload),
payload,
};
};
/** Project one validated capture-journal reference into the shared observation shape. */
export const projectProcessObservation = (
capture: UnverifiedProcessCapture,
location: ProcessObservationLocation,
): ProcessObservation | null => {
const projected = projectedRecord(capture, location);
if (projected === null) return null;
return createProcessObservation({
source: projected.source,
source_sequence: location.index,
captured_at_ms: projected.captured_at_ms,
subject_id: projected.subject_id,
location,
payload: projected.payload,
});
};
+117
View File
@@ -0,0 +1,117 @@
import { describe, expect, it } from "vitest";
import { processScenarioSchema } from "./processScenario.js";
describe("direct process scenarios", () => {
it("defaults to one command with inherited environment and no filesystem scan", () => {
expect(processScenarioSchema.parse({ executable: "node" })).toMatchObject({
executable: "node",
arguments: [],
working_directory: ".",
environment: {},
filesystem_observation_paths: [],
events: [],
});
});
it("accepts caller-selected environment and explicit filesystem observations", () => {
const environment = { "app.setting": "value", "1": "numbered" };
const scenario = processScenarioSchema.parse({
executable: "node",
arguments: ["./task.mjs"],
working_directory: "./project",
environment,
filesystem_observation_paths: ["state"],
});
expect(scenario.environment).toEqual(environment);
expect(scenario.filesystem_observation_paths).toEqual(["state"]);
});
it("rejects malformed environment names and adapter-reserved identity", () => {
for (const name of ["", "KEY=VALUE", "KEY\0VALUE", "REA_PROCESS_RUN_ID"]) {
const result = processScenarioSchema.safeParse({
executable: "node",
environment: { [name]: "value" },
});
expect(result.success).toBe(false);
if (name === "" && !result.success) {
const invalidKey = result.error.issues[0];
expect(invalidKey?.code).toBe("invalid_key");
if (invalidKey?.code === "invalid_key") {
expect(invalidKey.issues[0]?.message).toBe(
"Environment names must not be empty",
);
}
}
if (name === "REA_PROCESS_RUN_ID" && !result.success) {
const invalidKey = result.error.issues[0];
expect(invalidKey?.code).toBe("invalid_key");
if (invalidKey?.code === "invalid_key") {
expect(invalidKey.issues[0]?.message).toBe(
"REA_PROCESS_RUN_ID is reserved by the process adapter",
);
}
}
}
expect(
processScenarioSchema.safeParse({
executable: "node",
environment: { "REA_PROCESS_RUN_ID\n": "caller-value" },
}).success,
).toBe(true);
});
it("rejects NUL in strings passed to child-process APIs", () => {
const nul = "\0";
for (const input of [
{ executable: `node${nul}` },
{ executable: "node", arguments: [nul] },
{ executable: "node", working_directory: `.${nul}` },
{ executable: "node", environment: { KEY: nul } },
{ executable: "node", filesystem_observation_paths: [nul] },
])
expect(processScenarioSchema.safeParse(input).success).toBe(false);
expect(
processScenarioSchema.safeParse({
executable: "node",
events: [{ type: "input", at_ms: 0, data: nul }],
}).success,
).toBe(true);
});
it("keeps bounded capture controls and ordered scheduled interaction", () => {
const scenario = processScenarioSchema.parse({
executable: "node",
events: [
{ type: "input", at_ms: 10, data: "answer", sensitive: true },
{ type: "resize", at_ms: 20, columns: 100, rows: 30 },
{ type: "signal", at_ms: 30, signal: "SIGTERM" },
],
limits: { output_bytes: 2_000_000, filesystem_depth: 0 },
});
expect(scenario.events).toHaveLength(3);
expect(scenario.events[0]).toMatchObject({ sensitive: true });
expect(scenario.limits.output_bytes).toBe(2_000_000);
expect(scenario.limits.filesystem_depth).toBe(0);
});
it("rejects events after timeout and unknown orchestration fields", () => {
expect(
processScenarioSchema.safeParse({
executable: "node",
timeout_ms: 10,
events: [{ type: "input", at_ms: 11, data: "late" }],
}).success,
).toBe(false);
for (const [field, value] of [
["command_shims", []],
["replay", {}],
["reactive", {}],
["checkpoints", []],
] as const)
expect(
processScenarioSchema.safeParse({ executable: "node", [field]: value })
.success,
).toBe(false);
});
});
+209
View File
@@ -0,0 +1,209 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
const positiveBudget = z.number().int().safe().positive();
const timedEventBase = { at_ms: z.number().int().safe().nonnegative() };
const reservedRunIdEnvironmentName = "REA_PROCESS_RUN_ID";
const environmentName = z
.string()
.min(1, "Environment names must not be empty")
.regex(/^(?!REA_PROCESS_RUN_ID(?![\s\S]))[^=\0]+$/u, {
error: (issue) =>
issue.input === reservedRunIdEnvironmentName
? `${reservedRunIdEnvironmentName} is reserved by the process adapter`
: "Environment names cannot contain '=' or NUL",
});
const childProcessString = z
.string()
.regex(
/^[^\0]*$/u,
"Values passed to operating-system APIs cannot contain NUL",
);
export const normalizationSchema = z.object({
paths: z.boolean(),
pids: z.boolean(),
ports: z.boolean(),
time_bucket_ms: positiveBudget,
patterns: z.array(
z.object({
pattern: z.string(),
replacement: z.string(),
}),
),
});
/** Compute a canonical SHA-256 commitment independent of object key order. */
export const digestProcessCommitment = (value: unknown): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError("Process capture commitment is not canonical JSON");
return createHash("sha256").update(serialized).digest("hex");
};
const committedScenarioEvents = (
events: ProcessScenario["events"],
includeSensitiveInputLength: boolean,
): ProcessScenario["events"] =>
events.map((event) =>
event.type === "input" && event.sensitive
? {
...event,
data: includeSensitiveInputLength
? `<redacted-input:${String(Buffer.byteLength(event.data))}-bytes>`
: "<redacted-input>",
}
: event,
);
/** Build the caller-selected scenario projection committed by process-capture Evidence. */
export const processScenarioCommitment = (
scenario: ProcessScenario,
executableSha256?: string,
): Readonly<Record<string, unknown>> => ({
...scenario,
events: committedScenarioEvents(scenario.events, true),
executable_sha256: executableSha256 ?? null,
});
/** Project observation settings shared by capture and reconstruction. */
export const processComparisonContract = (
scenario: ProcessScenario,
): Readonly<Record<string, unknown>> => ({
working_directory: scenario.working_directory,
environment: scenario.environment,
ambient_environment: "unknown",
filesystem_observation_paths: scenario.filesystem_observation_paths,
terminal: scenario.terminal,
// Input bytes are intentionally absent from compatibility identity. Their
// redacted observations remain unknown, so equal commitments never imply
// that two secret values were the same.
events: committedScenarioEvents(scenario.events, false),
timeout_ms: scenario.timeout_ms,
idle_timeout_ms: scenario.idle_timeout_ms,
settle_ms: scenario.settle_ms,
limits: scenario.limits,
normalization: scenario.normalization,
});
/**
* Boundary schema for one bounded process experiment.
* Defaults are part of the evidence contract and must remain deterministic.
*/
export const processScenarioSchema = z
.object({
executable: childProcessString.min(1),
arguments: z.array(childProcessString).default([]),
working_directory: childProcessString.default("."),
environment: z.record(environmentName, childProcessString).default({}),
filesystem_observation_paths: z
.array(childProcessString.min(1))
.default([]),
terminal: z
.object({
columns: z.number().int().min(1).max(65_535).default(80),
rows: z.number().int().min(1).max(65_535).default(24),
scrollback: z.number().int().min(0).default(1_000),
})
.default({ columns: 80, rows: 24, scrollback: 1_000 }),
events: z
.array(
z.discriminatedUnion("type", [
z.object({
...timedEventBase,
type: z.literal("input"),
data: z.string(),
sensitive: z.boolean().default(false),
}),
z.object({
...timedEventBase,
type: z.literal("resize"),
columns: z.number().int().min(1).max(65_535),
rows: z.number().int().min(1).max(65_535),
}),
z.object({
...timedEventBase,
type: z.literal("signal"),
signal: z.enum(["SIGINT", "SIGTERM", "SIGKILL"]),
}),
]),
)
.default([]),
timeout_ms: positiveBudget.default(30_000),
idle_timeout_ms: positiveBudget.default(30_000),
settle_ms: z.number().int().safe().nonnegative().default(100),
limits: z
.object({
output_bytes: positiveBudget.default(1_000_000),
files: positiveBudget.default(10_000),
file_bytes: positiveBudget.default(10_000_000),
processes: positiveBudget.default(1_000),
filesystem_depth: z.number().int().safe().nonnegative().default(16),
})
.strict()
.default({
output_bytes: 1_000_000,
files: 10_000,
file_bytes: 10_000_000,
processes: 1_000,
filesystem_depth: 16,
}),
normalization: z
.object({
paths: z.boolean().default(false),
pids: z.boolean().default(true),
ports: z.boolean().default(true),
time_bucket_ms: positiveBudget.default(10),
patterns: z
.array(
z.object({
pattern: z.string(),
replacement: z.string(),
}),
)
.default([]),
})
.default({
paths: false,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
}),
})
.strict()
.superRefine((scenario, context) => {
for (let index = 1; index < scenario.events.length; index += 1) {
const event = scenario.events[index];
const previous = scenario.events[index - 1];
if (eventsOutOfOrder(event, previous)) {
context.addIssue({
code: "custom",
message: "events must be ordered by at_ms",
path: ["events", index],
});
}
}
for (const event of scenario.events) {
if (event.at_ms > scenario.timeout_ms) {
context.addIssue({
code: "custom",
message: "event occurs after the scenario timeout",
path: ["events"],
});
}
}
});
const eventsOutOfOrder = (
event: { readonly at_ms: number } | undefined,
previous: { readonly at_ms: number } | undefined,
): boolean =>
event !== undefined && previous !== undefined && event.at_ms < previous.at_ms;
/** 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. */
export const parseProcessScenario = (input: unknown): ProcessScenario =>
processScenarioSchema.parse(input);
@@ -0,0 +1,144 @@
import { describe, expect, it } from "vitest";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
import {
compareProcessCaptures,
parseProcessCapture,
} from "./processCapture.js";
import type { ProcessTraceSpecification } from "./processTraceComparison.js";
const beforeCheckpoint = {
name: "before",
at_ms: 0,
files: [],
effects: [],
truncated: false,
};
const afterCheckpoint = {
name: "after_settlement",
at_ms: 50,
files: [],
effects: [],
truncated: false,
};
const capture = {
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
event_journal: [
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
{ capture_order: 1, collection: "lifecycle", index: 0 },
{ capture_order: 2, collection: "lifecycle", index: 1 },
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
],
} as const;
const traceSpecification: ProcessTraceSpecification = {
events: [
{
id: "before",
source: "filesystem",
exact: beforeCheckpoint,
cardinality: { kind: "required" },
},
{
id: "exit",
source: "lifecycle",
exact: { event: "exit", ...capture.exit },
cardinality: { kind: "required" },
},
{
id: "settlement",
source: "lifecycle",
exact: { event: "settlement", ...capture.settlement },
cardinality: { kind: "required" },
},
{
id: "after",
source: "filesystem",
exact: afterCheckpoint,
cardinality: { kind: "required" },
},
],
language: {
kind: "finite_traces",
variants: [
{
id: "normal",
trace: ["before", "exit", "settlement", "after"],
},
],
},
};
describe("declared trace comparison nonconformance", () => {
it("does not call identical captures changed when both violate the language", () => {
const parsedCapture = parseProcessCapture(capture);
const specification: ProcessTraceSpecification = {
...traceSpecification,
language: {
kind: "finite_traces",
variants: [
{
id: "reversed",
trace: ["after", "settlement", "exit", "before"],
},
],
},
};
expect(
compareProcessCaptures(parsedCapture, parsedCapture, {
traceSpecification: specification,
}),
).toMatchObject({
status: "unchanged",
trace: { verdict: "nonconforming" },
});
});
it("does not mask distinct payloads when both traces are nonconforming", () => {
const withTerminal = (data: string) =>
parseProcessCapture({
...capture,
frames: [{ sequence: 0, at_ms: 1, data }],
event_journal: [
{
capture_order: 0,
collection: "filesystem_checkpoints",
index: 0,
},
{ capture_order: 1, collection: "frames", index: 0 },
{ capture_order: 2, collection: "lifecycle", index: 0 },
{ capture_order: 3, collection: "lifecycle", index: 1 },
{
capture_order: 4,
collection: "filesystem_checkpoints",
index: 1,
},
],
});
const specification: ProcessTraceSpecification = {
events: [
{
id: "expected",
source: "terminal_raw",
exact: { sequence: 0, at_ms: 1, data: "expected" },
cardinality: { kind: "required" },
},
],
language: {
kind: "finite_traces",
variants: [{ id: "expected", trace: ["expected"] }],
},
};
expect(
compareProcessCaptures(withTerminal("left"), withTerminal("right"), {
traceSpecification: specification,
}),
).toMatchObject({
status: "changed",
terminal: "changed",
trace: { verdict: "nonconforming" },
});
});
});
@@ -0,0 +1,92 @@
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
import { parseProcessCapture, type ProcessCapture } from "./processCapture.js";
import { type ProcessTraceSpecification } from "./processTraceComparison.js";
export const emptyCapture = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
export const terminal = { sequence: 0, at_ms: 900, data: "Ready" };
export const processStarted = {
at_ms: 1,
pid: 1,
parent_pid: 0,
command: "worker",
process_group_id: 1,
session_id: 1,
};
export const capture = (
values: Pick<ProcessCapture, "frames" | "process_samples"> & {
readonly event_journal: readonly Pick<
NonNullable<ProcessCapture["event_journal"]>[number],
"collection" | "index"
>[];
},
options: {
readonly truncated?: boolean;
readonly residualUnknowns?: ProcessCapture["residual_unknowns"];
} = {},
): ProcessCapture =>
parseProcessCapture({
...emptyCapture,
frames: values.frames,
process_samples: values.process_samples,
event_journal: [
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
...values.event_journal.map((entry, index) => ({
...entry,
capture_order: index + 1,
})),
{
capture_order: values.event_journal.length + 1,
collection: "lifecycle",
index: 0,
},
{
capture_order: values.event_journal.length + 2,
collection: "lifecycle",
index: 1,
},
{
capture_order: values.event_journal.length + 3,
collection: "filesystem_checkpoints",
index: 1,
},
],
truncated: options.truncated ?? false,
residual_unknowns: options.residualUnknowns ?? [],
});
export const values = (
order: readonly ("terminal" | "process")[],
): Parameters<typeof capture>[0] => ({
frames: [terminal],
process_samples: [processStarted],
event_journal: order.map((event) => ({
collection: event === "terminal" ? "frames" : "process_samples",
index: 0,
})),
});
export const partialSpecification = (): ProcessTraceSpecification => ({
events: [
{
id: "ready",
source: "terminal_raw",
exact: terminal,
cardinality: { kind: "required" },
},
{
id: "worker",
source: "process",
exact: processStarted,
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [{ before: "ready", after: "worker" }],
not_before: [],
unordered_groups: [],
prefix: ["ready"],
suffix: ["worker"],
},
});
@@ -0,0 +1,248 @@
import { describe, expect, it } from "vitest";
import { parseProcessCapture } from "./processCapture.js";
import {
compareProcessTraces,
processTraceComparisonResultSchema,
type ProcessTraceSpecification,
} from "./processTraceComparison.js";
import {
capture,
partialSpecification,
processStarted,
terminal,
values,
} from "./processTraceComparison.fixture.js";
describe("generic capture trace comparison", () => {
it("requires explicit partial ordering and never infers causality from timestamps", () => {
const specification = partialSpecification();
const left = capture(values(["terminal", "process"]));
const right = capture(values(["process", "terminal"]));
expect(compareProcessTraces(left, right, specification)).toMatchObject({
verdict: "different",
diagnostic: { kind: "edge", side: "right" },
});
const concurrent: ProcessTraceSpecification = {
...specification,
language: {
kind: "partial_order",
happens_before: [],
not_before: [],
unordered_groups: [{ events: ["ready", "worker"] }],
prefix: [],
suffix: [],
},
};
expect(compareProcessTraces(left, right, concurrent)).toMatchObject({
verdict: "equivalent",
});
});
it("rejects malformed result contracts", () => {
const result = compareProcessTraces(
capture(values(["terminal", "process"])),
capture(values(["terminal", "process"])),
partialSpecification(),
);
expect(
processTraceComparisonResultSchema.safeParse({
...result,
right: {
...result.right,
status: "fail",
matched_variant: "invented",
},
}).success,
).toBe(false);
});
it("supports declared optional events and bounded duplicates", () => {
const first = { sequence: 0, at_ms: 1, data: "tick" };
const second = { sequence: 1, at_ms: 2, data: "tick" };
const one = capture({
frames: [first],
process_samples: [],
event_journal: [{ collection: "frames", index: 0 }],
});
const two = capture({
frames: [first, second],
process_samples: [],
event_journal: [
{ collection: "frames", index: 0 },
{ collection: "frames", index: 1 },
],
});
const specification: ProcessTraceSpecification = {
events: [
{
id: "tick1",
source: "terminal_raw",
exact: first,
cardinality: { kind: "required" },
},
{
id: "tick2",
source: "terminal_raw",
exact: second,
cardinality: { kind: "optional" },
},
],
language: {
kind: "finite_traces",
variants: [
{ id: "one", trace: ["tick1"] },
{ id: "two", trace: ["tick1", "tick2"] },
],
},
};
expect(compareProcessTraces(one, two, specification)).toMatchObject({
verdict: "equivalent",
left: { matched_variant: "one" },
right: { matched_variant: "two" },
});
});
});
describe("process trace constraints and evidence sufficiency", () => {
it("enforces exact and range cardinality for a repeated terminal observation", () => {
const repeated = (count: number) =>
capture({
frames: Array.from({ length: count }, (_, sequence) => ({
sequence,
at_ms: sequence,
data: "tick",
})),
process_samples: [],
event_journal: Array.from({ length: count }, (_, index) => ({
collection: "frames" as const,
index,
})),
});
const event: Omit<
ProcessTraceSpecification["events"][number],
"cardinality"
> = {
id: "tick",
source: "terminal_raw",
exact: { data: "tick" },
ignore_fields: ["sequence", "at_ms"],
};
const rangeSpecification: ProcessTraceSpecification = {
events: [{ ...event, cardinality: { kind: "range", min: 2, max: 3 } }],
language: {
kind: "partial_order",
happens_before: [],
not_before: [],
unordered_groups: [],
prefix: [],
suffix: [],
},
};
expect(
compareProcessTraces(repeated(2), repeated(3), rangeSpecification),
).toMatchObject({ verdict: "equivalent" });
expect(
compareProcessTraces(repeated(1), repeated(2), rangeSpecification),
).toMatchObject({
verdict: "different",
diagnostic: { kind: "cardinality", side: "left" },
});
expect(
compareProcessTraces(repeated(2), repeated(4), rangeSpecification),
).toMatchObject({
verdict: "different",
diagnostic: { kind: "cardinality", side: "right" },
});
const exactSpecification: ProcessTraceSpecification = {
events: [{ ...event, cardinality: { kind: "exact", count: 2 } }],
language: {
kind: "finite_traces",
variants: [{ id: "two", trace: ["tick", "tick"] }],
},
};
expect(
compareProcessTraces(repeated(2), repeated(2), exactSpecification),
).toMatchObject({ verdict: "equivalent" });
expect(
compareProcessTraces(repeated(3), repeated(2), exactSpecification),
).toMatchObject({
verdict: "different",
diagnostic: { kind: "cardinality", side: "left" },
});
});
it("enforces an explicit not-before relation between terminal and process events", () => {
const specification: ProcessTraceSpecification = {
events: [
{
id: "ready",
source: "terminal_raw",
exact: terminal,
cardinality: { kind: "required" },
},
{
id: "worker",
source: "process",
exact: processStarted,
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [],
not_before: [{ event: "ready", anchor: "worker" }],
unordered_groups: [],
prefix: [],
suffix: [],
},
};
const readyFirst = capture(values(["terminal", "process"]));
const workerFirst = capture(values(["process", "terminal"]));
expect(
compareProcessTraces(workerFirst, readyFirst, specification),
).toMatchObject({
verdict: "different",
diagnostic: {
kind: "edge",
side: "right",
event_ids: ["ready", "worker"],
},
});
expect(
compareProcessTraces(workerFirst, workerFirst, specification),
).toMatchObject({ verdict: "equivalent" });
});
it("never proves equivalence from truncated, unknown, or journal-free evidence", () => {
const complete = capture(values(["terminal", "process"]));
const truncated = capture(values(["terminal", "process"]), {
truncated: true,
});
expect(
compareProcessTraces(complete, truncated, partialSpecification()).verdict,
).toBe("unknown");
const unknown = capture(values(["terminal", "process"]), {
residualUnknowns: [{ scope: "process", reason: "sampled" }],
});
expect(
compareProcessTraces(complete, unknown, partialSpecification()).verdict,
).toBe("unknown");
const noJournal = parseProcessCapture({ ...complete, event_journal: [] });
expect(
compareProcessTraces(complete, noJournal, partialSpecification()),
).toMatchObject({
verdict: "unknown",
diagnostic: { kind: "journal", side: "right" },
});
expect(() =>
parseProcessCapture({
...complete,
event_journal: (complete.event_journal ?? []).slice(1),
}),
).toThrow("event_journal");
});
});
@@ -0,0 +1,68 @@
import type { ProcessCapture } from "./processCapture.js";
import {
evaluateProcessTraceSide,
processTraceComparisonResultSchema,
type ProcessTraceComparisonResult,
} from "./processTraceEvaluation.js";
import {
processTraceSpecificationSchema,
type ProcessTraceSpecification,
} from "./processTraceSpecification.js";
export {
processTraceComparisonResultSchema,
type ProcessTraceComparisonResult,
} from "./processTraceEvaluation.js";
export {
processTraceSpecificationSchema,
type ProcessTraceSpecification,
} from "./processTraceSpecification.js";
/** Compare two captures against an explicit finite trace language. */
export const compareProcessTraces = (
left: ProcessCapture,
right: ProcessCapture,
specificationInput: ProcessTraceSpecification,
): ProcessTraceComparisonResult => {
const specification =
processTraceSpecificationSchema.parse(specificationInput);
const leftEvaluation = evaluateProcessTraceSide(left, specification);
const rightEvaluation = evaluateProcessTraceSide(right, specification);
const diagnostic =
leftEvaluation.diagnostic === null
? rightEvaluation.diagnostic === null
? null
: { side: "right" as const, ...rightEvaluation.diagnostic }
: { side: "left" as const, ...leftEvaluation.diagnostic };
const outcomesDiffer =
leftEvaluation.result.status !== rightEvaluation.result.status ||
JSON.stringify(
leftEvaluation.result.raw_trace.map(({ event_id }) => event_id),
) !==
JSON.stringify(
rightEvaluation.result.raw_trace.map(({ event_id }) => event_id),
);
return processTraceComparisonResultSchema.parse({
verdict:
leftEvaluation.result.status === "unknown" ||
rightEvaluation.result.status === "unknown"
? "unknown"
: leftEvaluation.result.status === "pass" &&
rightEvaluation.result.status === "pass"
? "equivalent"
: outcomesDiffer
? "different"
: "nonconforming",
left: leftEvaluation.result,
right: rightEvaluation.result,
diagnostic,
});
};
/** Whether trace conformance or raw declared order differs across captures. */
export const processTraceOutcomesDiffer = (
comparison: ProcessTraceComparisonResult,
): boolean =>
comparison.left.status !== comparison.right.status ||
JSON.stringify(comparison.left.raw_trace.map(({ event_id }) => event_id)) !==
JSON.stringify(comparison.right.raw_trace.map(({ event_id }) => event_id));
@@ -0,0 +1,53 @@
import type { ProcessCapture } from "./processCapture.js";
import type { ProcessTraceSource } from "./processTraceSpecification.js";
export type ProcessComparisonDimension =
| "terminal"
| "interaction"
| "exit"
| "filesystem"
| "process";
/** Map declared trace sources to legacy process-comparison dimensions. */
export const dimensionsForTraceSources = (
sources: ReadonlySet<ProcessTraceSource>,
): ReadonlySet<ProcessComparisonDimension> => {
const dimensions = new Set<ProcessComparisonDimension>();
for (const source of sources) {
if (source.startsWith("terminal_")) dimensions.add("terminal");
else if (source === "interaction") dimensions.add("interaction");
else if (source === "lifecycle") dimensions.add("exit");
else if (source === "filesystem") dimensions.add("filesystem");
else if (source === "process") dimensions.add("process");
}
return dimensions;
};
/** Whether a trace specification covers every observed source in a dimension. */
export const traceCoversObservedDimension = (
dimension: ProcessComparisonDimension,
sources: ReadonlySet<ProcessTraceSource>,
left: ProcessCapture,
right: ProcessCapture,
): boolean => {
const any = <Value>(
leftValues: readonly Value[],
rightValues: readonly Value[],
): boolean => leftValues.length > 0 || rightValues.length > 0;
switch (dimension) {
case "terminal":
return (
(!any(left.frames, right.frames) || sources.has("terminal_raw")) &&
(!any(left.rendered_frames, right.rendered_frames) ||
sources.has("terminal_rendered"))
);
case "interaction":
return sources.has("interaction");
case "exit":
return sources.has("lifecycle");
case "filesystem":
return false;
case "process":
return sources.has("process");
}
};
@@ -0,0 +1,433 @@
import { z } from "zod";
import type { JsonValue } from "../jsonValue.js";
import type { ProcessCapture } from "./processCapture.js";
import {
processObservationLocationSchema,
projectProcessObservation,
type ProcessObservationLocation,
} from "./processObservation.js";
import {
canonicalTraceJson,
comparableTracePayload,
processTraceCardinalityBounds,
type ProcessTraceSource,
type ProcessTraceSpecification,
} from "./processTraceSpecification.js";
const identifierSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._-]{0,63}$/u);
export type ProcessTraceLocation = ProcessObservationLocation;
const locationSchema = processObservationLocationSchema;
const matchedEventSchema = z.strictObject({
event_id: identifierSchema,
location: locationSchema,
});
const sideResultShape = {
satisfied_constraints: z.array(z.string()),
raw_trace: z.array(matchedEventSchema),
};
const sideResultSchema = z.union([
z.strictObject({
...sideResultShape,
status: z.literal("pass"),
matched_variant: identifierSchema.nullable(),
}),
z.strictObject({
...sideResultShape,
status: z.enum(["fail", "unknown"]),
matched_variant: z.null(),
}),
]);
const diagnosticSchema = z.strictObject({
kind: z.enum([
"journal",
"predicate",
"cardinality",
"edge",
"prefix",
"suffix",
"trace",
]),
side: z.enum(["left", "right"]),
message: z.string(),
event_ids: z.array(identifierSchema),
locations: z.array(locationSchema),
});
/** Structured verdict for one declared process trace language. */
export const processTraceComparisonResultSchema = z.strictObject({
verdict: z.enum(["equivalent", "different", "nonconforming", "unknown"]),
left: sideResultSchema,
right: sideResultSchema,
diagnostic: diagnosticSchema.nullable(),
});
export type ProcessTraceComparisonResult = z.infer<
typeof processTraceComparisonResultSchema
>;
type TraceRecord = {
readonly source: ProcessTraceSource;
readonly payload: JsonValue;
readonly location: ProcessTraceLocation;
};
const scopesFor = (
sources: ReadonlySet<ProcessTraceSource>,
): ReadonlySet<string> =>
new Set(
[...sources].map((source) => {
if (source.startsWith("terminal_")) return "terminal";
if (source === "lifecycle") return "exit";
if (source === "filesystem") return "filesystem";
if (source === "process") return "process";
return "interaction";
}),
);
const unknownSide = (): z.infer<typeof sideResultSchema> => ({
status: "unknown",
matched_variant: null,
satisfied_constraints: [],
raw_trace: [],
});
export type EvaluatedSide = {
readonly result: z.infer<typeof sideResultSchema>;
readonly diagnostic: Omit<z.infer<typeof diagnosticSchema>, "side"> | null;
};
type FailureInput = {
readonly kind: z.infer<typeof diagnosticSchema>["kind"];
readonly message: string;
readonly eventIds: readonly string[];
readonly locations: readonly ProcessTraceLocation[];
readonly rawTrace: z.infer<typeof matchedEventSchema>[];
};
const failure = (input: FailureInput): EvaluatedSide => ({
result: {
status: "fail",
matched_variant: null,
satisfied_constraints: [],
raw_trace: input.rawTrace,
},
diagnostic: {
kind: input.kind,
message: input.message,
event_ids: [...input.eventIds],
locations: [...input.locations],
},
});
const evaluateFiniteTrace = (
ids: readonly string[],
specification: ProcessTraceSpecification,
): string | null => {
if (specification.language.kind !== "finite_traces") return null;
for (const variant of specification.language.variants) {
let offset = 0;
let accepted = true;
for (const token of variant.trace) {
if (typeof token === "string") {
if (ids[offset] !== token) accepted = false;
offset += 1;
continue;
}
const actual = ids.slice(offset, offset + token.unordered.length).sort();
const expected = [...token.unordered].sort();
if (canonicalTraceJson(actual) !== canonicalTraceJson(expected))
accepted = false;
offset += token.unordered.length;
}
if (accepted && offset === ids.length) return variant.id;
}
return null;
};
type MatchedTrace = {
readonly rawTrace: z.infer<typeof matchedEventSchema>[];
readonly locationsById: ReadonlyMap<string, ProcessTraceLocation[]>;
};
const collectRecords = (
capture: ProcessCapture,
sources: ReadonlySet<ProcessTraceSource>,
): readonly TraceRecord[] => {
const records: TraceRecord[] = [];
for (const location of capture.event_journal ?? []) {
const record = projectProcessObservation(capture, location);
if (record !== null && sources.has(record.source))
records.push({
source: record.source,
payload: record.payload,
location,
});
}
return records;
};
const matchRecords = (
records: readonly TraceRecord[],
specification: ProcessTraceSpecification,
): MatchedTrace | EvaluatedSide => {
const rawTrace: z.infer<typeof matchedEventSchema>[] = [];
const locationsById = new Map<string, ProcessTraceLocation[]>();
const ignoredFieldsBySource = new Map<
ProcessTraceSource,
readonly string[]
>();
const eventsByKey = new Map<
string,
ProcessTraceSpecification["events"][number]
>();
for (const event of specification.events) {
const ignoredFields = event.ignore_fields ?? [];
ignoredFieldsBySource.set(event.source, ignoredFields);
eventsByKey.set(
`${event.source}\0${canonicalTraceJson(
comparableTracePayload(event.exact, ignoredFields),
)}`,
event,
);
}
for (const record of records) {
const match = eventsByKey.get(
`${record.source}\0${canonicalTraceJson(
comparableTracePayload(
record.payload,
ignoredFieldsBySource.get(record.source),
),
)}`,
);
if (match === undefined)
return failure({
kind: "predicate",
message: "Observed event does not match any declared exact predicate.",
eventIds: [],
locations: [record.location],
rawTrace,
});
rawTrace.push({ event_id: match.id, location: record.location });
const locations = locationsById.get(match.id) ?? [];
locations.push(record.location);
locationsById.set(match.id, locations);
}
return { rawTrace, locationsById };
};
const cardinalityFailure = (
trace: MatchedTrace,
specification: ProcessTraceSpecification,
): EvaluatedSide | null => {
for (const event of specification.events) {
const [minimum, maximum] = processTraceCardinalityBounds(event.cardinality);
const locations = trace.locationsById.get(event.id) ?? [];
if (locations.length < minimum || locations.length > maximum)
return failure({
kind: "cardinality",
message: `${event.id} observed ${String(locations.length)} times; expected ${String(minimum)}..${String(maximum)}.`,
eventIds: [event.id],
locations,
rawTrace: trace.rawTrace,
});
}
return null;
};
type PartialOrderLanguage = Extract<
ProcessTraceSpecification["language"],
{ readonly kind: "partial_order" }
>;
const evaluateOrderingConstraints = (
trace: MatchedTrace,
language: PartialOrderLanguage,
): { readonly failure: EvaluatedSide | null; readonly satisfied: string[] } => {
const satisfied: string[] = [];
for (const edge of language.happens_before) {
const before = trace.locationsById.get(edge.before) ?? [];
const after = trace.locationsById.get(edge.after) ?? [];
const lastBefore = before.at(-1);
const firstAfter = after[0];
if (lastBefore === undefined && firstAfter !== undefined)
return {
failure: failure({
kind: "edge",
message: `${edge.before} is required when ${edge.after} occurs.`,
eventIds: [edge.before, edge.after],
locations: [firstAfter],
rawTrace: trace.rawTrace,
}),
satisfied,
};
if (
lastBefore !== undefined &&
firstAfter !== undefined &&
lastBefore.capture_order >= firstAfter.capture_order
)
return {
failure: failure({
kind: "edge",
message: `${edge.before} must happen before ${edge.after}.`,
eventIds: [edge.before, edge.after],
locations: [lastBefore, firstAfter],
rawTrace: trace.rawTrace,
}),
satisfied,
};
satisfied.push(`happens_before:${edge.before}:${edge.after}`);
}
for (const constraint of language.not_before) {
const events = trace.locationsById.get(constraint.event) ?? [];
const anchors = trace.locationsById.get(constraint.anchor) ?? [];
const firstEvent = events[0];
const firstAnchor = anchors[0];
if (firstEvent !== undefined && firstAnchor === undefined)
return {
failure: failure({
kind: "edge",
message: `${constraint.anchor} is required when ${constraint.event} occurs.`,
eventIds: [constraint.event, constraint.anchor],
locations: [firstEvent],
rawTrace: trace.rawTrace,
}),
satisfied,
};
if (
firstEvent !== undefined &&
firstAnchor !== undefined &&
firstEvent.capture_order < firstAnchor.capture_order
)
return {
failure: failure({
kind: "edge",
message: `${constraint.event} must not occur before ${constraint.anchor}.`,
eventIds: [constraint.event, constraint.anchor],
locations: [firstEvent, firstAnchor],
rawTrace: trace.rawTrace,
}),
satisfied,
};
satisfied.push(`not_before:${constraint.event}:${constraint.anchor}`);
}
return { failure: null, satisfied };
};
const boundaryFailure = (
trace: MatchedTrace,
kind: "prefix" | "suffix",
expected: readonly string[],
): EvaluatedSide | null => {
const ids = trace.rawTrace.map(({ event_id }) => event_id);
const actual =
kind === "prefix"
? ids.slice(0, expected.length)
: expected.length === 0
? []
: ids.slice(-expected.length);
if (canonicalTraceJson(actual) === canonicalTraceJson(expected)) return null;
const locations =
kind === "prefix"
? trace.rawTrace.slice(0, expected.length)
: trace.rawTrace.slice(-expected.length);
return failure({
kind,
message: `Observed trace does not satisfy the declared ${kind}.`,
eventIds: expected,
locations: locations.map(({ location }) => location),
rawTrace: trace.rawTrace,
});
};
const evaluatePartialOrder = (
trace: MatchedTrace,
language: PartialOrderLanguage,
): EvaluatedSide => {
const ordering = evaluateOrderingConstraints(trace, language);
if (ordering.failure !== null) return ordering.failure;
const prefixFailure = boundaryFailure(trace, "prefix", language.prefix);
if (prefixFailure !== null) return prefixFailure;
const suffixFailure = boundaryFailure(trace, "suffix", language.suffix);
if (suffixFailure !== null) return suffixFailure;
const satisfied = ordering.satisfied;
satisfied.push(
...language.unordered_groups.map(
({ events }) => `unordered:${events.join(":")}`,
),
);
if (language.prefix.length > 0)
satisfied.push(`prefix:${language.prefix.join(":")}`);
if (language.suffix.length > 0)
satisfied.push(`suffix:${language.suffix.join(":")}`);
return {
result: {
status: "pass",
matched_variant: null,
satisfied_constraints: satisfied,
raw_trace: trace.rawTrace,
},
diagnostic: null,
};
};
const evaluateMatchedTrace = (
trace: MatchedTrace,
specification: ProcessTraceSpecification,
): EvaluatedSide => {
const invalidCardinality = cardinalityFailure(trace, specification);
if (invalidCardinality !== null) return invalidCardinality;
if (specification.language.kind === "partial_order")
return evaluatePartialOrder(trace, specification.language);
const ids = trace.rawTrace.map(({ event_id }) => event_id);
const variant = evaluateFiniteTrace(ids, specification);
return variant === null
? failure({
kind: "trace",
message: "Observed events do not match any finite trace variant.",
eventIds: ids,
locations: trace.rawTrace.map(({ location }) => location),
rawTrace: trace.rawTrace,
})
: {
result: {
status: "pass",
matched_variant: variant,
satisfied_constraints: [`variant:${variant}`],
raw_trace: trace.rawTrace,
},
diagnostic: null,
};
};
export const evaluateProcessTraceSide = (
capture: ProcessCapture,
specification: ProcessTraceSpecification,
): EvaluatedSide => {
const sources = new Set(specification.events.map(({ source }) => source));
const relevantScopes = scopesFor(sources);
if (
capture.truncated ||
capture.residual_unknowns.some(({ scope }) => relevantScopes.has(scope))
)
return { result: unknownSide(), diagnostic: null };
if ((capture.event_journal ?? []).length === 0)
return {
result: unknownSide(),
diagnostic: {
kind: "journal",
message: "Capture has no cross-source event journal.",
event_ids: [],
locations: [],
},
};
const matched = matchRecords(collectRecords(capture, sources), specification);
return "rawTrace" in matched
? evaluateMatchedTrace(matched, specification)
: matched;
};
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import {
processTraceSpecificationSchema,
type ProcessTraceSpecification,
} from "./processTraceComparison.js";
const ready = { sequence: 0, at_ms: 10, data: "ready" };
const worker = {
at_ms: 20,
pid: 1,
parent_pid: 0,
command: "worker",
process_group_id: 1,
session_id: 1,
};
const specification = (): ProcessTraceSpecification => ({
events: [
{
id: "ready",
source: "terminal_raw",
exact: ready,
cardinality: { kind: "required" },
},
{
id: "worker",
source: "process",
exact: worker,
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [{ before: "ready", after: "worker" }],
not_before: [],
unordered_groups: [],
prefix: ["ready"],
suffix: ["worker"],
},
});
describe("process trace specification", () => {
it("rejects cycles, implicit ordering gaps, invalid ignores, and unsatisfiable variants", () => {
const base = specification();
expect(
processTraceSpecificationSchema.safeParse({
...base,
language: {
kind: "partial_order",
happens_before: [
{ before: "ready", after: "worker" },
{ before: "worker", after: "ready" },
],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
...base,
language: { kind: "partial_order" },
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
events: [
{
id: "bad",
source: "terminal_raw",
exact: "ready",
ignore_fields: ["at_ms"],
},
],
language: {
kind: "finite_traces",
variants: [{ id: "one", trace: ["bad"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
events: [
{
...base.events[0],
cardinality: { kind: "exact", count: 2 },
},
],
language: {
kind: "finite_traces",
variants: [{ id: "once", trace: ["ready"] }],
},
}).success,
).toBe(false);
});
});
@@ -0,0 +1,489 @@
import canonicalize from "canonicalize";
import { z } from "zod";
import { jsonValueSchema } from "../jsonValue.js";
import {
comparableProcessObservationPayload,
processObservationSourceSchema,
type ProcessObservationSource,
} from "./processObservation.js";
const identifierSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._-]*$/u);
/** Process observation families admitted by a declared trace specification. */
export const processTraceSourceSchema = processObservationSourceSchema;
export type ProcessTraceSource = ProcessObservationSource;
const cardinalitySchema = z.discriminatedUnion("kind", [
z.strictObject({ kind: z.literal("required") }),
z.strictObject({ kind: z.literal("optional") }),
z.strictObject({
kind: z.literal("exact"),
count: z.number().int().min(0),
}),
z
.strictObject({
kind: z.literal("range"),
min: z.number().int().min(0),
max: z.number().int().min(0),
})
.refine(({ min, max }) => min <= max, {
message: "cardinality min must not exceed max",
path: ["min"],
}),
]);
const eventDeclarationSchema = z.strictObject({
id: identifierSchema,
source: processTraceSourceSchema,
exact: jsonValueSchema,
ignore_fields: z
.array(
z.enum([
"sequence",
"at_ms",
"scheduled_at_ms",
"dispatched_at_ms",
"elapsed_ms",
]),
)
.refine((values) => new Set(values).size === values.length, {
message: "ignored event fields must be unique",
})
.optional(),
cardinality: cardinalitySchema.default({ kind: "required" }),
});
const partialOrderLanguageSchema = z.strictObject({
kind: z.literal("partial_order"),
happens_before: z
.array(
z.strictObject({
before: identifierSchema,
after: identifierSchema,
}),
)
.default([]),
not_before: z
.array(
z.strictObject({
event: identifierSchema,
anchor: identifierSchema,
}),
)
.default([]),
unordered_groups: z
.array(z.strictObject({ events: z.array(identifierSchema).min(2) }))
.default([]),
prefix: z.array(identifierSchema).default([]),
suffix: z.array(identifierSchema).default([]),
});
const finiteTraceTokenSchema = z.union([
identifierSchema,
z.strictObject({ unordered: z.array(identifierSchema).min(2) }),
]);
const finiteTraceLanguageSchema = z.strictObject({
kind: z.literal("finite_traces"),
variants: z
.array(
z.strictObject({
id: identifierSchema,
trace: z.array(finiteTraceTokenSchema),
}),
)
.min(1),
});
const specificationShapeSchema = z.strictObject({
events: z.array(eventDeclarationSchema).min(1),
language: z.discriminatedUnion("kind", [
partialOrderLanguageSchema,
finiteTraceLanguageSchema,
]),
});
export type ProcessTraceSpecification = z.infer<
typeof specificationShapeSchema
>;
type PartialOrderLanguage = z.infer<typeof partialOrderLanguageSchema>;
export const canonicalTraceJson = (value: unknown): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError("Trace specification contains a non-JSON value");
return serialized;
};
/** Remove only explicitly declared schedule metadata before exact matching. */
export const comparableTracePayload = (
value: unknown,
ignoredFields: readonly string[] = [],
): unknown => comparableProcessObservationPayload(value, ignoredFields);
export const processTraceCardinalityBounds = (
cardinality: ProcessTraceSpecification["events"][number]["cardinality"],
): readonly [number, number] => {
switch (cardinality.kind) {
case "required":
return [1, 1];
case "optional":
return [0, 1];
case "exact":
return [cardinality.count, cardinality.count];
case "range":
return [cardinality.min, cardinality.max];
}
};
const addReferenceIssue = (
context: z.RefinementCtx,
known: ReadonlySet<string>,
id: string,
path: PropertyKey[],
): void => {
if (!known.has(id))
context.addIssue({
code: "custom",
message: `unknown event id: ${id}`,
path,
});
};
const pairKey = (left: string, right: string): string =>
[left, right].sort().join("\0");
const buildAdjacency = (
language: PartialOrderLanguage,
context: z.RefinementCtx,
known: ReadonlySet<string>,
): ReadonlyMap<string, Set<string>> => {
const adjacency = new Map([...known].map((id) => [id, new Set<string>()]));
for (const [index, edge] of language.happens_before.entries()) {
const path = ["language", "happens_before", index];
addReferenceIssue(context, known, edge.before, [...path, "before"]);
addReferenceIssue(context, known, edge.after, [...path, "after"]);
if (edge.before === edge.after)
context.addIssue({
code: "custom",
message: "happens-before edges must reference distinct events",
path,
});
adjacency.get(edge.before)?.add(edge.after);
}
return adjacency;
};
const validateNotBefore = (
language: PartialOrderLanguage,
context: z.RefinementCtx,
known: ReadonlySet<string>,
reachable: ReadonlyMap<string, ReadonlySet<string>>,
): ReadonlySet<string> => {
const pairs = new Set<string>();
for (const [index, constraint] of language.not_before.entries()) {
const path = ["language", "not_before", index];
addReferenceIssue(context, known, constraint.event, [...path, "event"]);
addReferenceIssue(context, known, constraint.anchor, [...path, "anchor"]);
if (constraint.event === constraint.anchor)
context.addIssue({
code: "custom",
message: "not-before constraints must reference distinct events",
path,
});
const key = pairKey(constraint.event, constraint.anchor);
if (pairs.has(key))
context.addIssue({
code: "custom",
message: "not-before event pairs must be declared once",
path,
});
pairs.add(key);
if (reachable.get(constraint.event)?.has(constraint.anchor) === true)
context.addIssue({
code: "custom",
message: "not-before constraint conflicts with happens-before order",
path,
});
}
return pairs;
};
const graphHasCycle = (
ids: readonly string[],
adjacency: ReadonlyMap<string, ReadonlySet<string>>,
): boolean => {
const active = new Set<string>();
const complete = new Set<string>();
const visit = (current: string): boolean => {
if (active.has(current)) return true;
if (complete.has(current)) return false;
active.add(current);
const cyclic = [...(adjacency.get(current) ?? [])].some(visit);
active.delete(current);
complete.add(current);
return cyclic;
};
return ids.some(visit);
};
const computeReachability = (
ids: readonly string[],
adjacency: ReadonlyMap<string, ReadonlySet<string>>,
): ReadonlyMap<string, ReadonlySet<string>> => {
const reachable = new Map<string, Set<string>>();
for (const origin of ids) {
const seen = new Set<string>();
const pending = [...(adjacency.get(origin) ?? [])];
while (pending.length > 0) {
const current = pending.pop();
if (current === undefined || seen.has(current)) continue;
seen.add(current);
pending.push(...(adjacency.get(current) ?? []));
}
reachable.set(origin, seen);
}
return reachable;
};
const isOrdered = (
reachable: ReadonlyMap<string, ReadonlySet<string>>,
left: string,
right: string,
): boolean =>
reachable.get(left)?.has(right) === true ||
reachable.get(right)?.has(left) === true;
type OrderingRelations = {
readonly reachable: ReadonlyMap<string, ReadonlySet<string>>;
readonly notBeforePairs: ReadonlySet<string>;
};
const validateUnorderedGroups = (
language: PartialOrderLanguage,
context: z.RefinementCtx,
known: ReadonlySet<string>,
relations: OrderingRelations,
): ReadonlySet<string> => {
const pairs = new Set<string>();
for (const [groupIndex, group] of language.unordered_groups.entries()) {
const path = ["language", "unordered_groups", groupIndex];
if (new Set(group.events).size !== group.events.length)
context.addIssue({
code: "custom",
message: "unordered groups must not repeat event ids",
path: [...path, "events"],
});
for (const [eventIndex, id] of group.events.entries())
addReferenceIssue(context, known, id, [...path, "events", eventIndex]);
for (const [leftIndex, leftId] of group.events.entries()) {
for (const rightId of group.events.slice(leftIndex + 1)) {
const key = pairKey(leftId, rightId);
if (pairs.has(key))
context.addIssue({
code: "custom",
message: "unordered event pairs must be declared once",
path,
});
pairs.add(key);
if (
isOrdered(relations.reachable, leftId, rightId) ||
relations.notBeforePairs.has(key)
)
context.addIssue({
code: "custom",
message: "ordered events cannot also be declared unordered",
path,
});
}
}
}
return pairs;
};
const validateCompletePairDeclarations = (
ids: readonly string[],
relations: OrderingRelations,
unorderedPairs: ReadonlySet<string>,
context: z.RefinementCtx,
): void => {
for (const [leftIndex, leftId] of ids.entries())
for (const rightId of ids.slice(leftIndex + 1))
if (
!isOrdered(relations.reachable, leftId, rightId) &&
!relations.notBeforePairs.has(pairKey(leftId, rightId)) &&
!unorderedPairs.has(pairKey(leftId, rightId))
)
context.addIssue({
code: "custom",
message: `event pair ${leftId}/${rightId} must be explicitly ordered or unordered`,
path: ["language"],
});
};
const validatePartialOrder = (
specification: ProcessTraceSpecification,
context: z.RefinementCtx,
): void => {
if (specification.language.kind !== "partial_order") return;
const ids = specification.events.map(({ id }) => id);
const known = new Set(ids);
const adjacency = buildAdjacency(specification.language, context, known);
if (graphHasCycle(ids, adjacency))
context.addIssue({
code: "custom",
message: "happens-before graph must be acyclic",
path: ["language"],
});
const reachable = computeReachability(ids, adjacency);
const notBeforePairs = validateNotBefore(
specification.language,
context,
known,
reachable,
);
const relations = { reachable, notBeforePairs };
const unorderedPairs = validateUnorderedGroups(
specification.language,
context,
known,
relations,
);
validateCompletePairDeclarations(ids, relations, unorderedPairs, context);
for (const [kind, values] of [
["prefix", specification.language.prefix],
["suffix", specification.language.suffix],
] as const)
for (const [index, id] of values.entries())
addReferenceIssue(context, known, id, ["language", kind, index]);
};
const countVariantEvents = (
trace: readonly (string | { readonly unordered: readonly string[] })[],
): ReadonlyMap<string, number> => {
const counts = new Map<string, number>();
for (const token of trace)
for (const id of typeof token === "string" ? [token] : token.unordered)
counts.set(id, (counts.get(id) ?? 0) + 1);
return counts;
};
const validateFiniteTraces = (
specification: ProcessTraceSpecification,
context: z.RefinementCtx,
): void => {
if (specification.language.kind !== "finite_traces") return;
const known = new Set(specification.events.map(({ id }) => id));
const variantIds = new Set<string>();
const variantTraces = new Set<string>();
for (const [
variantIndex,
variant,
] of specification.language.variants.entries()) {
const variantPath = ["language", "variants", variantIndex];
if (variantIds.has(variant.id))
context.addIssue({
code: "custom",
message: "finite trace variant ids must be unique",
path: [...variantPath, "id"],
});
variantIds.add(variant.id);
const canonicalTrace = canonicalTraceJson(variant.trace);
if (variantTraces.has(canonicalTrace))
context.addIssue({
code: "custom",
message: "finite trace variants must not duplicate a trace",
path: [...variantPath, "trace"],
});
variantTraces.add(canonicalTrace);
for (const [tokenIndex, token] of variant.trace.entries()) {
const values = typeof token === "string" ? [token] : token.unordered;
for (const [eventIndex, id] of values.entries())
addReferenceIssue(context, known, id, [
...variantPath,
"trace",
tokenIndex,
...(typeof token === "string" ? [] : ["unordered", eventIndex]),
]);
}
const counts = countVariantEvents(variant.trace);
for (const event of specification.events) {
const [minimum, maximum] = processTraceCardinalityBounds(
event.cardinality,
);
const count = counts.get(event.id) ?? 0;
if (count < minimum || count > maximum)
context.addIssue({
code: "custom",
message: `variant ${variant.id} violates ${event.id} cardinality`,
path: [...variantPath, "trace"],
});
}
}
};
/** Strict, bounded concurrency model for Process Capture observations. */
export const processTraceSpecificationSchema =
specificationShapeSchema.superRefine((specification, context) => {
const ids = new Set<string>();
const predicates = new Set<string>();
const ignoredFieldsBySource = new Map<string, string>();
for (const [index, event] of specification.events.entries()) {
if (ids.has(event.id))
context.addIssue({
code: "custom",
message: "event ids must be unique",
path: ["events", index, "id"],
});
ids.add(event.id);
const ignoredFields = [...(event.ignore_fields ?? [])].sort();
if (
ignoredFields.length > 0 &&
(typeof event.exact !== "object" ||
event.exact === null ||
Array.isArray(event.exact))
)
context.addIssue({
code: "custom",
message: "ignored schedule fields require an exact object payload",
path: ["events", index, "ignore_fields"],
});
const ignoredKey = canonicalTraceJson(ignoredFields);
const priorIgnoredKey = ignoredFieldsBySource.get(event.source);
if (priorIgnoredKey !== undefined && priorIgnoredKey !== ignoredKey)
context.addIssue({
code: "custom",
message:
"events from one source must use the same ignored schedule fields",
path: ["events", index, "ignore_fields"],
});
ignoredFieldsBySource.set(event.source, ignoredKey);
if (
ignoredFields.some(
(field) =>
typeof event.exact === "object" &&
event.exact !== null &&
!Array.isArray(event.exact) &&
field in event.exact,
)
)
context.addIssue({
code: "custom",
message: "exact payload must omit every ignored schedule field",
path: ["events", index, "exact"],
});
const predicate = `${event.source}\0${canonicalTraceJson(
comparableTracePayload(event.exact, ignoredFields),
)}`;
if (predicates.has(predicate))
context.addIssue({
code: "custom",
message: "exact event predicates must not overlap",
path: ["events", index],
});
predicates.add(predicate);
}
validatePartialOrder(specification, context);
validateFiniteTraces(specification, context);
});