refactor(test): keep coverage at behavioral boundaries (#474)

* refactor(test): keep coverage at behavioral boundaries

* fix(ci): restore package workflow temp-root classification
This commit is contained in:
morluto
2026-08-11 18:34:32 +08:00
committed by GitHub
parent d65730c4c2
commit d4dc940bd8
117 changed files with 1519 additions and 2419 deletions
@@ -1,424 +0,0 @@
import { describe, expect, it } from "vitest";
import {
containsProcess,
getDescendants,
maxTreeDepth,
reconstructProcessTree,
type ProcessTreeEvent,
type ProcessEventType,
type ProcessNode,
type ProcessTreeReconstruction,
} from "../../../src/domain/eventProcessTree.js";
describe("event-backed process tree reconstruction", () => {
it("reconstructs a simple process tree", () => {
const events: ProcessTreeEvent[] = [
{
sequence: 0,
at_ms: 0,
type: "spawn",
pid: 1,
ppid: 0,
process_name: "root",
executable: "/root",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
{
sequence: 1,
at_ms: 10,
type: "spawn",
pid: 2,
ppid: 1,
process_name: "child",
executable: "/child",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
{
sequence: 2,
at_ms: 20,
type: "exit",
pid: 2,
ppid: 1,
process_name: "child",
executable: null,
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: 0,
signal: null,
tid: null,
},
{
sequence: 3,
at_ms: 30,
type: "exit",
pid: 1,
ppid: 0,
process_name: "root",
executable: null,
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: 0,
signal: null,
tid: null,
},
];
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);
});
it("detects short-lived descendants", () => {
const events: ProcessTreeEvent[] = [
{
sequence: 0,
at_ms: 0,
type: "spawn",
pid: 1,
ppid: 0,
process_name: "root",
executable: "/root",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
{
sequence: 1,
at_ms: 10,
type: "spawn",
pid: 2,
ppid: 1,
process_name: "short",
executable: "/short",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
{
sequence: 2,
at_ms: 11,
type: "exit",
pid: 2,
ppid: 1,
process_name: "short",
executable: null,
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: 0,
signal: null,
tid: null,
},
];
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[] = [
{
sequence: 0,
at_ms: 0,
type: "spawn",
pid: 1,
ppid: 0,
process_name: "root",
executable: "/root",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
{
sequence: 1,
at_ms: 10,
type: "re_exec",
pid: 1,
ppid: 0,
process_name: "root",
executable: "/newroot",
arguments: ["--new"],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
];
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[] = [
{
sequence: 0,
at_ms: 0,
type: "spawn",
pid: 1,
ppid: 0,
process_name: "root",
executable: "/root",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
{
sequence: 1,
at_ms: 10,
type: "spawn",
pid: 2,
ppid: 1,
process_name: "child",
executable: "/child",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
{
sequence: 2,
at_ms: 20,
type: "reparent",
pid: 2,
ppid: 0,
process_name: "child",
executable: null,
arguments: [],
previous_pid: null,
previous_ppid: 1,
exit_code: null,
signal: null,
tid: null,
},
];
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[] = [
{
sequence: 0,
at_ms: 0,
type: "exit",
pid: 999,
ppid: null,
process_name: null,
executable: null,
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: 1,
signal: null,
tid: null,
},
];
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[] = [
{
sequence: 0,
at_ms: 0,
type: "spawn",
pid: 1,
ppid: 0,
process_name: "root",
executable: "/root",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
{
sequence: 1,
at_ms: 10,
type: "spawn",
pid: 2,
ppid: 1,
process_name: "child1",
executable: "/c1",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
{
sequence: 2,
at_ms: 20,
type: "spawn",
pid: 3,
ppid: 2,
process_name: "grandchild",
executable: "/gc",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
];
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[] = [
{
sequence: 0,
at_ms: 0,
type: "spawn",
pid: 1,
ppid: 0,
process_name: "root",
executable: "/root",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
];
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[] = [
{
sequence: 0,
at_ms: 0,
type: "spawn",
pid: 1,
ppid: 0,
process_name: "root",
executable: "/root",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
{
sequence: 1,
at_ms: 10,
type: "spawn",
pid: 2,
ppid: 1,
process_name: "child",
executable: "/c",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
{
sequence: 2,
at_ms: 20,
type: "spawn",
pid: 3,
ppid: 2,
process_name: "gc",
executable: "/gc",
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
},
];
const result = reconstructProcessTree(events, 1);
expect(maxTreeDepth(result.processes, 1)).toBe(2);
});
it("uses exported types", () => {
const node: ProcessNode = {
pid: 1,
ppid: null,
process_name: "test",
executable: "/test",
arguments: [],
children: [],
spawn_time_ms: 0,
exit_time_ms: null,
exit_code: null,
is_re_exec: false,
is_reparented: false,
previous_ppid: null,
};
expect(node.pid).toBe(1);
const recon: ProcessTreeReconstruction = {
root_pid: 1,
processes: [node],
events_consumed: 1,
events_unmatched: 0,
short_lived_descendants: 0,
has_re_exec: false,
has_reparenting: false,
};
expect(recon.root_pid).toBe(1);
});
it("uses ProcessEventType", () => {
const t: ProcessEventType = "spawn";
expect(t).toBe("spawn");
});
});
@@ -1,197 +0,0 @@
import { expect, it } from "vitest";
import {
compareUnverifiedProcessCaptures as compareProcessCaptures,
emptyProcessCapture as emptyCapture,
} from "../../fixtures/processCapture.js";
it("classifies missing observations as unknown and one-sided evidence as added", () => {
const base = {
schema_version: 4 as const,
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,
shim_events: [],
protocol_events: [],
replay_transitions: [],
reactive_run: null,
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.shim).toBe("unchanged");
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 = {
schema_version: 4 as const,
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,
shim_events: [],
protocol_events: [],
replay_transitions: [],
reactive_run: null,
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 = {
schema_version: 4 as const,
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,
shim_events: [],
protocol_events: [],
replay_transitions: [],
reactive_run: null,
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 transient = compareProcessCaptures(complete, {
...complete,
filesystem_checkpoints: [
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
{
name: "during_run",
at_ms: 10,
files: [],
effects: [],
truncated: false,
},
{
name: "after_settlement",
at_ms: 50,
files: [],
effects: [],
truncated: false,
},
],
});
expect(transient.filesystem).toBe("changed");
expect(transient.status).toBe("changed");
});
@@ -12,7 +12,7 @@ import {
parseProcessScenario,
type ProcessCapture,
} from "../../../src/domain/processCapture.js";
import { processCaptureIssues } from "../../fixtures/processCapture.js";
import { processCaptureIssues } from "../../../src/domain/processCapture.fixture.js";
type EventSource = "process" | "filesystem" | "http" | "websocket" | "shim";
@@ -1,337 +0,0 @@
import { expect, it } from "vitest";
import { snapshotRoots } from "../../../src/application/FilesystemSnapshot.js";
import {
buildCaptureResult,
prepareProcessCapture,
type ProcessPreparationHost,
} from "../../../src/application/ProcessCaptureLifecycle.js";
import { ProcessCheckpoints } from "../../../src/application/ProcessCheckpoints.js";
import { normalizeProcessSamples } from "../../../src/application/ProcessNormalization.js";
import {
isInitializedPtyRoot,
readLinuxChildren,
} from "../../../src/application/ProcessSampling.js";
import { TerminalRenderer } from "../../../src/application/TerminalRenderer.js";
import {
authorizeProcessScenario,
compareProcessCaptures,
parseProcessCapture,
parseProcessScenario,
type ProcessCapture,
} from "../../../src/domain/processCapture.js";
import { emptyProcessCapture as emptyCapture } from "../../fixtures/processCapture.js";
const base = {
approved: true as const,
executable: "/bin/sh",
working_directory: "/tmp",
};
it("returns detached terminal and filesystem checkpoint observations", async () => {
const observed: string[] = [];
const renderer = new TerminalRenderer({
columns: 40,
rows: 12,
scrollback: 100,
maxFrames: 10,
maxBytes: 10_000,
normalize: (value) => value,
recordEvent: (collection, index) =>
observed.push(`${collection}:${String(index)}`),
});
renderer.write("A", 20);
renderer.resize(40, 12, 10);
const frames = await renderer.frames();
expect(frames.map(({ at_ms }) => at_ms)).toEqual([20, 10]);
expect(observed).toEqual(["rendered_frames:0", "rendered_frames:1"]);
if (frames[0] !== undefined) Reflect.set(frames[0], "cursor_x", 999);
expect((await renderer.frames())[0]?.cursor_x).not.toBe(999);
await renderer.dispose();
const scenario = parseProcessScenario(base);
const checkpoints = new ProcessCheckpoints(
scenario,
Date.now(),
{ files: [], truncated: false },
{ signal: undefined },
);
const first = await checkpoints.finish({ files: [], truncated: false });
if (first[0] !== undefined) Reflect.set(first[0], "name", "tampered");
const second = await checkpoints.finish({ files: [], truncated: false });
expect(second[0]?.name).toBe("before");
await checkpoints.dispose();
});
it("preserves rendered observation order instead of timestamp sorting", () => {
const capture = emptyCapture();
const renderedFrames: ProcessCapture["rendered_frames"] = [
{
sequence: 0,
at_ms: 20,
columns: 1,
rows: 1,
cursor_x: 0,
cursor_y: 0,
active_buffer: "normal",
lines: ["first"],
serialized_state: "first",
},
{
sequence: 1,
at_ms: 10,
columns: 1,
rows: 1,
cursor_x: 0,
cursor_y: 0,
active_buffer: "normal",
lines: ["second"],
serialized_state: "second",
},
];
const result = buildCaptureResult({
frames: [],
exit: { exitCode: 0, reason: "exited" },
samples: [],
replay: {
httpUrl: "http://127.0.0.1",
websocketUrl: "ws://127.0.0.1/ws",
events: [],
transitions: [],
truncated: false,
close: () => Promise.resolve(),
},
before: { files: [], truncated: false },
after: { files: [], truncated: false },
truncated: false,
scenario: parseProcessScenario(base),
rootPid: 1,
samplingPartial: false,
renderedFrames,
interactions: [],
checkpoints: capture.filesystem_checkpoints,
shimEvents: [],
settlement: {
state: capture.settlement.state,
elapsed_ms: capture.settlement.elapsed_ms,
},
manifest: capture.manifest,
eventJournal: [],
});
expect(result.rendered_frames).toEqual(renderedFrames);
});
it("cleans the temporary root when capture home creation fails", async () => {
const cleaned: string[] = [];
const host: ProcessPreparationHost = {
createTemporaryRoot: () => Promise.resolve("/tmp/rea-process-fixture"),
createHome: () => Promise.reject(new Error("mkdir failed")),
cleanup: (path) => {
cleaned.push(path);
return Promise.resolve();
},
};
await expect(
prepareProcessCapture(
parseProcessScenario(base),
{
status: "enabled",
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
networkAccess: "external",
},
undefined,
host,
),
).rejects.toThrow("mkdir failed");
expect(cleaned).toEqual(["/tmp/rea-process-fixture"]);
});
it("normalizes every sampled process identifier in command text", () => {
const samples = normalizeProcessSamples(
[
{
at_ms: 0,
pid: 101,
parent_pid: 0,
process_group_id: 101,
session_id: 101,
command: "root 101",
},
{
at_ms: 10,
pid: 202,
parent_pid: 101,
process_group_id: 101,
session_id: 101,
command: "child 202 peer=101 unrelated 1202",
},
],
parseProcessScenario(base),
101,
);
expect(samples[1]?.command).toBe("child <pid> peer=<pid> unrelated 1202");
});
it("collects and deduplicates children from every Linux thread", async () => {
const signal = new AbortController().signal;
expect(
await readLinuxChildren(100, signal, {
taskIds: () => Promise.resolve([100, 101, 102]),
children: (_pid, taskId) =>
Promise.resolve(
taskId === 100 ? "201 202" : taskId === 101 ? "202 203" : "",
),
}),
).toEqual([201, 202, 203]);
});
it("admits PTY samples only after stable session and token setup", () => {
const initialized = {
pid: 100,
parent_pid: 10,
process_group_id: 100,
session_id: 100,
startTime: "200",
};
expect(
isInitializedPtyRoot({
rootPid: 100,
expectedRunId: "run-token",
before: { ...initialized, process_group_id: 10, session_id: 10 },
observedRunId: undefined,
after: initialized,
}),
).toBe(false);
expect(
isInitializedPtyRoot({
rootPid: 100,
expectedRunId: "run-token",
before: initialized,
observedRunId: "run-token",
after: { ...initialized, startTime: "201" },
}),
).toBe(false);
expect(
isInitializedPtyRoot({
rootPid: 100,
expectedRunId: "run-token",
before: initialized,
observedRunId: "run-token",
after: initialized,
}),
).toBe(true);
expect(
isInitializedPtyRoot({
rootPid: 100,
expectedRunId: "run-token",
before: { ...initialized, session_id: null },
observedRunId: "run-token",
after: { ...initialized, session_id: null },
}),
).toBe(true);
});
it("keeps interaction and shim residual uncertainty in separate scopes", () => {
const baseCapture = emptyCapture();
const interaction = parseProcessCapture({
...baseCapture,
residual_unknowns: [
{ scope: "interaction", reason: "Interaction capture was partial." },
],
});
const shim = parseProcessCapture({
...baseCapture,
residual_unknowns: [{ scope: "shim", reason: "Shim capture was partial." }],
});
expect(compareProcessCaptures(interaction, baseCapture)).toMatchObject({
status: "unknown",
terminal: "unchanged",
interaction: "unknown",
shim: "unchanged",
});
expect(compareProcessCaptures(shim, baseCapture)).toMatchObject({
status: "unknown",
terminal: "unchanged",
interaction: "unchanged",
shim: "unknown",
});
});
it("cancels filesystem snapshots before traversing declared roots", async () => {
const controller = new AbortController();
controller.abort();
await expect(
snapshotRoots(
parseProcessScenario({
...base,
filesystem_roots: ["/tmp"],
}),
controller.signal,
),
).rejects.toMatchObject({ name: "AbortError" });
});
it("parses bounded scenarios and rejects unordered events", () => {
expect(parseProcessScenario(base).timeout_ms).toBe(30_000);
expect(() =>
parseProcessScenario({
...base,
events: [
{ type: "input", at_ms: 2, data: "a" },
{ type: "input", at_ms: 1, data: "b" },
],
}),
).toThrow(/ordered/);
expect(() =>
parseProcessScenario({
...base,
environment: { HOME: "/unsafe" },
}),
).toThrow(/reserved/);
expect(() =>
parseProcessScenario({
...base,
events: [{ type: "input", at_ms: 31_000, data: "late" }],
}),
).toThrow(/after the scenario timeout/);
});
it("requires explicit operator approval for host network access", () => {
expect(
authorizeProcessScenario(parseProcessScenario(base), {
status: "enabled",
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
networkAccess: "none",
}),
).toEqual({
allowed: false,
reason: "host network access is not approved by operator policy",
});
});
it("refuses paths and environment outside operator policy", () => {
const scenario = parseProcessScenario({
...base,
environment: { TOKEN: "secret" },
});
expect(
authorizeProcessScenario(scenario, {
status: "enabled",
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
networkAccess: "external",
}),
).toEqual({
allowed: false,
reason: "scenario requests an environment variable not allowed by policy",
});
});
@@ -11,7 +11,7 @@ import {
parseProcessScenario,
type ProcessCapture,
} from "../../../src/domain/processCapture.js";
import { processCaptureIssues } from "../../fixtures/processCapture.js";
import { processCaptureIssues } from "../../../src/domain/processCapture.fixture.js";
function createInteractiveScenario(root: string, script: string) {
return parseProcessScenario({
@@ -1,125 +0,0 @@
import { expect, it } from "vitest";
import { digestProcessCommitment } from "../../../src/domain/processCapture.js";
import {
compareUnverifiedProcessCaptures as compareProcessCaptures,
emptyProcessCapture as emptyCapture,
} from "../../fixtures/processCapture.js";
it("detects changes in normalized process sample metadata", () => {
const capture = {
schema_version: 4 as const,
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,
shim_events: [],
protocol_events: [],
replay_transitions: [],
reactive_run: null,
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");
});
it("compares replay state transitions as protocol evidence", () => {
const replayPlan = {
machine: {
initial_state: "anonymous",
states: [
{ name: "anonymous" },
{ name: "authenticated", terminal: true },
],
transitions: [
{
id: "login",
from: "anonymous",
to: "authenticated",
trigger: { protocol: "http", method: "POST", path: "/login" },
captures: [
{
variable: "token",
value: { source: "request_json", path: ["token"] },
sensitive: true,
},
],
actions: [{ type: "http_response", status: 204, body: "" }],
max_uses: 1,
},
],
max_transitions: 1,
},
};
const empty = emptyCapture();
const baseline = {
...empty,
manifest: {
...empty.manifest,
replay_plan: replayPlan,
replay_plan_sha256: digestProcessCommitment(replayPlan),
},
};
const transitioned = {
...baseline,
replay_transitions: [
{
sequence: 0,
at_ms: 0,
transition_id: "login",
state_before: "anonymous",
state_after: "authenticated",
sensitive_aliases: ["token"],
},
],
};
expect(compareProcessCaptures(baseline, transitioned)).toMatchObject({
status: "changed",
protocol: "added",
});
});
@@ -1,283 +0,0 @@
import { expect, it } from "vitest";
import { createProcessCaptureJournal } from "../../../src/application/ProcessCaptureJournal.js";
import {
digestProcessCommitment,
LEGACY_PROCESS_CAPTURE_MESSAGE,
parseProcessCapture,
processCaptureSchema,
type ProcessCaptureEventJournalEntry,
type UnverifiedProcessCapture,
} from "../../../src/domain/processCapture.js";
import {
compareUnverifiedProcessCaptures as compareProcessCaptures,
emptyUnverifiedProcessCapture as emptyCapture,
processCaptureIssues,
} from "../../fixtures/processCapture.js";
it("never considers truncated captures equivalent", () => {
const capture = {
schema_version: 4 as const,
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,
shim_events: [],
protocol_events: [],
replay_transitions: [],
reactive_run: null,
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 journal = createProcessCaptureJournal();
const observed: ProcessCaptureEventJournalEntry[] = [];
const unsubscribe = journal.subscribe((entry) => observed.push(entry));
journal.recordEvent("lifecycle", 0);
const settlementEntry = journal.record("lifecycle", 1);
unsubscribe();
journal.recordEvent("frames", 0);
expect(journal.entries).toEqual([
{ capture_order: 0, collection: "lifecycle", index: 0 },
{ capture_order: 1, collection: "lifecycle", index: 1 },
{ capture_order: 2, collection: "frames", index: 0 },
]);
expect(observed).toEqual(journal.entries.slice(0, 2));
expect(settlementEntry).toEqual(journal.entries[1]);
const nestedJournal = createProcessCaptureJournal();
const notifications: string[] = [];
nestedJournal.subscribe((entry) => {
notifications.push(`a:${String(entry.capture_order)}`);
if (entry.capture_order === 0) nestedJournal.record("frames", 1);
});
nestedJournal.subscribe((entry) =>
notifications.push(`b:${String(entry.capture_order)}`),
);
nestedJournal.record("frames", 0);
expect(notifications).toEqual(["a:0", "b:0", "a:1", "b:1"]);
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.each([
["machine limit", 1, 5, 10],
["transition use limit", 5, 1, 10],
["state visit limit", 5, 5, 1],
])(
"rejects replay journals that exceed the declared %s",
(_name, maxTransitions, maxUses, maxVisits) => {
const replayPlan = {
machine: {
initial_state: "active",
states: [
{ name: "active", max_visits: maxVisits },
{ name: "complete", terminal: true },
],
transitions: [
{
id: "again",
from: "active",
to: "active",
trigger: {
protocol: "websocket_message",
path: "/ws",
body: "again",
},
actions: [{ type: "websocket_send", data: "again" }],
max_uses: maxUses,
},
{
id: "finish",
from: "active",
to: "complete",
trigger: {
protocol: "websocket_message",
path: "/ws",
body: "finish",
},
actions: [{ type: "websocket_send", data: "done" }],
max_uses: 1,
},
],
max_transitions: maxTransitions,
},
};
const capture = emptyCapture();
const candidate: UnverifiedProcessCapture = {
...capture,
manifest: {
...capture.manifest,
replay_plan: replayPlan,
replay_plan_sha256: digestProcessCommitment(replayPlan),
},
replay_transitions: [0, 1].map((sequence) => ({
sequence,
at_ms: sequence,
transition_id: "again",
state_before: "active",
state_after: "active",
sensitive_aliases: [],
})),
};
expect(processCaptureIssues(candidate)).toEqual(
expect.arrayContaining([
expect.objectContaining({
message: expect.stringContaining("limit"),
}),
]),
);
},
);
it("tells agents and users to recapture unsupported v3 evidence", () => {
const legacy = { ...emptyCapture(), schema_version: 3 };
expect(() => parseProcessCapture(legacy)).toThrow(
LEGACY_PROCESS_CAPTURE_MESSAGE,
);
const parsed = processCaptureSchema.safeParse(legacy);
expect(parsed.success).toBe(false);
if (parsed.success) throw new Error("expected legacy capture rejection");
expect(parsed.error.issues[0]?.message).toBe(LEGACY_PROCESS_CAPTURE_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");
});
@@ -1,160 +0,0 @@
import { describe, expect, it } from "vitest";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
import {
processCaptureSchema,
type UnverifiedProcessCapture,
} from "../../../src/domain/processCapture.js";
import {
createProcessObservation,
projectProcessObservation,
} from "../../../src/domain/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,
},
],
shim_events: [
{
sequence: 0,
at_ms: 5,
command: "helper",
route_index: 0,
arguments: [],
working_directory: "/fixture",
outcome: "matched",
},
],
protocol_events: [
{
sequence: 0,
at_ms: 6,
protocol: "http",
direction: "request",
method: "GET",
path: "/done",
data: "",
outcome: "matched",
},
],
replay_transitions: [
{
sequence: 0,
at_ms: 7,
transition_id: "done",
state_before: "open",
state_after: "closed",
sensitive_aliases: [],
},
],
};
describe("process observation vocabulary", () => {
it("projects every capture collection 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 },
{ collection: "shim_events", index: 0, capture_order: 5 },
{ collection: "protocol_events", index: 0, capture_order: 6 },
{ collection: "replay_transitions", index: 0, capture_order: 7 },
] 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",
"shim",
"http",
"replay_transition",
]);
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[7]).toMatchObject({
event_id: "obs.shim_events.0",
subject_id: "shim:helper:route:0",
});
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();
});
});
@@ -1,155 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import {
cleanupOwnedProcessGroup,
parseProcessEnvironment,
selectCapturedProcessGroupIds,
type ProcessOwnershipHost,
} from "../../../src/process/ProcessOwnership.js";
import { matchesOwnedProcessCommand } from "../../../src/process/ProcessCommandIdentity.js";
const ownership = {
runId: "run-token",
leaderPid: 100,
processGroupId: 100,
};
const host = (
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
): {
readonly adapter: ProcessOwnershipHost;
readonly signalGroup: ReturnType<typeof vi.fn>;
} => {
const signalGroup = vi.fn();
return {
adapter: {
listProcesses: () =>
Promise.resolve(
Object.keys(environments).map((pid) => ({
pid: Number(pid),
parentPid: Number(pid) === 100 ? 1 : 100,
processGroupId: 100,
state: "S",
command: "fixture",
})),
),
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
signalGroup,
},
signalGroup,
};
};
describe("owned process-group cleanup discovery", () => {
it("excludes sampled groups whose leader was outside the captured tree", () => {
expect(
selectCapturedProcessGroupIds(100, [
{ pid: 100, process_group_id: 42 },
{ pid: 100, process_group_id: 100 },
{ pid: 101, process_group_id: 42 },
{ pid: 102, process_group_id: 102 },
{ pid: 103, process_group_id: 102 },
]),
).toEqual([100, 102]);
});
it("drops nameless Linux environment entries", () => {
expect(
parseProcessEnvironment("=ignored\0REA_PROCESS_RUN_ID=owned\0EMPTY=\0"),
).toEqual({ REA_PROCESS_RUN_ID: "owned", EMPTY: "" });
});
it("matches macOS executable names after process-table normalization", () => {
expect(
matchesOwnedProcessCommand(
"node /tmp/fake-launcher.mjs",
"/opt/node/bin/node",
"darwin",
),
).toBe(true);
expect(
matchesOwnedProcessCommand("(node)", "/opt/node/bin/node", "darwin"),
).toBe(true);
expect(
matchesOwnedProcessCommand(
"node /tmp/fake-launcher.mjs",
"/opt/python/bin/python3",
"darwin",
),
).toBe(false);
expect(
matchesOwnedProcessCommand(
"node /tmp/fake-launcher.mjs",
"/opt/node/bin/node",
"linux",
),
).toBe(false);
expect(
matchesOwnedProcessCommand("(node)", "/opt/node/bin/node", "linux"),
).toBe(false);
});
it("signals only a group whose every member carries the run token", async () => {
const { adapter, signalGroup } = host({
100: { REA_PROCESS_RUN_ID: "run-token" },
101: { REA_PROCESS_RUN_ID: "run-token" },
});
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
cleaned: true,
signaled: true,
});
expect(signalGroup).toHaveBeenCalledWith(100, "SIGKILL");
});
it("validates and signals rooted descendant groups once, root first", async () => {
const processes = [
{ pid: 100, parentPid: 1, processGroupId: 100 },
{ pid: 110, parentPid: 100, processGroupId: 100 },
{ pid: 101, parentPid: 100, processGroupId: 101 },
{ pid: 102, parentPid: 101, processGroupId: 102 },
{ pid: 103, parentPid: 102, processGroupId: 102 },
].map((process) => ({
...process,
state: "S",
command: "fixture",
}));
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listProcesses: () => Promise.resolve(processes),
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
signalGroup,
};
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
{ cleaned: true, signaled: true },
);
expect(signalGroup.mock.calls).toEqual([
[100, "SIGKILL"],
[101, "SIGKILL"],
[102, "SIGKILL"],
]);
});
it("leaves an unrelated Hopper process group outside the rooted tree untouched", async () => {
const processes = [
{ pid: 100, parentPid: 1, processGroupId: 100, command: "rea-hopper" },
{ pid: 101, parentPid: 100, processGroupId: 101, command: "owned-child" },
{
pid: 900,
parentPid: 1,
processGroupId: 900,
command:
"/Applications/Hopper Disassembler.app/Contents/MacOS/Hopper Disassembler",
},
].map((process) => ({ ...process, state: "S" }));
const environment = vi.fn((pid: number) =>
Promise.resolve({
REA_PROCESS_RUN_ID: pid === 900 ? "unrelated-run" : "run-token",
}),
);
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listProcesses: () => Promise.resolve(processes),
environment,
signalGroup,
};
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
{ cleaned: true, signaled: true },
);
expect(signalGroup.mock.calls).toEqual([
[100, "SIGKILL"],
[101, "SIGKILL"],
]);
expect(environment.mock.calls.some(([pid]) => pid === 900)).toBe(false);
});
});
@@ -1,212 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import {
cleanupOwnedProcessGroup,
observeOwnedProcessLineage,
verifyNoTokenOwnedProcesses,
type ProcessOwnershipHost,
} from "../../../src/process/ProcessOwnership.js";
const ownership = {
runId: "run-token",
leaderPid: 100,
processGroupId: 100,
};
const host = (
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
): {
readonly adapter: ProcessOwnershipHost;
readonly signalGroup: ReturnType<typeof vi.fn>;
} => {
const signalGroup = vi.fn();
return {
adapter: {
listProcesses: () =>
Promise.resolve(
Object.keys(environments).map((pid) => ({
pid: Number(pid),
parentPid: Number(pid) === 100 ? 1 : 100,
processGroupId: 100,
state: "S",
command: "fixture",
})),
),
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
signalGroup,
},
signalGroup,
};
};
describe("owned process-group cleanup discovery", () => {
it("signals token-owned groups that were reparented outside the launcher tree", async () => {
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 100,
parentPid: 1,
processGroupId: 100,
state: "S",
command: "fixture",
},
{
pid: 900,
parentPid: 1,
processGroupId: 900,
state: "S",
command: "detached-helper",
},
{
pid: 901,
parentPid: 900,
processGroupId: 900,
state: "S",
command: "detached-worker",
},
]),
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
signalGroup,
};
await expect(
cleanupOwnedProcessGroup(
{ ...ownership, sweepTokenOwnedProcesses: true },
adapter,
),
).resolves.toEqual({ cleaned: true, signaled: true });
expect(signalGroup.mock.calls.map(([groupId]) => groupId)).toEqual([
100, 900,
]);
});
it("fails closed when a token-owned process remains after cleanup", async () => {
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 900,
parentPid: 1,
processGroupId: 900,
state: "S",
command: "detached-helper",
},
]),
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
signalGroup: vi.fn(),
};
await expect(
verifyNoTokenOwnedProcesses("run-token", adapter),
).resolves.toEqual({
cleaned: false,
reason: "token-owned process remained after cleanup",
});
});
});
describe("owned process-group cleanup discovery", () => {
it("fails before signaling when any descendant-group member is unowned", async () => {
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 100,
parentPid: 1,
processGroupId: 100,
state: "S",
command: "fixture",
},
{
pid: 101,
parentPid: 100,
processGroupId: 101,
state: "S",
command: "child-session",
},
{
pid: 104,
parentPid: 101,
processGroupId: 101,
state: "S",
command: "child-helper",
},
]),
environment: (pid) =>
Promise.resolve({
REA_PROCESS_RUN_ID: pid === 104 ? "other-run" : "run-token",
}),
signalGroup,
};
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
{
cleaned: false,
reason: "process tree contains an unowned or PID-reused process",
failures: [{ pid: 104, reason: "run-token-mismatch" }],
},
);
expect(signalGroup).not.toHaveBeenCalled();
});
it("fails before signaling when a descendant group leader is not rooted", async () => {
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 100,
parentPid: 1,
processGroupId: 100,
state: "S",
command: "fixture",
},
{
pid: 105,
parentPid: 100,
processGroupId: 101,
state: "S",
command: "descendant",
},
{
pid: 101,
parentPid: 999,
processGroupId: 101,
state: "S",
command: "unrelated-group-leader",
},
]),
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
signalGroup,
};
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
{
cleaned: false,
reason:
"descendant process-group leader identity could not be verified",
},
);
expect(signalGroup).not.toHaveBeenCalled();
});
it("records sorted launcher and descendant lineage after token checks", async () => {
const { adapter } = host({
102: { REA_PROCESS_RUN_ID: "run-token" },
100: { REA_PROCESS_RUN_ID: "run-token" },
101: { REA_PROCESS_RUN_ID: "run-token" },
});
await expect(
observeOwnedProcessLineage(ownership, adapter),
).resolves.toEqual({
status: "verified",
observedAt: expect.any(String),
lineage: {
schemaVersion: 1,
runId: "run-token",
launcherPid: 100,
launcherParentPid: 1,
processGroupId: 100,
descendants: [
{ pid: 101, parentPid: 100, processGroupId: 100 },
{ pid: 102, parentPid: 100, processGroupId: 100 },
],
},
});
});
});
@@ -1,72 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import {
observeOwnedProcessLineage,
type ProcessOwnershipHost,
} from "../../../src/process/ProcessOwnership.js";
const ownership = {
runId: "run-token",
leaderPid: 100,
processGroupId: 100,
};
describe("owned process-group cleanup discovery", () => {
it("walks the PPID tree across process-group boundaries", async () => {
const environment = vi.fn((pid: number) =>
Promise.resolve({
REA_PROCESS_RUN_ID: pid === 103 ? "unrelated-run" : "run-token",
}),
);
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 103,
parentPid: 999,
processGroupId: 100,
state: "S",
command: "unrelated-same-group",
},
{
pid: 102,
parentPid: 101,
processGroupId: 102,
state: "S",
command: "grandchild-session",
},
{
pid: 100,
parentPid: 1,
processGroupId: 100,
state: "S",
command: "fixture",
},
{
pid: 101,
parentPid: 100,
processGroupId: 101,
state: "S",
command: "child-group",
},
]),
environment,
signalGroup: vi.fn(),
};
await expect(
observeOwnedProcessLineage(ownership, adapter),
).resolves.toEqual({
status: "verified",
observedAt: expect.any(String),
lineage: {
schemaVersion: 1,
runId: "run-token",
launcherPid: 100,
launcherParentPid: 1,
processGroupId: 100,
descendants: [
{ pid: 101, parentPid: 100, processGroupId: 101 },
{ pid: 102, parentPid: 101, processGroupId: 102 },
],
},
});
expect(environment.mock.calls.map(([pid]) => pid)).toEqual([100, 101, 102]);
});
});
@@ -1,165 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import {
cleanupOwnedProcessGroup,
observeOwnedProcessLineage,
type ProcessOwnershipHost,
} from "../../../src/process/ProcessOwnership.js";
const ownership = {
runId: "run-token",
leaderPid: 100,
processGroupId: 100,
};
const host = (
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
): {
readonly adapter: ProcessOwnershipHost;
readonly signalGroup: ReturnType<typeof vi.fn>;
} => {
const signalGroup = vi.fn();
return {
adapter: {
listProcesses: () =>
Promise.resolve(
Object.keys(environments).map((pid) => ({
pid: Number(pid),
parentPid: Number(pid) === 100 ? 1 : 100,
processGroupId: 100,
state: "S",
command: "fixture",
})),
),
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
signalGroup,
},
signalGroup,
};
};
describe("owned process-group cleanup validation", () => {
it("fails closed when a descendant in another process group lacks the token", async () => {
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 100,
parentPid: 1,
processGroupId: 100,
state: "S",
command: "fixture",
},
{
pid: 101,
parentPid: 100,
processGroupId: 101,
state: "S",
command: "child-session",
},
]),
environment: (pid) =>
Promise.resolve({
REA_PROCESS_RUN_ID: pid === 100 ? "run-token" : "other-run",
}),
signalGroup: vi.fn(),
};
await expect(
observeOwnedProcessLineage(ownership, adapter),
).resolves.toEqual({
status: "unavailable",
observedAt: expect.any(String),
runId: "run-token",
launcherPid: 100,
processGroupId: 100,
reason: "process lineage contains an unowned or PID-reused process",
});
});
it("does not publish lineage when any member fails ownership checks", async () => {
const { adapter } = host({
100: { REA_PROCESS_RUN_ID: "run-token" },
101: { REA_PROCESS_RUN_ID: "other-run" },
});
await expect(
observeOwnedProcessLineage(ownership, adapter),
).resolves.toEqual({
status: "unavailable",
observedAt: expect.any(String),
runId: "run-token",
launcherPid: 100,
processGroupId: 100,
reason: "process lineage contains an unowned or PID-reused process",
});
});
it("fails closed for stale metadata or an unrelated concurrent process", async () => {
const { adapter, signalGroup } = host({
100: { REA_PROCESS_RUN_ID: "run-token" },
101: { REA_PROCESS_RUN_ID: "different-run" },
});
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
cleaned: false,
reason: "process tree contains an unowned or PID-reused process",
failures: [{ pid: 101, reason: "run-token-mismatch" }],
});
expect(signalGroup).not.toHaveBeenCalled();
});
it("checks every member and aggregates ownership read failures", async () => {
const environment = vi.fn((pid: number) => {
if (pid === 100)
return Promise.reject(new Error("transient procfs read"));
return Promise.resolve(
pid === 101
? { REA_PROCESS_RUN_ID: "different-run" }
: { REA_PROCESS_RUN_ID: "run-token" },
);
});
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve(
[100, 101, 102].map((pid) => ({
pid,
parentPid: pid === 100 ? 1 : 100,
processGroupId: 100,
state: "S",
command: "fixture",
})),
),
environment,
signalGroup,
};
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
cleaned: false,
reason: "process tree contains an unowned or PID-reused process",
failures: [
{ pid: 100, reason: "environment-unreadable" },
{ pid: 101, reason: "run-token-mismatch" },
],
});
expect(environment.mock.calls.map(([pid]) => pid)).toEqual([100, 101, 102]);
expect(signalGroup).not.toHaveBeenCalled();
});
it("accepts a member that exits during ownership revalidation", async () => {
const liveLauncher = {
pid: 100,
parentPid: 1,
processGroupId: 100,
state: "S",
command: "fixture",
};
const listProcesses = vi
.fn<ProcessOwnershipHost["listProcesses"]>()
.mockResolvedValueOnce([liveLauncher])
.mockResolvedValue([]);
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listProcesses,
environment: () =>
Promise.reject(new Error("process exited before environment read")),
signalGroup,
};
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
{
cleaned: true,
signaled: false,
},
);
expect(signalGroup).not.toHaveBeenCalled();
});
});
@@ -1,134 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import {
cleanupOwnedProcessGroup,
observeOwnedProcessGroup,
type ProcessOwnershipHost,
} from "../../../src/process/ProcessOwnership.js";
const ownership = {
runId: "run-token",
leaderPid: 100,
processGroupId: 100,
};
const host = (
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
): {
readonly adapter: ProcessOwnershipHost;
readonly signalGroup: ReturnType<typeof vi.fn>;
} => {
const signalGroup = vi.fn();
return {
adapter: {
listProcesses: () =>
Promise.resolve(
Object.keys(environments).map((pid) => ({
pid: Number(pid),
parentPid: Number(pid) === 100 ? 1 : 100,
processGroupId: 100,
state: "S",
command: "fixture",
})),
),
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
signalGroup,
},
signalGroup,
};
};
describe("owned process-group cleanup validation", () => {
it("ignores exited zombie members during live ownership checks", async () => {
const environment = vi.fn((pid: number) =>
Promise.resolve(pid === 101 ? {} : { REA_PROCESS_RUN_ID: "run-token" }),
);
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 100,
parentPid: 1,
processGroupId: 100,
state: "S",
command: "fixture",
},
{
pid: 101,
parentPid: 100,
processGroupId: 100,
state: "Z",
command: "[node] <defunct>",
},
]),
environment,
signalGroup,
};
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
cleaned: true,
signaled: true,
});
expect(environment.mock.calls).toEqual([[100], [100]]);
expect(signalGroup).toHaveBeenCalledWith(100, "SIGKILL");
});
it("observes a zombie-only group as settled", async () => {
const environment = vi.fn(() => Promise.resolve({}));
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 101,
parentPid: 1,
processGroupId: 100,
state: "Z+",
command: "[node] <defunct>",
},
]),
environment,
signalGroup: vi.fn(),
};
expect(await observeOwnedProcessGroup(ownership, adapter)).toEqual({
state: "empty",
});
expect(environment).not.toHaveBeenCalled();
});
it("is idempotent when the owned group has already exited", async () => {
const { adapter } = host({});
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
cleaned: true,
signaled: false,
});
});
it("fails closed when the launcher command identity changes", async () => {
const { adapter, signalGroup } = host({
100: { REA_PROCESS_RUN_ID: "run-token" },
});
expect(
await cleanupOwnedProcessGroup(
{
...ownership,
expectedCommand: "/owned/hopper",
expectedParentPid: 1,
},
adapter,
),
).toEqual({
cleaned: false,
reason:
"owned launcher command identity did not match (observed=fixture; expected=/owned/hopper)",
});
expect(signalGroup).not.toHaveBeenCalled();
});
it("fails closed when the launcher parent identity changes", async () => {
const { adapter, signalGroup } = host({
100: { REA_PROCESS_RUN_ID: "run-token" },
});
expect(
await cleanupOwnedProcessGroup(
{ ...ownership, expectedCommand: "fixture", expectedParentPid: 999 },
adapter,
),
).toEqual({
cleaned: false,
reason: "owned launcher parent identity did not match",
});
expect(signalGroup).not.toHaveBeenCalled();
});
});
@@ -1,37 +0,0 @@
import { describe, expect, it } from "vitest";
import {
cleanupWindowsProcessTree,
type WindowsProcessTreeHost,
} from "../../../src/process/ProcessOwnership.js";
describe("Windows P0 process-tree cleanup", () => {
it("reports whether taskkill signaled or found an exited tree", async () => {
const terminated: WindowsProcessTreeHost = {
terminateTree: () => Promise.resolve("terminated"),
};
const missing: WindowsProcessTreeHost = {
terminateTree: () => Promise.resolve("missing"),
};
await expect(cleanupWindowsProcessTree(42, terminated)).resolves.toEqual({
cleaned: true,
signaled: true,
});
await expect(cleanupWindowsProcessTree(42, missing)).resolves.toEqual({
cleaned: true,
signaled: false,
});
});
it("keeps invalid identity and termination failures explicit", async () => {
const failing: WindowsProcessTreeHost = {
terminateTree: () => Promise.reject(new Error("taskkill failed")),
};
await expect(cleanupWindowsProcessTree(0, failing)).resolves.toEqual({
cleaned: false,
reason: "Windows process-tree PID is invalid",
});
await expect(cleanupWindowsProcessTree(42, failing)).resolves.toEqual({
cleaned: false,
reason:
"Windows P0 process-tree termination failed; Job Object ownership is unavailable",
});
});
});