mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 19:53:50 +00:00
* test(mcp): check advertised schemas against a portable dialect in every profile * fix(mcp): re-emit advertised patterns in a portable regex grammar * fix(mcp): present discover_tools input through the selected profile The hot-cold catalog registered discover_tools directly with the SDK, so the default compact input profile still advertised its canonical schema, including page-size defaults clients apply on their own (#5322). Route every listed input schema, transport discovery included, through one server-owned presentation, and pass the selected presentation to the deferred server, which serves recorded tool schemas but not discovery. * fix(mcp): keep the Evidence union on described borrowed inputs borrowEvidenceInput installed its advertised projection on one schema instance. A call site's .describe() rebuilds the schema from its definition, so match_native_functions advertised left and right as unconstrained values in every input profile. Install the projection in the borrowed parser's constructor so derived schemas keep it, for both borrowed inputs and borrowed arrays. * fix(mcp): validate advertised dialect by selected profile * fix(mcp): preserve schema widening through references * feat(mcp): project compact input schemas into the portable advertised dialect One projection (advertisedDialectProjection.ts) owns the compact input advertisement: one type per node, items on every array, string literals as enums, oneOf widened to anyOf, allOf merged, tuples as element unions, exclusive bounds made inclusive, and every keyword outside the dialect dropped. Each rewrite is exact or widening; server validation is unchanged. The root description and sentences for dropped cross-field constraints move to the tool description, which Codex and Zed keep. The compact baseline falls to nullable values only (29), which the dialect cannot express without narrowing an input. The gateway shape repairs (typeArrayItemUnions, hasGatewayIncompatibleShape), the second dependentRequired-to-prose copy and the strict-gateway test denylist are removed; the dialect checker gates the inline presentation instead. * feat(mcp): omit output schemas from tools/list by default No surveyed model API reads an output schema, MCP client validators repeat REA's own result validation, and complete output schemas were about 92% of the default tools/list. REA_MCP_OUTPUT_SCHEMA_PROFILE now resolves to off through one owner (resolveMcpOutputSchemaProfile); compact and full remain selectable. structuredContent is still delivered, and the deferred server serves both off and full from the recorded catalog with the matching recorded identity. Tests and artifact verifiers that validate results against complete advertised output contracts select full explicitly. * docs: describe omitted output schemas as the default in README translations * fix(mcp): select schemas in verification workflows * fix(mcp): refuse zero-padded repeat bounds and record host-specific path patterns * fix(mcp): keep projected schemas permissive * fix(mcp): keep references valid when presentation widens their targets * fix(mcp): keep a single union branch's closure scoped to its properties * fix(mcp): select complete output schemas in the Electron verifier * fix(mcp): select complete output schemas in standalone verifier probes * fix(mcp): keep an allOf member's tuple tail with its own positions * fix(mcp): relax references into negations and conditionals presentation may remove * refactor(contracts): declare root discriminators as typed schema annotations * test(mcp): select the borrowed Evidence contract from its family * fix(mcp): keep astral literals and dynamic references widening in every mode * fix(mcp): omit astral literals and relax untracked references when presentation widens * fix(mcp): select complete output schemas in every verifier transport * fix(mcp): read reference pointers by schema position, not segment spelling * fix(mcp): protect references into collapsing boolean unions and keep referencing branches out of the collapse * fix(mcp): keep reduced schemas open when their root admits names by pattern * test(mcp): keep the reduced-schema pattern case outside the size-limited block * fix(mcp): omit patterns whose classes name astral characters * fix(mcp): decide union collapse and pointer protection from canonical branches * docs(mcp): document non-u astral matching and pin BMP agreement across V8 modes * fix(mcp): keep prototype-named properties as own properties in the dialect projection * test(mcp): select full output schemas in packet and signal schema checks * test(mcp): expect the advertised base64 schema to omit the unbounded pad-bit probe * fix(mcp): protect references into unevaluated keywords lost evaluation removes * fix(mcp): validate the doctor probe reply against the canonical output contract (#10655) * fix(mcp): validate the doctor probe reply against the canonical output contract * test(mcp): replay doctor probe validation under every output profile * test(mcp): accept typed-branch nullable unions in the advertised dialect (#10649) * test(mcp): select full output schemas in HTTP session workflows * fix(mcp): emit stack-safe classes with non-ASCII members and protect draft-07 reference siblings * fix(mcp): protect references into literal siblings of relaxed draft-07 references * feat(mcp): omit output schemas from tools/list by default (#10646) * feat(mcp): omit output schemas from tools/list by default No surveyed model API reads an output schema, MCP client validators repeat REA's own result validation, and complete output schemas were about 92% of the default tools/list. REA_MCP_OUTPUT_SCHEMA_PROFILE now resolves to off through one owner (resolveMcpOutputSchemaProfile); compact and full remain selectable. structuredContent is still delivered, and the deferred server serves both off and full from the recorded catalog with the matching recorded identity. Tests and artifact verifiers that validate results against complete advertised output contracts select full explicitly. * fix(mcp): select schemas in verification workflows * fix(mcp): select complete output schemas in the Electron verifier * fix(mcp): select complete output schemas in standalone verifier probes * fix(mcp): select complete output schemas in every verifier transport * test(mcp): select full output schemas in packet and signal schema checks * fix(mcp): validate the doctor probe reply against the canonical output contract (#10655) * fix(mcp): validate the doctor probe reply against the canonical output contract * test(mcp): replay doctor probe validation under every output profile * test(mcp): accept typed-branch nullable unions in the advertised dialect (#10649) * test(mcp): select full output schemas in HTTP session workflows * fix(mcp): keep the Evidence union on described borrowed inputs (#10597) * fix(mcp): keep the Evidence union on described borrowed inputs borrowEvidenceInput installed its advertised projection on one schema instance. A call site's .describe() rebuilds the schema from its definition, so match_native_functions advertised left and right as unconstrained values in every input profile. Install the projection in the borrowed parser's constructor so derived schemas keep it, for both borrowed inputs and borrowed arrays. * test(mcp): select the borrowed Evidence contract from its family * docs(mcp): admit baseline growth only for restored contract declarations * fix(mcp): state reduced multi-type properties as typed branches, not type lists The reduced fallback derived a property's types and emitted them as a type list, which Gemini, Moonshot and Ark reject. A property whose canonical schema is anyOf string and number therefore traded a typed union for a rejected construct when the inline projection fell back. Emit one type, or anyOf typed branches, so [T, null] becomes the dialect's nullable union. * feat(mcp)!: retire the full schema profiles and declare complete observations as a typed annotation (#10718) * refactor(mcp): declare complete observations as a typed annotation applied only on the wire * test(mcp): compare complete-observation declarations with their owning text * refactor(schema): couple Zod checks with their JSON Schema constraint keywords (#10725) * refactor(schema): couple Zod checks with their JSON Schema constraint keywords * refactor(schema): declare pattern approximations and object output roots as typed annotations (#10754) * refactor(schema): declare pattern approximations and object output roots as typed annotations * fix(schema): refuse pattern declarations JSON Schema cannot state * test(schema): select guided_workflows from its contract family * feat(mcp)!: retire the full input and output schema profiles (#10841) * feat(mcp)!: retire the full input and output schema profiles The compact input presentation is now the only advertised input schema, and output schemas are either omitted (`off`, the default) or bounded (`compact`). Catalog identity, the build-recorded digests and the recorded startup catalog collapse to those presentations: two digest profiles instead of six, one recorded catalog instead of two, and no input dialect baseline. Tests and verifiers that validated replies against listed full output schemas now validate against the canonical output contract, which REA already enforces server-side; tests that asserted canonical input restrictions read the canonical input schema instead of a full listing. BREAKING CHANGE: `REA_MCP_INPUT_SCHEMA_PROFILE=full` and `REA_MCP_OUTPUT_SCHEMA_PROFILE=full` are refused at startup and by `rea setup` with a configuration error naming the setting. Remove the setting from the client registration (or rerun setup with `REA_MCP_INPUT_SCHEMA_PROFILE=compact` / `REA_MCP_OUTPUT_SCHEMA_PROFILE=compact`). `REA_MCP_INPUT_SCHEMA_PROFILE` still accepts `compact`. Server-side validation is unchanged. * test(mcp): validate replies against canonical output contracts at every listed-schema reader tools/list omits output schemas by default, so fixtures, verifiers and the Android analysis runners that read a listed outputSchema now bind the canonical contract instead. connectLocalToolsMcp and advertisedMcpToolSchemas hand the SDK a definition carrying the canonical output schema, so the SDK client and caller-supplied validators check every successful reply. * test(mcp): resolve Android runners' output contracts from the selected repository The Android efficiency runners imported the canonical output-schema helper from the harness checkout while --repository selects the revision under test. Import it from the selected repository, as the runners already do for the SDK and Ajv. * test(mcp): let Android runners compare revisions before the canonical output helper A selected revision without scripts/lib/canonical-output-schema.mjs could not start the Android runners. Choose the output contracts in one harness helper: the selected revision's canonical contracts when it has them, otherwise its listed schemas under the full output profile it still supports. * fix(scripts): keep caller launch settings when the real Hopper verifier builds its server environment The verifier deleted REA_VERIFY_SERVER_COMMAND and REA_VERIFY_SERVER_ARGS_JSON from process.env itself before reading them, so a caller selecting an installed REA command silently ran the checkout's dist/main.js. Copy the environment, as main does, so only the child's environment changes. * test(mcp): validate whole replies against canonical output contracts wherever a listed definition is held tools/list omits output schemas by default and the full output profile is gone, so tests that handed the SDK a listed definition no longer checked complete replies. Attach the canonical output schema with withCanonicalOutputSchema at every held REA tool definition. Environment-served tools (not REA contracts), and the deferred-runtime and doctor tests that exercise per-profile listings, keep their listed definitions. * test(mcp): record the advertised catalog summary without the retired full profiles Retiring the full input and output profiles leaves only the compact input and compact output listings, so the summary drops the full-profile digests and every pattern only the full listings carried. Regenerated with npm run verify:advertised-schemas -- --update-summary.
633 lines
20 KiB
JavaScript
633 lines
20 KiB
JavaScript
import { canonicalOutputSchema } from "./canonical-output-schema.mjs";
|
|
import assert from "node:assert/strict";
|
|
import { execFile } from "node:child_process";
|
|
import { copyFile, mkdtemp, readFile, realpath, rm } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import { basename, join } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { promisify } from "node:util";
|
|
import Ajv from "ajv/dist/2020.js";
|
|
import addFormats from "ajv-formats";
|
|
import {
|
|
mcpTextValue,
|
|
requireMcpEvidenceResult,
|
|
requireMcpOperationResult,
|
|
requireMcpLifecycleResult,
|
|
} from "./mcp-verifier-results.mjs";
|
|
import { verifyHopperCliSelectors } from "./real-hopper-cli-selectors.mjs";
|
|
import { verifyLinuxHopperLaunchIsolation } from "./real-hopper-session-isolation.mjs";
|
|
import { verifyHopperNavigationAndText } from "./real-hopper-navigation.mjs";
|
|
import { verifyHopperWorkflows } from "./real-hopper-workflows.mjs";
|
|
import {
|
|
verifyHopperSearch,
|
|
verifyHopperRegexIsolation,
|
|
} from "./real-hopper-search.mjs";
|
|
|
|
const dispatcher = fileURLToPath(new URL("../rea.mjs", import.meta.url));
|
|
|
|
/** Exercise real Hopper annotation and malformed-input boundaries over MCP. */
|
|
export async function verifyHopperBoundaryContracts(
|
|
client,
|
|
options,
|
|
procedure,
|
|
targetPath,
|
|
) {
|
|
const catalog = await client.listTools();
|
|
const ajv = new Ajv({ strict: false });
|
|
addFormats(ajv);
|
|
const validators = new Map();
|
|
for (const tool of catalog.tools) {
|
|
assert.ok(
|
|
ajv.validateSchema(tool.inputSchema),
|
|
`${tool.name} input schema`,
|
|
);
|
|
assert.ok(
|
|
canonicalOutputSchema(tool.name),
|
|
`${tool.name} omitted its output schema`,
|
|
);
|
|
assert.ok(
|
|
ajv.validateSchema(canonicalOutputSchema(tool.name)),
|
|
`${tool.name} output schema`,
|
|
);
|
|
validators.set(
|
|
tool.name,
|
|
(canonicalOutputSchema(tool.name)?.$id &&
|
|
ajv.getSchema(canonicalOutputSchema(tool.name).$id)) ||
|
|
ajv.compile(canonicalOutputSchema(tool.name)),
|
|
);
|
|
}
|
|
let successfulCalls = 0;
|
|
let rejectedCalls = 0;
|
|
const rejectedOperations = new Set();
|
|
const call = async (name, args = {}) => {
|
|
const reply = await client.callTool({ name, arguments: args }, options);
|
|
const result = requireMcpOperationResult(reply, name);
|
|
const validate = validators.get(name);
|
|
assert.ok(validate, `${name} is missing from tools/list`);
|
|
assert.ok(
|
|
validate(reply.structuredContent),
|
|
`${name}: ${JSON.stringify(validate.errors)}`,
|
|
);
|
|
assert.deepEqual(reply.structuredContent, JSON.parse(mcpTextValue(reply)));
|
|
successfulCalls += 1;
|
|
return result;
|
|
};
|
|
const invalid = async (name, args, reason, failedOperation = name) => {
|
|
const reply = await client.callTool({ name, arguments: args }, options);
|
|
assert.equal(reply.isError, true, `${name} accepted invalid input`);
|
|
const { error } = JSON.parse(mcpTextValue(reply));
|
|
assert.equal(error.code, "invalid_request");
|
|
assert.equal(error.category, "invalid_input");
|
|
assert.equal(error.details.operation, failedOperation);
|
|
assert.match(error.message, reason);
|
|
rejectedCalls += 1;
|
|
rejectedOperations.add(name);
|
|
};
|
|
const address = procedure.address;
|
|
const originalName = await call("address_name", { address });
|
|
const originalComment = await call("comment", { address });
|
|
const originalInlineComment = await call("inline_comment", { address });
|
|
const activeDocument = await call("current_document");
|
|
const foreignDocument = (await call("list_documents")).find(
|
|
(name) => name !== activeDocument,
|
|
);
|
|
const navigationAndText = await verifyHopperNavigationAndText(
|
|
call,
|
|
invalid,
|
|
address,
|
|
);
|
|
const workflows = await verifyHopperWorkflows(call, invalid, procedure);
|
|
const search = {
|
|
...(await verifyHopperSearch(call, invalid, procedure)),
|
|
...(await verifyHopperRegexIsolation(client, options, call, address)),
|
|
};
|
|
const originalBookmark = (await call("list_bookmarks")).find(
|
|
(item) => item.address === address,
|
|
);
|
|
let bookmarkReplacement;
|
|
const boundaryFailures = [];
|
|
try {
|
|
if (originalBookmark !== undefined)
|
|
assert.equal(await call("unset_bookmark", { address }), true);
|
|
if (foreignDocument !== undefined) {
|
|
await invalid(
|
|
"read_bytes",
|
|
{ address, length: 8, document: foreignDocument },
|
|
/belongs to another target/u,
|
|
);
|
|
assert.equal(await call("current_document"), activeDocument);
|
|
}
|
|
for (const label of [undefined, "", "REA boundary bookmark 测试"]) {
|
|
assert.equal(
|
|
await call("set_bookmark", {
|
|
address,
|
|
...(label === undefined ? {} : { name: label }),
|
|
}),
|
|
true,
|
|
);
|
|
const bookmarks = await call("list_bookmarks");
|
|
const bookmark = bookmarks.find((item) => item.address === address);
|
|
assert.ok(bookmark, "set_bookmark did not create a bookmark");
|
|
assert.equal(bookmark.name, label || null);
|
|
const context = await call("inspect_address_context", { address });
|
|
assert.equal(context.bookmarks.state, "available");
|
|
assert.deepEqual(context.bookmarks.value, [bookmark]);
|
|
assert.equal(await call("unset_bookmark", { address }), true);
|
|
assert.ok(
|
|
!(await call("list_bookmarks")).some(
|
|
(item) => item.address === address,
|
|
),
|
|
);
|
|
}
|
|
|
|
assert.equal(
|
|
await call("set_bookmark", {
|
|
address,
|
|
name: "REA boundary bookmark before clear",
|
|
}),
|
|
true,
|
|
);
|
|
const beforeClear = (await call("list_bookmarks")).find(
|
|
(item) => item.address === address,
|
|
);
|
|
assert.deepEqual(beforeClear, {
|
|
address,
|
|
name: "REA boundary bookmark before clear",
|
|
});
|
|
assert.equal(await call("set_bookmark", { address, name: "" }), true);
|
|
const afterClear = (await call("list_bookmarks")).find(
|
|
(item) => item.address === address,
|
|
);
|
|
assert.deepEqual(afterClear, { address, name: null });
|
|
|
|
const replacementName = "REA boundary bookmark replacement";
|
|
assert.equal(
|
|
await call("set_bookmark", { address, name: replacementName }),
|
|
true,
|
|
);
|
|
const afterReplacement = (await call("list_bookmarks")).find(
|
|
(item) => item.address === address,
|
|
);
|
|
assert.deepEqual(afterReplacement, { address, name: replacementName });
|
|
assert.equal(await call("set_bookmark", { address }), true);
|
|
const afterOmittedName = (await call("list_bookmarks")).find(
|
|
(item) => item.address === address,
|
|
);
|
|
assert.deepEqual(afterOmittedName, {
|
|
address,
|
|
name: replacementName,
|
|
});
|
|
bookmarkReplacement = {
|
|
existingNameCleared: afterClear?.name === null,
|
|
nonemptyNameReplaced: afterReplacement?.name === replacementName,
|
|
omittedNamePreserved: afterOmittedName?.name === replacementName,
|
|
};
|
|
|
|
for (const [setter, getter] of [
|
|
["set_comment", "comment"],
|
|
["set_inline_comment", "inline_comment"],
|
|
]) {
|
|
const comment = "REA boundary comment 测试";
|
|
assert.equal(await call(setter, { address, comment }), true);
|
|
assert.equal(await call(getter, { address }), comment);
|
|
assert.equal(await call(setter, { address, comment: "" }), true);
|
|
assert.equal(await call(getter, { address }), null);
|
|
}
|
|
const inline = "REA inline\nsecond line";
|
|
const exact = await call("set_inline_comment", {
|
|
address,
|
|
comment: inline,
|
|
});
|
|
const observed = await call("inline_comment", { address });
|
|
assert.equal(
|
|
exact,
|
|
observed === inline,
|
|
"inline normalization must remain visible",
|
|
);
|
|
|
|
await invalid(
|
|
"set_addresses_names",
|
|
{
|
|
names: {
|
|
[address]: "rea_boundary_should_not_be_applied",
|
|
__rea_missing_batch_address__: "missing",
|
|
},
|
|
},
|
|
/Unknown Hopper address or name: __rea_missing_batch_address__/u,
|
|
);
|
|
assert.equal(await call("address_name", { address }), originalName);
|
|
assert.equal(
|
|
(await call("procedure_info", { procedure: address })).name,
|
|
originalName,
|
|
);
|
|
|
|
const renamed = "rea_boundary_renamed";
|
|
assert.equal(
|
|
await call("set_addresses_names", { names: { [address]: renamed } }).then(
|
|
(value) => value[address],
|
|
),
|
|
true,
|
|
);
|
|
assert.equal(await call("address_name", { address }), renamed);
|
|
const matches = await call("search_procedures", {
|
|
pattern: renamed,
|
|
case_sensitive: true,
|
|
});
|
|
assert.ok(
|
|
matches.some(
|
|
(item) => item.address === address && item.value === renamed,
|
|
),
|
|
);
|
|
assert.equal(
|
|
(
|
|
await call("analyze_function", {
|
|
procedure: address,
|
|
detail: "complete",
|
|
})
|
|
).procedure.name,
|
|
renamed,
|
|
);
|
|
assert.equal(
|
|
await call("set_address_name", { address, name: "add" }),
|
|
true,
|
|
);
|
|
assert.equal(
|
|
await call("procedure_address", { procedure: "add" }),
|
|
address,
|
|
);
|
|
assert.equal(
|
|
(await call("procedure_info", { procedure: "add" })).entrypoint,
|
|
address,
|
|
);
|
|
assert.equal(
|
|
(await call("read_bytes", { address: "add", length: 8 })).address,
|
|
address,
|
|
);
|
|
assert.equal(
|
|
await call("procedure_address", { procedure: address.slice(2) }),
|
|
address,
|
|
);
|
|
|
|
for (const query of ["-1", "0x10000000000000000", "0xffffffffffffffff"]) {
|
|
for (const name of [
|
|
"read_bytes",
|
|
"address_to_file_offset",
|
|
"resolve_containing_procedure",
|
|
"procedure_info",
|
|
]) {
|
|
await invalid(
|
|
name,
|
|
name === "procedure_info"
|
|
? { procedure: query }
|
|
: {
|
|
address: query,
|
|
...(name === "read_bytes" ? { length: 8 } : {}),
|
|
},
|
|
/usable unsigned 64-bit range/u,
|
|
);
|
|
}
|
|
}
|
|
await invalid(
|
|
"read_bytes",
|
|
{ address: "0x0", length: 8 },
|
|
/Address is outside every segment/u,
|
|
);
|
|
await invalid(
|
|
"procedure_info",
|
|
{ procedure: address, document: "__rea_missing_document__" },
|
|
/Unknown Hopper document/u,
|
|
);
|
|
await invalid(
|
|
"search_procedures",
|
|
{ pattern: "[", mode: "regex" },
|
|
/Invalid regex pattern/u,
|
|
);
|
|
// Invalid calls must leave the same authenticated bridge usable.
|
|
assert.equal(
|
|
(await call("read_bytes", { address, length: 8 })).returned_bytes,
|
|
8,
|
|
);
|
|
const mapping = await call("address_to_file_offset", { address });
|
|
const bytes = await call("read_bytes", { address, length: 8 });
|
|
const file = await readFile(targetPath);
|
|
assert.equal(
|
|
bytes.bytes_hex,
|
|
file
|
|
.subarray(mapping.file_offset, mapping.file_offset + 8)
|
|
.toString("hex"),
|
|
);
|
|
const segments = await call("list_segments");
|
|
const containing = segments.find(
|
|
(segment) =>
|
|
BigInt(segment.start) <= BigInt(address) &&
|
|
BigInt(address) < BigInt(segment.end),
|
|
);
|
|
assert.ok(containing, "fixture procedure has no containing segment");
|
|
const lastByte = `0x${(BigInt(containing.end) - 1n).toString(16)}`;
|
|
const prefix = await call("read_bytes", { address: lastByte, length: 8 });
|
|
assert.equal(prefix.returned_bytes, 1);
|
|
assert.equal(prefix.bytes_hex.length, 2);
|
|
assert.equal(prefix.complete, false);
|
|
const synthetic = segments.find(
|
|
(segment) => segment.name === "External Symbols",
|
|
);
|
|
assert.ok(synthetic, "fixture omitted synthetic external-symbol memory");
|
|
await invalid(
|
|
"address_to_file_offset",
|
|
{ address: synthetic.start },
|
|
/no authoritative file-offset mapping/u,
|
|
);
|
|
const health = (await call("binary_session")).provider_operation_health;
|
|
assert.equal(
|
|
health.state,
|
|
"idle",
|
|
"a live GUI bridge must remain healthy after its launcher helper exits",
|
|
);
|
|
} catch (error) {
|
|
boundaryFailures.push(error);
|
|
throw error;
|
|
} finally {
|
|
const restorations = [
|
|
() => call("set_address_name", { address, name: originalName ?? "" }),
|
|
() => call("set_comment", { address, comment: originalComment ?? "" }),
|
|
() =>
|
|
call("set_inline_comment", {
|
|
address,
|
|
comment: originalInlineComment ?? "",
|
|
}),
|
|
async () => {
|
|
await call("unset_bookmark", { address });
|
|
if (originalBookmark === undefined) return;
|
|
assert.equal(
|
|
await call("set_bookmark", {
|
|
address,
|
|
...(originalBookmark.name === null
|
|
? {}
|
|
: { name: originalBookmark.name }),
|
|
}),
|
|
true,
|
|
"Could not restore the original disposable-target bookmark",
|
|
);
|
|
const restored = (await call("list_bookmarks")).find(
|
|
(item) => item.address === address,
|
|
);
|
|
assert.deepEqual(restored, originalBookmark);
|
|
},
|
|
];
|
|
const restorationErrors = [];
|
|
for (const restore of restorations) {
|
|
try {
|
|
await restore();
|
|
} catch (error) {
|
|
restorationErrors.push(error);
|
|
}
|
|
}
|
|
if (restorationErrors.length > 0) {
|
|
throw new AggregateError(
|
|
[...boundaryFailures, ...restorationErrors],
|
|
"Could not restore all disposable Hopper boundary state",
|
|
);
|
|
}
|
|
}
|
|
return {
|
|
schemaCount: catalog.tools.length,
|
|
successfulCalls,
|
|
rejectedCalls,
|
|
rejectedOperations: [...rejectedOperations],
|
|
foreignDocumentVerified: foreignDocument !== undefined,
|
|
navigationAndText,
|
|
workflows,
|
|
search,
|
|
bookmarkReplacement,
|
|
};
|
|
}
|
|
|
|
/** Prove actual document disposal and shared CLI/MCP behavior on disposable copies. */
|
|
export async function verifyHopperLifecycleAndCli(client, options, targets) {
|
|
const directory = await realpath(
|
|
await mkdtemp(join(tmpdir(), "hopper-boundary-")),
|
|
);
|
|
const suffix = basename(directory);
|
|
const primary = join(directory, `primary-${suffix}`);
|
|
const secondary = join(directory, `secondary-${suffix}`);
|
|
const call = async (name, args = {}) =>
|
|
requireMcpOperationResult(
|
|
await client.callTool({ name, arguments: args }, options),
|
|
name,
|
|
);
|
|
const cli = promisify(execFile);
|
|
const runCli = (args) => {
|
|
const pending = cli(process.execPath, args, {
|
|
timeout: 180_000,
|
|
maxBuffer: 1_048_576,
|
|
});
|
|
if (pending.child.pid !== undefined)
|
|
targets.ownedProcessIds.add(pending.child.pid);
|
|
return pending;
|
|
};
|
|
try {
|
|
await copyFile(targets.primary, primary);
|
|
await copyFile(targets.secondary, secondary);
|
|
await call("open_binary", { path: primary });
|
|
const primaryProcedures = await call("list_procedures");
|
|
const entry = primaryProcedures.find((item) =>
|
|
item.value.endsWith("rea_entry"),
|
|
);
|
|
assert.ok(entry, "primary fixture omitted its entry procedure");
|
|
const expectedFunction = await call("analyze_function", {
|
|
procedure: entry.value,
|
|
detail: "complete",
|
|
});
|
|
const firstDocument = await call("current_document");
|
|
const linuxApplicationIsolation =
|
|
process.platform === "linux"
|
|
? await verifyLinuxHopperLaunchIsolation({
|
|
call,
|
|
runCli,
|
|
dispatcher,
|
|
primary,
|
|
secondary,
|
|
})
|
|
: null;
|
|
await call("open_binary", { path: secondary });
|
|
const secondDocument = await call("current_document");
|
|
assert.notEqual(firstDocument, secondDocument);
|
|
assert.ok(
|
|
!(await call("list_documents")).includes(firstDocument),
|
|
"target switching retained the old native document",
|
|
);
|
|
const procedures = await call("list_procedures");
|
|
await verifyBatchCancellation(client, options, procedures);
|
|
const address = procedures[0].address;
|
|
const expected = await call("read_bytes", {
|
|
address,
|
|
length: 8,
|
|
document: secondDocument,
|
|
});
|
|
await call("open_binary", { path: primary });
|
|
const query = "REA_C_LEAF __rea_missing_phrase__";
|
|
const expectedTrace = await call("trace_feature", { query });
|
|
assert.deepEqual(expectedTrace.matches, []);
|
|
await call("close_binary");
|
|
|
|
const common = [
|
|
"--length",
|
|
"8",
|
|
"--provider",
|
|
"hopper",
|
|
"--format",
|
|
"json",
|
|
];
|
|
const { stdout } = await runCli([
|
|
dispatcher,
|
|
"read-bytes",
|
|
secondary,
|
|
address,
|
|
...common,
|
|
]);
|
|
const evidence = JSON.parse(stdout);
|
|
assert.equal(evidence.provider.id, "hopper");
|
|
assert.equal(evidence.subject.local_path, secondary);
|
|
assert.deepEqual(evidence.normalized_result, expected);
|
|
const traced = await runCli([
|
|
dispatcher,
|
|
"trace",
|
|
primary,
|
|
query,
|
|
"--provider",
|
|
"hopper",
|
|
"--format",
|
|
"json",
|
|
]);
|
|
const traceEvidence = JSON.parse(traced.stdout);
|
|
assert.equal(traceEvidence.subject.local_path, primary);
|
|
assert.deepEqual(traceEvidence.normalized_result, expectedTrace);
|
|
const analyzed = await runCli([
|
|
dispatcher,
|
|
"function",
|
|
primary,
|
|
entry.value,
|
|
"--provider",
|
|
"hopper",
|
|
"--format",
|
|
"json",
|
|
]);
|
|
assert.deepEqual(
|
|
JSON.parse(analyzed.stdout).normalized_result,
|
|
expectedFunction,
|
|
);
|
|
let cliTerminalFunctionParity = null;
|
|
let cliNamedSelectorParity = null;
|
|
if (targets.unicode !== undefined) {
|
|
const objc = join(directory, `objc-${suffix}`);
|
|
await copyFile(targets.unicode, objc);
|
|
await call("open_binary", { path: objc });
|
|
const procedures = await call("list_procedures");
|
|
const delegate = procedures.find(
|
|
(item) => item.value === "-[REAWidget delegate]",
|
|
);
|
|
assert.ok(delegate, "Objective-C fixture omitted its tail-call method");
|
|
const expected = await call("analyze_function", {
|
|
procedure: delegate.address,
|
|
detail: "complete",
|
|
});
|
|
await call("close_binary");
|
|
const analyzed = await runCli([
|
|
dispatcher,
|
|
"function",
|
|
objc,
|
|
delegate.address,
|
|
"--provider",
|
|
"hopper",
|
|
"--format",
|
|
"json",
|
|
]);
|
|
assert.deepEqual(JSON.parse(analyzed.stdout).normalized_result, expected);
|
|
cliTerminalFunctionParity = true;
|
|
await call("open_binary", { path: objc });
|
|
cliNamedSelectorParity = await verifyHopperCliSelectors(
|
|
call,
|
|
runCli,
|
|
dispatcher,
|
|
objc,
|
|
);
|
|
}
|
|
let failure;
|
|
try {
|
|
await runCli([
|
|
dispatcher,
|
|
"read-bytes",
|
|
secondary,
|
|
"0x10000000000000000",
|
|
...common,
|
|
]);
|
|
} catch (error) {
|
|
assert.equal(error.code, 1);
|
|
failure = JSON.parse(error.stdout);
|
|
}
|
|
assert.ok(failure, "CLI accepted an overflowing address");
|
|
assert.equal(failure.code, "invalid_request");
|
|
assert.equal(failure.category, "invalid_input");
|
|
assert.match(failure.message, /usable unsigned 64-bit range/u);
|
|
|
|
await call("open_binary", { path: primary });
|
|
assert.ok(
|
|
!(await call("list_documents")).includes(secondDocument),
|
|
"MCP or CLI cleanup retained the closed native document",
|
|
);
|
|
await call("close_binary");
|
|
return {
|
|
targetSwitchDisposedDocument: true,
|
|
cliByteParity: true,
|
|
cliInvalidAddress: true,
|
|
cliLiteralTraceParity: true,
|
|
cliFunctionDossierParity: true,
|
|
cliTerminalFunctionParity,
|
|
cliNamedSelectorParity,
|
|
callerCancellationRecovered: true,
|
|
closedDocumentAbsent: true,
|
|
linuxApplicationIsolation,
|
|
};
|
|
} finally {
|
|
await call("close_binary");
|
|
await rm(directory, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
const verifyBatchCancellation = async (client, options, procedures) => {
|
|
const controller = new AbortController();
|
|
let cancelled = false;
|
|
await assert.rejects(
|
|
client.callTool(
|
|
{
|
|
name: "batch_decompile",
|
|
arguments: { addresses: procedures.map((item) => item.address) },
|
|
},
|
|
{
|
|
...options,
|
|
signal: controller.signal,
|
|
onprogress: (update) => {
|
|
options.onprogress?.(update);
|
|
// Cancel between real decompilations, after Hopper served one item.
|
|
if (update.message?.includes("Hopper bridge completed request")) {
|
|
cancelled = true;
|
|
controller.abort();
|
|
}
|
|
},
|
|
},
|
|
),
|
|
/aborted/u,
|
|
);
|
|
assert.ok(cancelled, "cancellation did not follow a real Hopper response");
|
|
const recovered = requireMcpEvidenceResult(
|
|
await client.callTool({ name: "list_procedures", arguments: {} }, options),
|
|
"list_procedures",
|
|
);
|
|
assert.deepEqual(recovered, procedures);
|
|
const status = requireMcpLifecycleResult(
|
|
await client.callTool({ name: "binary_session", arguments: {} }, options),
|
|
"binary_session",
|
|
);
|
|
assert.equal(status.provider_operation_health.state, "idle");
|
|
};
|