Files
rea/src/application/binary/BinarySessionOpen.ts
T
morluto 52bca6de41 fix(native): retain value trace source evidence (#8384)
* fix(native): retain value trace source evidence

* fix(native): build trace error evidence only on failure

* test(mcp): expect unowned value trace refusal

* test(mcp): avoid freezing trace error wording

* test(native): keep value-trace stop coverage with source evidence

Main's stop and continuation cases now meet the trace's evidence-owner
precondition: direct calls supply a source id, and a completed MCP trace
runs in a session that can retain it.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-11-05 00:19:50 +08:00

213 lines
7.6 KiB
TypeScript

import type { EspFlashSelection } from "../../domain/firmware/espFlashLocation.js";
import type { ExecutableFormatHint } from "../../domain/dosCom.js";
import type {
BinaryArchitecture,
BinaryTarget,
} from "../../domain/binaryTargetTypes.js";
import { artifactTargetSelectedPath } from "../../domain/binaryTargetTypes.js";
import type { AnalysisProviderSelector } from "../../domain/providerSelection.js";
import type { AnalysisProfileCommitment } from "../../domain/analysisProfile.js";
import {
snapshotBindingMismatch,
snapshotMatchesTarget,
snapshotTarget,
type SnapshotBindingMismatch,
type AnalysisSnapshot,
} from "../../domain/analysisSnapshot.js";
import { parseBinaryTarget } from "../BinaryTargetResolver.js";
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import {
EvidenceIntegrityError,
AnalysisSnapshotMismatchError,
} from "../../domain/evidenceErrors.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { err, type Result } from "../../domain/result.js";
import type { SessionProviderRoute } from "./SessionProviderRouter.js";
import {
profilelessSnapshotMismatch,
profilelessNativeDispatchProfile,
} from "./ProfilelessNativeWorkflowSnapshot.js";
import { SessionProviderRouter } from "./SessionProviderRouter.js";
/** Read a staged snapshot once the open holds its place in the session order. */
export type AnalysisSnapshotLoader = () => Promise<
Result<AnalysisSnapshot, AnalysisError>
>;
export interface BinarySessionOpenOptions {
readonly signal?: AbortSignal;
readonly targetKind?: BinaryTarget["kind"];
readonly formatHint?: ExecutableFormatHint;
readonly architecture?: BinaryArchitecture;
readonly entryPoint?: string;
/** Inputs for format=esp-flash-image. */
readonly espFlash?: EspFlashSelection;
readonly snapshot?: AnalysisSnapshot;
/**
* Load the snapshot inside the open's turn instead of before it, so calls
* dispatched after the open cannot overtake its file read.
*/
readonly loadSnapshot?: AnalysisSnapshotLoader;
readonly providerId?: AnalysisProviderSelector;
}
interface CurrentOpenBinding {
readonly target: BinaryTarget;
readonly profile: AnalysisProfileCommitment | null;
readonly route: SessionProviderRoute;
}
export interface ResolvedSessionOpen {
readonly target: BinaryTarget;
readonly route: SessionProviderRoute;
readonly sameTarget: boolean;
}
interface ResolveSessionOpenInput {
readonly resources: ArtifactResourceScope;
readonly router: SessionProviderRouter;
readonly current: CurrentOpenBinding | undefined;
readonly path: string;
readonly options: BinarySessionOpenOptions;
readonly stagedSnapshotMismatch: (
target: BinaryTarget,
profile: AnalysisProfileCommitment | null,
) => SnapshotBindingMismatch | undefined;
}
interface ResolveSessionTargetInput {
readonly router: SessionProviderRouter;
readonly current: CurrentOpenBinding | undefined;
readonly target: BinaryTarget;
readonly options: BinarySessionOpenOptions;
readonly stagedSnapshotMismatch: (
target: BinaryTarget,
profile: AnalysisProfileCommitment | null,
) => SnapshotBindingMismatch | undefined;
}
/** Parse a target, resolve its provider route, and validate snapshot binding. */
export const resolveSessionOpen = async (
input: ResolveSessionOpenInput,
): Promise<Result<ResolvedSessionOpen, AnalysisError>> => {
const { path, options } = input;
const parsed = await parseBinaryTarget(path, {
resources: input.resources,
...(options.targetKind === undefined
? {}
: { targetKind: options.targetKind }),
...(options.formatHint === undefined
? {}
: { formatHint: options.formatHint }),
...(options.architecture === undefined
? {}
: { architecture: options.architecture }),
...(options.entryPoint === undefined
? {}
: { entryPoint: options.entryPoint }),
...(options.espFlash === undefined ? {} : { espFlash: options.espFlash }),
...(options.signal === undefined ? {} : { signal: options.signal }),
});
if (!parsed.ok) return parsed;
return resolveSessionTarget({ ...input, target: parsed.value });
};
/** Resolve a known target's provider route and validate snapshot binding. */
export const resolveSessionTarget = async (
input: ResolveSessionTargetInput,
): Promise<Result<ResolvedSessionOpen, AnalysisError>> => {
const { router, current, target, options } = input;
const sameTarget = sameSessionTarget(current?.target, target);
const resolvedRoute =
sameTarget && options.providerId === undefined && current !== undefined
? ({ ok: true, value: current.route } as const)
: await router.resolve(target, options.providerId, options.signal);
if (!resolvedRoute.ok) return resolvedRoute;
return validateResolvedSessionTarget({
...input,
route: resolvedRoute.value,
});
};
/** Revalidate a previewed route against the current session and snapshot binding. */
export const validateResolvedSessionTarget = (
input: Omit<ResolveSessionTargetInput, "router"> & {
readonly route: SessionProviderRoute;
},
): Result<ResolvedSessionOpen, AnalysisError> => {
const { current, target, route, options, stagedSnapshotMismatch } = input;
const sameTarget = sameSessionTarget(current?.target, target);
const snapshotError = validateSnapshot({
snapshot: options.snapshot,
target,
profile: route.profile,
profilelessWorkflowProfile: profilelessNativeDispatchProfile(route),
current,
stagedSnapshotMismatch,
});
if (snapshotError !== undefined) return err(snapshotError);
return { ok: true, value: { target, route, sameTarget } };
};
const sameSessionTarget = (
current: BinaryTarget | undefined,
target: BinaryTarget,
): boolean =>
current !== undefined &&
current.path === target.path &&
// Native admission is bound to the requested path, not just its realpath.
(current.sourcePath ?? current.path) === (target.sourcePath ?? target.path) &&
// Artifact name hints and companions depend on the selected spelling.
artifactTargetSelectedPath(current) === artifactTargetSelectedPath(target) &&
snapshotMatchesTarget(snapshotTarget(current), target);
interface ValidateSnapshotInput {
readonly snapshot: AnalysisSnapshot | undefined;
readonly target: BinaryTarget;
readonly profile: AnalysisProfileCommitment | null;
readonly profilelessWorkflowProfile: AnalysisProfileCommitment | undefined;
readonly current: CurrentOpenBinding | undefined;
readonly stagedSnapshotMismatch: (
target: BinaryTarget,
profile: AnalysisProfileCommitment | null,
) => SnapshotBindingMismatch | undefined;
}
const validateSnapshot = ({
snapshot,
target,
profile,
profilelessWorkflowProfile,
current,
stagedSnapshotMismatch,
}: ValidateSnapshotInput): EvidenceIntegrityError | undefined => {
if (snapshot !== undefined) {
const mismatch =
profile === null
? profilelessSnapshotMismatch(
snapshot,
target,
profilelessWorkflowProfile,
)
: snapshotBindingMismatch(snapshot, target, profile);
if (mismatch !== undefined)
return new AnalysisSnapshotMismatchError(
"Analysis snapshot target, provider, or analysis profile does not match the requested binary",
mismatch,
);
}
const stagedMismatch =
current === undefined
? stagedSnapshotMismatch(
target,
profile ?? profilelessWorkflowProfile ?? null,
)
: undefined;
if (stagedMismatch !== undefined)
return new AnalysisSnapshotMismatchError(
"Analysis snapshot does not match the staged target, provider, or analysis profile",
stagedMismatch,
);
return undefined;
};