refactor(captures)!: require canonical producer metadata

Require process retention accounting, browser network transaction identity, and all web comparison dimensions. Remove obsolete omission repairs and derive completeness from the owning producer facts.

BREAKING CHANGE: Historical captures without current producer accounting or transaction identity, and web diffs missing accessibility or storage dimensions, are rejected.
This commit is contained in:
morluto
2026-10-09 23:35:19 +08:00
parent dea3498b2b
commit 3283a45d09
33 changed files with 624 additions and 303 deletions
+6 -11
View File
@@ -3,17 +3,12 @@ import { constants as fsConstants } from "node:fs";
import { lstat, open, readdir, readlink } from "node:fs/promises";
import { dirname, join, relative, resolve } from "node:path";
import type { ProcessScenario } from "../../domain/process/processScenario.js";
import type { Stats } from "node:fs";
import type { FilesystemCoverage } from "../../domain/process/processCaptureCoverage.js";
import type { FileState } from "../../domain/process/processCapture.js";
export interface SnapshotResult {
readonly files: readonly FileState[];
readonly truncated: boolean;
/** Root aliases whose path enumeration was exhausted, regardless of hash coverage. */
readonly completeRoots: readonly string[];
readonly coverage?: FilesystemCoverage;
}
import type { Stats } from "node:fs";
import type {
FileState,
ProcessFilesystemSnapshot,
} from "../../domain/process/processCapture.js";
const hasSameIdentity = (
before: Stats,
@@ -92,7 +87,7 @@ export const hashFile = async (
export const snapshotRoots = async (
scenario: ProcessScenario,
signal?: AbortSignal,
): Promise<SnapshotResult> => {
): Promise<ProcessFilesystemSnapshot> => {
const entries: FileState[] = [];
const completeRoots: string[] = [];
let remainingBytes = scenario.limits.file_bytes;
+17 -31
View File
@@ -15,7 +15,6 @@ import {
} from "../../domain/process/processScenario.js";
import { parseProcessCapture } from "../../domain/process/processCaptureParsing.js";
import { PRODUCT_IDENTITY } from "../../identity.js";
import type { SnapshotResult } from "./FilesystemSnapshot.js";
import { snapshotRoots } from "./FilesystemSnapshot.js";
import { classifyFilesystemEffects } from "./ProcessFilesystemEffects.js";
import {
@@ -59,7 +58,7 @@ import type {
ProcessCaptureCleanupReport,
PartialProcessCaptureObservation,
IncompleteProcessCaptureObservations,
PartialFilesystemSnapshot,
ProcessFilesystemSnapshot,
PartialProcessObservationField,
ProcessCaptureEventJournalEntry,
RecordProcessCaptureEvent,
@@ -86,10 +85,9 @@ interface CaptureResultOptions {
readonly reason: "exited" | "timeout" | "idle_timeout";
};
readonly samples: readonly ProcessSample[];
readonly before: SnapshotResult;
readonly after: SnapshotResult;
readonly truncated: boolean;
readonly truncationDetails?: ProcessCaptureTruncationDetails;
readonly before: ProcessFilesystemSnapshot;
readonly after: ProcessFilesystemSnapshot;
readonly truncationDetails: ProcessCaptureTruncationDetails;
readonly scenario: ProcessScenario;
readonly rootPid: number;
readonly samplingPartial: boolean;
@@ -134,8 +132,8 @@ export interface ProcessCaptureObservationBuffer {
settlement: IncompleteProcessCaptureObservations["settlement"];
process_samples: PartialProcessObservationField<readonly ProcessSample[]>;
filesystem_snapshots: {
before: PartialProcessObservationField<PartialFilesystemSnapshot>;
after: PartialProcessObservationField<PartialFilesystemSnapshot>;
before: PartialProcessObservationField<ProcessFilesystemSnapshot>;
after: PartialProcessObservationField<ProcessFilesystemSnapshot>;
};
event_journal: PartialProcessObservationField<
readonly ProcessCaptureEventJournalEntry[]
@@ -149,7 +147,7 @@ export const createProcessCaptureObservationBuffer = (options: {
readonly interactions: readonly InteractionEvent[];
readonly samples: readonly ProcessSample[];
readonly eventJournal: readonly ProcessCaptureEventJournalEntry[];
readonly before: SnapshotResult;
readonly before: ProcessFilesystemSnapshot;
}): ProcessCaptureObservationBuffer => ({
target_pid: {
state: "unavailable",
@@ -175,10 +173,7 @@ export const createProcessCaptureObservationBuffer = (options: {
filesystem_snapshots: {
before: {
state: "available",
value: {
files: options.before.files,
truncated: options.before.truncated,
},
value: options.before,
},
after: {
state: "unavailable",
@@ -285,13 +280,8 @@ export const buildCaptureResult = (
files_before: options.before.files,
files_after: options.after.files,
filesystem_effects: filesystemEffects,
truncated:
options.truncationDetails === undefined
? options.truncated
: hasCaptureTruncation(options.truncationDetails),
...(options.truncationDetails === undefined
? {}
: { truncation_details: options.truncationDetails }),
truncated: hasCaptureTruncation(options.truncationDetails),
truncation_details: options.truncationDetails,
limitations: [
"The executable digest is a prelaunch file sample; matching path metadata immediately after spawn does not prove an atomic operating-system image binding.",
"Process trees are sampled and may omit short-lived descendants.",
@@ -302,11 +292,9 @@ export const buildCaptureResult = (
"Inherited host environment variables are not recorded and may affect results.",
...(!hasFilesystemObservations ? [filesystemObservationUnknown] : []),
...(hasUnknownFilesystemEffects ? [incompleteFilesystemUnknown] : []),
...(options.truncationDetails === undefined
? []
: captureCoverageUnknowns(options.truncationDetails).map(
({ reason }) => reason,
)),
...captureCoverageUnknowns(options.truncationDetails).map(
({ reason }) => reason,
),
...(hasSensitiveScriptedInput ? [sensitiveInputUnknown] : []),
],
residual_unknowns: [
@@ -347,11 +335,9 @@ export const buildCaptureResult = (
...(hasSensitiveScriptedInput
? [{ scope: "interaction" as const, reason: sensitiveInputUnknown }]
: []),
...(options.truncationDetails === undefined
? []
: captureCoverageUnknowns(options.truncationDetails).filter(
({ scope }) => scope !== "terminal",
)),
...captureCoverageUnknowns(options.truncationDetails).filter(
({ scope }) => scope !== "terminal",
),
],
};
};
@@ -1106,7 +1092,7 @@ export const prepareProcessCapture = async (
readonly temporaryRoot: string;
readonly runId: string;
readonly ownershipBaseline: ProcessOwnershipBaseline;
readonly before: SnapshotResult;
readonly before: ProcessFilesystemSnapshot;
}> => {
assertNotCancelled(signal);
await host.prepareOwnershipInspector?.(signal);
@@ -6,6 +6,7 @@ import { isInitializedPtyRoot, readLinuxChildren } from "./ProcessSampling.js";
import { TerminalRenderer } from "./TerminalRenderer.js";
import { parseProcessScenario } from "../../domain/process/processScenario.js";
import { type ProcessCapture } from "../../domain/process/processCaptureParsing.js";
import type { ProcessCaptureTruncationDetails } from "../../domain/process/processCaptureCoverage.js";
import { emptyProcessCapture as emptyCapture } from "../../domain/process/processCapture.fixture.js";
const base = {
@@ -13,6 +14,51 @@ const base = {
working_directory: "/tmp",
};
const emptyFilesystemCoverage = () =>
emptyCapture().truncation_details.filesystem_before;
const truncationDetails = (
frames: readonly ProcessCapture["frames"][number][],
renderedFrames: readonly ProcessCapture["rendered_frames"][number][],
samples: readonly ProcessCapture["process_samples"][number][],
): ProcessCaptureTruncationDetails => {
const emptyDetails = emptyCapture().truncation_details;
const rawBytes = frames.reduce(
(total, frame) => total + Buffer.byteLength(frame.raw_data ?? frame.data),
0,
);
const renderedBytes = renderedFrames.reduce(
(total, frame) =>
frame.lines.reduce(
(sum, line) => sum + Buffer.byteLength(line),
total + Buffer.byteLength(frame.serialized_state),
),
0,
);
return {
raw_terminal: {
...emptyDetails.raw_terminal,
observed_bytes: rawBytes,
retained_bytes: rawBytes,
observed_frames: frames.length,
retained_frames: frames.length,
},
rendered_terminal: {
...emptyDetails.rendered_terminal,
observed_bytes: renderedBytes,
retained_bytes: renderedBytes,
observed_frames: renderedFrames.length,
retained_frames: renderedFrames.length,
},
filesystem_before: emptyDetails.filesystem_before,
filesystem_after: emptyDetails.filesystem_after,
process: {
...emptyDetails.process,
retained_samples: samples.length,
},
};
};
it("returns detached terminal observations", async () => {
const observed: string[] = [];
const renderer = new TerminalRenderer({
@@ -72,9 +118,19 @@ it("preserves rendered observation order instead of timestamp sorting", () => {
frames: [],
exit: { exitCode: 0, reason: "exited" },
samples: [],
before: { files: [], truncated: false, completeRoots: [] },
after: { files: [], truncated: false, completeRoots: [] },
truncated: false,
before: {
files: [],
truncated: false,
completeRoots: [],
coverage: emptyFilesystemCoverage(),
},
after: {
files: [],
truncated: false,
completeRoots: [],
coverage: emptyFilesystemCoverage(),
},
truncationDetails: truncationDetails([], renderedFrames, []),
scenario: parseProcessScenario(base),
rootPid: 1,
samplingPartial: false,
@@ -98,9 +154,19 @@ it("marks redacted scripted input as an interaction unknown", () => {
frames: [],
exit: { exitCode: 0, reason: "exited" },
samples: [],
before: { files: [], truncated: false, completeRoots: [] },
after: { files: [], truncated: false, completeRoots: [] },
truncated: false,
before: {
files: [],
truncated: false,
completeRoots: [],
coverage: emptyFilesystemCoverage(),
},
after: {
files: [],
truncated: false,
completeRoots: [],
coverage: emptyFilesystemCoverage(),
},
truncationDetails: truncationDetails([], [], []),
scenario: parseProcessScenario({
...base,
events: [{ type: "input", at_ms: 0, data: "secret", sensitive: true }],
@@ -1,9 +1,9 @@
import type {
FileState,
FilesystemCheckpoint,
ProcessFilesystemSnapshot,
} from "../../domain/process/processCapture.js";
import { sep } from "node:path";
import type { SnapshotResult } from "./FilesystemSnapshot.js";
const unobservedAbsenceReason = (
path: string,
@@ -31,8 +31,8 @@ const unobservedAbsenceReason = (
/** Classify effects only when a snapshot establishes the missing path's absence. */
export const classifyFilesystemEffects = (
before: SnapshotResult,
after: SnapshotResult,
before: ProcessFilesystemSnapshot,
after: ProcessFilesystemSnapshot,
): FilesystemCheckpoint["effects"] => {
const beforeByPath = new Map(before.files.map((file) => [file.path, file]));
const afterByPath = new Map(after.files.map((file) => [file.path, file]));
+133 -23
View File
@@ -6,7 +6,10 @@ import { settleProcessCaptureJournal } from "./ProcessCaptureLifecycle.js";
import { parseProcessCapture } from "../../domain/process/processCaptureParsing.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../domain/process/processCaptureExample.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { emptyProcessCapture } from "../../domain/process/processCapture.fixture.js";
import {
accountFullyObservedProcessCapture,
emptyProcessCapture,
} from "../../domain/process/processCapture.fixture.js";
import { analysisErrorProjectionSchema } from "../../contracts/errorSchemas.js";
import {
ProcessCaptureError,
@@ -15,6 +18,7 @@ import {
} from "./ProcessCaptureError.js";
import {
releaseProcessResources,
createProcessCaptureObservationBuffer,
prepareProcessCapture,
resolveProcessResult,
type ProcessCaptureCleanupHost,
@@ -25,6 +29,13 @@ import {
partialProcessCaptureObservationSchema,
processCaptureSchema,
} from "../../domain/process/processCapture.js";
const emptyFilesystemCoverage =
emptyProcessCapture().truncation_details.filesystem_before;
const incompleteFilesystemCoverage = {
...emptyFilesystemCoverage,
enumeration_truncated: true,
enumeration_reasons: ["identity_changed"],
} satisfies typeof emptyFilesystemCoverage;
it("retains cancellation and cleanup facts when ownership baseline inspection aborts", async () => {
const controller = new AbortController();
const scenario = processScenarioSchema.parse({
@@ -34,7 +45,12 @@ it("retains cancellation and cleanup facts when ownership baseline inspection ab
prepareProcessCapture(
scenario,
controller.signal,
async () => ({ files: [], truncated: false, completeRoots: [] }),
async () => ({
files: [],
truncated: false,
completeRoots: [],
coverage: emptyFilesystemCoverage,
}),
{
createTemporaryRoot: async () => "/fixture/allocated-root",
captureOwnershipBaseline: async () => {
@@ -56,7 +72,12 @@ it("retains cancellation and cleanup facts when ownership baseline inspection ab
filesystem_snapshots: {
before: {
state: "available",
value: { files: [], truncated: false },
value: {
files: [],
truncated: false,
completeRoots: [],
coverage: emptyFilesystemCoverage,
},
},
},
},
@@ -68,12 +89,18 @@ it("keeps prelaunch snapshot evidence and the ownership failure when root cleanu
const ownershipFailure = new Error("process identity baseline denied");
const scenario = processScenarioSchema.parse({
executable: process.execPath,
filesystem_observation_paths: ["/fixture/root"],
});
try {
await prepareProcessCapture(
scenario,
undefined,
async () => ({ files: [], truncated: true, completeRoots: [] }),
async () => ({
files: [],
truncated: true,
completeRoots: [],
coverage: incompleteFilesystemCoverage,
}),
{
createTemporaryRoot: async () => "/fixture/allocated-root",
captureOwnershipBaseline: async () => {
@@ -102,7 +129,12 @@ it("keeps prelaunch snapshot evidence and the ownership failure when root cleanu
filesystem_snapshots: {
before: {
state: "available",
value: { files: [], truncated: true },
value: {
files: [],
truncated: true,
completeRoots: [],
coverage: incompleteFilesystemCoverage,
},
},
},
},
@@ -112,6 +144,76 @@ it("keeps prelaunch snapshot evidence and the ownership failure when root cleanu
}
});
it("projects complete after-snapshot metadata when a later capture stage fails", () => {
const scenario = processScenarioSchema.parse({
executable: process.execPath,
filesystem_observation_paths: ["/fixture/root"],
});
const observations = createProcessCaptureObservationBuffer({
frames: [],
interactions: [],
samples: [],
eventJournal: [],
before: {
files: [],
truncated: false,
completeRoots: [],
coverage: emptyFilesystemCoverage,
},
});
observations.filesystem_snapshots.after = {
state: "available",
value: {
files: [],
truncated: true,
completeRoots: [],
coverage: incompleteFilesystemCoverage,
},
};
const cleanup = {
owned_process_group: { state: "cleaned" as const, reason: null },
terminal_renderer: { state: "cleaned" as const, reason: null },
temporary_root: { state: "cleaned" as const, reason: null },
};
let error: ProcessCaptureError | undefined;
try {
resolveProcessResult(
undefined,
new Error("capture manifest failed after final snapshot"),
cleanup,
observations,
{ scenario },
);
} catch (cause: unknown) {
if (!(cause instanceof ProcessCaptureError)) throw cause;
error = cause;
}
if (error === undefined) throw new Error("expected capture failure");
expect(
analysisErrorProjectionSchema.parse(projectAnalysisError(error)),
).toMatchObject({
details: {
partial_observation: {
observations: {
filesystem_snapshots: {
after: {
state: "available",
value: {
files: [],
truncated: true,
completeRoots: [],
coverage: incompleteFilesystemCoverage,
},
},
},
},
},
},
});
});
it("rejects legacy replay output instead of silently discarding it", () => {
expect(
processCaptureSchema.safeParse({
@@ -230,8 +332,10 @@ it.each(["termination", "verification"] as const)(
const executionFailure = new Error("capture snapshot failed");
const capture = parseProcessCapture({
...emptyProcessCapture(),
frames: [{ sequence: 0, at_ms: 0, data: "collected before failure" }],
...accountFullyObservedProcessCapture({
...emptyProcessCapture(),
frames: [{ sequence: 0, at_ms: 0, data: "collected before failure" }],
}),
event_journal: [],
});
try {
@@ -441,18 +545,20 @@ it("passes sampled detached groups into cleanup even when their token is unknown
it("retains observations and both causes when process cleanup is unverifiable", () => {
const verified = emptyProcessCapture();
const capture = parseProcessCapture({
...verified,
frames: [{ sequence: 0, at_ms: 0, data: "observed output" }],
process_samples: [
{
at_ms: 1,
pid: 654,
parent_pid: 321,
command: "sanitized-detached-child",
process_group_id: 654,
session_id: 654,
},
],
...accountFullyObservedProcessCapture({
...verified,
frames: [{ sequence: 0, at_ms: 0, data: "observed output" }],
process_samples: [
{
at_ms: 1,
pid: 654,
parent_pid: 321,
command: "sanitized-detached-child",
process_group_id: 654,
session_id: 654,
},
],
}),
event_journal: [],
});
const executionFailure = new Error("capture ended after a fixture error");
@@ -561,8 +667,10 @@ it("projects execution and cleanup failures when capture never completed", () =>
it("retains completed observations when finalization fails after clean cleanup", () => {
const capture = parseProcessCapture({
...emptyProcessCapture(),
frames: [{ sequence: 0, at_ms: 0, data: "observed before finalization" }],
...accountFullyObservedProcessCapture({
...emptyProcessCapture(),
frames: [{ sequence: 0, at_ms: 0, data: "observed before finalization" }],
}),
event_journal: [],
});
const executionFailure = new Error("final filesystem snapshot failed");
@@ -614,8 +722,10 @@ it("retains completed observations when finalization fails after clean cleanup",
it("preserves cancellation while projecting observations and successful cleanup", () => {
const capture = parseProcessCapture({
...emptyProcessCapture(),
frames: [{ sequence: 0, at_ms: 0, data: "observed before cancellation" }],
...accountFullyObservedProcessCapture({
...emptyProcessCapture(),
frames: [{ sequence: 0, at_ms: 0, data: "observed before cancellation" }],
}),
event_journal: [],
});
const cleanup = {
+8 -23
View File
@@ -333,7 +333,6 @@ const completeCapture = async (options: {
readonly exit: Awaited<ReturnType<typeof awaitTerminalExit>>;
readonly signal?: AbortSignal;
readonly captureSnapshot: typeof snapshotRoots;
readonly initiallyTruncated: boolean;
readonly eventJournal: readonly ProcessCaptureEventJournalEntry[];
readonly observationBuffer: ProcessCaptureObservationBuffer;
readonly recordEvent: RecordProcessCaptureEvent;
@@ -385,7 +384,7 @@ const completeCapture = async (options: {
...options.observationBuffer.filesystem_snapshots,
after: {
state: "available",
value: { files: after.files, truncated: after.truncated },
value: after,
},
};
options.recordEvent("filesystem_checkpoints", 1);
@@ -436,32 +435,19 @@ const completeCapture = async (options: {
throw cause;
}
options.observationBuffer.manifest = { state: "available", value: manifest };
const truncated =
options.initiallyTruncated ||
after.truncated ||
runtime.rawTerminalRetention().observed_frames >
runtime.rawTerminalRetention().retained_frames ||
checkpoints.some(({ truncated: partial }) => partial) ||
samplingPartial ||
runtime.renderer.truncated();
return buildCaptureResult({
frames: options.frames,
exit: { ...options.exit, reason },
samples: options.samples,
before: options.before,
after,
truncated,
...(options.before.coverage === undefined || after.coverage === undefined
? {}
: {
truncationDetails: {
raw_terminal: runtime.rawTerminalRetention(),
rendered_terminal: runtime.renderer.retention(),
filesystem_before: options.before.coverage,
filesystem_after: after.coverage,
process: sampling.coverage,
},
}),
truncationDetails: {
raw_terminal: runtime.rawTerminalRetention(),
rendered_terminal: runtime.renderer.retention(),
filesystem_before: options.before.coverage,
filesystem_after: after.coverage,
process: sampling.coverage,
},
scenario,
rootPid: runtime.terminal.pid,
samplingPartial,
@@ -558,7 +544,6 @@ const runProcessScenario = async (
samples,
interactions,
exit,
initiallyTruncated: before.truncated,
eventJournal,
observationBuffer: observations,
recordEvent,