2026-08-09 11:58:01 +08:00
import canonicalize from "canonicalize" ;
2026-07-12 21:12:18 +00:00
import { z } from "zod" ;
import type { ProcessCapture } from "./processCapture.js" ;
2026-10-08 09:04:35 -07:00
import { AnalysisInputError } from "../analysisErrorCore.js" ;
2026-10-08 00:46:21 +08:00
import { jsonValueSchema } from "../jsonValue.js" ;
2026-07-22 20:39:03 +00:00
import {
compareProcessTraces ,
2026-07-22 20:48:34 +00:00
processTraceOutcomesDiffer ,
2026-07-22 20:39:03 +00:00
processTraceComparisonResultSchema ,
type ProcessTraceSpecification ,
} from "./processTraceComparison.js" ;
2026-07-22 20:48:34 +00:00
import {
dimensionsForTraceSources ,
traceCoversObservedDimension ,
} from "./processTraceDimensionProjection.js" ;
2026-07-12 21:12:18 +00:00
2026-10-08 09:04:35 -07:00
const OPERATION = "compare_process_captures" ;
2026-07-12 21:12:18 +00:00
/** Comparison classification that never equates incomplete evidence. */
export const comparisonStatusSchema = z . enum ([
"unchanged" ,
"added" ,
"removed" ,
"changed" ,
"truncated" ,
"unknown" ,
2026-07-14 01:12:27 +00:00
"contradiction" ,
2026-07-12 21:12:18 +00:00
]);
type ComparisonStatus = z . infer < typeof comparisonStatusSchema >;
2026-07-14 14:39:02 +08:00
/** Canonical ordered dimensions that contribute to an overall process status. */
export const PROCESS_COMPARISON_DIMENSIONS = [
"terminal" ,
"interaction" ,
"exit" ,
"filesystem" ,
"process" ,
] as const ;
/** Derive the overall comparison status from every process dimension. */
export const deriveProcessComparisonStatus = (
dimensions : readonly ComparisonStatus [],
) : ComparisonStatus => {
if ( dimensions . includes ( "truncated" )) return "truncated" ;
if (
dimensions . some (( status ) =>
[ "changed" , "added" , "removed" ]. includes ( status ),
)
)
return "changed" ;
return dimensions . includes ( "unknown" ) ? "unknown" : "unchanged" ;
};
2026-07-12 21:12:18 +00:00
/** Pure normalized comparison between two captures. */
export const processCaptureComparisonSchema = z
. object ({
status : comparisonStatusSchema ,
terminal : comparisonStatusSchema ,
2026-07-13 17:01:09 +08:00
interaction : comparisonStatusSchema ,
2026-07-12 21:12:18 +00:00
exit : comparisonStatusSchema ,
filesystem : comparisonStatusSchema ,
process : comparisonStatusSchema ,
2026-07-13 17:01:09 +08:00
first_divergence : z.discriminatedUnion ( "status" , [
z . object ({ status : z.literal ( "none" ) }),
z . object ({ status : z.literal ( "unknown" ), reason : z.string () }),
z . object ({
status : z.literal ( "found" ),
dimension : z.enum ([
"terminal" ,
"interaction" ,
"exit" ,
"filesystem" ,
"process" ,
]),
index : z.number (). int (). nonnegative (),
left_at_ms : z.number (). int (). nonnegative (). nullable (),
right_at_ms : z.number (). int (). nonnegative (). nullable (),
2026-07-13 11:51:19 +00:00
left : jsonValueSchema.nullable (),
right : jsonValueSchema.nullable (),
2026-07-13 17:01:09 +08:00
}),
]),
2026-07-22 20:39:03 +00:00
trace : processTraceComparisonResultSchema.optional (),
2026-07-12 21:12:18 +00:00
limitations : z.array ( z . string ()),
})
. superRefine (( comparison , context ) => {
2026-07-14 14:39:02 +08:00
const expected = deriveProcessComparisonStatus (
PROCESS_COMPARISON_DIMENSIONS . map (( dimension ) => comparison [ dimension ]),
);
2026-07-12 21:12:18 +00:00
if ( comparison . status !== expected )
context . addIssue ({
code : "custom" ,
message : "Process comparison status contradicts its dimensions" ,
path : [ "status" ],
});
});
2026-07-20 11:45:27 +00:00
export type ProcessCaptureComparison = z . infer <
typeof processCaptureComparisonSchema
> ;
2026-07-12 21:12:18 +00:00
2026-07-13 17:01:09 +08:00
const terminalObservations = ( capture : ProcessCapture ) : readonly unknown [] =>
[
... capture . frames . map (( frame ) => ({ kind : "raw" as const , ... frame })),
... capture . rendered_frames . map (( frame ) => ({
kind : "rendered" as const ,
... frame ,
})),
]. sort (( left , right ) => {
const time = left . at_ms - right . at_ms ;
if ( time !== 0 ) return time ;
if ( left . kind !== right . kind ) return left . kind === "raw" ? - 1 : 1 ;
return left . sequence - right . sequence ;
});
2026-10-05 21:15:04 +08:00
const filesystemObservations = ( capture : ProcessCapture ) : readonly unknown [] =>
capture . filesystem_checkpoints ;
2026-07-12 21:12:18 +00:00
2026-08-09 11:58:01 +08:00
const sameJsonValue = ( left : unknown , right : unknown ) : boolean => {
const encodedLeft = canonicalize ( left );
return encodedLeft !== undefined && encodedLeft === canonicalize ( right );
};
2026-07-20 11:45:27 +00:00
/** Canonical observations for one process-comparison dimension. */
export const processDimensionObservations = (
capture : ProcessCapture ,
dimension : ( typeof PROCESS_COMPARISON_DIMENSIONS )[ number ],
) : readonly unknown [] => {
switch ( dimension ) {
case "terminal" :
return terminalObservations ( capture );
case "interaction" :
return capture . interaction_events ;
case "exit" :
return [{ ... capture . exit , settlement : capture.settlement }];
case "filesystem" :
return filesystemObservations ( capture );
case "process" :
return capture . process_samples ;
}
};
2026-07-12 21:12:18 +00:00
const classifyCollection = (
left : readonly unknown [],
right : readonly unknown [],
) : ComparisonStatus => {
2026-08-09 11:58:01 +08:00
if ( sameJsonValue ( left , right )) return "unchanged" ;
2026-07-12 21:12:18 +00:00
if ( left . length === 0 ) return "added" ;
if ( right . length === 0 ) return "removed" ;
return "changed" ;
};
const hasUnknown = (
capture : ProcessCapture ,
scope : ProcessCapture [ "residual_unknowns" ][ number ][ "scope" ],
) : boolean => capture . residual_unknowns . some (( item ) => item . scope === scope );
2026-07-13 17:01:09 +08:00
type DivergenceDimension = Exclude <
ProcessCaptureComparison [ "first_divergence" ],
{ readonly status : "none" | "unknown" }
> [ "dimension" ];
const eventTime = ( value : unknown ) : number | null => {
if (
typeof value === "object" &&
value !== null &&
"at_ms" in value &&
typeof value . at_ms === "number" &&
Number . isSafeInteger ( value . at_ms ) &&
value . at_ms >= 0
)
return value . at_ms ;
return null ;
};
const firstCollectionDivergence = (
dimension : DivergenceDimension ,
left : readonly unknown [],
right : readonly unknown [],
) : Extract <
ProcessCaptureComparison [ "first_divergence" ],
{ readonly status : "found" }
> | null => {
const length = Math . max ( left . length , right . length );
for ( let index = 0 ; index < length ; index += 1 ) {
const leftValue = left [ index ] ?? null ;
const rightValue = right [ index ] ?? null ;
2026-08-09 11:58:01 +08:00
if ( sameJsonValue ( leftValue , rightValue )) continue ;
2026-07-13 17:01:09 +08:00
return {
status : "found" ,
dimension ,
index ,
left_at_ms : eventTime ( leftValue ),
right_at_ms : eventTime ( rightValue ),
2026-07-13 11:51:19 +00:00
left : jsonValueSchema.parse ( leftValue ),
right : jsonValueSchema.parse ( rightValue ),
2026-07-13 17:01:09 +08:00
};
}
return null ;
};
const chooseFirstDivergence = (
candidates : ReadonlyArray < Extract <
ProcessCaptureComparison [ "first_divergence" ] ,
{ readonly status : "found" }
> | null > ,
) : ProcessCaptureComparison [ "first_divergence" ] => {
const found = candidates . filter (
( candidate ) : candidate is NonNullable < typeof candidate > =>
candidate !== null ,
);
return (
found . sort (( left , right ) => {
const leftTime = Math . min (
left . left_at_ms ?? Number . MAX_SAFE_INTEGER ,
left . right_at_ms ?? Number . MAX_SAFE_INTEGER ,
);
const rightTime = Math . min (
right . left_at_ms ?? Number . MAX_SAFE_INTEGER ,
right . right_at_ms ?? Number . MAX_SAFE_INTEGER ,
);
return leftTime - rightTime ;
})[ 0 ] ?? { status : "none" }
);
};
2026-07-13 18:20:17 +08:00
const assertComparable = (
2026-07-12 21:12:18 +00:00
left : ProcessCapture ,
right : ProcessCapture ,
2026-07-13 18:20:17 +08:00
options : { readonly maxCaptureAgeMs? : number ; readonly now ?: () => number },
) : void => {
2026-07-13 18:03:41 +08:00
if (
left . manifest . comparison_contract_sha256 !==
2026-09-29 07:08:46 +08:00
right . manifest . comparison_contract_sha256
2026-10-08 09:04:35 -07:00
) {
const fields = differingContractFields (
left . manifest . comparison_contract ,
right . manifest . comparison_contract ,
2026-07-13 18:03:41 +08:00
);
2026-10-08 09:04:35 -07:00
throw new AnalysisInputError ( OPERATION , undefined , [
{
path : [ "right" ],
reason : "invalid_value" ,
message : `Process captures have incompatible comparison contracts ${ fields . length === 0 ? "" : `; these scenario fields differ: ${ fields . join ( ", " ) } ` } . Capture both scenarios with the same values for these fields, then compare them.` ,
expected : fields ,
},
]);
}
2026-07-13 18:20:17 +08:00
if ( options . maxCaptureAgeMs === undefined ) return ;
const maxCaptureAgeMs = options . maxCaptureAgeMs ;
const now = ( options . now ?? Date . now )();
2026-10-08 09:04:35 -07:00
const stale = (
[
[ "left" , left ],
[ "right" , right ],
] as const
). flatMap (([ side , { manifest }]) => {
const age = now - Date . parse ( manifest . completed_at );
return age > maxCaptureAgeMs
? [
` ${ side } completed at ${ manifest . completed_at } ( ${ String ( age ) } ms ago)` ,
]
: [];
});
if ( stale . length > 0 )
throw new AnalysisInputError ( OPERATION , undefined , [
{
path : [ "max_capture_age_ms" ],
reason : "out_of_range" ,
message : `Process capture exceeds max_capture_age_ms ${ String ( maxCaptureAgeMs ) } : ${ stale . join ( "; " ) } . Recapture the stale scenario or raise max_capture_age_ms.` ,
},
]);
2026-07-13 18:20:17 +08:00
};
2026-10-08 09:04:35 -07:00
/** Name top-level contract fields whose canonical values differ. */
const differingContractFields = (
left : Readonly < Record < string , unknown >>,
right : Readonly < Record < string , unknown >>,
) : string [] =>
[... new Set ([... Object . keys ( left ), ... Object . keys ( right )])]
. filter (
( field ) =>
! Object . hasOwn ( left , field ) ||
! Object . hasOwn ( right , field ) ||
canonicalize ( left [ field ]) !== canonicalize ( right [ field ]),
)
. sort ();
2026-07-13 18:20:17 +08:00
const truncatedComparison = () : ProcessCaptureComparison => ({
status : "truncated" ,
terminal : "truncated" ,
interaction : "truncated" ,
exit : "truncated" ,
filesystem : "truncated" ,
process : "truncated" ,
first_divergence : {
status : "unknown" ,
reason : "At least one capture is truncated." ,
},
limitations : [ "At least one capture is truncated." ],
});
2026-07-22 20:39:03 +00:00
const applyTraceVerdict = (
dimensions : ComparisonDimensions ,
specification : ProcessTraceSpecification ,
trace : ReturnType < typeof compareProcessTraces >,
captures : readonly [ left : ProcessCapture , right : ProcessCapture ],
) : ComparisonDimensions => {
2026-07-22 20:48:34 +00:00
const traceShowsDifference = processTraceOutcomesDiffer ( trace );
const traceStatus =
trace . verdict === "unknown"
? "unknown"
: trace . verdict === "equivalent" || ! traceShowsDifference
? "unchanged"
: "changed" ;
2026-07-22 20:39:03 +00:00
const sources = new Set ( specification . events . map (({ source }) => source ));
const covered = dimensionsForTraceSources ( sources );
const statusFor = (
dimension : ( typeof PROCESS_COMPARISON_DIMENSIONS )[ number ],
) : ComparisonStatus => {
const exact = dimensions [ dimension ];
if ( ! covered . has ( dimension )) return exact ;
2026-07-22 21:06:10 +00:00
if ( trace . verdict === "nonconforming" ) return exact ;
2026-07-22 20:48:34 +00:00
if ( trace . verdict === "different" )
return traceShowsDifference ? "changed" : exact ;
2026-07-22 20:39:03 +00:00
if (
trace . verdict === "unknown" &&
[ "changed" , "added" , "removed" ]. includes ( exact )
)
return exact ;
return traceCoversObservedDimension (
dimension ,
sources ,
captures [ 0 ],
captures [ 1 ],
)
? traceStatus
: exact ;
};
return {
terminal : statusFor ( "terminal" ),
interaction : statusFor ( "interaction" ),
exit : statusFor ( "exit" ),
filesystem : statusFor ( "filesystem" ),
process : statusFor ( "process" ),
};
};
2026-07-13 18:20:17 +08:00
type ComparisonDimensions = Pick <
ProcessCaptureComparison ,
2026-10-05 21:15:04 +08:00
"terminal" | "interaction" | "exit" | "filesystem" | "process"
2026-07-13 18:20:17 +08:00
> ;
const compareDimensions = (
left : ProcessCapture ,
right : ProcessCapture ,
sameNormalization : boolean ,
) : ComparisonDimensions => {
2026-07-12 21:12:18 +00:00
const classify = (
scope : ProcessCapture [ "residual_unknowns" ][ number ][ "scope" ],
leftValues : readonly unknown [],
rightValues : readonly unknown [],
) : ComparisonStatus =>
! sameNormalization || hasUnknown ( left , scope ) || hasUnknown ( right , scope )
? "unknown"
: classifyCollection ( leftValues , rightValues );
2026-07-13 18:20:17 +08:00
return {
terminal : classify (
"terminal" ,
terminalObservations ( left ),
terminalObservations ( right ),
),
interaction : classify (
2026-07-14 14:39:02 +08:00
"interaction" ,
2026-07-13 18:20:17 +08:00
left . interaction_events ,
right . interaction_events ,
),
exit :
hasUnknown ( left , "exit" ) || hasUnknown ( right , "exit" )
? "unknown"
2026-08-09 11:58:01 +08:00
: sameJsonValue (
{ exit : left.exit , settlement : left.settlement },
{ exit : right.exit , settlement : right.settlement },
)
2026-07-13 18:20:17 +08:00
? "unchanged"
: "changed" ,
filesystem : classify (
"filesystem" ,
filesystemObservations ( left ),
filesystemObservations ( right ),
),
process : classify ( "process" , left . process_samples , right . process_samples ),
};
};
/**
2026-09-29 07:08:46 +08:00
* Compare two process capture observations without treating absence as proof.
2026-07-13 18:20:17 +08:00
*
* Observed differences outrank residual unknowns. A capture may therefore be
* definitively changed in one dimension while completeness remains unknown.
*/
export const compareProcessCaptures = (
left : ProcessCapture ,
right : ProcessCapture ,
options : {
readonly maxCaptureAgeMs? : number ;
readonly now ?: () => number ;
2026-07-22 20:39:03 +00:00
readonly traceSpecification? : ProcessTraceSpecification ;
2026-07-13 18:20:17 +08:00
} = {},
) : ProcessCaptureComparison => {
assertComparable ( left , right , options );
2026-07-22 20:39:03 +00:00
if ( left . truncated || right . truncated ) {
const truncated = truncatedComparison ();
return options . traceSpecification === undefined
? truncated
: {
... truncated ,
trace : compareProcessTraces ( left , right , options . traceSpecification ),
};
}
2026-08-09 11:58:01 +08:00
const sameNormalization = sameJsonValue (
left . normalization ,
right . normalization ,
);
2026-07-22 20:39:03 +00:00
const exactDimensions = compareDimensions ( left , right , sameNormalization );
const trace =
options . traceSpecification === undefined
? undefined
: compareProcessTraces ( left , right , options . traceSpecification );
const dimensions =
trace === undefined || options . traceSpecification === undefined
? exactDimensions
: applyTraceVerdict ( exactDimensions , options . traceSpecification , trace , [
left ,
right ,
]);
const divergenceCandidates = PROCESS_COMPARISON_DIMENSIONS . map (( dimension ) =>
2026-07-13 17:01:09 +08:00
firstCollectionDivergence (
2026-07-22 20:39:03 +00:00
dimension ,
processDimensionObservations ( left , dimension ),
processDimensionObservations ( right , dimension ),
2026-07-13 17:01:09 +08:00
),
2026-07-22 20:39:03 +00:00
);
const observedFirstDivergence = chooseFirstDivergence (
divergenceCandidates . map (( candidate ) =>
candidate !== null &&
trace ? . verdict === "equivalent" &&
dimensions [ candidate . dimension ] === "unchanged"
? null
: candidate ,
2026-07-13 17:01:09 +08:00
),
2026-07-22 20:39:03 +00:00
);
2026-07-13 17:01:09 +08:00
const firstDivergence =
2026-07-22 20:39:03 +00:00
trace ? . verdict === "equivalent" &&
deriveProcessComparisonStatus (
PROCESS_COMPARISON_DIMENSIONS . map (( dimension ) => dimensions [ dimension ]),
) === "unchanged"
? ({ status : "none" } as const )
: observedFirstDivergence . status === "found"
? observedFirstDivergence
: ! sameNormalization ||
left . residual_unknowns . length > 0 ||
right . residual_unknowns . length > 0
? ({
status : "unknown" ,
reason :
"Residual unknowns prevent proving that no divergence occurred." ,
} as const )
: observedFirstDivergence ;
2026-10-05 20:16:44 +08:00
const observedStatus = deriveProcessComparisonStatus (
PROCESS_COMPARISON_DIMENSIONS . map (( dimension ) => dimensions [ dimension ]),
);
2026-07-12 21:12:18 +00:00
return {
2026-10-05 20:16:44 +08:00
status : observedStatus ,
2026-07-13 18:20:17 +08:00
... dimensions ,
2026-07-13 17:01:09 +08:00
first_divergence : firstDivergence ,
2026-07-22 20:39:03 +00:00
...( trace === undefined ? {} : { trace }),
2026-07-12 21:12:18 +00:00
limitations : [
... left . limitations ,
... right . limitations ,
... left . residual_unknowns . map (({ reason }) => reason ),
... right . residual_unknowns . map (({ reason }) => reason ),
...( sameNormalization ? [] : [ "Capture normalization rules differ." ]),
],
};
};