2026-07-13 18:20:17 +08:00
import { createHash , randomUUID } from "node:crypto" ;
2026-10-08 04:46:46 +08:00
import { constants , statSync , type BigIntStats } from "node:fs" ;
import { open , mkdtemp , rm , stat } from "node:fs/promises" ;
2026-07-13 18:20:17 +08:00
import { tmpdir } from "node:os" ;
import { join } from "node:path" ;
2026-10-09 19:26:41 +08:00
import { setTimeout as delay } from "node:timers/promises" ;
2026-07-17 00:16:46 +00:00
import type { IPty } from "@lydell/node-pty" ;
2026-07-13 18:20:17 +08:00
import type {
FilesystemCheckpoint ,
InteractionEvent ,
ProcessCapture ,
2026-08-10 14:57:44 +08:00
UnverifiedProcessCapture ,
2026-07-13 18:20:17 +08:00
ProcessSample ,
2026-08-10 14:57:44 +08:00
ProcessSettlement ,
2026-10-08 04:46:46 +08:00
ProcessCaptureCleanupReport ,
PartialProcessCaptureObservation ,
IncompleteProcessCaptureObservations ,
PartialFilesystemSnapshot ,
PartialProcessObservationField ,
2026-07-13 18:20:17 +08:00
ProcessScenario ,
2026-07-22 20:07:49 +00:00
ProcessCaptureEventJournalEntry ,
RecordProcessCaptureEvent ,
2026-07-13 18:20:17 +08:00
TerminalFrame ,
2026-10-08 00:46:21 +08:00
} from "../../domain/process/processCapture.js" ;
2026-07-13 18:20:17 +08:00
import {
digestProcessCommitment ,
2026-10-08 04:46:46 +08:00
parseProcessCapture ,
partialProcessCaptureObservationSchema ,
2026-07-13 18:20:17 +08:00
processComparisonContract ,
processScenarioCommitment ,
2026-10-08 00:46:21 +08:00
} from "../../domain/process/processCapture.js" ;
import { PRODUCT_IDENTITY } from "../../identity.js" ;
2026-07-13 18:20:17 +08:00
import type { SnapshotResult } from "./FilesystemSnapshot.js" ;
import { snapshotRoots } from "./FilesystemSnapshot.js" ;
2026-10-05 21:15:04 +08:00
import { classifyFilesystemEffects } from "./ProcessFilesystemEffects.js" ;
2026-10-08 04:46:46 +08:00
import {
cleanupOwnedProcessGroup ,
verifyNoTokenOwnedProcesses ,
type ProcessCleanupResult ,
type ProcessOwnershipBaseline ,
} from "../ProcessOwnership.js" ;
import {
observeOwnedProcessGroup ,
prepareProcessOwnershipInspection ,
systemProcessOwnershipHost ,
} from "../ProcessOwnershipObservation.js" ;
import {
describeProcessCaptureExecutionFailure ,
ProcessCaptureError ,
} from "./ProcessCaptureError.js" ;
2026-10-05 20:16:44 +08:00
import { assertNotCancelled } from "./ProcessScenarioRuntimeValidation.js" ;
2026-07-13 18:20:17 +08:00
import {
2026-07-22 23:17:42 +00:00
normalizeProcessElapsedTime ,
2026-07-13 18:20:17 +08:00
normalizeProcessSamples ,
normalizeProcessText ,
} from "./ProcessNormalization.js" ;
2026-10-08 00:46:21 +08:00
import { PROCESS_PROVIDER } from "../../domain/process/processEvidenceProvider.js" ;
2026-07-13 18:20:17 +08:00
import { TerminalRenderer } from "./TerminalRenderer.js" ;
2026-09-29 16:28:46 +08:00
import { scheduleProcessInterval , type ProcessTimer } from "./ProcessTimer.js" ;
2026-07-13 18:20:17 +08:00
interface TerminalExitOptions {
readonly terminal : IPty ;
readonly scenario : ProcessScenario ;
readonly started : number ;
readonly lastOutput : () => number ;
readonly signal : AbortSignal | undefined ;
2026-09-29 16:28:46 +08:00
readonly timers : Set < ProcessTimer >;
2026-07-13 18:20:17 +08:00
readonly interactions : InteractionEvent [];
readonly dispatchedEventIndexes : ReadonlySet < number >;
2026-07-22 20:07:49 +00:00
readonly recordEvent : RecordProcessCaptureEvent ;
2026-07-13 18:20:17 +08:00
}
interface CaptureResultOptions {
readonly frames : readonly TerminalFrame [];
readonly exit : {
readonly exitCode : number ;
readonly signal? : number ;
readonly reason : "exited" | "timeout" | "idle_timeout" ;
};
readonly samples : readonly ProcessSample [];
readonly before : SnapshotResult ;
readonly after : SnapshotResult ;
readonly truncated : boolean ;
readonly scenario : ProcessScenario ;
readonly rootPid : number ;
readonly samplingPartial : boolean ;
2026-08-10 14:57:44 +08:00
readonly renderedFrames : UnverifiedProcessCapture [ "rendered_frames" ];
2026-07-13 18:20:17 +08:00
readonly interactions : readonly InteractionEvent [];
readonly checkpoints : readonly FilesystemCheckpoint [];
2026-08-10 14:57:44 +08:00
readonly settlement : ObservedProcessSettlement ;
readonly manifest : UnverifiedProcessCapture [ "manifest" ];
2026-07-22 20:07:49 +00:00
readonly eventJournal : readonly ProcessCaptureEventJournalEntry [];
2026-07-13 18:20:17 +08:00
}
2026-08-10 14:57:44 +08:00
/** Settlement observation before process-resource cleanup has completed. */
export type ObservedProcessSettlement =
| Pick <
Extract < ProcessSettlement , { readonly state : "quiesced" }>,
"state" | "elapsed_ms"
>
| Pick <
Exclude < ProcessSettlement , { readonly state : "quiesced" }>,
"state" | "elapsed_ms"
> ;
2026-10-05 21:15:04 +08:00
/** Capture observations before owned-resource cleanup has been verified. */
2026-08-10 14:57:44 +08:00
export type PendingProcessCapture = Omit <
UnverifiedProcessCapture ,
2026-10-05 21:15:04 +08:00
"cleanup" | "settlement"
2026-08-10 14:57:44 +08:00
> & {
readonly settlement : ObservedProcessSettlement ;
};
2026-10-08 04:46:46 +08:00
/** Mutable collection of facts available if completion stops before a capture exists. */
export interface ProcessCaptureObservationBuffer {
target_pid : PartialProcessObservationField < number >;
frames : PartialProcessObservationField < readonly TerminalFrame [] >;
rendered_frames : PartialProcessObservationField <
UnverifiedProcessCapture [ "rendered_frames" ]
> ;
interaction_events : PartialProcessObservationField <
UnverifiedProcessCapture [ "interaction_events" ]
> ;
exit : IncompleteProcessCaptureObservations [ "exit" ];
settlement : IncompleteProcessCaptureObservations [ "settlement" ];
process_samples : PartialProcessObservationField < readonly ProcessSample [] >;
filesystem_snapshots : {
before : PartialProcessObservationField < PartialFilesystemSnapshot >;
after : PartialProcessObservationField < PartialFilesystemSnapshot >;
};
event_journal : PartialProcessObservationField <
readonly ProcessCaptureEventJournalEntry []
> ;
manifest : IncompleteProcessCaptureObservations [ "manifest" ];
}
/** Seed explicit observation availability before capture completion begins. */
export const createProcessCaptureObservationBuffer = ( options : {
readonly frames : readonly TerminalFrame [];
readonly interactions : readonly InteractionEvent [];
readonly samples : readonly ProcessSample [];
readonly eventJournal : readonly ProcessCaptureEventJournalEntry [];
readonly before : SnapshotResult ;
}) : ProcessCaptureObservationBuffer => ({
target_pid : {
state : "unavailable" ,
reason : "No PTY process was spawned before the run failed." ,
},
frames : { state : "available" , value : options.frames },
rendered_frames : {
state : "unavailable" ,
reason :
"Rendered terminal frames were not collected before capture completion finished." ,
},
interaction_events : { state : "available" , value : options.interactions },
exit : {
state : "unavailable" ,
reason : "Terminal exit was not observed before the run failed." ,
},
settlement : {
state : "unavailable" ,
reason :
"Process settlement was not observed before capture completion finished." ,
},
process_samples : { state : "available" , value : options.samples },
filesystem_snapshots : {
before : {
state : "available" ,
value : {
files : options.before.files ,
truncated : options.before.truncated ,
},
},
after : {
state : "unavailable" ,
reason :
"Final filesystem snapshot was not collected before capture completion finished." ,
},
},
event_journal : { state : "available" , value : options.eventJournal },
manifest : {
state : "unavailable" ,
reason :
"Capture manifest was not produced before capture completion finished." ,
},
});
const normalizePartialProcessObservations = (
observations : IncompleteProcessCaptureObservations ,
context : { readonly scenario : ProcessScenario ; readonly rootPid? : number },
) : IncompleteProcessCaptureObservations => {
const targetPid = observations . target_pid ;
const target_pid =
targetPid . state === "available" && context . rootPid !== undefined
? {
state : "available" as const ,
value : context.scenario.normalization.pids ? 1 : context.rootPid ,
}
: targetPid ;
const samples = observations . process_samples ;
const process_samples =
samples . state === "available" && context . rootPid !== undefined
? {
state : "available" as const ,
value : normalizeProcessSamples (
samples . value ,
context . scenario ,
context . rootPid ,
),
}
: samples ;
return { ... observations , target_pid , process_samples };
};
2026-10-05 21:15:04 +08:00
/** Wait for trailing PTY callbacks before the capture becomes immutable. */
export const settleProcessCaptureJournal = async (
journal : readonly ProcessCaptureEventJournalEntry [],
quietMs = 25 ,
maxWaitMs = 500 ,
) : Promise < void > => {
const deadline = Date . now () + maxWaitMs ;
let observed = journal . length ;
let lastChangeAt = Date . now ();
while ( Date . now () < deadline ) {
await new Promise < void >(( resolve ) => setTimeout ( resolve , 4 ));
if ( journal . length !== observed ) {
observed = journal . length ;
lastChangeAt = Date . now ();
} else if ( Date . now () - lastChangeAt >= quietMs ) return ;
}
};
2026-07-13 18:20:17 +08:00
export const buildCaptureResult = (
options : CaptureResultOptions ,
2026-10-05 20:16:44 +08:00
) : PendingProcessCapture => {
const hasSensitiveScriptedInput = options . scenario . events . some (
( event ) => event . type === "input" && event . sensitive ,
);
const sensitiveInputUnknown =
"Sensitive scripted input values are redacted from process capture Evidence." ;
const filesystemObservationUnknown =
"No filesystem observation paths were selected; filesystem effects remain unknown." ;
const hasFilesystemObservations =
options . scenario . filesystem_observation_paths . length > 0 ;
2026-10-09 20:09:24 +08:00
const filesystemEffects = classifyFilesystemEffects (
options . before ,
options . after ,
);
const hasUnknownFilesystemEffects = filesystemEffects . some (
({ status }) => status === "unknown" ,
);
const incompleteFilesystemUnknown =
"Path absence in incomplete enumeration or below an unfollowed symbolic link remains unknown." ;
2026-10-05 20:16:44 +08:00
return {
manifest : options.manifest ,
normalization : options.scenario.normalization ,
frames : options.frames ,
rendered_frames : options.renderedFrames ,
interaction_events : options.interactions ,
exit : {
code :
options.exit.reason === "exited" && options . exit . exitCode >= 0
? options.exit.exitCode
: null ,
signal : options.exit.signal ?? null ,
reason : options.exit.reason ,
2026-07-13 18:20:17 +08:00
},
2026-10-05 20:16:44 +08:00
settlement : options.settlement ,
process_samples : normalizeProcessSamples (
options . samples ,
options . scenario ,
options . rootPid ,
),
filesystem_checkpoints : options.checkpoints ,
event_journal : options.eventJournal ,
files_before : options.before.files ,
files_after : options.after.files ,
2026-10-09 20:09:24 +08:00
filesystem_effects : filesystemEffects ,
2026-10-05 20:16:44 +08:00
truncated : options.truncated ,
limitations : [
2026-10-08 04:46:46 +08:00
"The executable digest is a prelaunch file sample; matching path metadata immediately after spawn does not prove an atomic operating-system image binding." ,
2026-10-05 20:16:44 +08:00
"Process trees are sampled and may omit short-lived descendants." ,
...( options . samplingPartial
? [ "Process-tree sampling ended with an incomplete observation." ]
: []),
"Filesystem observations are before/after snapshots, not syscall traces." ,
"Inherited host environment variables are not recorded and may affect results." ,
...( ! hasFilesystemObservations ? [ filesystemObservationUnknown ] : []),
2026-10-09 20:09:24 +08:00
...( hasUnknownFilesystemEffects ? [ incompleteFilesystemUnknown ] : []),
2026-10-05 20:16:44 +08:00
...( hasSensitiveScriptedInput ? [ sensitiveInputUnknown ] : []),
],
residual_unknowns : [
{
scope : "process" ,
reason :
"Process trees are sampled and may omit short-lived descendants." ,
},
2026-10-08 04:46:46 +08:00
{
scope : "process" ,
reason :
"The executable digest is a prelaunch file sample; operating-system image binding is not atomically observed." ,
},
2026-10-05 20:16:44 +08:00
{
scope : "environment" ,
reason : "Inherited host environment variables are not recorded." ,
},
2026-10-05 21:15:04 +08:00
{
scope : "network" ,
reason : "Network activity is not observed by this capture." ,
},
2026-10-05 20:16:44 +08:00
...( ! hasFilesystemObservations
? [
{
scope : "filesystem" as const ,
reason : filesystemObservationUnknown ,
},
]
: []),
2026-10-09 20:09:24 +08:00
...( hasUnknownFilesystemEffects
? [
{
scope : "filesystem" as const ,
reason : incompleteFilesystemUnknown ,
},
]
: []),
2026-10-05 20:16:44 +08:00
...( hasSensitiveScriptedInput
? [{ scope : "interaction" as const , reason : sensitiveInputUnknown }]
: []),
],
};
};
2026-07-13 18:20:17 +08:00
2026-10-08 04:46:46 +08:00
interface ExecutableFileIdentity {
readonly dev : bigint ;
readonly ino : bigint ;
readonly mode : bigint ;
readonly size : bigint ;
readonly mtimeNs : bigint ;
readonly ctimeNs : bigint ;
}
export interface SelectedExecutableObservation {
readonly sha256 : string | null ;
readonly identity : ExecutableFileIdentity | null ;
readonly reason : string | null ;
}
export interface LaunchedExecutableObservation {
readonly selectedSha256 : string | null ;
readonly sha256 : string | null ;
readonly state : "path_metadata_unchanged" | "unknown" ;
readonly reason : string | null ;
}
const identityFromStats = ( stats : BigIntStats ) : ExecutableFileIdentity => ({
dev : stats.dev ,
ino : stats.ino ,
mode : stats.mode ,
size : stats.size ,
mtimeNs : stats.mtimeNs ,
ctimeNs : stats.ctimeNs ,
});
const sameExecutableIdentity = (
left : ExecutableFileIdentity ,
right : ExecutableFileIdentity ,
) : boolean =>
left . dev === right . dev &&
left . ino === right . ino &&
left . mode === right . mode &&
left . size === right . size &&
left . mtimeNs === right . mtimeNs &&
left . ctimeNs === right . ctimeNs ;
const filesystemFailure = ( cause : unknown ) : string | undefined => {
if ( ! ( cause instanceof Error ) || ! ( "code" in cause ) || ! ( "syscall" in cause ))
return undefined ;
return `Executable file observation failed: ${ cause . message } ` ;
};
2026-10-08 07:53:41 +08:00
/** Metadata IO seam for deterministic prelaunch cancellation and identity checks. */
export interface SelectedExecutableFileSystem {
open ( path : string , flags : number ) : ReturnType < typeof open >;
stat ( path : string ) : Promise < BigIntStats >;
}
const selectedExecutableFileSystem : SelectedExecutableFileSystem = {
open ,
stat : ( path ) => stat ( path , { bigint : true }),
};
/** Sample the selected file without launching it; retain cancellation and file identity. */
2026-10-08 04:46:46 +08:00
export const observeSelectedExecutable = async (
path : string ,
signal? : AbortSignal ,
2026-10-08 07:53:41 +08:00
fileSystem : SelectedExecutableFileSystem = selectedExecutableFileSystem ,
2026-10-08 04:46:46 +08:00
) : Promise < SelectedExecutableObservation > => {
assertNotCancelled ( signal );
let handle : Awaited < ReturnType < typeof open >> | undefined ;
try {
2026-10-08 07:53:41 +08:00
handle = await fileSystem . open (
path ,
constants . O_RDONLY | constants . O_NONBLOCK ,
);
2026-10-08 04:46:46 +08:00
const openedStats = await handle . stat ({ bigint : true });
if ( ! openedStats . isFile ())
return {
sha256 : null ,
identity : null ,
reason : "Selected executable is not a regular file." ,
};
const openedIdentity = identityFromStats ( openedStats );
2026-10-08 07:53:41 +08:00
const selectedPathIdentity = identityFromStats ( await fileSystem . stat ( path ));
2026-10-08 04:46:46 +08:00
if ( ! sameExecutableIdentity ( openedIdentity , selectedPathIdentity ))
return {
sha256 : null ,
identity : null ,
reason : "Selected executable path changed while it was being opened." ,
};
2026-10-08 07:53:41 +08:00
// IO above can settle after cancellation. Do not construct a stream with an
// already-aborted signal: Node can emit a second, unhandled AbortError.
assertNotCancelled ( signal );
2026-10-08 04:46:46 +08:00
const hash = createHash ( "sha256" );
for await ( const chunk of handle . createReadStream ({
autoClose : false ,
signal ,
})) {
assertNotCancelled ( signal );
hash . update ( chunk );
}
assertNotCancelled ( signal );
const finalIdentity = identityFromStats (
await handle . stat ({ bigint : true }),
);
if ( ! sameExecutableIdentity ( openedIdentity , finalIdentity ))
return {
sha256 : null ,
identity : null ,
reason : "Selected executable changed while its contents were sampled." ,
};
return {
sha256 : hash.digest ( "hex" ),
identity : openedIdentity ,
reason : null ,
};
} catch ( cause : unknown ) {
assertNotCancelled ( signal );
const reason = filesystemFailure ( cause );
if ( reason !== undefined ) return { sha256 : null , identity : null , reason };
throw cause ;
} finally {
await handle ? . close ();
}
};
/** Compare the selected file metadata with the path immediately after PTY spawn. */
export const observeLaunchedExecutable = (
path : string ,
selected : SelectedExecutableObservation ,
) : LaunchedExecutableObservation => {
if ( selected . identity === null || selected . sha256 === null )
return {
selectedSha256 : selected.sha256 ,
sha256 : null ,
state : "unknown" ,
reason : selected.reason ?? "Selected executable identity is unavailable." ,
};
try {
const currentStats = statSync ( path , { bigint : true });
const currentIdentity = identityFromStats ( currentStats );
if (
currentStats . isFile () &&
sameExecutableIdentity ( selected . identity , currentIdentity )
)
return {
selectedSha256 : selected.sha256 ,
sha256 : selected.sha256 ,
state : "path_metadata_unchanged" ,
reason : null ,
};
return {
selectedSha256 : selected.sha256 ,
sha256 : null ,
state : "unknown" ,
reason : "Executable path metadata changed between sampling and spawn." ,
};
} catch ( cause : unknown ) {
const reason = filesystemFailure ( cause );
if ( reason !== undefined )
return {
selectedSha256 : selected.sha256 ,
sha256 : null ,
state : "unknown" ,
reason ,
};
throw cause ;
}
2026-07-13 18:20:17 +08:00
};
export const createRunManifest = async (
scenario : ProcessScenario ,
startedAt : Date ,
completedAt : Date ,
2026-10-08 04:46:46 +08:00
executable : LaunchedExecutableObservation ,
2026-10-06 00:50:38 +08:00
host : {
readonly platform : NodeJS.Platform ;
readonly architecture : NodeJS.Architecture ;
} = {
platform : process.platform ,
architecture : process.arch ,
},
2026-08-10 14:57:44 +08:00
) : Promise < UnverifiedProcessCapture [ "manifest" ] > => {
2026-07-13 18:20:17 +08:00
const scenarioCommitment = processScenarioCommitment (
scenario ,
2026-10-08 04:46:46 +08:00
executable . selectedSha256 ?? undefined ,
2026-07-13 18:20:17 +08:00
);
const comparisonContract = processComparisonContract ( scenario );
return {
rea_version : PRODUCT_IDENTITY.packageVersion ,
provider_version : PROCESS_PROVIDER.version ,
2026-10-06 00:50:38 +08:00
platform : host.platform ,
architecture : host.architecture ,
2026-07-13 18:20:17 +08:00
pty_backend : "node-pty" ,
started_at : startedAt.toISOString (),
completed_at : completedAt.toISOString (),
scenario : scenarioCommitment ,
comparison_contract : comparisonContract ,
full_scenario_sha256 : digestProcessCommitment ( scenarioCommitment ),
comparison_contract_sha256 : digestProcessCommitment ( comparisonContract ),
2026-10-08 04:46:46 +08:00
selected_executable_sha256 : executable.selectedSha256 ,
executable_sha256 : executable.sha256 ,
executable_identity : {
state : executable.state ,
reason : executable.reason ,
},
2026-07-13 18:20:17 +08:00
normalization_sha256 : digestProcessCommitment ( scenario . normalization ),
};
};
export const observeSettlement = async (
runId : string ,
processGroupIds : readonly number [],
settleMs : number ,
2026-07-22 20:07:49 +00:00
recordEvent : RecordProcessCaptureEvent = () => undefined ,
2026-10-06 00:50:38 +08:00
platform : NodeJS.Platform = process . platform ,
2026-10-09 19:26:41 +08:00
signal? : AbortSignal ,
2026-08-10 14:57:44 +08:00
) : Promise < ObservedProcessSettlement > => {
2026-10-09 19:26:41 +08:00
assertNotCancelled ( signal );
2026-10-06 00:50:38 +08:00
if ( platform === "win32" ) {
2026-07-22 20:07:49 +00:00
recordEvent ( "lifecycle" , 1 );
2026-07-13 18:20:17 +08:00
return { state : "unverifiable" , elapsed_ms : 0 };
2026-07-22 20:07:49 +00:00
}
2026-07-13 18:20:17 +08:00
const started = Date . now ();
let consecutiveEmpty = 0 ;
let deadlineReached = false ;
while ( ! deadlineReached ) {
2026-10-09 19:26:41 +08:00
assertNotCancelled ( signal );
2026-07-13 18:20:17 +08:00
const observations = await Promise . all (
[... new Set ( processGroupIds )]. map (( processGroupId ) =>
2026-10-09 19:26:41 +08:00
observeOwnedProcessGroup (
{ runId , leaderPid : processGroupId , processGroupId },
undefined ,
signal ,
),
2026-07-13 18:20:17 +08:00
),
);
2026-10-09 19:26:41 +08:00
assertNotCancelled ( signal );
2026-07-22 20:07:49 +00:00
if ( observations . some (({ state }) => state === "unverifiable" )) {
recordEvent ( "lifecycle" , 1 );
2026-07-13 18:20:17 +08:00
return { state : "unverifiable" , elapsed_ms : Date.now () - started };
2026-07-22 20:07:49 +00:00
}
2026-07-13 18:20:17 +08:00
if ( observations . every (({ state }) => state === "empty" )) {
consecutiveEmpty += 1 ;
2026-07-22 20:07:49 +00:00
if ( consecutiveEmpty >= 2 ) {
recordEvent ( "lifecycle" , 1 );
2026-07-13 18:20:17 +08:00
return { state : "quiesced" , elapsed_ms : Date.now () - started };
2026-07-22 20:07:49 +00:00
}
2026-07-13 18:20:17 +08:00
} else consecutiveEmpty = 0 ;
deadlineReached = Date . now () - started >= settleMs ;
if ( deadlineReached ) break ;
2026-10-09 19:26:41 +08:00
await delay ( 50 , undefined , { signal });
2026-07-13 18:20:17 +08:00
}
2026-07-22 20:07:49 +00:00
recordEvent ( "lifecycle" , 1 );
2026-07-13 18:20:17 +08:00
return { state : "alive_at_deadline" , elapsed_ms : Date.now () - started };
};
export const awaitTerminalExit = async ({
terminal ,
scenario ,
started ,
lastOutput ,
signal ,
timers ,
interactions ,
dispatchedEventIndexes ,
2026-07-22 20:07:49 +00:00
recordEvent ,
2026-07-13 18:20:17 +08:00
} : TerminalExitOptions ) : Promise < {
exitCode : number ;
signal? : number ;
reason : "exited" | "timeout" | "idle_timeout" | "cancelled" ;
} > =>
new Promise (( resolveExit ) => {
// The kill caused by a deadline is observed later as an ordinary PTY exit.
// Keep the initiating lifecycle reason so comparisons distinguish a target
// exit from harness-owned timeout, idle-timeout, and cancellation cleanup.
let reason : "exited" | "timeout" | "idle_timeout" | "cancelled" = "exited" ;
terminal . onExit (( exit ) => {
2026-07-22 20:07:49 +00:00
recordEvent ( "lifecycle" , 0 );
2026-07-13 18:20:17 +08:00
for ( const [ eventIndex , event ] of scenario . events . entries ()) {
if ( dispatchedEventIndexes . has ( eventIndex )) continue ;
2026-07-22 20:07:49 +00:00
const sequence = interactions . length ;
2026-07-13 18:20:17 +08:00
interactions . push ({
2026-07-22 20:07:49 +00:00
sequence ,
2026-07-13 18:20:17 +08:00
scheduled_at_ms : event.at_ms ,
dispatched_at_ms : Math.max ( 0 , Date . now () - started ),
type : event . type ,
data :
event.type === "input"
? "<not-dispatched>"
: event . type === "resize"
? ` ${ String ( event . columns ) } x ${ String ( event . rows ) } `
: event . signal ,
outcome : "target_exited" ,
});
2026-07-22 20:07:49 +00:00
recordEvent ( "interaction_events" , sequence );
2026-07-13 18:20:17 +08:00
}
for ( const timer of timers ) {
2026-09-29 16:28:46 +08:00
timer . cancel ();
2026-07-13 18:20:17 +08:00
}
timers . clear ();
resolveExit ({ ... exit , reason });
});
2026-09-29 16:28:46 +08:00
const timeout = scheduleProcessInterval (() => {
2026-07-13 18:20:17 +08:00
if ( signal ? . aborted === true ) {
reason = "cancelled" ;
terminal . kill ( "SIGKILL" );
} else if ( Date . now () - started >= scenario . timeout_ms ) {
reason = "timeout" ;
terminal . kill ( "SIGKILL" );
} else if ( Date . now () - lastOutput () >= scenario . idle_timeout_ms ) {
reason = "idle_timeout" ;
terminal . kill ( "SIGKILL" );
}
}, 20 );
timers . add ( timeout );
});
2026-10-05 20:16:44 +08:00
/** Host operations used when releasing one captured process run. */
export interface ProcessCaptureCleanupHost {
readonly platform : NodeJS.Platform ;
readonly cleanupProcessGroup : typeof cleanupOwnedProcessGroup ;
2026-10-08 04:46:46 +08:00
readonly verifyTokenOwnedProcesses : typeof verifyNoTokenOwnedProcesses ;
2026-10-05 20:16:44 +08:00
readonly removeTemporaryRoot : ( path : string ) => Promise < void >;
}
const processCaptureCleanupHost : ProcessCaptureCleanupHost = {
platform : process.platform ,
cleanupProcessGroup : cleanupOwnedProcessGroup ,
2026-10-08 04:46:46 +08:00
verifyTokenOwnedProcesses : verifyNoTokenOwnedProcesses ,
2026-10-05 20:16:44 +08:00
removeTemporaryRoot : ( path ) => rm ( path , { recursive : true , force : true }),
};
2026-10-08 04:46:46 +08:00
const PROCESS_CLEANUP_VERIFICATION_GRACE_MS = 1 _000 ;
const PROCESS_CLEANUP_VERIFICATION_INTERVAL_MS = 25 ;
const verifyTokenOwnedProcessesUntilSettled = async (
verify : () => Promise < ProcessCleanupResult >,
) : Promise < ProcessCleanupResult > => {
const deadline = Date . now () + PROCESS_CLEANUP_VERIFICATION_GRACE_MS ;
let result = await verify ();
while ( ! result . cleaned ) {
const remaining = deadline - Date . now ();
if ( remaining <= 0 ) return result ;
await new Promise < void >(( resolve ) =>
setTimeout (
resolve ,
Math . min ( PROCESS_CLEANUP_VERIFICATION_INTERVAL_MS , remaining ),
),
);
result = await verify ();
}
return result ;
};
2026-07-13 18:20:17 +08:00
export const releaseProcessResources = async ( options : {
2026-09-29 16:28:46 +08:00
readonly timers : ReadonlySet < ProcessTimer >;
2026-10-08 04:46:46 +08:00
readonly terminal : Pick < IPty , "pid" > | undefined ;
2026-07-13 18:20:17 +08:00
readonly renderer : TerminalRenderer | undefined ;
readonly runId : string ;
readonly temporaryRoot : string ;
2026-10-08 04:46:46 +08:00
readonly captureBaseline? : ProcessOwnershipBaseline ;
readonly sampledProcessGroupIds? : readonly number [];
2026-10-05 20:16:44 +08:00
readonly host? : ProcessCaptureCleanupHost ;
2026-10-08 04:46:46 +08:00
}) : Promise < ProcessCaptureCleanupReport > => {
2026-10-05 20:16:44 +08:00
const host = options . host ?? processCaptureCleanupHost ;
2026-09-29 16:28:46 +08:00
for ( const timer of options . timers ) timer . cancel ();
2026-10-08 04:46:46 +08:00
let terminalRenderer : ProcessCaptureCleanupReport [ "terminal_renderer" ] = {
state : options.renderer === undefined ? "not_required" : "cleaned" ,
reason : null ,
};
2026-07-13 18:20:17 +08:00
try {
await options . renderer ? . dispose ();
2026-10-06 05:58:46 +08:00
} catch ( cause : unknown ) {
2026-10-08 04:46:46 +08:00
terminalRenderer = {
state : "failed" ,
reason :
cause instanceof Error
? cause . message || cause . name || "renderer dispose failed"
: "renderer dispose failed" ,
};
2026-07-13 18:20:17 +08:00
}
2026-10-08 04:46:46 +08:00
let ownedProcessGroup : ProcessCaptureCleanupReport [ "owned_process_group" ] = {
state : options.terminal === undefined ? "not_required" : "cleaned" ,
reason : null ,
};
if ( options . terminal !== undefined ) {
if ( host . platform === "win32" ) {
ownedProcessGroup = {
state : "unverified" ,
reason :
"owned process cleanup is unverifiable on Windows without process-job authority" ,
};
} else {
2026-10-08 17:01:05 +03:00
const terminalPid = options . terminal . pid ;
const relation = {
leaderPid : terminalPid ,
processGroupId : terminalPid ,
...( options . sampledProcessGroupIds === undefined
? {}
: { sampledProcessGroupIds : options.sampledProcessGroupIds }),
};
2026-10-05 20:16:44 +08:00
const cleaned = await host . cleanupProcessGroup ({
2026-07-13 18:20:17 +08:00
runId : options.runId ,
2026-10-08 17:01:05 +03:00
leaderPid : terminalPid ,
processGroupId : terminalPid ,
2026-10-08 04:46:46 +08:00
sweepTokenOwnedProcesses : true ,
...( options . sampledProcessGroupIds === undefined
? {}
: { sampledProcessGroupIds : options.sampledProcessGroupIds }),
...( options . captureBaseline === undefined
? {}
: { captureBaseline : options.captureBaseline }),
2026-07-13 18:20:17 +08:00
});
2026-10-08 17:01:05 +03:00
const unverified = [...( cleaned . unverified ?? [])];
2026-10-08 04:46:46 +08:00
if ( ! cleaned . cleaned ) {
ownedProcessGroup = { state : "unverified" , reason : cleaned.reason };
} else {
const verified = await verifyTokenOwnedProcessesUntilSettled (() =>
host . verifyTokenOwnedProcesses (
options . runId ,
undefined ,
options . captureBaseline ,
2026-10-08 17:01:05 +03:00
relation ,
2026-10-08 04:46:46 +08:00
),
);
2026-10-08 17:01:05 +03:00
unverified . push (...( verified . unverified ?? []));
2026-10-08 04:46:46 +08:00
if ( ! verified . cleaned )
ownedProcessGroup = { state : "unverified" , reason : verified.reason };
}
2026-10-08 17:01:05 +03:00
if ( unverified . length > 0 )
ownedProcessGroup = {
... ownedProcessGroup ,
unverified_processes : [
... new Map (
unverified . map (({ pid , diagnostic }) => [
` ${ String ( pid ) } : ${ diagnostic } ` ,
{ pid , reason : diagnostic },
]),
). values (),
],
};
2026-07-13 18:20:17 +08:00
}
}
2026-10-08 04:46:46 +08:00
let temporaryRoot : ProcessCaptureCleanupReport [ "temporary_root" ] = {
state : "cleaned" ,
reason : null ,
};
2026-07-13 18:20:17 +08:00
try {
2026-10-05 20:16:44 +08:00
await host . removeTemporaryRoot ( options . temporaryRoot );
2026-10-06 05:58:46 +08:00
} catch ( cause : unknown ) {
2026-10-08 04:46:46 +08:00
temporaryRoot = {
state : "failed" ,
reason :
cause instanceof Error
? cause . message || cause . name || "temporary root removal failed"
: "temporary root removal failed" ,
};
2026-07-13 18:20:17 +08:00
}
2026-10-08 04:46:46 +08:00
return {
owned_process_group : ownedProcessGroup ,
terminal_renderer : terminalRenderer ,
temporary_root : temporaryRoot ,
};
};
export const cleanupReportFailure = (
report : ProcessCaptureCleanupReport ,
) : string | undefined => {
const failures = Object . entries ( report ). filter (
([, outcome ]) =>
outcome . state === "failed" || outcome . state === "unverified" ,
);
return failures . length === 0
? undefined
: failures
. map (
([ resource , outcome ]) =>
` ${ resource } : ${ outcome . reason ?? outcome . state } ` ,
)
. join ( "; " );
2026-07-13 18:20:17 +08:00
};
export const captureTerminalFrames = ( options : {
readonly terminal : IPty ;
readonly scenario : ProcessScenario ;
readonly frames : TerminalFrame [];
readonly started : number ;
readonly temporaryRoot : string ;
readonly onOutput : () => void ;
readonly renderer : TerminalRenderer ;
2026-07-22 20:07:49 +00:00
readonly recordEvent : RecordProcessCaptureEvent ;
2026-07-13 18:20:17 +08:00
}) : (() => boolean ) => {
let outputBytes = 0 ;
let truncated = false ;
options . terminal . onData (( data ) => {
options . onOutput ();
const bytes = Buffer . byteLength ( data );
2026-09-29 13:57:50 +08:00
if ( outputBytes + bytes > options . scenario . limits . output_bytes ) {
2026-07-13 18:20:17 +08:00
truncated = true ;
return ;
}
outputBytes += bytes ;
2026-07-22 23:17:42 +00:00
const atMs = normalizeProcessElapsedTime (
Date . now () - options . started ,
options . scenario . normalization . time_bucket_ms ,
);
2026-07-13 18:20:17 +08:00
const normalized = normalizeProcessText (
data ,
options . scenario ,
options . temporaryRoot ,
options . terminal . pid ,
);
2026-07-22 20:07:49 +00:00
const sequence = options . frames . length ;
2026-07-13 18:20:17 +08:00
options . frames . push ({
2026-07-22 20:07:49 +00:00
sequence ,
2026-07-13 18:20:17 +08:00
at_ms : atMs ,
data : normalized ,
2026-10-09 17:55:28 +08:00
...( normalized === data ? {} : { raw_data : data }),
2026-07-13 18:20:17 +08:00
});
options . renderer . write ( data , atMs );
2026-10-04 16:02:36 +08:00
options . recordEvent ( "frames" , sequence );
2026-07-13 18:20:17 +08:00
});
return () => truncated ;
};
export const resolveProcessResult = (
2026-10-08 04:46:46 +08:00
capture : PendingProcessCapture | ProcessCapture | undefined ,
2026-07-13 18:20:17 +08:00
executionFailure : unknown ,
2026-10-08 04:46:46 +08:00
cleanup : ProcessCaptureCleanupReport ,
observations? : IncompleteProcessCaptureObservations ,
partialContext ?: {
readonly scenario : ProcessScenario ;
readonly rootPid? : number ;
},
2026-07-13 18:20:17 +08:00
) : ProcessCapture => {
2026-10-08 04:46:46 +08:00
const cleanupFailure = cleanupReportFailure ( cleanup );
2026-10-08 23:29:34 +08:00
const executionFailureReason =
describeProcessCaptureExecutionFailure ( executionFailure );
let partialObservation : PartialProcessCaptureObservation | undefined ;
if (
( cleanupFailure !== undefined || executionFailure !== undefined ) &&
( capture !== undefined || observations !== undefined )
) {
const normalizedObservations =
observations === undefined || partialContext === undefined
? observations
: normalizePartialProcessObservations ( observations , partialContext );
if ( capture === undefined ) {
if ( normalizedObservations !== undefined ) {
const partialResult = partialProcessCaptureObservationSchema . safeParse ({
observations : normalizedObservations ,
cleanup ,
execution_failure : executionFailureReason ?? null ,
});
if ( partialResult . success ) partialObservation = partialResult . data ;
}
} else {
const captureData =
"cleanup" in capture
? (() => {
const { cleanup : _cleanup , ... data } = capture ;
void _cleanup ;
return data ;
})()
: capture ;
const settlement =
cleanupFailure !== undefined
? { ... capture . settlement , cleanup_outcome : "failed" as const }
: capture . settlement . state === "quiesced"
? {
2026-10-08 04:46:46 +08:00
... capture . settlement ,
2026-10-08 23:29:34 +08:00
cleanup_outcome : "not_required" as const ,
}
: { ... capture . settlement , cleanup_outcome : "cleaned" as const };
2026-10-08 04:46:46 +08:00
const partialResult = partialProcessCaptureObservationSchema . safeParse ({
2026-10-08 23:29:34 +08:00
capture : { ... captureData , settlement },
2026-10-08 04:46:46 +08:00
cleanup ,
execution_failure : executionFailureReason ?? null ,
});
if ( partialResult . success ) partialObservation = partialResult . data ;
}
2026-10-08 23:29:34 +08:00
}
if ( cleanupFailure !== undefined ) {
const cleanupResources = Object . entries ( cleanup )
. filter (
([, outcome ]) =>
outcome . state === "failed" || outcome . state === "unverified" ,
)
. map (([ resource ]) => resource );
2026-10-08 04:46:46 +08:00
throw new ProcessCaptureError ( cleanupFailure , {
cause : executionFailure ,
reason : "cleanup_incomplete" ,
cleanupResources ,
...( executionFailureReason === undefined
? {}
: { executionFailure : executionFailureReason }),
...( partialObservation === undefined ? {} : { partialObservation }),
cleanupReport : cleanup ,
});
}
2026-10-08 23:29:34 +08:00
if ( executionFailure instanceof ProcessCaptureError ) {
const retainedExecutionFailure =
executionFailure . executionFailure ?? executionFailureReason ;
const retainedPartialObservation =
executionFailure . partialObservation ?? partialObservation ;
throw new ProcessCaptureError ( executionFailure . message , {
cause : executionFailure ,
...( executionFailure . userMessage === undefined
? {}
: { userMessage : executionFailure.userMessage }),
...( executionFailure . userCategory === undefined
? {}
: { userCategory : executionFailure.userCategory }),
reason : executionFailure.reason ,
cleanupResources : executionFailure.cleanupResources ,
...( retainedExecutionFailure === undefined
? {}
: { executionFailure : retainedExecutionFailure }),
...( retainedPartialObservation === undefined
? {}
: { partialObservation : retainedPartialObservation }),
cleanupReport : executionFailure.cleanupReport ?? cleanup ,
});
}
2026-10-08 04:46:46 +08:00
if ( executionFailure !== undefined ) {
2026-07-13 18:20:17 +08:00
throw new ProcessCaptureError ( "process capture failed" , {
cause : executionFailure ,
2026-10-08 23:29:34 +08:00
reason : "capture_failed" ,
2026-10-08 04:46:46 +08:00
...( executionFailureReason === undefined
? {}
: { executionFailure : executionFailureReason }),
2026-10-08 23:29:34 +08:00
...( partialObservation === undefined ? {} : { partialObservation }),
cleanupReport : cleanup ,
2026-07-13 18:20:17 +08:00
});
2026-10-08 04:46:46 +08:00
}
2026-07-13 18:20:17 +08:00
if ( capture === undefined )
throw new ProcessCaptureError ( "process capture produced no result" );
2026-10-08 17:01:05 +03:00
const unverifiedProcesses = cleanup . owned_process_group . unverified_processes ;
if ( "cleanup" in capture && unverifiedProcesses === undefined ) return capture ;
2026-10-08 04:46:46 +08:00
const settlement : UnverifiedProcessCapture [ "settlement" ] =
capture . settlement . state === "quiesced"
? { ... capture . settlement , cleanup_outcome : "not_required" }
: { ... capture . settlement , cleanup_outcome : "cleaned" };
try {
return parseProcessCapture ({
... capture ,
settlement ,
2026-10-08 17:01:05 +03:00
residual_unknowns : [
... capture . residual_unknowns ,
...( unverifiedProcesses ?? []). map (({ pid , reason }) => ({
scope : "process" as const ,
reason : `Ownership of unrelated process ${ String ( pid ) } could not be verified; it was left untouched: ${ reason } ` ,
})),
],
2026-10-08 04:46:46 +08:00
cleanup : {
2026-10-08 17:01:05 +03:00
...( "cleanup" in capture ? capture . cleanup : {}),
2026-10-08 04:46:46 +08:00
owned_process_group : "verified" ,
temporary_root : "removed" ,
2026-10-08 17:01:05 +03:00
...( unverifiedProcesses === undefined
? {}
: { unverified_processes : unverifiedProcesses }),
2026-10-08 04:46:46 +08:00
},
});
} catch ( cause : unknown ) {
throw new ProcessCaptureError (
`process capture validation failed ${ cause instanceof Error ? `: ${ cause . message } ` : "" } ` ,
{ cause },
);
}
2026-07-13 18:20:17 +08:00
};
export const prepareProcessCapture = async (
scenario : ProcessScenario ,
signal : AbortSignal | undefined ,
2026-10-07 23:45:23 +08:00
captureSnapshot : typeof snapshotRoots = snapshotRoots ,
2026-07-14 14:39:02 +08:00
host : ProcessPreparationHost = systemProcessPreparationHost ,
2026-07-13 18:20:17 +08:00
) : Promise < {
readonly temporaryRoot : string ;
readonly runId : string ;
2026-10-08 04:46:46 +08:00
readonly ownershipBaseline : ProcessOwnershipBaseline ;
2026-07-13 18:20:17 +08:00
readonly before : SnapshotResult ;
} > => {
2026-10-08 04:46:46 +08:00
assertNotCancelled ( signal );
await host . prepareOwnershipInspector ? .( signal );
2026-07-13 18:20:17 +08:00
assertNotCancelled ( signal );
2026-10-07 23:45:23 +08:00
const before = await captureSnapshot ( scenario , signal );
2026-07-14 14:39:02 +08:00
const temporaryRoot = await host . createTemporaryRoot ();
try {
2026-10-08 04:46:46 +08:00
assertNotCancelled ( signal );
2026-07-14 14:39:02 +08:00
const runId = randomUUID ();
2026-10-08 04:46:46 +08:00
const ownershipBaseline =
( await host . captureOwnershipBaseline ? .( signal )) ?? [];
assertNotCancelled ( signal );
return { temporaryRoot , runId , ownershipBaseline , before };
2026-07-14 14:39:02 +08:00
} catch ( cause : unknown ) {
await host . cleanup ( temporaryRoot );
throw cause ;
}
};
2026-10-05 20:16:44 +08:00
/** Filesystem seam for allocating and cleaning a capture's temporary root. */
2026-07-14 14:39:02 +08:00
export interface ProcessPreparationHost {
2026-10-08 04:46:46 +08:00
prepareOwnershipInspector ? ( signal? : AbortSignal ) : Promise < void >;
/** Capture the process baseline with the caller's startup cancellation. */
captureOwnershipBaseline ? (
signal? : AbortSignal ,
) : Promise < ProcessOwnershipBaseline >;
2026-07-14 14:39:02 +08:00
createTemporaryRoot () : Promise < string >;
cleanup ( path : string ) : Promise < void >;
}
const systemProcessPreparationHost : ProcessPreparationHost = {
2026-10-08 04:46:46 +08:00
prepareOwnershipInspector : prepareProcessOwnershipInspection ,
captureOwnershipBaseline : ( signal ) =>
systemProcessOwnershipHost . captureBaseline ? .( signal ) ?? Promise . resolve ([]),
2026-07-14 14:39:02 +08:00
createTemporaryRoot : () => mkdtemp ( join ( tmpdir (), "rea-process-" )),
cleanup : ( path ) => rm ( path , { recursive : true , force : true }),
2026-07-13 18:20:17 +08:00
};