Add evidence-backed investigation workflows

This commit is contained in:
morluto
2026-07-12 21:12:18 +00:00
parent 4110a4d717
commit 4ff4c11a00
178 changed files with 26320 additions and 1222 deletions
+283
View File
@@ -0,0 +1,283 @@
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { dirname, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import writeFileAtomic from "write-file-atomic";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const outputPath = resolve(root, "metadata/completion-manifest.json");
const check = process.argv.slice(2).includes("--check");
const unexpected = process.argv
.slice(2)
.filter((argument) => argument !== "--check");
if (unexpected.length > 0)
throw new Error(`Unknown argument: ${unexpected.join(" ")}`);
const artifactPaths = [
"bridge/hopper_bridge.py",
"package-lock.json",
"scripts/verify-conformance-fixtures.mjs",
"scripts/verify-package.mjs",
"scripts/verify-real-hopper.mjs",
"skills/rea-analysis/SKILL.md",
"src/application/AnalysisProvider.ts",
"src/application/ArtifactExtraction.ts",
"src/application/ArtifactGraphConstruction.ts",
"src/application/ArtifactInventory.ts",
"src/application/CompositeProvider.ts",
"src/application/EvidenceLedger.ts",
"src/application/DirectAnalysis.ts",
"src/application/ProcessSampling.ts",
"src/application/ReferenceSourceImport.ts",
"src/application/ReferenceSourceImportEntries.ts",
"src/application/ReferenceSourceImportPolicy.ts",
"src/application/ReferenceSourceImportTypes.ts",
"src/application/ReferenceSourceVcsAdapter.ts",
"src/application/RealHopperAssertions.ts",
"src/application/runtime.ts",
"src/contracts/nativeToolContracts.ts",
"src/contracts/artifactToolContracts.ts",
"src/contracts/artifactComparisonExample.ts",
"src/contracts/functionComparisonExample.ts",
"src/contracts/investigationExamples.ts",
"src/contracts/toolContractExamples.ts",
"src/contracts/processCaptureExample.ts",
"src/contracts/enhancedInputs.ts",
"src/contracts/toolContracts.ts",
"src/contracts/toolOutputSchemas.ts",
"src/contracts/unknownContractExamples.ts",
"src/domain/evidence.ts",
"src/domain/artifactGraph.ts",
"src/domain/artifactComparison.ts",
"src/domain/artifactInventoryEvidence.ts",
"src/domain/functionComparison.ts",
"src/domain/functionComparisonNormalization.ts",
"src/domain/functionComparisonResults.ts",
"src/domain/functionComparisonSchemas.ts",
"src/domain/bundleComparison.ts",
"src/domain/changedBehavior.ts",
"src/domain/callPath.ts",
"src/domain/staticRuntimeCorrelation.ts",
"src/domain/reconstructionVerification.ts",
"src/domain/reconstructionVerificationSchemas.ts",
"src/domain/reconstructionUnknowns.ts",
"src/domain/referenceSourceGraph.ts",
"src/domain/referenceSourceClassification.ts",
"src/domain/referenceSourceImportParsing.ts",
"src/domain/referenceSourcePolicy.ts",
"src/domain/functionDossierEvidence.ts",
"src/domain/evidenceBundle.ts",
"src/domain/nativeInspection.ts",
"src/domain/processCapture.ts",
"src/domain/residualUnknown.ts",
"src/server/sessionToolPolicies.ts",
"src/server/registerEnhancedTools.ts",
"src/server/registerEvidenceTools.ts",
"src/server/registerArtifactTools.ts",
"src/server/registerArtifactComparisonTool.ts",
"src/server/registerFunctionComparisonTool.ts",
"src/server/registerBundleComparisonTool.ts",
"src/server/registerInvestigationTools.ts",
"src/server/recordDerivedEvidence.ts",
"src/server/registerNativeTools.ts",
"src/server/registerProcessComparisonTool.ts",
"src/server/registerSessionTools.ts",
"src/native/CommandRunner.ts",
"src/native/NativeMacOSProvider.ts",
"src/native/NativeMachoInspection.ts",
"src/native/parsers/codesign.ts",
"src/native/parsers/demangle.ts",
"src/native/parsers/dyldInfo.ts",
"src/native/parsers/lipo.ts",
"src/native/parsers/otool.ts",
"src/native/parsers/plist.ts",
"src/artifacts/ArtifactPaths.ts",
"src/artifacts/ArtifactProvider.ts",
"src/artifacts/ArtifactReader.ts",
"src/artifacts/AsarArtifactReader.ts",
"src/artifacts/DirectoryArtifactReader.ts",
"src/artifacts/MachOSliceArtifactReader.ts",
"src/artifacts/SafeOutputTree.ts",
"src/artifacts/StreamBytes.ts",
"src/artifacts/ZipArtifactReader.ts",
"src/reference/ReferenceSourceReaderEntries.ts",
"src/reference/ReferenceSourceReaderErrors.ts",
"src/reference/ReferenceSourceReaderFile.ts",
"src/reference/ReferenceSourceReaderPaths.ts",
"src/reference/ReferenceSourceReaderTypes.ts",
"src/reference/ReferenceSourceReaderValidate.ts",
"src/reference/ReferenceSourceReader.ts",
];
const artifacts = await Promise.all(
artifactPaths.map(async (path) => ({
path,
sha256: sha256(await readFile(resolve(root, path))),
})),
);
const packageJson = JSON.parse(
await readFile(resolve(root, "package.json"), "utf8"),
);
const toolSource = await readFile(
resolve(root, "src/contracts/toolContracts.ts"),
"utf8",
);
const nativeToolSource = await readFile(
resolve(root, "src/contracts/nativeToolContracts.ts"),
"utf8",
);
const artifactToolSource = await readFile(
resolve(root, "src/contracts/artifactToolContracts.ts"),
"utf8",
);
const skillSource = await readFile(
resolve(root, "skills/rea-analysis/SKILL.md"),
"utf8",
);
const toolCount =
countContracts(toolSource) +
countProviderContracts(nativeToolSource, "NATIVE", "native") +
countProviderContracts(artifactToolSource, "ARTIFACT", "artifact");
const skillToolCount = Number(/tool_count:\s*(\d+)/u.exec(skillSource)?.[1]);
if (!Number.isSafeInteger(skillToolCount) || skillToolCount !== toolCount)
throw new Error(
`Skill tool_count drift: skill=${String(skillToolCount)} contracts=${toolCount}`,
);
const manifest = {
schema_version: 1,
inputs: {
artifacts,
package: { name: packageJson.name, version: packageJson.version },
providers: [
{
id: "hopper",
version: null,
authority: "shipped-artifact",
},
{
id: "native-macos",
version: null,
authority: "shipped-artifact",
},
{
id: "rea-artifact-graph",
version: "1",
authority: "shipped-artifact",
},
],
environments: [
{ id: "package-isolation", isolation: "process" },
{ id: "real-hopper-macos", isolation: "process" },
],
scenarios: [
{ id: "conformance-fixtures", version: 1 },
{ id: "package-install", version: 1 },
{ id: "real-hopper-two-binary", version: 2 },
],
schemas: { evidence: 2, evidence_bundle: 2, completion: 1 },
tool_count: toolCount,
},
evidence_index: [],
outcomes: {
pass: [],
fail: [],
unsupported: [
{
claim_id: "real-hopper-verification",
reason:
"Generated repository metadata contains no checked-in real-Hopper capture.",
evidence_ids: [],
},
],
truncated: [],
unknown: [
{
claim_id: "semantic-conformance-complete",
reason:
"Completion requires external verifier evidence and cannot be inferred from test counts.",
evidence_ids: [],
},
],
},
};
validateOutcomeEvidence(manifest);
const serialized = `${JSON.stringify(manifest, null, 2)}\n`;
if (check) {
let existing;
try {
existing = await readFile(outputPath, "utf8");
} catch (error) {
if (error?.code === "ENOENT")
throw new Error(
`Missing generated manifest: ${relative(root, outputPath)}`,
);
throw error;
}
if (existing !== serialized)
throw new Error(
`Generated completion metadata is stale or tampered: run npm run completion:generate`,
);
} else {
await writeFileAtomic(outputPath, serialized, { encoding: "utf8" });
}
process.stdout.write(
`${JSON.stringify({ mode: check ? "check" : "generate", path: relative(root, outputPath), toolCount })}\n`,
);
function sha256(value) {
return createHash("sha256").update(value).digest("hex");
}
function countContracts(source) {
const sections = [
["OFFICIAL", "official"],
["ENHANCED", "enhanced"],
["SESSION", "session"],
];
return sections.reduce((total, [section, constructor]) => {
const match = new RegExp(
`export const ${section}_TOOL_CONTRACTS = \\[([\\s\\S]*?)\\n\\] as const satisfies`,
"u",
).exec(source);
if (match?.[1] === undefined)
throw new Error(`Cannot derive ${section.toLowerCase()} tool contracts`);
return (
total +
[...match[1].matchAll(new RegExp(`^ ${constructor}\\($`, "gmu"))].length
);
}, 0);
}
function countProviderContracts(source, section, constructor) {
const match = new RegExp(
`export const ${section}_TOOL_CONTRACTS = \\[([\\s\\S]*?)\\n\\] as const satisfies`,
"u",
).exec(source);
if (match?.[1] === undefined)
throw new Error(`Cannot derive ${section.toLowerCase()} tool contracts`);
return [...match[1].matchAll(new RegExp(`^ ${constructor}\\($`, "gmu"))]
.length;
}
function validateOutcomeEvidence(value) {
const evidenceIds = new Set(
value.evidence_index.map(({ evidence_id }) => evidence_id),
);
for (const status of ["pass", "fail"]) {
for (const outcome of value.outcomes[status]) {
if (outcome.evidence_ids.length === 0)
throw new Error(
`${status} outcome ${outcome.claim_id} has no evidence`,
);
for (const evidenceId of outcome.evidence_ids)
if (!evidenceIds.has(evidenceId))
throw new Error(
`${status} outcome ${outcome.claim_id} references missing evidence ${evidenceId}`,
);
}
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env node
// Route production MCP before importing Incur. Incur owns registration helpers
// such as `mcp add`, while only dist/main.js may serve the 50-tool stdio server.
// such as `mcp add`, while only dist/main.js may serve the 68-tool stdio server.
const args = process.argv.slice(2);
const isMcpMode =
args[0] === "--mcp" || (args.length === 1 && args[0] === "mcp");
+150 -46
View File
@@ -13,12 +13,17 @@ import { promisify } from "node:util";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
const expectedToolCount = TOOL_CONTRACTS.length;
// Exercise the packed artifact in isolated HOME and prefix directories so the
// verifier cannot mutate real MCP registrations or rely on checkout-only files.
const exec = promisify(execFile);
const root = process.cwd();
const workspace = await mkdtemp(join(tmpdir(), "rea-package-"));
const evidenceRoot = join(workspace, "evidence");
let tarball;
try {
@@ -39,6 +44,7 @@ try {
const home = join(workspace, "home");
const fakeBin = join(workspace, "bin");
await mkdir(fakeBin, { recursive: true });
await mkdir(evidenceRoot, { recursive: true });
const brew = join(fakeBin, "brew");
const swVers = join(fakeBin, "sw_vers");
const npx = join(fakeBin, "npx");
@@ -77,6 +83,7 @@ try {
PATH: `${fakeBin}:${process.env.PATH ?? ""}`,
HOPPER_LAUNCHER_PATH: hopper,
REA_NPX_LOG: npxLog,
REA_EVIDENCE_ROOTS_JSON: JSON.stringify([evidenceRoot]),
};
await exec(
"npm",
@@ -87,66 +94,150 @@ try {
const help = await run(cli, ["--help"], environment);
const llms = await run(cli, ["--llms"], environment);
const doctor = json(await run(cli, ["doctor", "--json"], environment));
const expectedDoctorHealth = process.platform === "darwin";
if (
!help.includes("setup") ||
!help.includes("inventory-artifact") ||
!help.includes("extract-artifact") ||
!llms.includes("decompile") ||
doctor.healthy !== true
!llms.includes("inventory-artifact") ||
doctor.healthy !== expectedDoctorHealth ||
doctor.checks?.find(({ name }) => name === "hopper")?.ok !== true
)
throw new Error("packaged CLI discovery or doctor failed");
throw new Error(
`packaged CLI discovery or doctor failed: ${JSON.stringify({ helpSetup: help.includes("setup"), llmsDecompile: llms.includes("decompile"), doctor })}`,
);
const artifactArchive = join(workspace, "artifact.zip");
const artifactWriter = new ZipWriter(new Uint8ArrayWriter());
await artifactWriter.add("app/main.js", new TextReader("main();"));
await writeFile(artifactArchive, await artifactWriter.close());
const artifactInventory = json(
await run(
cli,
["inventory-artifact", artifactArchive, "--limit", "500", "--json"],
environment,
),
);
if (
artifactInventory.operation !== "inventory_artifact" ||
artifactInventory.provider?.id !== "rea-artifact-graph" ||
artifactInventory.normalized_result?.manifest?.root_format !== "zip"
)
throw new Error("packaged artifact inventory CLI failed");
const { createEvidence } = await import(
new URL("../dist/domain/evidence.js", import.meta.url)
);
const { createEvidenceBundle, serializeEvidenceBundle } = await import(
new URL("../dist/domain/evidenceBundle.js", import.meta.url)
);
const sourceBundle = createEvidenceBundle([
createEvidence(
undefined,
{ id: "package", name: "Package verifier", version: "1" },
{ operation: "health", parameters: {}, result: true },
),
]);
const sourceBundlePath = join(evidenceRoot, "source.json");
const canonicalBundlePath = join(evidenceRoot, "canonical.json");
await writeFile(sourceBundlePath, serializeEvidenceBundle(sourceBundle));
const importedBundle = json(
await run(
cli,
["evidence-import", sourceBundlePath, "--json"],
environment,
),
);
const exportedBundle = json(
await run(
cli,
["evidence-export", sourceBundlePath, canonicalBundlePath, "--json"],
environment,
),
);
if (
importedBundle.imported !== 1 ||
importedBundle.total !== 1 ||
exportedBundle.records !== 1 ||
(await readFile(canonicalBundlePath, "utf8")) !==
serializeEvidenceBundle(sourceBundle)
)
throw new Error("packaged CLI evidence bundle round trip failed");
await run(cli, ["mcp", "add"], environment);
const mcpRegistration = await readFile(npxLog, "utf8");
if (!mcpRegistration.includes("add-mcp npx -y rea-agents mcp --name rea"))
throw new Error("Incur mcp add did not register the floating npx command");
const skillPath = join(home, ".agents/skills/rea-analysis/SKILL.md");
const siblingSkillPath = join(home, ".agents/skills/unrelated/SKILL.md");
if (process.platform === "darwin") {
await mkdir(join(home, ".agents/skills/rea-analysis"), {
recursive: true,
});
await mkdir(join(home, ".agents/skills/unrelated"), { recursive: true });
await writeFile(skillPath, "stale managed skill\n");
await writeFile(siblingSkillPath, "unrelated skill\n");
}
const first = json(await run(cli, ["setup", "--yes", "--json"], environment));
const second = json(
await run(cli, ["setup", "--yes", "--json"], environment),
);
if (
first.status !== "ready" ||
second.status !== "ready" ||
second.actions.length !== 0
)
throw new Error("packaged setup was not ready and idempotent");
for (const configPath of [claudeConfig, cursorConfig]) {
const config = json(await readFile(configPath, "utf8"));
if (process.platform === "darwin") {
if (
config.existing !== true ||
config.mcpServers?.rea?.command !== "npx" ||
JSON.stringify(config.mcpServers?.rea?.args) !==
JSON.stringify(["-y", "rea-agents", "mcp"])
first.status !== "ready" ||
second.status !== "ready" ||
second.actions.length !== 0
)
throw new Error("packaged client readback failed");
throw new Error("packaged setup was not ready and idempotent");
for (const configPath of [claudeConfig, cursorConfig]) {
const config = json(await readFile(configPath, "utf8"));
if (
config.existing !== true ||
config.mcpServers?.rea?.command !== "npx" ||
JSON.stringify(config.mcpServers?.rea?.args) !==
JSON.stringify(["-y", "rea-agents", "mcp"])
)
throw new Error("packaged client readback failed");
if (
!(await readFile(`${configPath}.rea.backup`, "utf8")).includes(
"existing",
)
)
throw new Error("packaged client backup failed");
}
const skill = await readFile(skillPath, "utf8");
const canonicalSkill = await readFile(
join(root, "skills/rea-analysis/SKILL.md"),
"utf8",
);
if (skill !== canonicalSkill)
throw new Error("packaged skill did not match its canonical source");
if (
!(await readFile(`${configPath}.rea.backup`, "utf8")).includes("existing")
(await readFile(`${skillPath}.rea.backup`, "utf8")) !==
"stale managed skill\n" ||
(await readFile(siblingSkillPath, "utf8")) !== "unrelated skill\n"
)
throw new Error("packaged client backup failed");
}
const skill = await readFile(
join(home, ".agents/skills/rea-analysis/SKILL.md"),
"utf8",
);
const canonicalSkill = await readFile(
join(root, "skills/rea-analysis/SKILL.md"),
"utf8",
);
if (skill !== canonicalSkill)
throw new Error("packaged skill did not match its canonical source");
throw new Error("packaged stale-skill upgrade was not isolated");
await writeFile(cursorConfig, "malformed");
const failed = json(
await run(cli, ["setup", "--yes", "--json"], environment),
);
if (
failed.status !== "needs_human" ||
(await readFile(cursorConfig, "utf8")) !== "malformed"
)
throw new Error("packaged setup failure recovery did not preserve input");
await writeFile(cursorConfig, "{}\n");
const recovered = json(
await run(cli, ["setup", "--yes", "--json"], environment),
);
if (recovered.status !== "ready")
throw new Error("packaged setup did not recover");
await writeFile(cursorConfig, "malformed");
const failed = json(
await run(cli, ["setup", "--yes", "--json"], environment),
);
if (
failed.status !== "needs_human" ||
(await readFile(cursorConfig, "utf8")) !== "malformed"
)
throw new Error("packaged setup failure recovery did not preserve input");
await writeFile(cursorConfig, "{}\n");
const recovered = json(
await run(cli, ["setup", "--yes", "--json"], environment),
);
if (recovered.status !== "ready")
throw new Error("packaged setup did not recover");
} else if (
first.status !== "needs_human" ||
second.status !== "needs_human"
) {
throw new Error("packaged setup did not reject an unsupported host");
}
const transport = new StdioClientTransport({
command: cli,
@@ -161,14 +252,27 @@ try {
const client = new Client({ name: "package-smoke", version: "1.0.0" });
try {
await client.connect(transport);
if ((await client.listTools()).tools.length !== 50)
throw new Error("packaged MCP did not expose 50 tools");
if ((await client.listTools()).tools.length !== expectedToolCount)
throw new Error("packaged MCP tool inventory diverged from contracts");
const result = await client.callTool({
name: "current_document",
arguments: {},
});
if (result.isError !== true)
throw new Error("packaged target-free MCP omitted no-target error");
const mcpBundlePath = join(evidenceRoot, "mcp.json");
const mcpExport = await client.callTool({
name: "export_evidence_bundle",
arguments: { path: mcpBundlePath },
});
if (mcpExport.isError === true)
throw new Error("packaged MCP evidence export failed");
const mcpImport = await client.callTool({
name: "import_evidence_bundle",
arguments: { path: mcpBundlePath },
});
if (mcpImport.isError === true)
throw new Error("packaged MCP evidence import failed");
} catch (cause) {
throw new Error(`packaged MCP smoke failed: ${mcpStderr}`, { cause });
} finally {
@@ -177,7 +281,7 @@ try {
}
process.stdout.write(
`${JSON.stringify({ cli: true, incurMcpCommand: "npx -y rea-agents mcp", doctor: true, setup: "idempotent", clients: 2, backupReadback: true, failureRecovery: true, skill: true, mcpTools: 50, targetFree: true })}\n`,
`${JSON.stringify({ cli: true, artifactCli: true, evidenceCli: true, incurMcpCommand: "npx -y rea-agents mcp", doctor: "platform-appropriate", setup: process.platform === "darwin" ? "idempotent" : "unsupported-host-rejected", clients: process.platform === "darwin" ? 2 : 0, backupReadback: process.platform === "darwin", failureRecovery: process.platform === "darwin", skill: process.platform === "darwin", mcpTools: expectedToolCount, evidenceMcp: true, targetFree: true })}\n`,
);
} finally {
if (tarball) await rm(join(root, tarball), { force: true });
+187 -152
View File
@@ -6,6 +6,12 @@ import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
import {
firstProcedureAddress,
requireAddressArray,
requireFunctionDossier,
requirePseudocode,
} from "../dist/application/RealHopperAssertions.js";
const execFileAsync = promisify(execFile);
const timeout = 180_000;
@@ -26,90 +32,176 @@ const requireSuccessfulTool = (result, operation) => {
throw new Error(`${operation} failed: ${textValue(result)}`);
}
const value = jsonValue(result);
if (value === null || typeof value !== "object" || !("result" in value)) {
if (
value === null ||
typeof value !== "object" ||
!("normalized_result" in value)
) {
throw new Error(`${operation} omitted its evidence result`);
}
return value.result;
return value.normalized_result;
};
const firstProcedureAddress = (result) => {
const items = result.structuredContent?.result?.items;
if (!Array.isArray(items) || items.length === 0) {
throw new Error("The verifier target contains no analyzed procedure");
}
const address = items[0]?.address;
if (typeof address !== "string" || !/^0x[0-9a-f]+$/iu.test(address)) {
throw new Error("list_procedures returned an invalid procedure address");
}
return address;
};
const requirePseudocode = (value, operation) => {
if (typeof value !== "string" || value.trim().length === 0) {
throw new Error(`${operation} returned empty pseudocode`);
}
if (value === "No output" || value.startsWith("Error:")) {
throw new Error(`${operation} returned an embedded failure: ${value}`);
const requireOverview = (value, operation) => {
if (
value === null ||
typeof value !== "object" ||
typeof value.document !== "string" ||
value.document.length === 0 ||
!Number.isInteger(value.procedure_count) ||
value.procedure_count < 1 ||
!Number.isInteger(value.segment_count) ||
value.segment_count < 1 ||
!Array.isArray(value.segments)
) {
throw new Error(`${operation} returned no analyzed binary overview`);
}
return value;
};
const requireFunctionDossier = (value, expectedAddress) => {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
throw new Error("analyze_function returned no function dossier");
const requireTruthfulMemoryRegions = (segments) => {
if (!Array.isArray(segments) || segments.length === 0) {
throw new Error("list_segments returned no real memory regions");
}
if (value.procedure?.address !== expectedAddress) {
throw new Error("analyze_function returned the wrong procedure");
}
if (
typeof value.procedure?.name !== "string" ||
value.procedure.name.trim().length === 0
) {
throw new Error("analyze_function omitted the procedure name");
}
requirePseudocode(value.pseudocode?.text, "analyze_function");
for (const field of [
"comments",
"callers",
"callees",
"incoming_references",
"outgoing_references",
"referenced_strings",
"referenced_names",
"basic_blocks",
]) {
const collection = value[field];
if (
collection === null ||
typeof collection !== "object" ||
!Array.isArray(collection.items) ||
!Number.isInteger(collection.total)
) {
throw new Error(`analyze_function returned an invalid ${field} result`);
}
}
for (const field of ["callers", "callees"]) {
for (const identity of value[field].items) {
if (
typeof identity?.address !== "string" ||
typeof identity?.name !== "string"
) {
throw new Error(`analyze_function returned an untyped ${field} item`);
const regions = segments.flatMap((segment) => [
segment,
...(Array.isArray(segment.sections) ? segment.sections : []),
]);
for (const region of regions) {
for (const permission of ["readable", "writable", "executable"]) {
if (![true, false, null].includes(region?.[permission])) {
throw new Error(`list_segments omitted tri-state ${permission}`);
}
}
}
for (const block of value.basic_blocks.items) {
if (!Array.isArray(block?.successors)) {
throw new Error("analyze_function omitted CFG successor evidence");
if (
region.provenance !== "hopper-public-python-api" ||
region.permissions?.available !== false ||
typeof region.permissions.reason !== "string"
) {
throw new Error("list_segments omitted permission provenance");
}
}
if (
typeof value.instruction_scan?.scanned !== "number" ||
typeof value.instruction_scan?.truncated !== "boolean"
) {
throw new Error("analyze_function omitted instruction scan limitations");
};
const verifyRelationships = async (client, options, procedure) => {
const related = {};
for (const operation of ["procedure_callers", "procedure_callees"]) {
related[operation] = requireAddressArray(
requireSuccessfulTool(
await client.callTool(
{ name: operation, arguments: { procedure } },
options,
),
operation,
),
operation,
);
}
return value;
related.xrefs = requireAddressArray(
requireSuccessfulTool(
await client.callTool(
{ name: "xrefs", arguments: { address: procedure } },
options,
),
"xrefs",
),
"xrefs",
);
return related;
};
const verifyCurrentTarget = async (client, options) => {
const procedures = requireSuccessfulTool(
await client.callTool({ name: "list_procedures", arguments: {} }, options),
"list_procedures",
);
const firstAddress = firstProcedureAddress(procedures);
const containment = requireSuccessfulTool(
await client.callTool(
{
name: "resolve_containing_procedure",
arguments: { address: firstAddress },
},
options,
),
"resolve_containing_procedure",
);
if (
containment?.found !== true ||
containment.procedure?.address !== firstAddress
) {
throw new Error(
"resolve_containing_procedure returned the wrong procedure",
);
}
const references = requireSuccessfulTool(
await client.callTool(
{
name: "procedure_references",
arguments: {
procedure: firstAddress,
direction: "outgoing",
limit: 10,
max_instructions: 100,
},
},
options,
),
"procedure_references",
);
if (!Array.isArray(references?.references?.items)) {
throw new Error("procedure_references returned an invalid bounded result");
}
const relationships = await verifyRelationships(
client,
options,
firstAddress,
);
const boundedResult = requireSuccessfulTool(
await client.callTool(
{
name: "batch_decompile",
arguments: { addresses: [firstAddress] },
},
options,
),
"batch_decompile",
);
if (
boundedResult === null ||
typeof boundedResult !== "object" ||
Array.isArray(boundedResult) ||
Object.keys(boundedResult).length !== 1
) {
throw new Error("batch_decompile returned an invalid result");
}
const boundedPseudocode = requirePseudocode(
boundedResult[firstAddress],
"batch_decompile",
);
const dossier = requireFunctionDossier(
requireSuccessfulTool(
await client.callTool(
{
name: "analyze_function",
arguments: { procedure: firstAddress },
},
options,
),
"analyze_function",
),
firstAddress,
);
return {
procedure: dossier.procedure,
procedureCount: procedures.total,
boundedPseudocodeChars: boundedPseudocode.length,
analyzedPseudocodeChars: [...dossier.pseudocode.text].length,
callerCount: relationships.procedure_callers.length,
calleeCount: relationships.procedure_callees.length,
xrefCount: relationships.xrefs.length,
outgoingReferenceCount: references.references.items.length,
};
};
const requireSafeDiagnostics = (chunks) => {
@@ -176,7 +268,7 @@ try {
const expectedNames = TOOL_CONTRACTS.map(({ name }) => name).sort();
const actualNames = listed.tools.map(({ name }) => name).sort();
if (JSON.stringify(actualNames) !== JSON.stringify(expectedNames)) {
throw new Error("The real server did not expose the intended 50 tools");
throw new Error("The real server did not expose the intended 68 tools");
}
const options = { timeout };
@@ -203,77 +295,17 @@ try {
{ name: "list_segments", arguments: {} },
options,
);
const procedures = await client.callTool(
{ name: "list_procedures", arguments: {} },
options,
requireTruthfulMemoryRegions(
requireSuccessfulTool(segments, "list_segments"),
);
requireSuccessfulTool(procedures, "list_procedures");
const firstAddress = firstProcedureAddress(procedures);
const containment = requireSuccessfulTool(
await client.callTool(
{
name: "resolve_containing_procedure",
arguments: { address: firstAddress },
},
options,
),
"resolve_containing_procedure",
);
if (
containment?.found !== true ||
containment.procedure?.address !== firstAddress
) {
throw new Error(
"resolve_containing_procedure returned the wrong procedure",
);
}
const references = requireSuccessfulTool(
await client.callTool(
{
name: "procedure_references",
arguments: {
procedure: firstAddress,
direction: "outgoing",
limit: 10,
max_instructions: 100,
},
},
options,
),
"procedure_references",
);
if (!Array.isArray(references?.references?.items)) {
throw new Error("procedure_references returned an invalid bounded result");
}
const bounded = await client.callTool(
{ name: "batch_decompile", arguments: { addresses: [firstAddress] } },
options,
);
const boundedResult = requireSuccessfulTool(bounded, "batch_decompile");
if (
boundedResult === null ||
typeof boundedResult !== "object" ||
Array.isArray(boundedResult)
) {
throw new Error("batch_decompile returned an invalid result");
}
const boundedPseudocode = requirePseudocode(
boundedResult[firstAddress],
"batch_decompile",
);
const dossier = requireFunctionDossier(
requireSuccessfulTool(
await client.callTool(
{
name: "analyze_function",
arguments: { procedure: firstAddress },
},
options,
),
"analyze_function",
),
firstAddress,
const firstDocuments = requireSuccessfulTool(documents, "list_documents");
if (!Array.isArray(firstDocuments) || firstDocuments.length === 0)
throw new Error("list_documents returned no real Hopper document");
const firstOverview = requireOverview(
requireSuccessfulTool(overview, "binary_overview"),
"binary_overview",
);
const firstAnalysis = await verifyCurrentTarget(client, options);
const switched = await client.callTool(
{ name: "open_binary", arguments: { path: targetB } },
options,
@@ -288,8 +320,11 @@ try {
{ name: "binary_overview", arguments: {} },
options,
);
if (secondOverview.isError === true)
throw new Error(textValue(secondOverview));
const verifiedSecondOverview = requireOverview(
requireSuccessfulTool(secondOverview, "binary_overview"),
"binary_overview after target switch",
);
const secondAnalysis = await verifyCurrentTarget(client, options);
const processList = await execFileAsync("ps", ["-ax", "-o", "command="]);
const bundledMcpRunning = processList.stdout
@@ -307,25 +342,25 @@ try {
options,
);
if (closed.isError === true) throw new Error(textValue(closed));
const closedSession = jsonValue(
await client.callTool({ name: "binary_session", arguments: {} }, options),
);
if (closedSession.open !== false)
throw new Error("The real session remained open after close_binary");
summary = {
toolCount: actualNames.length,
documentCount: jsonValue(documents).length,
overview: jsonValue(overview),
segmentCount: jsonValue(segments).length,
boundedTool: "batch_decompile",
boundedInputCount: 1,
boundedResultKeys: Object.keys(boundedResult).length,
boundedPseudocodeChars: boundedPseudocode.length,
analyzedProcedure: dossier.procedure,
analyzedPseudocodeChars: dossier.pseudocode.text.length,
documentCount: firstDocuments.length,
overview: firstOverview,
segmentCount: firstOverview.segment_count,
analyses: [firstAnalysis, secondAnalysis],
bundledMcpRunning,
stderrBytes,
diagnosticCount,
dynamicSession: true,
targets: [targetA, targetB],
switched: true,
secondOverview: jsonValue(secondOverview),
secondOverview: verifiedSecondOverview,
};
} finally {
const keepAlive = setInterval(() => undefined, 100);