fix(native): preserve caller-selected paths in binary sessions (#12102)

* fix(mcp): preserve caller-selected binary session paths

* test(mcp): verify caller paths across snapshot replay

* test(mcp): separate session alias and snapshot replay coverage

* fix(evidence): preserve selected paths across binary workflows

* fix(evidence): retain authentication admission for caller aliases
This commit is contained in:
morluto authored and GitHub committed 2026-11-18 18:27:29 -05:00
1 parent c3531b9f1c
commit e09d6273a1
17 files changed
+469 -109

No files matched your search

+18 -2
View File
@@ -1259,9 +1259,25 @@ An unverified release may still be usable; the optional remediation preserves
the caller's choice. Omission means verification was not reported. Target-free
discovery does not probe a version solely to populate this fact.
`open_binary` and `binary_session` report the inspected file in `path` and its
SHA-256. When the selected spelling differs, `caller_input_path` carries that
spelling verbatim. An alias that changes only this spelling, such as a second
POSIX symlink to the same executable, refreshes the selection and can reuse the
live analysis engine. Reuse still requires the same provider profile, source
admission path, and artifact selection and companions. Use the canonical `path`
for an explicit provider `document` selector when that provider identifies its
document by path.
Inline provider and composed workflow Evidence for that file includes the
current `caller_input_path` when the selection differs from the canonical path. The alias is outside the
Evidence ID and snapshot binding. Ordinary recording of a duplicate retains the
first record, including its selection metadata, so later inline responses may
carry a different alias from the bundled record with the same ID. The bundle
records retained observations and does not log every target selection.
When an admitted `open_binary` attempt fails, `error.details.selection_at_failure`
records the canonical binary path and SHA-256, resource root (including its
caller-selected path), or absence of selection at
records the canonical binary path and SHA-256 with its differing caller path,
a resource root with its caller-selected path, or absence of selection at
the end of that serialized attempt. This is a past observation: a queued or
later operation may already have changed the selection. No selection does not
establish that cleanup is complete. Call `binary_session` for current state
+11 -2
View File
@@ -213,6 +213,7 @@ export const parseBinaryTarget = async (
{
path,
sourcePath,
callerInputPath: admitted.data,
selectedPath: candidate,
classifiedAs,
...bundle,
@@ -293,6 +294,7 @@ const readOpenedBinaryTarget = async (
selected: {
readonly path: string;
readonly sourcePath: string;
readonly callerInputPath: string;
readonly selectedPath: string;
/** Spelling whose name supplies format hints: the selected file, or a bundle's executable. */
readonly classifiedAs: string;
@@ -301,13 +303,20 @@ const readOpenedBinaryTarget = async (
options: BinaryTargetResolverOptions,
): Promise<TargetResolution> => {
const { handle, initial: metadata } = source;
const { path, sourcePath, selectedPath, classifiedAs, bundleInfoPlist } =
selected;
const {
path,
sourcePath,
callerInputPath,
selectedPath,
classifiedAs,
bundleInfoPlist,
} = selected;
const bundle = bundleInfoPlist === undefined ? {} : { bundleInfoPlist };
// Every admitted target shares one identity; routes add their own facts.
const identity = async () => ({
path,
sourcePath,
...(callerInputPath === path ? {} : { callerInputPath }),
...bundle,
sha256: await sha256Handle(source, path, signal),
});
+9 -20
View File
@@ -57,30 +57,19 @@ export const executeFunctionAnalysisEvidence = async (
: {}),
};
const dossier = parseFunctionDossier(execution.value.result);
const evidence = createAnalysisExecutionEvidence(
"analyze_function",
arguments_,
dossier.ok ? { ...observation, result: dossier.value } : observation,
"observed",
{ callerTarget: target },
);
if (!dossier.ok) {
dossier.error.retainPartialObservation(
createAnalysisExecutionEvidence(
"analyze_function",
arguments_,
observation,
"observed",
),
);
dossier.error.retainPartialObservation(evidence);
return withEvidenceSources(dossier, sources);
}
return withEvidenceSources(
completeProviderEvidence(
createAnalysisExecutionEvidence(
"analyze_function",
arguments_,
{
...observation,
result: dossier.value,
},
"observed",
),
options?.signal,
),
completeProviderEvidence(evidence, options?.signal),
sources,
);
};
+30 -25
View File
@@ -25,7 +25,6 @@ import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import {
createEvidence,
evidenceEnvelopeForAdmission,
evidenceSubjectTarget,
type Evidence,
type EvidenceLocation,
} from "../domain/evidence.js";
@@ -248,30 +247,35 @@ const workflowSubject = (target: BinaryTarget | undefined) =>
export const createWorkflowEvidence = (
input: WorkflowEvidenceInput,
): Evidence =>
createEvidence(workflowSubject(input.target), REA_WORKFLOW_PROVIDER, {
operation: input.operation,
parameters: input.parameters,
result: input.result,
...(input.upstreamProfile === undefined
? {}
: {
analysisProfile: workflowAnalysisProfile(
input.upstreamProfile,
input.operation,
),
}),
confidence: "derived",
...(input.upstreamEvidenceLinks === undefined
? {}
: { evidenceLinks: input.upstreamEvidenceLinks }),
limitations: [
...workflowLimitations(input.operation),
...input.upstreamLimitations,
],
...(input.operation === "batch_decompile"
? { locations: batchProcedureLocations(input.result) }
: {}),
});
createEvidence(
workflowSubject(input.target),
REA_WORKFLOW_PROVIDER,
{
operation: input.operation,
parameters: input.parameters,
result: input.result,
...(input.upstreamProfile === undefined
? {}
: {
analysisProfile: workflowAnalysisProfile(
input.upstreamProfile,
input.operation,
),
}),
confidence: "derived",
...(input.upstreamEvidenceLinks === undefined
? {}
: { evidenceLinks: input.upstreamEvidenceLinks }),
limitations: [
...workflowLimitations(input.operation),
...input.upstreamLimitations,
],
...(input.operation === "batch_decompile"
? { locations: batchProcedureLocations(input.result) }
: {}),
},
{ callerTarget: input.target },
);
const admitWorkflowRecovery = (
observation: ComposedWorkflowObservation,
@@ -325,6 +329,7 @@ const admitWorkflowRecovery = (
locations: [],
evidenceLinks: [],
},
evidenceInput.target,
);
const additional = estimateJsonStorage([
observation.result,
+19 -5
View File
@@ -382,6 +382,9 @@ export class BinarySession
const imported = this.importAnalysisSnapshot(options.snapshot);
if (!imported.ok) return imported;
}
// The same bytes can be selected through a different spelling without retiring the engine.
if (retained.target.callerInputPath !== target.callerInputPath)
this.#active = { ...retained, target };
return ok(target);
}
@@ -541,6 +544,9 @@ export class BinarySession
kind: "binary",
path: this.#active.target.path,
sha256: this.#active.target.sha256,
...(this.#active.target.callerInputPath === undefined
? {}
: { caller_input_path: this.#active.target.callerInputPath }),
};
if (this.#activeBundleResources !== undefined)
return {
@@ -1468,12 +1474,13 @@ export class BinarySession
const execution = { ...result.value, subject: null };
return ok(execution);
}
const sessionBinding = this.#active;
const prepared = prepareSessionExecution({
active: this.#active,
active: sessionBinding,
operation: name,
parameters: arguments_,
snapshotContext: options?.snapshotContext,
nativeSourceAdmitted: this.#active?.nativeSourceAdmitted === true,
nativeSourceAdmitted: sessionBinding?.nativeSourceAdmitted === true,
isOperationAvailable: (operation) => this.#currentlyAvailable(operation),
isOperationAdvertised: options?.isOperationAdvertised,
unboundOperationError: (operation, route) =>
@@ -1510,12 +1517,14 @@ export class BinarySession
: profiled;
// A successful Ghidra operation proves this client's native source snapshot
// was admitted; a composite health response and parsed path do not.
const currentBinding = this.#active;
if (
execution.ok &&
capability.provider.id === "ghidra" &&
this.#active === active
currentBinding !== undefined &&
currentBinding.runId === sessionBinding?.runId
)
this.#active.nativeSourceAdmitted = true;
currentBinding.nativeSourceAdmitted = true;
if (
this.#runtimeAvailability.observe(
dispatch,
@@ -1571,7 +1580,10 @@ export class BinarySession
name,
arguments_,
evidenceExecution,
this.admitRecoveryObservation.bind(this),
{
callerTarget: active.target,
admit: this.admitRecoveryObservation.bind(this),
},
);
if (!admitted.ok) return admitted;
const evidence = createAnalysisExecutionEvidence(
@@ -1579,6 +1591,7 @@ export class BinarySession
arguments_,
evidenceExecution,
"observed",
{ callerTarget: active.target },
);
const recorded = this.recordEvidence(evidence);
if (!recorded.ok) {
@@ -1593,6 +1606,7 @@ export class BinarySession
: bindSessionEvidenceExecution(
{ ...execution.value, evidenceId: evidence.evidence_id },
authenticated,
active.target.callerInputPath,
);
if (cacheable && execution.value.cachePolicy !== "live")
this.recordSnapshot({
+6 -1
View File
@@ -33,7 +33,12 @@ import type { SavedAnalysisSnapshot } from "../../domain/savedAnalysisSnapshot.j
/** Selection observed at the end of one serialized open attempt. */
export type OpenSelectionReceipt =
| { readonly kind: "binary"; readonly path: string; readonly sha256: string }
| {
readonly kind: "binary";
readonly path: string;
readonly sha256: string;
readonly caller_input_path?: string;
}
| {
readonly kind: "resources";
readonly path: string;
@@ -6,6 +6,9 @@ import { liveBinaryTargetSummarySchema } from "../../domain/liveBinaryTargetSumm
export const binaryTargetSummary = (target: BinaryTarget) =>
liveBinaryTargetSummarySchema.parse({
path: target.path,
...(target.callerInputPath === undefined
? {}
: { caller_input_path: target.callerInputPath }),
format: target.format,
kind: target.kind,
sha256: target.sha256,
+11 -9
View File
@@ -1,7 +1,9 @@
import { evidenceSubjectDisplay } from "../../domain/evidence.js";
import {
evidenceSubjectDisplay,
type Evidence,
} from "../../domain/evidence.js";
import { basename } from "node:path";
import type { AnalysisExecution } from "../../ports/AnalysisProvider.js";
import type { Evidence } from "../../domain/evidence.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import { equalJsonText } from "../../domain/jsonSerialization.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
@@ -18,11 +20,12 @@ const issued = new WeakMap<AnalysisExecution, Evidence>();
export const bindSessionEvidenceExecution = (
execution: AnalysisExecution,
evidence: Evidence,
callerInputPath: string | undefined,
): AnalysisExecution => {
if (
(execution.sourceEvidence !== undefined &&
execution.sourceEvidence.length > 0) ||
evidence.caller_input_path !== undefined
evidence.caller_input_path !== callerInputPath
)
return execution;
// Semantic IDs intentionally omit display paths and names. A duplicate in
@@ -113,12 +116,10 @@ export const completedOperationEvidence = (
subject:
execution.subject === undefined ? options.target : execution.subject,
};
const admitted = admitCompletedAnalysis(
operation,
parameters,
observation,
options.admitRecovery,
);
const admitted = admitCompletedAnalysis(operation, parameters, observation, {
callerTarget: options.target,
admit: options.admitRecovery,
});
if (!admitted.ok) return admitted;
return ok(
createAnalysisExecutionEvidence(
@@ -126,6 +127,7 @@ export const completedOperationEvidence = (
parameters,
observation,
"observed",
{ callerTarget: options.target },
),
);
};
@@ -14,6 +14,9 @@ import {
} from "../../domain/residualUnknown.js";
import { createAnalysisExecutionEvidence } from "../../domain/analysisObservation.js";
import { estimateJsonStorage } from "../JsonAuthenticationHeadroom.js";
import { createWorkflowEvidence } from "../WorkflowEvidence.js";
import { completedOperationEvidence } from "../binary/SessionEvidenceReuse.js";
import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
import { ok } from "../../domain/result.js";
import { admitCompletedAnalysis } from "./admitCompletedAnalysis.js";
import { recordEvidenceSources } from "./recordEvidenceSources.js";
@@ -97,6 +100,64 @@ it("returns only authenticated Evidence when a completed record exceeds retentio
expect(noHeadroom.error.partialObservation).toBeUndefined();
});
it("applies authentication admission to a fresh caller-selected alias", () => {
const target: BinaryTarget = {
kind: "executable",
format: "mach-o",
architecture: "arm64",
availableArchitectures: ["arm64"],
path: "/fixture/target",
callerInputPath: "/fixture/alias",
sha256: "a".repeat(64),
};
const workflow = createWorkflowEvidence({
target,
operation: "binary_overview",
parameters: {},
result: { value: 1 },
upstreamProfile: undefined,
upstreamLimitations: [],
});
const primitive = completedOperationEvidence(
"address_name",
{},
{
result: { value: 1 },
rawResult: null,
provider,
locations: [],
limitations: [],
},
{
target,
admitRecovery: (input) => {
expect(input).toMatchObject({
caller_input_path: target.callerInputPath,
});
return ok(undefined);
},
},
);
if (!primitive.ok) throw primitive.error;
const constrained = new InvestigationRecords({
availableAuthenticationBytes: () => 0,
});
for (const evidence of [workflow, primitive.value]) {
expect(evidence.caller_input_path).toBe(target.callerInputPath);
const refused = constrained.recordEvidence(evidence);
if (refused.ok)
throw new Error(
`Bypassed authentication admission: ${evidence.operation}`,
);
expect(refused.error._tag).toBe("AnalysisResourceConstraintError");
expect(refused.error.partialObservation).toBeUndefined();
expect(constrained.hasEvidence(evidence.evidence_id)).toBe(false);
expect(new InvestigationRecords().recordEvidence(evidence)).toEqual(
ok("added"),
);
}
});
it("admits exact capacity, rejects cumulative growth atomically, and releases accounting on clear", () => {
const first = observe(1);
const second = observe(2);
@@ -374,11 +435,8 @@ it("accounts for the generated subject limitation before admitting a subjectless
subject: null,
} as const;
let admitted: ReturnType<typeof estimateJsonStorage> | undefined;
const result = admitCompletedAnalysis(
"health",
{},
observation,
(input, _operation, additional) => {
const result = admitCompletedAnalysis("health", {}, observation, {
admit: (input, _operation, additional) => {
const estimate = estimateJsonStorage(input);
admitted = {
valueBytes: estimate.valueBytes + additional.valueBytes,
@@ -387,7 +445,7 @@ it("accounts for the generated subject limitation before admitting a subjectless
};
return ok(undefined);
},
);
});
expect(result.ok).toBe(true);
const actual = estimateJsonStorage(
createAnalysisExecutionEvidence("health", {}, observation, "observed"),
@@ -3,6 +3,7 @@ import {
type AnalysisObservation,
} from "../../domain/analysisObservation.js";
import { estimateJsonArrayScalarEntry } from "../JsonAuthenticationHeadroom.js";
import type { EvidenceCreationOptions } from "../../domain/evidence.js";
import {
admitInvestigationAuthentication,
type RecoveryAdmission,
@@ -13,14 +14,20 @@ export const admitCompletedAnalysis = (
operation: string,
parameters: unknown,
observation: AnalysisObservation,
admit: RecoveryAdmission = (input, name, additional) =>
admitInvestigationAuthentication(input, name, {}, additional),
{
callerTarget,
admit = (input, name, additional) =>
admitInvestigationAuthentication(input, name, {}, additional),
}: {
readonly callerTarget?: EvidenceCreationOptions["callerTarget"];
readonly admit?: RecoveryAdmission | undefined;
} = {},
) => {
const envelope = analysisExecutionEnvelopeForAdmission(
operation,
parameters,
observation,
"observed",
callerTarget,
);
let valueBytes = 0;
let serializedUtf16Bytes = 0;
+1 -6
View File
@@ -102,12 +102,7 @@ export class WasmArtifactService {
if (!inspected.ok) return inspected;
const execution = inspected.value;
const admission = requireAuthenticationHeadroom(
analysisExecutionEnvelopeForAdmission(
OPERATION,
input.value,
execution,
"observed",
),
analysisExecutionEnvelopeForAdmission(OPERATION, input.value, execution),
{
operation: OPERATION,
path: input.value.path,
+3 -2
View File
@@ -67,12 +67,13 @@ export const analysisExecutionEnvelopeForAdmission = (
operation: string,
input: unknown,
execution: AnalysisObservation,
confidence: "observed" | "derived",
callerTarget?: EvidenceCreationOptions["callerTarget"],
) =>
evidenceEnvelopeForAdmission(
execution.subject ?? unknownTarget("not-observed"),
execution.provider,
analysisExecutionEvidenceInput(operation, input, execution, confidence),
analysisExecutionEvidenceInput(operation, input, execution, "observed"),
callerTarget,
);
/** Commit identical facts on success and when retaining a completed observation after cancellation. */
+2
View File
@@ -164,6 +164,8 @@ export interface UniversalMachOSliceIdentity extends UniversalMachOSlice {
interface BinaryTargetIdentity {
readonly path: string;
readonly sourcePath?: string;
/** Verbatim selected spelling when it differs from the inspected file path. */
readonly callerInputPath?: string;
/** Selected artifact spelling determines name-based format hints and external companions. */
readonly artifactSelectedPath?: string;
/** Info.plist of the app bundle the target was resolved from. */
+21 -1
View File
@@ -529,6 +529,8 @@ const rememberImmutableEvidence = (evidence: Evidence): Evidence => {
/** Ownership policy for the freshly parsed Evidence snapshot. */
export interface EvidenceCreationOptions {
readonly immutable?: boolean;
/** Selected spelling is recorded only when this target matches the subject. */
readonly callerTarget?: BinaryTarget | null | undefined;
}
/** Admit payloads into deterministic Evidence bound to an immutable artifact subject. */
@@ -542,6 +544,7 @@ export const createEvidence = (
target,
provider,
observation,
options?.callerTarget,
);
const evidence = {
...normalized,
@@ -590,9 +593,20 @@ export const evidenceEnvelopeForAdmission = (
target: EvidenceSubjectInput,
provider: EvidenceProvider,
observation: EvidenceObservationInput,
callerTarget?: EvidenceCreationOptions["callerTarget"],
) => {
const subject = evidenceSubject(target);
const callerInputPath =
callerTarget?.callerInputPath !== undefined &&
isFileSubject(subject) &&
subject.local_path === callerTarget.path &&
sameTargetIdentity(subject.identity, binaryTargetIdentity(callerTarget))
? callerTarget.callerInputPath
: undefined;
return {
...(callerInputPath === undefined
? {}
: { caller_input_path: callerInputPath }),
evidence_id: `ev_${"0".repeat(64)}`,
evidence_format: EVIDENCE_FORMAT_REVISION,
subject,
@@ -629,8 +643,14 @@ const normalizeEvidenceObservation = (
target: EvidenceSubjectInput,
provider: EvidenceProvider,
observation: EvidenceObservationInput,
callerTarget?: EvidenceCreationOptions["callerTarget"],
) => {
const envelope = evidenceEnvelopeForAdmission(target, provider, observation);
const envelope = evidenceEnvelopeForAdmission(
target,
provider,
observation,
callerTarget,
);
const sharedResult =
typeof observation.result === "object" &&
observation.result !== null &&
+10 -1
View File
@@ -6,6 +6,7 @@ import {
RAW_ONLY_ARCHITECTURES,
} from "./binaryTargetTypes.js";
import { digestSchema } from "./digests.js";
import { localPathStringSchema } from "./localPath.js";
import {
binaryArchitectureSchema,
rawBinaryEntryPointSchema,
@@ -16,7 +17,15 @@ const architectureSchema = z.enum(BINARY_ARCHITECTURES);
const headerArchitectureSchema = architectureSchema.exclude(
HEADER_ARCHITECTURE_EXCLUSIONS,
);
const identity = { path: z.string(), sha256: digestSchema };
const identity = {
path: z.string(),
sha256: digestSchema,
caller_input_path: localPathStringSchema
.exactOptional()
.describe(
"Verbatim selected path when it differs from the inspected file path.",
),
};
const executable = { ...identity, kind: z.literal("executable") };
/** Live target classifications; historical Evidence and snapshots retain their own admission. */
@@ -43,8 +43,7 @@ import { mcpTest } from "../../support/mcp/mcpFixture.js";
*
* KNOWN_DIFFERENCES records how main differs today. The W2 invoke path
* removes them; when a change removes one, delete its entry. An entry never
* grows. The CLI-only `caller_input_path` is the declared exception: it is
* checked to carry the caller's spelling, then left out of the comparison.
* grows. Both adapters must retain the exact caller-selected spelling.
*
* Simulated providers return the smallest result each contract admits, so
* this checks adapter composition, not real provider behavior.
@@ -276,37 +275,36 @@ const isObject = (
): value is Readonly<Record<string, JsonValue>> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const evidenceOutcome = (value: unknown, target: string): Outcome => {
if (!isObject(value)) throw new Error("Expected an Evidence response object");
expect(value.caller_input_path).toBe(target);
expect(value.caller_input_paths).toBeUndefined();
return { outcome: "evidence", evidence: value };
};
const cliOutcome = (
served: { readonly stdout: string; readonly exitCode: number },
target: string,
): Outcome => {
const value = parseJson(served.stdout);
if (served.exitCode !== 0) return { outcome: "failure", failure: value };
if (!isObject(value)) throw new Error(`CLI printed ${served.stdout}`);
// The CLI keeps the caller's spelling; MCP selected the target on open.
const {
caller_input_path: callerInputPath,
caller_input_paths: callerInputPaths,
...evidence
} = value;
expect(callerInputPath).toBe(target);
expect(callerInputPaths).toBeUndefined();
return { outcome: "evidence", evidence };
return served.exitCode !== 0
? { outcome: "failure", failure: value }
: evidenceOutcome(value, target);
};
const mcpOutcome = (called: {
readonly isError?: unknown;
readonly structuredContent?: unknown;
readonly content?: unknown;
}): Outcome => {
const mcpOutcome = (
called: {
readonly isError?: unknown;
readonly structuredContent?: unknown;
readonly content?: unknown;
},
target: string,
): Outcome => {
if (called.isError !== true)
return evidenceOutcome(called.structuredContent, target);
const [first] = Array.isArray(called.content) ? called.content : [];
const text =
isObject(first) && typeof first.text === "string" ? first.text : "";
if (called.isError !== true)
return {
outcome: "evidence",
evidence: called.structuredContent as JsonValue,
};
const value = parseJson(text);
return {
outcome: "failure",
@@ -349,7 +347,7 @@ mcpTest.for(
async ([name, { contract, description }], { mcp }) => {
const directory = await createTestTempDirectory("rea-adapter-parity-");
await writeFile(join(directory, "fixture"), minimalMachoImage(64));
// A non-canonical spelling shows whose path each adapter records.
// Both adapters select the same file through the same noncanonical spelling.
const target = `${directory}/./fixture`;
const input = callInput(contract, description, directory, target);
const cliResult = cliOutcome(
@@ -377,6 +375,7 @@ mcpTest.for(
expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true);
const mcpResult = mcpOutcome(
await client.callTool({ name, arguments: input }),
target,
);
const found = differences(
cliResult as unknown as JsonValue,
+228 -2
View File
@@ -3,7 +3,7 @@ import {
withCanonicalOutputSchema,
} from "../../fixtures/canonicalOutputSchema.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { writeFile } from "node:fs/promises";
import { realpath, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -12,10 +12,11 @@ import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it, vi } from "vitest";
import { z } from "zod";
import { jsonObjectSchema } from "../../../src/domain/jsonValue.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { sha256Hex } from "../../../src/kernel/sha256Hex.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { phaseGate } from "../../support/lifecycleHarness.js";
import { phaseArrival, phaseGate } from "../../support/lifecycleHarness.js";
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
import {
@@ -111,6 +112,231 @@ it("delivers provider-owned diagnostic keys without narrowing their JSON facts",
expect(JSON.parse(text.text)).toEqual(response.structuredContent);
});
const createAliasedTargetMcp = async (beforeLookup?: () => Promise<void>) => {
const directory = await createTestTempDirectory("rea-session-aliases-");
const physical = join(directory, "fixture.com");
const bytes = Buffer.from([0xb8, 0, 0x4c, 0xcd, 0x21]);
const digest = sha256Hex(bytes);
await writeFile(physical, bytes);
const canonical = await realpath(physical);
const firstAlias = join(directory, "first");
const secondAlias = join(directory, "second");
await Promise.all([
symlink(canonical, firstAlias),
symlink(canonical, secondAlias),
]);
const starts: string[] = [];
const provider = candidate("alpha", starts);
const session = composeBinarySession(
new AnalysisProviderRegistry([
{
...provider,
createClient: (...args) => {
const child = provider.createClient(...args);
return {
...child,
execute: async (operation, ...parameters) => {
if (operation === "address_name") await beforeLookup?.();
return child.execute(operation, ...parameters);
},
};
},
},
]),
);
const server = createServer(
{ kind: "session", session },
{ logger: silentLogger },
);
const client = new Client(
{ name: "target-aliases", version: "1" },
{ jsonSchemaValidator: createMcpSchemaValidation() },
);
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, { close: () => session.close() });
await server.connect(serverTransport);
await client.connect(clientTransport);
const tools = new Map(
(await client.listTools()).tools.map((tool) => [tool.name, tool]),
);
const call = (name: string, input: Record<string, unknown> = {}) => {
const definition = tools.get(name);
if (definition === undefined) throw new Error(`Missing tool ${name}`);
return client.callTool(
{ name, arguments: input },
{
toolDefinition: withCanonicalOutputSchema(definition),
},
);
};
const open = (path: string) =>
call("open_binary", { path, format: "dos-com" });
const current = async () => structured(await call("binary_session")).result;
const observation = async (document?: string) =>
parseEvidence(
structured(
await call("address_name", {
address: "0x100",
...(document === undefined ? {} : { document }),
}),
),
);
const selected = (path: string) => ({
path: canonical,
sha256: digest,
caller_input_path: path,
});
return {
directory,
canonical,
digest,
firstAlias,
secondAlias,
session,
starts,
call,
open,
current,
observation,
selected,
};
};
it.skipIf(process.platform === "win32")(
"keeps caller-selected aliases separate from native session and Evidence identity",
async () => {
const firstDispatch = phaseGate();
const {
directory,
canonical,
digest,
firstAlias,
secondAlias,
session,
starts,
call,
open,
current,
observation,
selected,
} = await createAliasedTargetMcp(() => firstDispatch.hold());
expect(structured(await open(firstAlias)).result).toMatchObject(
selected(firstAlias),
);
const firstStatus = await current();
expect(firstStatus).toMatchObject(selected(firstAlias));
const reopening = phaseArrival();
const openTarget = session.open.bind(session);
const openSpy = vi.spyOn(session, "open").mockImplementation((...args) => {
const opened = openTarget(...args);
reopening.arrive();
return opened;
});
const inFlight = observation();
let secondOpen: Promise<CallToolResult> | undefined;
try {
await firstDispatch.reached(inFlight, "first-alias analysis dispatch");
secondOpen = open(secondAlias);
await reopening.reached(secondOpen, "second-alias open queued");
expect(await current()).toMatchObject(selected(firstAlias));
} finally {
firstDispatch.release();
await Promise.allSettled([inFlight, secondOpen]);
openSpy.mockRestore();
}
const first = await inFlight;
expect(first).toMatchObject({
caller_input_path: firstAlias,
subject: { local_path: canonical, identity: { sha256: digest } },
});
if (secondOpen === undefined) throw new Error("Expected an alias reopen");
expect(structured(await secondOpen).result).toMatchObject(
selected(secondAlias),
);
const secondStatus = await current();
expect(secondStatus).toMatchObject(selected(secondAlias));
const firstRun = z
.object({ analysis_run: z.object({ run_id: z.string() }) })
.parse(firstStatus).analysis_run;
expect(secondStatus).toMatchObject({ analysis_run: firstRun });
expect(starts).toEqual(["alpha"]);
const second = await observation();
expect(second).toMatchObject({
evidence_id: first.evidence_id,
caller_input_path: secondAlias,
subject: first.subject,
});
const rejected = await open(join(directory, "missing"));
expect(parseMcpToolError(rejected).error.details).toMatchObject({
selection_at_failure: selected(secondAlias),
target_at_open_completion: selected(secondAlias),
});
expect(await current()).toMatchObject(selected(secondAlias));
expect(
structured(await call("get_evidence_bundle", { detail: "complete" }))
.result,
).toMatchObject({
records: [
{ evidence_id: first.evidence_id, caller_input_path: firstAlias },
],
});
expect(structured(await open(canonical)).result).not.toHaveProperty(
"caller_input_path",
);
expect(await current()).not.toHaveProperty("caller_input_path");
expect(await observation()).not.toHaveProperty("caller_input_path");
expect(starts).toEqual(["alpha"]);
},
);
it.skipIf(process.platform === "win32")(
"replays a snapshot against the same file through a different selected alias",
async () => {
const {
directory,
canonical,
firstAlias,
secondAlias,
call,
open,
observation,
selected,
} = await createAliasedTargetMcp();
expect((await open(firstAlias)).isError).not.toBe(true);
const seeded = await observation(canonical);
expect(seeded.caller_input_path).toBe(firstAlias);
const snapshotPath = join(directory, "analysis.json");
expect(
structured(await call("close_binary", { snapshot_path: snapshotPath }))
.result,
).toMatchObject({ primitive_entries: 1 });
expect(
structured(
await call("open_binary", {
path: secondAlias,
format: "dos-com",
snapshot_path: snapshotPath,
}),
).result,
).toMatchObject(selected(secondAlias));
const replay = await observation(canonical);
expect(replay).toMatchObject({
caller_input_path: secondAlias,
subject: seeded.subject,
normalized_result: seeded.normalized_result,
});
expect(replay.limitations).toEqual(
expect.arrayContaining([
expect.stringContaining("Loaded from a local REA analysis snapshot"),
]),
);
},
);
const expectUnknownProviderKeepsBinding = async (
mcp: Client,
session: ReturnType<typeof composeBinarySession>,