chore: merge main and reconcile CI projections

This commit is contained in:
morluto
2026-10-08 23:45:07 +08:00
17 changed files with 657 additions and 149 deletions
+14 -40
View File
@@ -30,11 +30,7 @@ import {
snapshotEvidenceForQuery,
snapshotMatchesTarget,
} from "../domain/analysisSnapshot.js";
import {
analysisProfileSchema,
committedProviderSchema,
type AnalysisProfileCommitment,
} from "../domain/analysisProfile.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import { err, ok, type Result } from "../domain/result.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import type {
@@ -45,6 +41,10 @@ import {
REA_WORKFLOW_PROVIDER,
workflowAnalysisProfile,
} from "./InvestigationProviders.js";
import {
createWorkflowEvidence,
workflowSnapshotRecord,
} from "./WorkflowEvidence.js";
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
import { artifactInspectionResultSchema } from "../domain/artifactInspection.js";
@@ -268,35 +268,13 @@ const runAnalysis = async (
tool !== "trace_native_ui_action" &&
snapshotPath !== undefined &&
evidence !== undefined &&
"analysis_profile" in evidence &&
session.allowsSnapshotReplay(tool)
) {
const recorded = session.recordWorkflowSnapshot({
operation: tool,
parameters: arguments_,
execution: {
result: evidence.normalized_result,
rawResult: evidence.raw_result,
provider: committedProviderSchema.parse(evidence.provider),
analysisProfile: analysisProfileSchema.parse(
evidence.analysis_profile,
),
limitations: evidence.limitations,
locations: evidence.locations,
subject:
evidence.subject === null
? null
: {
path: evidence.subject.local_path,
sha256: evidence.subject.digest.sha256,
format: evidence.subject.format,
...(evidence.subject.architecture === null
? {}
: { architecture: evidence.subject.architecture }),
},
},
});
if (!recorded.ok) return cliError(recorded.error);
const workflowRecord = workflowSnapshotRecord(evidence, tool);
if (workflowRecord !== undefined) {
const recorded = session.recordWorkflowSnapshot(workflowRecord);
if (!recorded.ok) return cliError(recorded.error);
}
}
if (
tool !== "trace_native_ui_action" &&
@@ -356,15 +334,12 @@ const executeAnalysisTool = async (input: {
signal,
);
if (!result.ok) return { output: cliError(result.error) };
const evidence = createEvidence(input.openedTarget, REA_WORKFLOW_PROVIDER, {
const evidence = createWorkflowEvidence({
target: input.openedTarget,
operation: tool,
parameters: input.arguments,
result: result.value,
...(evidenceProfile === undefined
? {}
: { analysisProfile: evidenceProfile }),
confidence: "derived",
limitations: ["Derived by an REA composed workflow."],
upstreamProfile: evidenceProfile,
});
return { output: evidence, evidence };
}
@@ -493,8 +468,7 @@ const analysisProfileForEvidence = (
| DirectAnalysisTool,
): AnalysisProfileCommitment | undefined => {
if (!isWorkflowEvidenceTool(tool)) return session.analysisProfile(tool);
const upstream = session.analysisProfile();
return upstream === undefined ? undefined : workflowAnalysisProfile(upstream);
return session.analysisProfile();
};
const isWorkflowEvidenceTool = (
+64
View File
@@ -0,0 +1,64 @@
import {
REA_WORKFLOW_PROVIDER,
workflowAnalysisProfile,
} from "./InvestigationProviders.js";
import type { AnalysisOperation } from "./AnalysisProvider.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { WorkflowSnapshotRecordInput } from "./binary/BinarySessionRecords.js";
import {
analysisProfileSchema,
committedProviderSchema,
} from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import type { JsonValue } from "../domain/jsonValue.js";
/** Build the shared Evidence record for a successful composed binary workflow. */
export const createWorkflowEvidence = (input: {
readonly target: BinaryTarget | undefined;
readonly operation: AnalysisOperation;
readonly parameters: Readonly<Record<string, JsonValue>>;
readonly result: JsonValue;
readonly upstreamProfile: AnalysisProfileCommitment | undefined;
}): Evidence =>
createEvidence(input.target, REA_WORKFLOW_PROVIDER, {
operation: input.operation,
parameters: input.parameters,
result: input.result,
...(input.upstreamProfile === undefined
? {}
: { analysisProfile: workflowAnalysisProfile(input.upstreamProfile) }),
confidence: "derived",
limitations: ["Derived by an REA composed workflow."],
});
/** Convert workflow Evidence into its exact replay binding, when it has a profile. */
export const workflowSnapshotRecord = (
evidence: Evidence,
operation: AnalysisOperation,
): WorkflowSnapshotRecordInput | undefined => {
if (!("analysis_profile" in evidence)) return undefined;
return {
operation,
parameters: evidence.parameters,
execution: {
result: evidence.normalized_result,
rawResult: evidence.raw_result,
provider: committedProviderSchema.parse(evidence.provider),
analysisProfile: analysisProfileSchema.parse(evidence.analysis_profile),
limitations: evidence.limitations,
locations: evidence.locations,
subject:
evidence.subject === null
? null
: {
path: evidence.subject.local_path,
sha256: evidence.subject.digest.sha256,
format: evidence.subject.format,
...(evidence.subject.architecture === null
? {}
: { architecture: evidence.subject.architecture }),
},
},
};
};
@@ -7,6 +7,8 @@ import type { AnalysisProfileCommitment } from "../../domain/analysisProfile.js"
import type { AnalysisProviderSelector } from "../../contracts/providerSelection.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Result } from "../../domain/result.js";
import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import type { WorkflowSnapshotRecordInput } from "./BinarySessionRecords.js";
import type {
AnalysisOperation,
@@ -43,6 +45,10 @@ export interface BinarySessionPort
analysisProfile(
operation?: AnalysisOperation,
): AnalysisProfileCommitment | undefined;
allowsSnapshotReplay(operation: AnalysisOperation): boolean;
recordWorkflowSnapshot(
input: WorkflowSnapshotRecordInput,
): Result<null, EvidenceIntegrityError>;
openCompatibility(): Readonly<Record<string, JsonValue>>;
onAvailabilityChanged?(listener: () => void | Promise<void>): () => void;
onAnalysisSnapshotChanged?(listener: () => void | Promise<void>): () => void;
+13 -9
View File
@@ -3,6 +3,7 @@ import type { AnalysisSnapshot } from "../../domain/analysisSnapshot.js";
import type { BinaryTarget } from "../../domain/binaryTarget.js";
import type { Evidence } from "../../domain/evidence.js";
import type { EvidenceBundle } from "../../domain/evidenceBundle.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import { evidenceBundleForTarget } from "../../domain/evidenceBundle.js";
import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
@@ -26,6 +27,15 @@ export interface ActiveAnalysisBinding {
readonly profile: AnalysisProfileCommitment | null;
}
/** Validated composed-workflow payload bound to the active target and profile. */
export interface WorkflowSnapshotRecordInput {
readonly operation: AnalysisOperation;
readonly parameters: Readonly<Record<string, JsonValue>>;
readonly execution: Parameters<
AnalysisSnapshotCache["recordWorkflow"]
>[0]["execution"];
}
/** Binary snapshot owner and compatibility facade for composed investigation records. */
export abstract class BinarySessionRecords {
readonly #records: InvestigationRecords;
@@ -161,15 +171,9 @@ export abstract class BinarySessionRecords {
}
/** Retain one derived workflow result alongside its provider cache entries. */
recordWorkflowSnapshot(input: {
readonly operation: string;
readonly parameters: Readonly<
Record<string, import("../../domain/jsonValue.js").JsonValue>
>;
readonly execution: Parameters<
AnalysisSnapshotCache["recordWorkflow"]
>[0]["execution"];
}): Result<null, EvidenceIntegrityError> {
recordWorkflowSnapshot(
input: WorkflowSnapshotRecordInput,
): Result<null, EvidenceIntegrityError> {
const active = this.activeAnalysisBinding();
if (active === undefined || active.profile === null)
return err(
+21 -10
View File
@@ -393,16 +393,27 @@ const lifecycleErrorDetails = (
),
}),
};
if (
error._tag === "ProcessCaptureError" &&
error.userCategory === "cancelled"
)
return { operation: "process_capture", cleanup: "complete" };
if (
error._tag === "ProcessCaptureError" &&
error.executionFailure !== undefined
)
return { execution_failure: error.executionFailure };
if (error._tag === "ProcessCaptureError") {
const details = {
...(error.userCategory === "cancelled"
? { operation: "process_capture", cleanup: "complete" }
: {}),
...(error.cleanupReport === undefined
? {}
: { cleanup_report: jsonValueSchema.parse(error.cleanupReport) }),
...(error.executionFailure === undefined
? {}
: { execution_failure: error.executionFailure }),
...(error.partialObservation === undefined
? {}
: {
partial_observation: jsonValueSchema.parse(
error.partialObservation,
),
}),
};
return Object.keys(details).length === 0 ? undefined : details;
}
if (error instanceof BinaryTargetError)
return {
path: error.path,
+8 -8
View File
@@ -578,7 +578,7 @@ const incompleteCaptureObservationSchema = z.strictObject({
observations: incompleteProcessCaptureObservationsSchema,
});
/** Validated, non-comparable process observations attached to cleanup errors. */
/** Validated, non-comparable process observations attached to execution or cleanup errors. */
export const partialProcessCaptureObservationSchema = z
.union([
completedCaptureObservationSchema.extend(
@@ -589,15 +589,15 @@ export const partialProcessCaptureObservationSchema = z
),
])
.superRefine((partial, context) => {
if (
!Object.values(partial.cleanup).some(
({ state }) => state === "failed" || state === "unverified",
)
)
const cleanupIncomplete = Object.values(partial.cleanup).some(
({ state }) => state === "failed" || state === "unverified",
);
if (!cleanupIncomplete && partial.execution_failure === null)
context.addIssue({
code: "custom",
path: ["cleanup"],
message: "partial observations require incomplete resource cleanup",
path: ["execution_failure"],
message:
"partial observations require incomplete cleanup or an execution failure",
});
if ("observations" in partial) {
+73 -41
View File
@@ -846,6 +846,52 @@ export const resolveProcessResult = (
},
): ProcessCapture => {
const cleanupFailure = cleanupReportFailure(cleanup);
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"
? {
...capture.settlement,
cleanup_outcome: "not_required" as const,
}
: { ...capture.settlement, cleanup_outcome: "cleaned" as const };
const partialResult = partialProcessCaptureObservationSchema.safeParse({
capture: { ...captureData, settlement },
cleanup,
execution_failure: executionFailureReason ?? null,
});
if (partialResult.success) partialObservation = partialResult.data;
}
}
if (cleanupFailure !== undefined) {
const cleanupResources = Object.entries(cleanup)
.filter(
@@ -853,44 +899,6 @@ export const resolveProcessResult = (
outcome.state === "failed" || outcome.state === "unverified",
)
.map(([resource]) => resource);
const executionFailureReason =
describeProcessCaptureExecutionFailure(executionFailure);
let partialObservation: PartialProcessCaptureObservation | undefined;
if (capture !== undefined || observations !== undefined) {
const normalizedObservations =
observations === undefined || partialContext === undefined
? observations
: normalizePartialProcessObservations(observations, partialContext);
const partialPayload =
capture === undefined
? { observations: normalizedObservations }
: { capture };
const pendingCapture =
capture === undefined
? undefined
: {
...capture,
settlement: {
...capture.settlement,
cleanup_outcome: "failed" as const,
},
};
const partialResult = partialProcessCaptureObservationSchema.safeParse({
...partialPayload,
...(pendingCapture === undefined
? {}
: {
capture: Object.fromEntries(
Object.entries(pendingCapture).filter(
([key]) => key !== "cleanup",
),
),
}),
cleanup,
execution_failure: executionFailureReason ?? null,
});
if (partialResult.success) partialObservation = partialResult.data;
}
throw new ProcessCaptureError(cleanupFailure, {
cause: executionFailure,
reason: "cleanup_incomplete",
@@ -902,15 +910,39 @@ export const resolveProcessResult = (
cleanupReport: cleanup,
});
}
if (executionFailure instanceof ProcessCaptureError) throw executionFailure;
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,
});
}
if (executionFailure !== undefined) {
const executionFailureReason =
describeProcessCaptureExecutionFailure(executionFailure);
throw new ProcessCaptureError("process capture failed", {
cause: executionFailure,
reason: "capture_failed",
...(executionFailureReason === undefined
? {}
: { executionFailure: executionFailureReason }),
...(partialObservation === undefined ? {} : { partialObservation }),
cleanupReport: cleanup,
});
}
if (capture === undefined)
+102
View File
@@ -16,6 +16,7 @@ import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../domain/process/processCaptu
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { emptyProcessCapture } from "../../domain/process/processCapture.fixture.js";
import { analysisErrorProjectionSchema } from "../../contracts/errorSchemas.js";
import { processCaptureCancelled } from "./ProcessCaptureError.js";
import {
releaseProcessResources,
resolveProcessResult,
@@ -352,8 +353,20 @@ it("retains observations and both causes when process cleanup is unverifiable",
terminal_renderer: { state: "cleaned", reason: null },
temporary_root: { state: "cleaned", reason: null },
},
execution_failure: null,
}).success,
).toBe(false);
expect(
partialProcessCaptureObservationSchema.safeParse({
...partialObservation,
cleanup: {
owned_process_group: { state: "cleaned", reason: null },
terminal_renderer: { state: "cleaned", reason: null },
temporary_root: { state: "cleaned", reason: null },
},
execution_failure: "capture ended after a fixture error",
}).success,
).toBe(true);
if (!("capture" in partialObservation))
throw new Error("expected completed partial capture observations");
const partialCapture = partialObservation.capture;
@@ -392,6 +405,95 @@ it("projects execution and cleanup failures when capture never completed", () =>
});
});
it("retains completed observations when finalization fails after clean cleanup", () => {
const capture = parseProcessCapture({
...emptyProcessCapture(),
frames: [{ sequence: 0, at_ms: 0, data: "observed before finalization" }],
event_journal: [],
});
const executionFailure = new Error("final filesystem snapshot failed");
const cleanup = {
owned_process_group: { state: "cleaned" as const, reason: null },
terminal_renderer: { state: "cleaned" as const, reason: null },
temporary_root: { state: "cleaned" as const, reason: null },
};
let error: ProcessCaptureError | undefined;
try {
resolveProcessResult(capture, executionFailure, cleanup);
} catch (cause: unknown) {
if (!(cause instanceof ProcessCaptureError)) throw cause;
error = cause;
}
expect(error).toBeDefined();
if (error === undefined) throw new Error("expected capture failure");
expect(error).toMatchObject({
reason: "capture_failed",
cleanupIncomplete: false,
executionFailure: "final filesystem snapshot failed",
cleanupReport: cleanup,
});
expect(error.cause).toBe(executionFailure);
expect(error.partialObservation).toMatchObject({
capture: {
frames: [{ data: "observed before finalization" }],
settlement: { cleanup_outcome: "not_required" },
},
cleanup,
execution_failure: "final filesystem snapshot failed",
});
expect(projectAnalysisError(error)).toMatchObject({
code: "process_capture_failed",
details: {
cleanup_report: cleanup,
execution_failure: "final filesystem snapshot failed",
partial_observation: {
capture: { frames: [{ data: "observed before finalization" }] },
},
},
});
expect(
analysisErrorProjectionSchema.safeParse(projectAnalysisError(error))
.success,
).toBe(true);
});
it("preserves cancellation while projecting observations and successful cleanup", () => {
const capture = parseProcessCapture({
...emptyProcessCapture(),
frames: [{ sequence: 0, at_ms: 0, data: "observed before cancellation" }],
event_journal: [],
});
const cleanup = {
owned_process_group: { state: "cleaned" as const, reason: null },
terminal_renderer: { state: "cleaned" as const, reason: null },
temporary_root: { state: "cleaned" as const, reason: null },
};
let error: ProcessCaptureError | undefined;
try {
resolveProcessResult(capture, processCaptureCancelled(), cleanup);
} catch (cause: unknown) {
if (!(cause instanceof ProcessCaptureError)) throw cause;
error = cause;
}
expect(error).toBeDefined();
if (error === undefined) throw new Error("expected cancellation");
expect(projectAnalysisError(error)).toMatchObject({
code: "cancelled",
message: "Process capture was cancelled. Start it again when ready.",
details: {
operation: "process_capture",
cleanup: "complete",
cleanup_report: cleanup,
partial_observation: {
capture: { frames: [{ data: "observed before cancellation" }] },
},
},
});
});
it("fails closed on Windows before resolving or launching scenario paths", async () => {
const scenario = processScenarioSchema.parse({
executable: "Z:/missing/should-never-be-resolved.exe",
+8
View File
@@ -349,6 +349,14 @@ const registerBinaryAnalysisTools = ({
...analysisOptions,
analysisProfile:
session === undefined ? undefined : () => session.analysisProfile(),
allowsSnapshotReplay:
session === undefined
? undefined
: (operation) => session.allowsSnapshotReplay(operation),
recordWorkflowSnapshot:
session === undefined
? undefined
: (input) => session.recordWorkflowSnapshot(input),
});
const evidenceOptions = { logger, activeTarget, recordEvidence };
registerNativeTools(server, analysis, evidenceOptions);
+30 -23
View File
@@ -9,19 +9,19 @@ import type {
} from "@modelcontextprotocol/server";
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js";
import {
EnhancedTools,
type ValidatedEnhancedCall,
} from "../application/EnhancedTools.js";
import {
REA_WORKFLOW_PROVIDER,
workflowAnalysisProfile,
} from "../application/InvestigationProviders.js";
createWorkflowEvidence,
workflowSnapshotRecord,
} from "../application/WorkflowEvidence.js";
import { toolContract, type ToolContract } from "../contracts/toolContracts.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { UnknownRegistryError } from "../domain/unknownRegistryError.js";
import { createEvidence } from "../domain/evidence.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Logger } from "../logger.js";
import { mcpProgressReporter } from "./mcpProgress.js";
@@ -39,6 +39,14 @@ export interface EnhancedToolRegistration {
| undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
readonly recordUnknown: UnknownRegistryPort["recordUnknown"] | undefined;
readonly allowsSnapshotReplay:
| ((operation: ValidatedEnhancedCall["name"]) => boolean)
| undefined;
readonly recordWorkflowSnapshot:
| ((
input: Parameters<BinarySessionPort["recordWorkflowSnapshot"]>[0],
) => ReturnType<BinarySessionPort["recordWorkflowSnapshot"]>)
| undefined;
}
/** Register composed workflows against the same port as direct bridge tools. */
@@ -235,28 +243,27 @@ const executeEnhancedTool = async (
terminal: true,
});
if (result.ok) {
const upstreamProfile = registration.analysisProfile?.();
const evidence = createEvidence(
registration.activeTarget?.(),
REA_WORKFLOW_PROVIDER,
{
operation: name,
parameters,
result: result.value,
...(upstreamProfile === undefined
? {}
: {
analysisProfile: workflowAnalysisProfile(upstreamProfile),
}),
confidence: "derived",
limitations: [
"Derived by an REA workflow from one or more provider observations.",
],
},
);
const evidence = createWorkflowEvidence({
target: registration.activeTarget?.(),
operation: name,
parameters,
result: result.value,
upstreamProfile: registration.analysisProfile?.(),
});
const recorded = registration.recordEvidence?.(evidence);
if (recorded !== undefined && !recorded.ok)
return toCallToolResult(recorded, contract);
if (
name !== "trace_native_ui_action" &&
registration.allowsSnapshotReplay?.(name) === true
) {
const workflowRecord = workflowSnapshotRecord(evidence, name);
if (workflowRecord !== undefined) {
const snapshot = registration.recordWorkflowSnapshot?.(workflowRecord);
if (snapshot !== undefined && !snapshot.ok)
return toCallToolResult(snapshot, contract);
}
}
const unknowns = recordWorkflowUnknowns({
name,
result: result.value,