fix(hopper)!: bind analysis to the active target and correct boundary contracts

Preserve native document identity, nullable bookmark labels, address diagnostics, segment-end byte prefixes, and verified file mappings. Validate batch rename addresses before mutation.

BREAKING CHANGE: remove set_current_document. Use open_binary to switch targets; document arguments are scoped to the active target.
This commit is contained in:
morluto
2026-10-09 02:05:31 +08:00
parent 34cc9259c1
commit 2f71375efc
23 changed files with 140 additions and 146 deletions
+5 -12
View File
@@ -6,6 +6,7 @@ import type {
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { analysisBookmarkSchema } from "../domain/hopperValues.js";
import { resolveAnalysisDocument } from "./AnalysisDocument.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -188,25 +189,17 @@ const matchingBookmarks = (value: JsonValue, address: string): Facet => {
remediation:
"Retry list_bookmarks directly and report the provider output shape if it remains malformed.",
};
if (!value.every(isBookmark))
const parsed = analysisBookmarkSchema.array().safeParse(value);
if (!parsed.success)
return {
state: "unavailable",
reason:
"list_bookmarks returned malformed entries; expected address and name strings.",
"list_bookmarks returned malformed entries; expected an address string and a string or null name.",
remediation:
"Retry list_bookmarks directly and report the provider output shape if it remains malformed.",
};
return {
state: "available",
value: value.filter((bookmark) => bookmark.address === address),
value: parsed.data.filter((bookmark) => bookmark.address === address),
};
};
const isBookmark = (
value: JsonValue,
): value is { readonly address: string; readonly name: string } =>
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
typeof value.address === "string" &&
typeof value.name === "string";
@@ -35,7 +35,6 @@ const STATEFUL_OPERATIONS: ReadonlySet<AnalysisOperation> = new Set([
"current_document",
"goto_address",
"list_documents",
"set_current_document",
]);
const CURSOR_DEFAULT_OPERATIONS: ReadonlySet<AnalysisOperation> = new Set([
@@ -49,10 +48,7 @@ const CURSOR_DEFAULT_OPERATIONS: ReadonlySet<AnalysisOperation> = new Set([
const DOCUMENT_SCOPED_OPERATIONS: ReadonlySet<string> = new Set(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name).filter(
(name) =>
name !== "current_document" &&
name !== "list_documents" &&
name !== "set_current_document",
(name) => name !== "current_document" && name !== "list_documents",
),
);
-1
View File
@@ -143,7 +143,6 @@ export const MCP_TOOLS_WITHOUT_DEDICATED_CLI = Object.freeze([
"set_addresses_names",
"set_bookmark",
"set_comment",
"set_current_document",
"set_inline_comment",
"unset_bookmark",
"get_objc_classes",
+1 -7
View File
@@ -1,11 +1,5 @@
import { z } from "zod";
const document = z.string().optional().describe("The document name");
const address = z
.string()
.describe(
"A provider-normalized address; default memory uses 0x-prefixed hexadecimal",
);
import { address, document } from "./toolContractHelpers.js";
/** Hopper memory and file-mapping contracts. */
export const HOPPER_MEMORY_TOOL_DEFINITIONS = [
+4 -9
View File
@@ -101,7 +101,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"list_bookmarks",
"List every bookmark in the selected Hopper document as address and name pairs. Use bookmarks as analyst-authored navigation aids; this does not discover code references.",
"List every bookmark in the selected Hopper document as address and name pairs; unnamed bookmarks retain a null name. Use bookmarks as analyst-authored navigation aids; this does not discover code references.",
z.object({ document }),
),
official(
@@ -208,7 +208,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"set_addresses_names",
"Assign analyst names to multiple addresses in one call and return per-address success booleans. This mutates analysis metadata; verify failures individually.",
"Assign analyst names to multiple addresses in one call and return per-address success booleans. Hopper validates every address before applying names. This mutates analysis metadata; verify failures individually.",
z.object({ names: z.record(z.string(), z.string()), document }),
),
official(
@@ -218,17 +218,12 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"set_comment",
"Write a regular analysis comment at a hexadecimal address and return whether readback matched. This mutates the Hopper document; use comments to record evidence IDs or reasoning.",
"Write a regular analysis comment at a hexadecimal address and return whether readback matched. An empty comment clears it. This mutates the Hopper document; use comments to record evidence IDs or reasoning.",
z.object({ address, comment: z.string(), document }),
),
official(
"set_current_document",
"Select an already-open Hopper document by exact document name. This changes subsequent default-document routing; list_documents can supply names when needed, while explicit document inputs keep calls reproducible.",
z.object({ document: z.string() }),
),
official(
"set_inline_comment",
"Write an inline instruction comment at a hexadecimal address and return whether readback matched. This mutates analysis metadata.",
"Write an inline instruction comment at a hexadecimal address and return whether readback matched. An empty comment clears it; Hopper may flatten newlines, producing false on exact readback. This mutates analysis metadata.",
z.object({ address, comment: z.string(), document }),
),
official(
+3 -3
View File
@@ -104,7 +104,7 @@ export const PROMPT_CONTRACTS = [
target_path: optional(
"Absolute target path; omit when the intended target is already open",
),
document: optional("Open Hopper document to inspect", "document"),
document: optional("Active target's provider document name", "document"),
procedure: optional(
"Known procedure name or address to prioritize",
"procedure",
@@ -121,9 +121,9 @@ export const PROMPT_CONTRACTS = [
"For a JavaScript/Electron application directory, call analyze_javascript_application with input_path=target_path directly; no open_binary call is needed. For a file or macOS app bundle, open target_path only when the required target is not active.",
},
{
tools: ["list_documents", "set_current_document"],
tools: ["current_document"],
instruction:
"Select a document only when needed for the requested analysis.",
"Analysis stays bound to the active target's provider document. Use open_binary to switch targets; document names never select another artifact.",
},
{
tools: ["search_strings", "search_procedures", "procedure_address"],
-1
View File
@@ -36,7 +36,6 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
set_addresses_names: { names: { "0x1000": "entry" } },
set_bookmark: { address: "0x1000" },
set_comment: { address: "0x1000", comment: "validated entry point" },
set_current_document: { document: "fixture" },
set_inline_comment: { address: "0x1000", comment: "calls parser" },
unset_bookmark: { address: "0x1000" },
get_call_graph: { address: "0x1000" },
+6 -1
View File
@@ -4,7 +4,12 @@ import { jsonValueSchema } from "../domain/jsonValue.js";
import { TOOL_EXAMPLE_OVERRIDES } from "./toolContractExamples.js";
import type { ToolExample } from "./toolContractTypes.js";
export const document = z.string().optional().describe("The document name");
export const document = z
.string()
.optional()
.describe(
"The active target's provider document name; use open_binary to switch targets",
);
export const address = z
.string()
.describe(
-1
View File
@@ -163,7 +163,6 @@ const PUBLISHED_TOOL_NAME_FLOOR = [
"set_addresses_names",
"set_bookmark",
"set_comment",
"set_current_document",
"set_inline_comment",
"trace_application_feature",
"trace_call_path",
-1
View File
@@ -161,7 +161,6 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
set_addresses_names: effects({ mutatesTarget: true, mutatesSession: true }),
set_bookmark: effects({ mutatesTarget: true, mutatesSession: true }),
set_comment: effects({ mutatesTarget: true, mutatesSession: true }),
set_current_document: effects({ mutatesSession: true, changesUiState: true }),
set_inline_comment: effects({ mutatesTarget: true, mutatesSession: true }),
unset_bookmark: effects({
mutatesTarget: true,
+6 -3
View File
@@ -18,6 +18,7 @@ import {
processCaptureSchema,
} from "../domain/process/processCapture.js";
import {
analysisBookmarkSchema,
functionInstructionWindowSchema,
referenceKindSchema,
} from "../domain/hopperValues.js";
@@ -82,7 +83,10 @@ const contextFacetSchema = z.discriminatedUnion("state", [
}),
]);
const bookmarkFacetSchema = z.discriminatedUnion("state", [
z.object({ state: z.literal("available"), value: z.array(addressedEntry) }),
z.object({
state: z.literal("available"),
value: z.array(analysisBookmarkSchema),
}),
z.object({
state: z.literal("unavailable"),
reason: z.string(),
@@ -116,7 +120,7 @@ export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
current_document: resultOf(z.string()),
goto_address: resultOf(z.string()),
inline_comment: resultOf(nullableText),
list_bookmarks: resultOf(z.array(addressedEntry)),
list_bookmarks: resultOf(z.array(analysisBookmarkSchema)),
list_documents: resultOf(z.array(z.string())),
list_names: resultOf(z.array(addressedValue)),
list_procedures: resultOf(z.array(addressedValue)),
@@ -176,7 +180,6 @@ export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
set_addresses_names: resultOf(z.record(z.string(), z.boolean())),
set_bookmark: resultOf(z.boolean()),
set_comment: resultOf(z.boolean()),
set_current_document: resultOf(z.string()),
set_inline_comment: resultOf(z.boolean()),
unset_bookmark: resultOf(z.boolean()),
xrefs: resultOf(addressList),
+8 -1
View File
@@ -56,7 +56,9 @@ export const analysisErrorRemediationAction = (
? "Check the Hopper launcher and target details, then retry opening the target."
: `Use the active REA session ${error.ownerRunId} or close it before opening this target again.`;
if (error instanceof HopperRemoteError)
return "Review the Hopper diagnostic details; correct the request or retry if the failure was transient.";
return error.diagnosticType === "invalid_request"
? "Correct the reported address, document, or arguments and retry."
: "Review the Hopper diagnostic details; correct the request or retry if the failure was transient.";
if (error instanceof EvidenceReferenceError)
return "Use an exact Evidence reference retained by this session, supply the complete inline Evidence, re-run its producer, or import its Evidence bundle. close_binary clears retained records.";
if (
@@ -87,6 +89,11 @@ export const analysisErrorCategory = (
return error.userCategory ?? "execution_failure";
if (error instanceof BrowserObservationError)
return browserErrorCategory(error.reason);
if (
error instanceof HopperRemoteError &&
error.diagnosticType === "invalid_request"
)
return "invalid_input";
if (
error instanceof HopperRemoteError &&
error.diagnosticType === "authorization"
+5
View File
@@ -82,6 +82,11 @@ export const projectAnalysisError = (
const underlyingErrorCode = (
error: AnalysisError,
): AnalysisErrorProjection["code"] => {
if (
error instanceof HopperRemoteError &&
error.diagnosticType === "invalid_request"
)
return "invalid_request";
if (error instanceof ProviderSelectionError)
return error.reason === "provider_unavailable"
? "provider_unavailable"
+5
View File
@@ -62,6 +62,11 @@ const segmentSchema = z.object({
const unavailableAnalysisFactSchema = z
.object({ available: z.literal(false), reason: z.string() })
.strict();
/** An analyzed bookmark retains a missing provider label as null. */
export const analysisBookmarkSchema = z.strictObject({
address: z.string(),
name: z.string().nullable(),
});
/** Complete observed function-body ranges; every range endpoint is inclusive. */
export const functionBodySchema = z.discriminatedUnion("available", [
unavailableAnalysisFactSchema,
+5
View File
@@ -201,6 +201,11 @@ export class HopperProvider implements AnalysisProviderCandidate {
...(profile === undefined ? {} : { analysisProfile: profile }),
limitations: [
"Results depend on Hopper's completed static analysis.",
...(operation === "read_bytes"
? [
"Hopper byte reads stop at the containing segment's exclusive end; a readable prefix is returned with complete=false when the requested range crosses it.",
]
: []),
...(operation === "procedure_references"
? [
"Hopper's public Python API does not expose flow classification for calls without resolved targets; unresolved_calls is empty and its coverage is unknown.",
-1
View File
@@ -45,7 +45,6 @@ export const HOPPER_OPERATIONS = Object.freeze([
"set_addresses_names",
"set_bookmark",
"set_comment",
"set_current_document",
"set_inline_comment",
"unset_bookmark",
"xrefs",