diff --git a/scripts/verify-real-hopper.mjs b/scripts/verify-real-hopper.mjs index 8a47c4207..8877cc688 100644 --- a/scripts/verify-real-hopper.mjs +++ b/scripts/verify-real-hopper.mjs @@ -346,6 +346,10 @@ try { requireSuccessfulTool(overview, "binary_overview"), "binary_overview", ); + if (firstOverview.document !== currentDocument) + throw new Error( + "binary_overview did not identify the selected Hopper document", + ); const firstAnalysis = await verifyCurrentTarget(client, options); const fixtureAnalysis = await verifyRealHopperFixture({ client, @@ -382,6 +386,16 @@ try { await client.callTool({ name: "list_documents", arguments: {} }, options), "list_documents after target switch", ); + const secondDocument = await requireCurrentDocument( + client, + options, + documentsAfterTargetSwitch, + requireSuccessfulTool, + ); + if (verifiedSecondOverview.document !== secondDocument) + throw new Error( + "binary_overview retained another document after target switch", + ); const expectedDocumentsAfterTargetSwitch = process.platform === "linux" ? firstDocuments.length diff --git a/src/application/AnalysisContextQueries.ts b/src/application/AnalysisContextQueries.ts index a48a19541..30fa4c648 100644 --- a/src/application/AnalysisContextQueries.ts +++ b/src/application/AnalysisContextQueries.ts @@ -3,13 +3,10 @@ import type { AnalysisOperation, AnalysisOperationPort, } from "./AnalysisProvider.js"; -import { - AnalysisCapabilityUnavailableError, - AnalysisOutputError, -} from "../domain/analysisErrorCore.js"; +import { AnalysisOutputError } from "../domain/analysisErrorCore.js"; import { type AnalysisError } from "../domain/analysisErrorBase.js"; import type { JsonValue } from "../domain/jsonValue.js"; -import { parseDocuments } from "../domain/hopperValues.js"; +import { resolveAnalysisDocument } from "./AnalysisDocument.js"; import { err, ok, type Result } from "../domain/result.js"; type Facet = @@ -88,7 +85,11 @@ export const inspectAddressContext = async ( input: { readonly address: string; readonly document?: string | undefined }, signal?: AbortSignal, ): Promise> => { - const document = await resolveDocument(analysis, input.document, signal); + const document = await resolveAnalysisDocument( + analysis, + input.document, + signal, + ); if (!document.ok) return document; const args = parameters(document.value, input.address); const operations = [ @@ -132,62 +133,6 @@ export const inspectAddressContext = async ( }); }; -const resolveDocument = async ( - analysis: AnalysisOperationPort, - document: string | undefined, - signal: AbortSignal | undefined, -): Promise> => { - if (document !== undefined) return ok(document); - const current = await analysis.execute( - "current_document", - {}, - executionOptions(signal), - ); - if (!current.ok) { - if (!(current.error instanceof AnalysisCapabilityUnavailableError)) - return current; - const listed = await analysis.execute( - "list_documents", - {}, - executionOptions(signal), - ); - if (!listed.ok) return listed; - const parsed = parseDocuments(listed.value.result); - if (!parsed.ok) - return err( - new AnalysisOutputError( - "list_documents", - "expected one document identity when resolving a headless provider", - { cause: parsed.error }, - ), - ); - if (parsed.value.length !== 1) - return err( - new AnalysisOutputError( - "list_documents", - `expected exactly one document identity for a provider without current-document selection, received ${parsed.value.length}`, - ), - ); - const [documentName] = parsed.value; - if (documentName === undefined) - return err( - new AnalysisOutputError( - "list_documents", - "provider returned no document identity", - ), - ); - return ok(documentName); - } - return typeof current.value.result === "string" - ? ok(current.value.result) - : err( - new AnalysisOutputError( - "current_document", - "expected a document identity string", - ), - ); -}; - const facet = ( result: Result | undefined, operation: AnalysisOperation, diff --git a/src/application/AnalysisDocument.ts b/src/application/AnalysisDocument.ts new file mode 100644 index 000000000..22f4b565f --- /dev/null +++ b/src/application/AnalysisDocument.ts @@ -0,0 +1,72 @@ +import type { AnalysisOperationPort } from "./AnalysisProvider.js"; +import { + AnalysisCancelledError, + AnalysisCapabilityUnavailableError, + AnalysisOutputError, +} from "../domain/analysisErrorCore.js"; +import type { AnalysisError } from "../domain/analysisErrorBase.js"; +import { parseDocuments } from "../domain/hopperValues.js"; +import { err, ok, type Result } from "../domain/result.js"; + +const executionOptions = (signal: AbortSignal | undefined) => + signal === undefined ? undefined : { signal }; + +/** Resolve an explicit or provider-selected document without guessing among candidates. */ +export const resolveAnalysisDocument = async ( + analysis: AnalysisOperationPort, + document: string | undefined, + signal: AbortSignal | undefined, +): Promise> => { + if (document !== undefined) return ok(document); + if (signal?.aborted === true) + return err(new AnalysisCancelledError("current_document")); + const current = await analysis.execute( + "current_document", + {}, + executionOptions(signal), + ); + if (!current.ok) { + if (!(current.error instanceof AnalysisCapabilityUnavailableError)) + return current; + const listed = await analysis.execute( + "list_documents", + {}, + executionOptions(signal), + ); + if (!listed.ok) return listed; + const parsed = parseDocuments(listed.value.result); + if (!parsed.ok) + return err( + new AnalysisOutputError( + "list_documents", + "expected one document identity when resolving a headless provider", + { cause: parsed.error }, + ), + ); + if (parsed.value.length !== 1) + return err( + new AnalysisOutputError( + "list_documents", + `expected exactly one document identity for a provider without current-document selection, received ${parsed.value.length}`, + ), + ); + const [documentName] = parsed.value; + if (documentName === undefined || documentName.length === 0) + return err( + new AnalysisOutputError( + "list_documents", + "provider returned no document identity", + ), + ); + return ok(documentName); + } + return typeof current.value.result === "string" && + current.value.result.length > 0 + ? ok(current.value.result) + : err( + new AnalysisOutputError( + "current_document", + "expected a nonempty document identity string", + ), + ); +}; diff --git a/src/application/DirectAnalysis.ts b/src/application/DirectAnalysis.ts index 0adce674c..db54c06b5 100644 --- a/src/application/DirectAnalysis.ts +++ b/src/application/DirectAnalysis.ts @@ -455,7 +455,8 @@ const analysisProfileForRoute = ( ): AnalysisProfileCommitment | undefined => { const profile = route.profile; if (profile === null || profile === undefined) return undefined; - if (isWorkflowEvidenceTool(tool)) return workflowAnalysisProfile(profile); + if (isWorkflowEvidenceTool(tool)) + return workflowAnalysisProfile(profile, tool); const provider = providerIdentityForRoute(route, tool); return provider.id === profile.provider.id ? profile : undefined; }; diff --git a/src/application/EnhancedTools.ts b/src/application/EnhancedTools.ts index 2a2f701a3..18f873514 100644 --- a/src/application/EnhancedTools.ts +++ b/src/application/EnhancedTools.ts @@ -15,7 +15,6 @@ import { type AnalysisError } from "../domain/analysisErrorBase.js"; import { addressDistance, functionDossierSchema, - parseDocuments, parseFunctionDossier, parseListCount, parseRelatedAddresses, @@ -37,6 +36,7 @@ import { type EnhancedResult, type ValidatedEnhancedCall, } from "./EnhancedToolTypes.js"; +import { resolveAnalysisDocument } from "./AnalysisDocument.js"; import { traceCallPath } from "./CallPathTracing.js"; import { traceLiteralFeature } from "./EnhancedLiteralTracing.js"; import { projectNativeApiInspection } from "./native/NativeApiInspection.js"; @@ -388,29 +388,32 @@ export class EnhancedTools { } async #binaryOverview(signal?: AbortSignal): EnhancedResult { - const [segmentsResult, documentsResult, proceduresResult, stringsResult] = - await Promise.all([ + const document = await resolveAnalysisDocument( + this.analysis, + undefined, + signal, + ); + if (!document.ok) return document; + const [segmentsResult, proceduresResult, stringsResult] = await Promise.all( + [ this.#call("list_segments", {}, signal), - this.#call("list_documents", {}, signal), this.#call("list_procedures", {}, signal), this.#call("list_strings", {}, signal), - ]); + ], + ); if (!segmentsResult.ok) return segmentsResult; - if (!documentsResult.ok) return documentsResult; if (!proceduresResult.ok) return proceduresResult; if (!stringsResult.ok) return stringsResult; const segments = parseSegments(segmentsResult.value); if (!segments.ok) return segments; - const documents = parseDocuments(documentsResult.value); - if (!documents.ok) return documents; const procedureCount = parseListCount(proceduresResult.value, "procedures"); if (!procedureCount.ok) return procedureCount; const stringCount = parseListCount(stringsResult.value, "strings"); if (!stringCount.ok) return stringCount; return ok({ - document: documents.value[0] ?? "unknown", + document: document.value, segments: segments.value.map(({ name, start, end }) => ({ name, start, diff --git a/src/application/InvestigationProviders.ts b/src/application/InvestigationProviders.ts index d54d89023..e99a1773f 100644 --- a/src/application/InvestigationProviders.ts +++ b/src/application/InvestigationProviders.ts @@ -1,3 +1,4 @@ +import type { AnalysisOperation } from "./AnalysisProvider.js"; import { createAnalysisProfile, type AnalysisProfileCommitment, @@ -10,12 +11,14 @@ export const REA_WORKFLOW_PROVIDER = { version: "1", } as const; -/** Commit a workflow result to the exact upstream deep-analysis profile. */ +/** Commit a workflow result to its upstream profile and applicable semantic revision. */ export const workflowAnalysisProfile = ( upstream: AnalysisProfileCommitment, + operation?: AnalysisOperation, ): AnalysisProfileCommitment => createAnalysisProfile(REA_WORKFLOW_PROVIDER, { upstream_analysis_profile: upstream, + ...(operation === "binary_overview" ? { workflow_revision: 2 } : {}), }); /** Provider identity for deterministic artifact inventories. */ diff --git a/src/application/WorkflowEvidence.ts b/src/application/WorkflowEvidence.ts index 070a6ba58..b9ccfe783 100644 --- a/src/application/WorkflowEvidence.ts +++ b/src/application/WorkflowEvidence.ts @@ -29,7 +29,12 @@ export const createWorkflowEvidence = (input: { result: input.result, ...(input.upstreamProfile === undefined ? {} - : { analysisProfile: workflowAnalysisProfile(input.upstreamProfile) }), + : { + analysisProfile: workflowAnalysisProfile( + input.upstreamProfile, + input.operation, + ), + }), confidence: "derived", limitations: ["Derived by an REA composed workflow."], }); diff --git a/tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts b/tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts index fa7bfe1e5..f4a28a24c 100644 --- a/tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts +++ b/tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts @@ -123,6 +123,8 @@ const fixturePort = (): AnalysisOperationPort => ({ return Promise.resolve( ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]), ); + case "current_document": + return Promise.resolve(ok("fixture")); case "list_documents": return Promise.resolve(ok(["fixture"])); case "list_strings": diff --git a/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts b/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts index 939782f89..7e024f604 100644 --- a/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts +++ b/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts @@ -5,6 +5,16 @@ import { connect, jsonResult, } from "./enhancedToolsHarness.js"; +import type { + AnalysisExecution, + AnalysisOperationPort, +} from "../../../src/application/AnalysisProvider.js"; +import type { AnalysisError } from "../../../src/domain/analysisErrorBase.js"; +import { + AnalysisCapabilityUnavailableError, + AnalysisProtocolError, +} from "../../../src/domain/analysisErrorCore.js"; +import { err, type Result } from "../../../src/domain/result.js"; import { observed as ok } from "../../fixtures/analysisExecution.js"; afterEach(closeEnhancedToolResources); @@ -39,8 +49,10 @@ describe("enhanced MCP tools", () => { { name: "__DATA", start: "0x1800", end: "0x2000" }, ]), ); + case "current_document": + return Promise.resolve(ok("fixture")); case "list_documents": - return Promise.resolve(ok(["fixture"])); + return Promise.resolve(ok(["New Document", "fixture"])); case "list_strings": return Promise.resolve( ok( @@ -101,3 +113,86 @@ describe("enhanced MCP tools", () => { ); }); }); + +const overviewPort = ( + current: Result, + documents: readonly string[], +): AnalysisOperationPort => ({ + execute: (name) => { + switch (name) { + case "current_document": + return Promise.resolve(current); + case "list_documents": + return Promise.resolve(ok([...documents])); + case "list_segments": + return Promise.resolve( + ok([{ name: "text", start: "0x1000", end: "0x2000" }]), + ); + default: + return Promise.resolve(ok([])); + } + }, +}); + +describe("overview document identity through MCP", () => { + const unsupported = () => + err( + new AnalysisCapabilityUnavailableError( + "fixture", + "current_document", + "headless provider", + ), + ); + + it("uses the sole headless document when current-document selection is unsupported", async () => { + const client = await connect( + overviewPort(unsupported(), ["single-target"]), + ); + expect( + jsonResult( + await client.callTool({ name: "binary_overview", arguments: {} }), + ), + ).toMatchObject({ document: "single-target" }); + }); + + it.each([ + { documents: [] }, + { documents: [""] }, + { documents: ["one", "two"] }, + ])( + "rejects ambiguous or missing headless identities: $documents", + async ({ documents }) => { + const client = await connect(overviewPort(unsupported(), documents)); + expect( + (await client.callTool({ name: "binary_overview", arguments: {} })) + .isError, + ).toBe(true); + }, + ); + + it.each([{ value: null }, { value: "" }, { value: [] }])( + "rejects a malformed current-document result: $value", + async ({ value }) => { + const client = await connect( + overviewPort(ok(value), ["fallback-must-not-hide-error"]), + ); + expect( + (await client.callTool({ name: "binary_overview", arguments: {} })) + .isError, + ).toBe(true); + }, + ); + + it("preserves non-capability current-document failures", async () => { + const client = await connect( + overviewPort( + err(new AnalysisProtocolError("failed current-document transport")), + ["must-not-be-selected"], + ), + ); + expect( + (await client.callTool({ name: "binary_overview", arguments: {} })) + .isError, + ).toBe(true); + }); +}); diff --git a/tests/composition/directAnalysisSnapshotReplay.test.ts b/tests/composition/directAnalysisSnapshotReplay.test.ts index 7596f0608..41ea4d65e 100644 --- a/tests/composition/directAnalysisSnapshotReplay.test.ts +++ b/tests/composition/directAnalysisSnapshotReplay.test.ts @@ -176,11 +176,25 @@ const withAlternateWorkflowProfile = ( snapshot: AnalysisSnapshot, path: string, current: Evidence, + scenario: "alternate" | "legacy" = "alternate", ): AnalysisSnapshot => { - const alternateProfile = createAnalysisProfile(REA_WORKFLOW_PROVIDER, { - workflow: "binary_overview", - fixture: "alternate-profile", - }); + const alternateProfile = + scenario === "legacy" + ? workflowAnalysisProfile(snapshot.binding.analysis_profile) + : createAnalysisProfile(REA_WORKFLOW_PROVIDER, { + workflow: "binary_overview", + fixture: "alternate-profile", + }); + if ( + typeof current.normalized_result !== "object" || + current.normalized_result === null || + Array.isArray(current.normalized_result) + ) + throw new Error("Expected overview object"); + const result = + scenario === "legacy" + ? { ...current.normalized_result, document: "New Document" } + : current.normalized_result; const subject = { path, sha256: snapshot.target.sha256, @@ -192,7 +206,7 @@ const withAlternateWorkflowProfile = ( const alternateEvidence = createEvidence(subject, REA_WORKFLOW_PROVIDER, { operation: current.operation, parameters: current.parameters, - result: current.normalized_result, + result, rawResult: current.raw_result, analysisProfile: alternateProfile, confidence: "derived", @@ -205,7 +219,7 @@ const withAlternateWorkflowProfile = ( operation: current.operation, parameters: current.parameters, execution: { - result: current.normalized_result, + result, rawResult: current.raw_result, provider: REA_WORKFLOW_PROVIDER, analysisProfile: alternateProfile, @@ -243,6 +257,7 @@ const withEarlierHistoricalEvidence = ( result: `historical-${index}`, analysisProfile: workflowAnalysisProfile( snapshot.binding.analysis_profile, + "binary_overview", ), confidence: "derived", limitations: ["Derived by an REA composed workflow."], @@ -416,7 +431,7 @@ describe("binary overview snapshot replay", () => { {}, { snapshotPath }, ); - expect(calls).toEqual(["health", ...operations]); + expect(calls.toSorted()).toEqual(["health", ...operations].toSorted()); expect(starts).toHaveLength(1); const loaded = await readAnalysisSnapshot(snapshotPath); @@ -445,7 +460,7 @@ describe("binary overview snapshot replay", () => { { snapshotPath }, ); expect(second).toEqual(first); - expect(calls).toEqual(["health", ...operations]); + expect(calls.toSorted()).toEqual(["health", ...operations].toSorted()); expect(starts).toHaveLength(1); }); }); @@ -565,52 +580,60 @@ describe("snapshot replay provider identity", () => { }); describe("workflow snapshot profile and cancellation binding", () => { - it("does not replay a valid entry from another workflow profile", async () => { - const directory = await createTestTempDirectory("rea-workflow-profile-"); - const path = join(directory, "fixture.hop"); - const snapshotPath = join(directory, "snapshot.json"); - await writeFile(path, "fixture"); - const starts: string[] = []; - const calls: string[] = []; - const provider = makeProvider(starts, calls); - const dependencies: DirectAnalysisDependencies = { - createBinarySession: () => createTestBinarySession(provider), - createManagedBinarySession: () => createTestBinarySession(provider), - }; - await runDirectAnalysis( - dependencies, - path, - "binary_overview", - {}, - { snapshotPath }, - ); - const loaded = await readAnalysisSnapshot(snapshotPath); - if (!loaded.ok) throw loaded.error; - const current = loaded.value.evidence_bundle.records.find( - (record) => record.operation === "binary_overview", - ); - if (current === undefined) - throw new Error("composed Evidence was not saved"); - expect( - ( - await writeAnalysisSnapshot( - withAlternateWorkflowProfile(loaded.value, path, current), - snapshotPath, - true, - ) - ).ok, - ).toBe(true); + it.each(["alternate", "legacy"] as const)( + "does not replay a valid entry from the $0 workflow profile", + async (scenario) => { + const directory = await createTestTempDirectory("rea-workflow-profile-"); + const path = join(directory, "fixture.hop"); + const snapshotPath = join(directory, "snapshot.json"); + await writeFile(path, "fixture"); + const starts: string[] = []; + const calls: string[] = []; + const provider = makeProvider(starts, calls); + const dependencies: DirectAnalysisDependencies = { + createBinarySession: () => createTestBinarySession(provider), + createManagedBinarySession: () => createTestBinarySession(provider), + }; + await runDirectAnalysis( + dependencies, + path, + "binary_overview", + {}, + { snapshotPath }, + ); + const loaded = await readAnalysisSnapshot(snapshotPath); + if (!loaded.ok) throw loaded.error; + const current = loaded.value.evidence_bundle.records.find( + (record) => record.operation === "binary_overview", + ); + if (current === undefined) + throw new Error("composed Evidence was not saved"); + expect( + ( + await writeAnalysisSnapshot( + withAlternateWorkflowProfile(loaded.value, path, current, scenario), + snapshotPath, + true, + ) + ).ok, + ).toBe(true); - await runDirectAnalysis( - dependencies, - path, - "binary_overview", - {}, - { snapshotPath }, - ); - expect(calls).toEqual(["health", ...operations, "health", ...operations]); - expect(starts).toHaveLength(2); - }); + const refreshed = await runDirectAnalysis( + dependencies, + path, + "binary_overview", + {}, + { snapshotPath }, + ); + expect(refreshed).toMatchObject({ + normalized_result: { document: "fixture" }, + }); + expect(calls.toSorted()).toEqual( + ["health", ...operations, "health", ...operations].toSorted(), + ); + expect(starts).toHaveLength(2); + }, + ); it("does not return a cached result when cancelled during route resolution", async () => { const directory = await createTestTempDirectory("rea-workflow-cancel-"); @@ -658,7 +681,7 @@ describe("workflow snapshot profile and cancellation binding", () => { error: "Analysis failed", code: "cancelled", }); - expect(calls).toEqual(["health", ...operations]); + expect(calls.toSorted()).toEqual(["health", ...operations].toSorted()); expect(starts).toHaveLength(1); }); });