refactor: return complete tool results inline

This commit is contained in:
morluto
2026-09-29 07:08:46 +08:00
parent 2160d4fae5
commit 0d96275b68
535 changed files with 4084 additions and 13537 deletions
-264
View File
@@ -1,264 +0,0 @@
import { z } from "zod";
const valuesAt = (node, path) => {
if (typeof node !== "object" || node === null) return [];
if ("anyOf" in node && Array.isArray(node.anyOf))
return node.anyOf.flatMap((alternative) => valuesAt(alternative, path));
if ("oneOf" in node && Array.isArray(node.oneOf))
return node.oneOf.flatMap((alternative) => valuesAt(alternative, path));
if (path.length === 0)
return "const" in node &&
(typeof node.const === "number" || typeof node.const === "string")
? [node.const]
: [];
if (
!("properties" in node) ||
typeof node.properties !== "object" ||
node.properties === null
)
return [];
const [segment, ...remaining] = path;
return segment !== undefined && segment in node.properties
? valuesAt(node.properties[segment], remaining)
: [];
};
const versionAt = (schema, path) => {
const versions = [
...new Set(
valuesAt(z.toJSONSchema(schema, { unrepresentable: "any" }), path).map(
String,
),
),
];
if (versions.length !== 1)
throw new Error(
`Schema version path ${path.join(".")} has ${String(versions.length)} constant values`,
);
const version = versions[0];
if (version === undefined) throw new Error("Schema version disappeared");
return /^\d+$/u.test(version) ? Number(version) : version;
};
const durableSchemaDefinitions = (sources) => [
[
"analysis_snapshot",
sources.analysisSnapshot.analysisSnapshotSchema,
["snapshot_version"],
],
[
"artifact_graph",
sources.artifactGraph.artifactInventoryResultSchema,
["manifest", "schema_version"],
],
[
"artifact_extraction",
sources.artifactGraph.artifactExtractionResultSchema,
["extraction_manifest", "schema_version"],
],
[
"browser_scenario",
sources.browserScenario.browserScenarioSchema,
["schema_version"],
],
["evidence", sources.evidence.evidenceSchema, ["schema_version"]],
[
"evidence_bundle",
sources.evidenceBundle.evidenceBundleSchema,
["bundle_version"],
],
[
"evidence_completion_ledger",
sources.evidenceCompletion.evidenceCompletionLedgerSchema,
["schema_version"],
],
[
"evidence_completion_manifest",
sources.completionGeneration.completionManifestSchema,
["schema_version"],
],
[
"investigation_run",
sources.investigationWorkspace.investigationRunSchema,
["schema_version"],
],
[
"investigation_run_summary",
sources.investigationWorkspace.investigationRunSummarySchema,
["schema_version"],
],
[
"investigation_workspace",
sources.investigationWorkspace.investigationWorkspaceSchema,
["workspace_version"],
],
[
"javascript_application_graph",
sources.javascriptApplicationGraph.javascriptApplicationGraphSchema,
["schema_version"],
],
[
"javascript_application_version_comparison",
sources.javascriptVersionComparison
.applicationVersionComparisonResultSchema,
["schema_version"],
],
[
"javascript_semantic_graph",
sources.javascriptSemanticGraph.javaScriptSemanticGraphSchema,
["schema_version"],
],
[
"javascript_semantic_query",
sources.javascriptSemanticQuery.javaScriptSemanticQueryResultSchema,
["schema_version"],
],
[
"javascript_semantic_trace",
sources.javascriptSemanticTrace.javaScriptSemanticTraceResultSchema,
["schema_version"],
],
[
"javascript_feature_trace",
sources.javascriptFeatureTrace.applicationFeatureTraceResultSchema,
["schema_version"],
],
[
"process_capture",
sources.processCapture.processCaptureSchema,
["schema_version"],
],
[
"reconstruction_verification",
sources.reconstructionVerification.reconstructionSpecificationSchema,
["schema_version"],
],
[
"residual_unknown",
sources.residualUnknown.residualUnknownSchema,
["registry_version"],
],
];
const browserScenarioObservationSchemaDefinitions = (sources) => [
[
"browser_scenario_capture",
sources.browserScenarioCapture.browserScenarioCaptureSchema,
["schema_version"],
],
[
"browser_scenario_diff",
sources.browserScenarioDiff.browserScenarioDiffSchema,
["schema_version"],
],
];
const observationSchemaDefinitions = (sources) => [
[
"managed_artifact_inspection",
sources.managedArtifact.managedArtifactInspectionSchema,
["schema_version"],
],
[
"managed_member_inspection",
sources.managedArtifact.managedMemberInspectionSchema,
["schema_version"],
],
[
"managed_native_boundary_inspection",
sources.managedArtifact.managedNativeBoundaryInspectionSchema,
["schema_version"],
],
[
"managed_member_comparison",
sources.managedComparison.managedMemberComparisonResultSchema,
["schema_version"],
],
[
"managed_native_verification",
sources.managedNativeVerification.managedNativeVerificationResultSchema,
["schema_version"],
],
[
"browser_target_list",
sources.browserObservation.browserTargetListSchema,
["schema_version"],
],
...browserScenarioObservationSchemaDefinitions(sources),
[
"electron_page_inspection",
sources.electronObservation.electronPageInspectionSchema,
["schema_version"],
],
[
"electron_target_list",
sources.electronObservation.electronTargetListSchema,
["schema_version"],
],
[
"javascript_application_analysis",
sources.javascriptApplicationAnalysis
.javaScriptApplicationAnalysisResultV2Schema,
["schema_version"],
],
[
"javascript_runtime_observation",
sources.javascriptRuntimeObservation.javascriptRuntimeObservationSchema,
["schema_version"],
],
[
"javascript_runtime_target_list",
sources.javascriptRuntimeObservation.javascriptRuntimeTargetListSchema,
["schema_version"],
],
[
"web_bundle_analysis",
sources.webBundleAnalysis.webBundleAnalysisSchema,
["schema_version"],
],
[
"web_capture_diff",
sources.webCaptureDiff.webCaptureDiffSchema,
["schema_version"],
],
[
"web_mcp_discovery",
sources.webMcpDiscovery.webMcpDiscoverySchema,
["schema_version"],
],
[
"web_observation_session",
sources.browserSession.webObservationSessionSchema,
["schema_version"],
],
[
"web_page_inspection",
sources.browserObservation.webPageInspectionSchema,
["schema_version"],
],
[
"web_screenshot",
sources.webScreenshot.webScreenshotSchema,
["schema_version"],
],
[
"web_screenshot_diff",
sources.webScreenshot.webScreenshotDiffSchema,
["schema_version"],
],
];
/** Derive the catalog of durable and observation schema versions. */
export const schemaCatalog = (sources) =>
[
...durableSchemaDefinitions(sources),
...observationSchemaDefinitions(sources),
]
.map(([id, schema, path]) => {
try {
return { id, version: versionAt(schema, path) };
} catch (cause) {
throw new Error(`Could not derive ${id} schema version`, { cause });
}
})
.sort((left, right) => left.id.localeCompare(right.id));
+2 -2
View File
@@ -21,12 +21,12 @@ export const generateLargeFixture = (count = LARGE_FIXTURE_COUNT) => {
const declarations = Array.from(
{ length: count },
(_, index) =>
`__attribute__((noinline, used)) int rea_page_${String(index).padStart(4, "0")}(void) { puts("REA_PAGE_${String(index).padStart(4, "0")}"); return ${index}; }`,
`__attribute__((noinline, used)) int rea_inventory_${String(index).padStart(4, "0")}(void) { puts("REA_INVENTORY_${String(index).padStart(4, "0")}"); return ${index}; }`,
);
return [
"#include <stdio.h>",
...declarations,
"int main(void) { return rea_page_0000(); }",
"int main(void) { return rea_inventory_0000(); }",
"",
].join("\n");
};
-17
View File
@@ -56,23 +56,6 @@ export const documentationFactIssues = async (root, catalog) => {
requireText(issues, templatePath, template, "docs/product-catalog.json");
const english = await readFile(join(root, "README.md"), "utf8");
const schemaVersion = (id) => {
const schema = catalog.schemas.find((candidate) => candidate.id === id);
if (schema === undefined) throw new Error(`Missing ${id} catalog schema`);
return String(schema.version);
};
requireText(
issues,
"README.md",
english,
`Evidence v${schemaVersion("evidence")}`,
);
requireText(
issues,
"README.md",
english,
`Process Capture v${schemaVersion("process_capture")}`,
);
requireText(issues, "README.md", english, "docs/product-catalog.json");
return issues;
};
+10 -32
View File
@@ -41,14 +41,6 @@ export const nativeBoundaryLimits = {
maxHeapItemBytes: 1024 * 1024,
};
export const applicationGraphLimits = {
max_types: 100,
max_methods: 100,
max_fields: 100,
max_pinvoke_imports: 100,
max_native_implementations: 100,
};
export const comparisonLimits = {
max_method_matches: 100,
max_field_matches: 100,
@@ -60,13 +52,6 @@ export const defaultIlBody = Buffer.from([
]);
export function functionDossier(name) {
const emptyPage = {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
};
return {
procedure: {
address: "0x401000",
@@ -80,23 +65,16 @@ export function functionDossier(name) {
signature: null,
locals: [],
},
pseudocode: {
text: "",
total_chars: 0,
returned_chars: 0,
truncated: false,
next_offset: null,
},
assembly: emptyPage,
comments: emptyPage,
callers: emptyPage,
callees: emptyPage,
incoming_references: emptyPage,
outgoing_references: emptyPage,
referenced_strings: emptyPage,
referenced_names: emptyPage,
basic_blocks: emptyPage,
instruction_scan: { scanned: 0, truncated: false },
pseudocode: "",
assembly: [],
comments: [],
callers: [],
callees: [],
incoming_references: [],
outgoing_references: [],
referenced_strings: [],
referenced_names: [],
basic_blocks: [],
limitations: [],
};
}
+3 -14
View File
@@ -202,13 +202,6 @@ function verifyManagedAppManifestApplicationGraph({
case_sensitive: expectedTrace.case_sensitive,
},
direction: "incoming",
limits: {
max_seed_matches: 10,
max_depth: 4,
max_nodes: 100,
max_edges: 200,
max_paths: 20,
},
});
ensure(
traced.ok,
@@ -245,11 +238,8 @@ function verifyManagedAppManifestApplicationGraph({
}
const projectManifestMethod = (state, token) => {
const {
appManifestInspectionLimits,
appManifestMemberLimits,
applicationGraphLimits,
} = state.context;
const { appManifestInspectionLimits, appManifestMemberLimits } =
state.context;
const existing = state.graphByToken.get(token);
if (existing !== undefined) return existing;
const method = state.inspectedMethods.get(token);
@@ -289,7 +279,6 @@ const projectManifestMethod = (state, token) => {
const projected = projectManagedApplicationGraphEvidence({
managed_artifact: artifactEvidence,
managed_members: memberEvidence,
limits: applicationGraphLimits,
});
ensure(
projected.ok,
@@ -316,7 +305,7 @@ function inspectManagedMethodByToken(context, bytes, target, expectedMethod) {
target,
expectedMethod.token,
);
const method = members.methods.items.find(
const method = members.methods.find(
({ token }) => token === expectedMethod.token,
);
ensure(
+2 -2
View File
@@ -39,7 +39,7 @@ async function runManagedAppManifestSelfTest(context) {
sample.target,
context.memberLimits,
);
const method = members.methods.items[0];
const method = members.methods[0];
assert.ok(method);
const summary = await context.verifyManagedAppManifest(
{
@@ -143,7 +143,7 @@ async function runOptionalIlspyOracle(context) {
sample.target,
context.memberLimits,
);
const method = members.methods.items[0];
const method = members.methods[0];
ensureIlspy(method !== undefined, "source-owned fixture has no method");
const listOutput = await runIlspy(
ilspyPath,
+11 -49
View File
@@ -19,35 +19,29 @@ export const requireMcpResult = (result, operation) => {
return value.result;
};
/** Verify direct-provider provenance through the complete Evidence resource. */
export const requireEvidenceProvider = async (
client,
result,
operation,
providerId,
) => {
const evidence = await readMcpEvidence(client, result, operation);
/** Verify provider identity directly from the tool result. */
export const requireEvidenceProvider = (result, operation, providerId) => {
const evidence = jsonValue(result);
if (
evidence?.provider?.id !== providerId ||
evidence?.analysis_profile?.provider?.id !== providerId ||
typeof evidence.analysis_profile.provider.version !== "string"
evidence?.evidence?.provider?.id !== providerId ||
evidence?.evidence?.analysis_profile?.provider?.id !== providerId ||
typeof evidence.evidence.analysis_profile.provider.version !== "string"
) {
throw new Error(`${operation} omitted its concrete provider provenance`);
}
};
/** Verify composed-workflow and upstream provenance through full Evidence. */
export const requireWorkflowEvidenceProvider = async (
client,
/** Verify composed workflow and upstream provider provenance inline. */
export const requireWorkflowEvidenceProvider = (
result,
operation,
expected,
) => {
const evidence = await readMcpEvidence(client, result, operation);
const profile = evidence?.analysis_profile;
const evidence = jsonValue(result);
const profile = evidence?.evidence?.analysis_profile;
const upstream = profile?.parameters?.upstream_analysis_profile;
if (
evidence?.provider?.id !== expected.workflowProviderId ||
evidence?.evidence?.provider?.id !== expected.workflowProviderId ||
profile?.provider?.id !== expected.workflowProviderId ||
upstream?.provider?.id !== expected.upstreamProviderId ||
typeof upstream.provider.version !== "string"
@@ -57,35 +51,3 @@ export const requireWorkflowEvidenceProvider = async (
);
}
};
const readMcpEvidence = async (client, result, operation) => {
const compact = jsonValue(result);
if (
compact === null ||
typeof compact !== "object" ||
typeof compact.evidence_id !== "string" ||
compact.evidence_uri !== `rea://evidence/${compact.evidence_id}`
) {
throw new Error(`${operation} omitted its Evidence reference`);
}
const resource = await client.readResource({ uri: compact.evidence_uri });
const text = resource.contents.find(
(content) =>
content.uri === compact.evidence_uri && typeof content.text === "string",
)?.text;
if (text === undefined)
throw new Error(`${operation} Evidence resource omitted JSON text`);
const evidence = JSON.parse(text);
if (
evidence === null ||
typeof evidence !== "object" ||
evidence.evidence_id !== compact.evidence_id ||
JSON.stringify(evidence.normalized_result) !==
JSON.stringify(compact.result)
) {
throw new Error(
`${operation} Evidence resource did not match its projection`,
);
}
return evidence;
};
-1
View File
@@ -1,5 +1,4 @@
export interface ProductCatalog {
readonly catalog_schema_version: number;
readonly package: {
readonly name: string;
readonly version: string;
-3
View File
@@ -7,7 +7,6 @@ import {
cliCommandOptionNames,
} from "./catalog-cli.mjs";
import { providerCatalog, toolFamilyCatalog } from "./catalog-builders.mjs";
import { schemaCatalog } from "./catalog-schemas.mjs";
export {
createCliInventory,
@@ -31,7 +30,6 @@ export const createProductCatalog = async (root) => {
const providers = providerCatalog(sources);
const metadata = sources.packageMetadata.PACKAGE_METADATA;
return {
catalog_schema_version: 1,
package: {
name: metadata.name,
version: metadata.version,
@@ -52,7 +50,6 @@ export const createProductCatalog = async (root) => {
configuration: format === "unsupported" ? "detect-only" : "managed",
}),
),
schemas: schemaCatalog(sources),
cli: {
primary_count: cli.primary.length,
commands: cli.primary,
@@ -0,0 +1,21 @@
interface ToolClient {
callTool(request: unknown, options: unknown): Promise<unknown>;
}
interface SearchSummary {
readonly count: number;
readonly calls: 1;
}
export function openAndVerifyLargeFixture(input: {
readonly client: ToolClient;
readonly options: unknown;
readonly normalizedResult: (value: unknown, operation: string) => unknown;
readonly path: string;
readonly expectedCount: number;
readonly symbolPrefix: string;
readonly stringPrefix: string;
}): Promise<{
readonly procedures: SearchSummary;
readonly strings: SearchSummary;
}>;
@@ -0,0 +1,83 @@
/** Open the large fixture and verify complete inline search results. */
export async function openAndVerifyLargeFixture({
client,
options,
normalizedResult,
path,
expectedCount,
symbolPrefix,
stringPrefix,
}) {
const opened = await client.callTool(
{ name: "open_binary", arguments: { path } },
options,
);
if (opened.isError === true)
throw new Error("Hopper rejected the large fixture");
const procedures = await collectAllMatches({
client,
options,
normalizedResult,
tool: "search_procedures",
pattern: symbolPrefix.replace(/^_+/u, ""),
expectedPrefix: symbolPrefix.replace(/^_+/u, ""),
expectedCount,
normalize: (value) => value.replace(/^_+/u, ""),
});
const strings = await collectAllMatches({
client,
options,
normalizedResult,
tool: "search_strings",
pattern: stringPrefix,
expectedPrefix: stringPrefix,
expectedCount,
normalize: (value) => value,
});
return { procedures, strings };
}
async function collectAllMatches({
client,
options,
normalizedResult,
tool,
pattern,
expectedPrefix,
expectedCount,
normalize,
}) {
const matches = normalizedResult(
await client.callTool(
{
name: tool,
arguments: { pattern, mode: "literal", case_sensitive: true },
},
options,
),
tool,
);
if (!Array.isArray(matches) || matches.length !== expectedCount)
throw new Error(`${tool} did not return every expected match`);
const addresses = new Set();
const values = new Set();
for (const item of matches) {
const value = normalize(item.value);
if (
typeof item.address !== "string" ||
!/^0x[0-9a-f]+$/iu.test(item.address)
)
throw new Error(`${tool} returned a malformed address`);
if (addresses.has(item.address) || values.has(value))
throw new Error(`${tool} returned duplicate matches`);
addresses.add(item.address);
values.add(value);
}
const expectedValues = Array.from(
{ length: expectedCount },
(_, index) => `${expectedPrefix}${String(index).padStart(4, "0")}`,
);
if (expectedValues.some((value) => !values.has(value)))
throw new Error(`${tool} omitted expected matches`);
return { count: values.size, calls: 1 };
}
+1 -1
View File
@@ -69,7 +69,7 @@ function requireLargeOracle(largeOracle) {
largeOracle.symbolCount !== largeOracle.stringCount ||
largeOracle.symbolCount <= 0
)
throw new Error("Large fixture omitted its exact pagination oracle");
throw new Error("Large fixture omitted its complete-inventory oracle");
return largeOracle;
}
-33
View File
@@ -1,33 +0,0 @@
interface ToolClient {
callTool(request: unknown, options: unknown): Promise<unknown>;
}
interface PaginationSummary {
readonly count: number;
readonly pages: number;
}
export function verifyLargeFixturePagination(input: {
readonly client: ToolClient;
readonly options: unknown;
readonly normalizedResult: (value: unknown, operation: string) => unknown;
readonly expectedCount: number;
readonly symbolPrefix: string;
readonly stringPrefix: string;
}): Promise<{
readonly procedures: PaginationSummary;
readonly strings: PaginationSummary;
}>;
export function openAndVerifyLargeFixture(input: {
readonly client: ToolClient;
readonly options: unknown;
readonly normalizedResult: (value: unknown, operation: string) => unknown;
readonly path: string;
readonly expectedCount: number;
readonly symbolPrefix: string;
readonly stringPrefix: string;
}): Promise<{
readonly procedures: PaginationSummary;
readonly strings: PaginationSummary;
}>;
-138
View File
@@ -1,138 +0,0 @@
const PAGE_LIMIT = 100;
/** Open the large fixture and exhaustively prove its public search pages. */
export async function openAndVerifyLargeFixture({
client,
options,
normalizedResult,
path,
expectedCount,
symbolPrefix,
stringPrefix,
}) {
const opened = await client.callTool(
{ name: "open_binary", arguments: { path } },
options,
);
if (opened.isError === true)
throw new Error("Hopper rejected the large fixture");
return verifyLargeFixturePagination({
client,
options,
normalizedResult,
expectedCount,
symbolPrefix,
stringPrefix,
});
}
/** Exhaustively prove the source-owned large fixture through public search pages. */
export async function verifyLargeFixturePagination({
client,
options,
normalizedResult,
expectedCount,
symbolPrefix,
stringPrefix,
}) {
const procedures = await collectExactPages({
client,
options,
normalizedResult,
tool: "search_procedures",
pattern: symbolPrefix.replace(/^_+/u, ""),
expectedPrefix: symbolPrefix.replace(/^_+/u, ""),
expectedCount,
normalize: (value) => value.replace(/^_+/u, ""),
});
const strings = await collectExactPages({
client,
options,
normalizedResult,
tool: "search_strings",
pattern: stringPrefix,
expectedPrefix: stringPrefix,
expectedCount,
normalize: (value) => value,
});
return { procedures, strings };
}
async function collectExactPages({
client,
options,
normalizedResult,
tool,
pattern,
expectedPrefix,
expectedCount,
normalize,
}) {
const seenAddresses = new Set();
const seenValues = new Set();
let offset = 0;
let pages = 0;
while (true) {
const page = normalizedResult(
await client.callTool(
{
name: tool,
arguments: {
pattern,
mode: "literal",
case_sensitive: true,
offset,
limit: PAGE_LIMIT,
},
},
options,
),
`${tool} offset ${offset}`,
);
validatePage(page, { offset, expectedCount });
for (const item of page.items) {
const value = normalize(item.value);
if (item.value_truncated || !/^0x[0-9a-f]+$/iu.test(item.address))
throw new Error(`${tool} returned truncated or malformed evidence`);
if (seenAddresses.has(item.address) || seenValues.has(value))
throw new Error(`${tool} returned duplicate evidence`);
seenAddresses.add(item.address);
seenValues.add(value);
}
pages += 1;
if (page.next_offset === null) break;
offset = page.next_offset;
}
const expectedValues = Array.from(
{ length: expectedCount },
(_, index) => `${expectedPrefix}${String(index).padStart(4, "0")}`,
);
if (
seenValues.size !== expectedCount ||
expectedValues.some((value) => !seenValues.has(value))
)
throw new Error(`${tool} did not exhaustively prove the fixture values`);
return { count: seenValues.size, pages };
}
function validatePage(page, { offset, expectedCount }) {
if (
page === null ||
typeof page !== "object" ||
!Array.isArray(page.items) ||
page.offset !== offset ||
page.limit !== PAGE_LIMIT ||
page.total !== expectedCount ||
page.items.length !== Math.min(PAGE_LIMIT, expectedCount - offset)
)
throw new Error("Hopper returned an inconsistent fixture search page");
const expectedNext =
offset + page.items.length < expectedCount
? offset + page.items.length
: null;
if (
page.next_offset !== expectedNext ||
page.has_more !== (expectedNext !== null)
)
throw new Error("Hopper returned inconsistent pagination metadata");
}
+33
View File
@@ -0,0 +1,33 @@
import { HOPPER_PROVIDER_IDENTITY } from "../../dist/hopper/HopperProvider.js";
/** Verify the selected Hopper candidate and concrete provider binding. */
export const requireHopperSelection = (status, expected) => {
const candidates = status.analysis_provider_candidates;
const hopper = Array.isArray(candidates)
? candidates.find(
(candidate) => candidate?.provider?.id === HOPPER_PROVIDER_IDENTITY.id,
)
: undefined;
if (
hopper === undefined ||
hopper.availability?.status !== "available" ||
hopper.target_support?.status !== expected.targetSupport ||
hopper.selected !== expected.selected
)
throw new Error("binary_session omitted truthful Hopper candidate status");
if (!expected.selected) {
if (status.analysis_provider_binding !== null)
throw new Error("Target-free status unexpectedly selected a provider");
return null;
}
const binding = status.analysis_provider_binding;
if (
binding?.provider?.id !== HOPPER_PROVIDER_IDENTITY.id ||
typeof binding.provider.version !== "string" ||
binding.selection_source !== "auto-single-candidate" ||
binding.analysis_profile?.provider?.id !== HOPPER_PROVIDER_IDENTITY.id ||
binding.analysis_profile.provider.version !== binding.provider.version
)
throw new Error("binary_session omitted its concrete Hopper binding");
return binding;
};
+15 -12
View File
@@ -152,7 +152,7 @@ export async function verifyRealHopperFixture({
};
}
/** Reject malformed, unsafe, or error-level diagnostics from the MCP runtime. */
/** Reject malformed, unsafe, or unexpected failure diagnostics from MCP. */
export function requireSafeDiagnostics(chunks) {
const lines = chunks
.join("")
@@ -171,7 +171,12 @@ export function requireSafeDiagnostics(chunks) {
typeof diagnostic !== "object" ||
diagnostic.application !== "rea" ||
typeof diagnostic.level !== "number" ||
diagnostic.level >= 40
diagnostic.level >= 50 ||
(diagnostic.level >= 40 &&
diagnostic.errorTag !== "HopperRemoteError" &&
!(
diagnostic.tool === "procedure_info" && diagnostic.status === "error"
))
)
throw new Error(`The MCP runtime emitted unsafe stderr: ${line}`);
}
@@ -204,7 +209,7 @@ export async function resolveFixtureProcedure(
expectedName,
normalizedResult,
) {
const page = normalizedResult(
const matches = normalizedResult(
await client.callTool(
{
name: "search_procedures",
@@ -212,30 +217,28 @@ export async function resolveFixtureProcedure(
pattern: expectedName,
mode: "literal",
case_sensitive: true,
limit: 100,
},
},
options,
),
`search_procedures ${expectedName}`,
);
const matches = Array.isArray(page?.items)
? page.items.filter(
const exactMatches = Array.isArray(matches)
? matches.filter(
(item) =>
typeof item?.value === "string" &&
item.value_truncated === false &&
item.value.replace(/^_+/u, "") === expectedName,
)
: [];
if (
matches.length !== 1 ||
typeof matches[0]?.address !== "string" ||
!/^0x[0-9a-f]+$/iu.test(matches[0].address)
exactMatches.length !== 1 ||
typeof exactMatches[0]?.address !== "string" ||
!/^0x[0-9a-f]+$/iu.test(exactMatches[0].address)
)
throw new Error(
`Expected exactly one Hopper procedure named ${expectedName}`,
);
return { address: matches[0].address, name: matches[0].value };
return { address: exactMatches[0].address, name: exactMatches[0].value };
}
/** Request the assembly evidence required by the fixture oracle. */
@@ -249,7 +252,7 @@ export const analyzeFixtureProcedure = async (
await client.callTool(
{
name: "analyze_function",
arguments: { procedure: procedure.address, include_assembly: true },
arguments: { procedure: procedure.address },
},
options,
),
+11 -25
View File
@@ -32,7 +32,7 @@ export const json = (text) => JSON.parse(text);
export const verifyCompleteToolCatalog = async (client, options) => {
const listed = await client.listTools(undefined, options);
const status = await client.callTool(
{ name: "binary_session", arguments: { detail: "full" } },
{ name: "binary_session", arguments: {} },
options,
);
const availability = status.structuredContent?.result?.tool_availability;
@@ -61,13 +61,6 @@ export const pathExists = async (path) => {
/** Synthetic function dossier for managed/native verification fixtures. */
export const functionDossier = (name) => {
const emptyPage = {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
};
return {
procedure: {
address: "0x401000",
@@ -81,23 +74,16 @@ export const functionDossier = (name) => {
signature: null,
locals: [],
},
pseudocode: {
text: "",
total_chars: 0,
returned_chars: 0,
truncated: false,
next_offset: null,
},
assembly: emptyPage,
comments: emptyPage,
callers: emptyPage,
callees: emptyPage,
incoming_references: emptyPage,
outgoing_references: emptyPage,
referenced_strings: emptyPage,
referenced_names: emptyPage,
basic_blocks: emptyPage,
instruction_scan: { scanned: 0, truncated: false },
pseudocode: "",
assembly: [],
comments: [],
callers: [],
callees: [],
incoming_references: [],
outgoing_references: [],
referenced_strings: [],
referenced_names: [],
basic_blocks: [],
limitations: [],
};
};