feat(process): add deterministic capture v3

This commit is contained in:
morluto
2026-07-13 17:01:09 +08:00
parent a504342d2b
commit 5a361a6725
29 changed files with 1616 additions and 243 deletions
+2 -2
View File
@@ -64,10 +64,10 @@ type RuntimeStatus = z.infer<typeof processCaptureComparisonSchema>["status"];
const EXPECTED_PROVIDERS = {
compare_process_captures: {
predicate: "rea.process-comparison/v1",
predicate: "rea.process-comparison/v2",
id: "rea-process",
name: "REA deterministic process harness",
version: "1",
version: "2",
},
compare_artifacts: {
predicate: "rea.artifact-comparison/v1",
+206 -60
View File
@@ -10,6 +10,7 @@ const reservedEnvironment = new Set([
"REA_PROCESS_RUN_ID",
"REA_REPLAY_HTTP_URL",
"REA_REPLAY_WEBSOCKET_URL",
"REA_SHIM_LEDGER_URL",
]);
const normalizationSchema = z.object({
paths: z.boolean(),
@@ -23,6 +24,17 @@ const normalizationSchema = z.object({
}),
),
});
const checkpointNameSchema = z
.string()
.regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/u);
const commandNameSchema = z
.string()
.regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u);
const outputChunkSchema = z.object({
at_ms: z.number().int().nonnegative().max(300_000),
stream: z.enum(["stdout", "stderr"]),
data: z.string().max(1_000_000),
});
/** Exact boundary schema for bounded dynamic process scenarios. */
export const processScenarioSchema = z
@@ -44,6 +56,62 @@ export const processScenarioSchema = z
secret_aliases: z.array(environmentName).max(64).default([]),
network_access: z.literal("host").default("host"),
filesystem_roots: z.array(z.string().startsWith("/")).max(16).default([]),
terminal: z
.object({
columns: z.number().int().min(1).max(1_000).default(80),
rows: z.number().int().min(1).max(1_000).default(24),
scrollback: z.number().int().min(0).max(10_000).default(1_000),
})
.default({ columns: 80, rows: 24, scrollback: 1_000 }),
checkpoints: z
.array(
z.object({
name: checkpointNameSchema,
trigger: z.discriminatedUnion("type", [
z.object({
type: z.literal("time"),
at_ms: z.number().int().nonnegative().max(300_000),
}),
z.object({
type: z.literal("terminal_literal"),
value: z.string().min(1).max(10_000),
occurrence: z.number().int().positive().max(1_000).default(1),
}),
z.object({ type: z.literal("root_exit") }),
z.object({ type: z.literal("settled") }),
]),
}),
)
.max(64)
.default([]),
command_shims: z
.array(
z.object({
name: commandNameSchema,
routes: z
.array(
z.object({
arguments: z.array(z.string()).max(256),
outputs: z.array(outputChunkSchema).max(1_000).default([]),
termination: z.discriminatedUnion("type", [
z.object({
type: z.literal("exit"),
code: z.number().int().min(0).max(255),
}),
z.object({
type: z.literal("signal"),
signal: z.enum(["SIGINT", "SIGTERM", "SIGKILL"]),
}),
]),
max_calls: z.number().int().positive().max(100).default(1),
}),
)
.min(1)
.max(100),
}),
)
.max(32)
.default([]),
events: z
.array(
z.discriminatedUnion("type", [
@@ -51,6 +119,7 @@ export const processScenarioSchema = z
...timedEventBase,
type: z.literal("input"),
data: z.string(),
sensitive: z.boolean().default(false),
}),
z.object({
...timedEventBase,
@@ -216,6 +285,28 @@ export const processScenarioSchema = z
});
}
}
const checkpointNames = scenario.checkpoints.map(({ name }) => name);
for (const [index, name] of checkpointNames.entries()) {
if (name === "before" || name === "after_settlement")
context.addIssue({
code: "custom",
message: "checkpoint name is reserved by the capture lifecycle",
path: ["checkpoints", index, "name"],
});
}
if (new Set(checkpointNames).size !== checkpointNames.length)
context.addIssue({
code: "custom",
message: "checkpoint names must be unique",
path: ["checkpoints"],
});
const shimNames = scenario.command_shims.map(({ name }) => name);
if (new Set(shimNames).size !== shimNames.length)
context.addIssue({
code: "custom",
message: "command shim names must be unique",
path: ["command_shims"],
});
});
/** A parsed, bounded dynamic process observation scenario. */
@@ -304,6 +395,29 @@ export interface TerminalFrame {
readonly data: string;
}
/** One rendered terminal state after xterm has parsed a PTY chunk or resize. */
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;
}
/** One attempted scripted interaction with the PTY. */
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. */
export interface FileState {
readonly path: string;
@@ -327,6 +441,27 @@ export interface ProcessSample {
readonly pid: number;
readonly parent_pid: number;
readonly command: string;
readonly process_group_id: number | null;
readonly session_id: number | null;
}
/** A named filesystem observation captured during a process lifecycle. */
export interface FilesystemCheckpoint {
readonly name: string;
readonly at_ms: number;
readonly files: readonly FileState[];
readonly effects: readonly FileEffect[];
readonly truncated: boolean;
}
/** One invocation observed by the declarative command-shim replay adapter. */
export interface ShimEvent {
readonly sequence: number;
readonly at_ms: number;
readonly command: string;
readonly arguments: readonly string[];
readonly working_directory: string;
readonly outcome: "matched" | "unmatched" | "exhausted";
}
/** A bounded loopback replay observation. */
@@ -347,15 +482,19 @@ export interface ProtocolEvent {
/** A bounded process observation with explicit incompleteness metadata. */
export interface ProcessCapture {
readonly schema_version: 2;
readonly schema_version: 3;
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 process_samples: readonly ProcessSample[];
readonly filesystem_checkpoints: readonly FilesystemCheckpoint[];
readonly shim_events: readonly ShimEvent[];
readonly protocol_events: readonly ProtocolEvent[];
readonly files_before: readonly FileState[];
readonly files_after: readonly FileState[];
@@ -379,9 +518,27 @@ export interface ProcessCapture {
};
}
const fileStateSchema = z.object({
path: z.string(),
type: z.enum(["file", "directory", "symlink", "other"]),
mode: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
symlink_target: z.string().nullable(),
});
const fileEffectSchema = z.object({
path: z.string(),
status: z.enum(["created", "modified", "deleted", "unchanged"]),
before: fileStateSchema.nullable(),
after: fileStateSchema.nullable(),
});
/** Exact serialized shape of a bounded process capture. */
export const processCaptureSchema: z.ZodType<ProcessCapture> = z.object({
schema_version: z.literal(2),
schema_version: z.literal(3),
normalization: normalizationSchema,
frames: z.array(
z.object({
@@ -390,6 +547,29 @@ export const processCaptureSchema: z.ZodType<ProcessCapture> = z.object({
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(),
@@ -401,6 +581,27 @@ export const processCaptureSchema: z.ZodType<ProcessCapture> = z.object({
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.string(),
at_ms: z.number().int().nonnegative(),
files: z.array(fileStateSchema),
effects: z.array(fileEffectSchema),
truncated: z.boolean(),
}),
),
shim_events: z.array(
z.object({
sequence: z.number().int().nonnegative(),
at_ms: z.number().int().nonnegative(),
command: z.string(),
arguments: z.array(z.string()),
working_directory: z.string(),
outcome: z.enum(["matched", "unmatched", "exhausted"]),
}),
),
protocol_events: z.array(
@@ -420,64 +621,9 @@ export const processCaptureSchema: z.ZodType<ProcessCapture> = z.object({
]),
}),
),
files_before: z.array(
z.object({
path: z.string(),
type: z.enum(["file", "directory", "symlink", "other"]),
mode: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
symlink_target: z.string().nullable(),
}),
),
files_after: z.array(
z.object({
path: z.string(),
type: z.enum(["file", "directory", "symlink", "other"]),
mode: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
symlink_target: z.string().nullable(),
}),
),
filesystem_effects: z.array(
z.object({
path: z.string(),
status: z.enum(["created", "modified", "deleted", "unchanged"]),
before: z
.object({
path: z.string(),
type: z.enum(["file", "directory", "symlink", "other"]),
mode: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
symlink_target: z.string().nullable(),
})
.nullable(),
after: z
.object({
path: z.string(),
type: z.enum(["file", "directory", "symlink", "other"]),
mode: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
symlink_target: z.string().nullable(),
})
.nullable(),
}),
),
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(
+192 -20
View File
@@ -18,19 +18,44 @@ export const processCaptureComparisonSchema = z
.object({
status: comparisonStatusSchema,
terminal: comparisonStatusSchema,
interaction: comparisonStatusSchema,
exit: comparisonStatusSchema,
filesystem: comparisonStatusSchema,
protocol: comparisonStatusSchema,
process: comparisonStatusSchema,
shim: 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",
"protocol",
"process",
"shim",
]),
index: z.number().int().nonnegative(),
left_at_ms: z.number().int().nonnegative().nullable(),
right_at_ms: z.number().int().nonnegative().nullable(),
left: z.unknown().nullable(),
right: z.unknown().nullable(),
}),
]),
limitations: z.array(z.string()),
})
.superRefine((comparison, context) => {
const dimensions = [
comparison.terminal,
comparison.interaction,
comparison.exit,
comparison.filesystem,
comparison.protocol,
comparison.process,
comparison.shim,
];
const expected = dimensions.includes("truncated")
? "truncated"
@@ -50,12 +75,30 @@ export const processCaptureComparisonSchema = z
});
type ProcessCaptureComparison = z.infer<typeof processCaptureComparisonSchema>;
const stableFiles = (capture: ProcessCapture): string =>
JSON.stringify(
[...capture.files_after].sort((left, right) =>
left.path.localeCompare(right.path),
),
);
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,
{
name: "final",
files: capture.files_after,
effects: capture.filesystem_effects,
},
];
const classifyCollection = (
left: readonly unknown[],
@@ -84,6 +127,75 @@ const comparisonStatus = (
return dimensions.includes("unknown") ? "unknown" : "unchanged";
};
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 (JSON.stringify(leftValue) === JSON.stringify(rightValue)) continue;
return {
status: "found",
dimension,
index,
left_at_ms: eventTime(leftValue),
right_at_ms: eventTime(rightValue),
left: leftValue,
right: 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" }
);
};
/** Compare bounded captures without equating missing or incompatible evidence. */
export const compareProcessCaptures = (
left: ProcessCapture,
@@ -93,10 +205,16 @@ export const compareProcessCaptures = (
return {
status: "truncated",
terminal: "truncated",
interaction: "truncated",
exit: "truncated",
filesystem: "truncated",
protocol: "truncated",
process: "truncated",
shim: "truncated",
first_divergence: {
status: "unknown",
reason: "At least one capture is truncated.",
},
limitations: ["At least one capture is truncated."],
};
}
@@ -112,8 +230,13 @@ export const compareProcessCaptures = (
: classifyCollection(leftValues, rightValues);
const terminal = classify(
"terminal",
left.frames.map(({ data }) => data),
right.frames.map(({ data }) => data),
terminalObservations(left),
terminalObservations(right),
);
const interaction = classify(
"terminal",
left.interaction_events,
right.interaction_events,
);
const exit =
hasUnknown(left, "exit") || hasUnknown(right, "exit")
@@ -121,17 +244,11 @@ export const compareProcessCaptures = (
: JSON.stringify(left.exit) === JSON.stringify(right.exit)
? "unchanged"
: "changed";
const filesystem =
!hasUnknown(left, "filesystem") &&
!hasUnknown(right, "filesystem") &&
sameNormalization &&
stableFiles(left) === stableFiles(right)
? "unchanged"
: classify(
"filesystem",
left.filesystem_effects,
right.filesystem_effects,
);
const filesystem = classify(
"filesystem",
filesystemObservations(left),
filesystemObservations(right),
);
const protocol = classify(
"protocol",
left.protocol_events,
@@ -142,13 +259,68 @@ export const compareProcessCaptures = (
left.process_samples,
right.process_samples,
);
const shim = sameNormalization
? classifyCollection(left.shim_events, right.shim_events)
: "unknown";
const observedFirstDivergence = chooseFirstDivergence([
firstCollectionDivergence(
"terminal",
terminalObservations(left),
terminalObservations(right),
),
firstCollectionDivergence(
"interaction",
left.interaction_events,
right.interaction_events,
),
firstCollectionDivergence("exit", [left.exit], [right.exit]),
firstCollectionDivergence(
"filesystem",
filesystemObservations(left),
filesystemObservations(right),
),
firstCollectionDivergence(
"protocol",
left.protocol_events,
right.protocol_events,
),
firstCollectionDivergence(
"process",
left.process_samples,
right.process_samples,
),
firstCollectionDivergence("shim", left.shim_events, right.shim_events),
]);
const firstDivergence =
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;
return {
status: comparisonStatus([terminal, exit, filesystem, protocol, process]),
status: comparisonStatus([
terminal,
interaction,
exit,
filesystem,
protocol,
process,
shim,
]),
terminal,
interaction,
exit,
filesystem,
protocol,
process,
shim,
first_divergence: firstDivergence,
limitations: [
...left.limitations,
...right.limitations,
+3 -3
View File
@@ -44,7 +44,7 @@ const MAX_CANONICAL_BYTES = 32 * 1024 * 1024;
const providers = {
behavioral: {
operation: "compare_process_captures",
predicate: "rea.process-comparison/v1",
predicate: "rea.process-comparison/v2",
id: "rea-process",
name: "REA deterministic process harness",
},
@@ -199,7 +199,7 @@ const validateSourceKinds = (
): void => {
const expected =
claim.kind === "behavioral"
? ["capture_process_scenario", "rea.process-capture/v2"]
? ["capture_process_scenario", "rea.process-capture/v3"]
: claim.kind === "structural-function"
? ["analyze_function", "rea.analysis/v2"]
: ["inventory_artifact", "rea.analysis/v2"];
@@ -230,7 +230,7 @@ const validateComparisonIdentity = (claim: Claim, evidence: Evidence): void => {
evidence.predicate_type !== expected.predicate ||
evidence.provider.id !== expected.id ||
evidence.provider.name !== expected.name ||
evidence.provider.version !== "1" ||
evidence.provider.version !== (claim.kind === "behavioral" ? "2" : "1") ||
evidence.confidence !== "derived" ||
evidence.authority !== "analyst-inference" ||
evidence.subject !== null
+3 -2
View File
@@ -158,7 +158,7 @@ const EXPECTED = {
"REA function comparison",
],
compare_process_captures: [
"rea.process-comparison/v1",
"rea.process-comparison/v2",
"rea-process",
"REA deterministic process harness",
],
@@ -402,7 +402,8 @@ const assertComparisonIdentity = (evidence: Evidence): void => {
evidence.predicate_type !== expected[0] ||
evidence.provider.id !== expected[1] ||
evidence.provider.name !== expected[2] ||
evidence.provider.version !== "1" ||
evidence.provider.version !==
(evidence.operation === "compare_process_captures" ? "2" : "1") ||
evidence.confidence !== "derived" ||
evidence.authority !== "analyst-inference" ||
evidence.subject !== null ||