refactor(adapters): split oversized provider workflows

This commit is contained in:
morluto
2026-07-18 05:49:14 +00:00
parent 20c88dd567
commit 1a99a60a29
52 changed files with 6251 additions and 4830 deletions
@@ -0,0 +1,18 @@
export function sourceMapSummary(sourceMaps) {
return {
status: sourceMaps.status,
requested: sourceMaps.requested,
processed: sourceMaps.processed,
dropped: sourceMaps.dropped,
items: sourceMaps.items.map((item) => ({
status: item.status,
declaredUrl: item.declared_url,
sources: item.original_sources.map(({ source }) => source),
edgeSpecifiers: item.original_module_edges.map(({ specifier }) =>
specifier.slice(0, 256),
),
mappings: item.mappings.length,
limitation: item.limitation,
})),
};
}
+150
View File
@@ -0,0 +1,150 @@
import { names } from "./catalog-core.mjs";
/** Build tool-family counts and sorted tool-name lists. */
export const toolFamilyCatalog = (sources) => {
const families = [
{
id: "direct",
surface: "official-proxy",
contracts: sources.toolContracts.OFFICIAL_TOOL_CONTRACTS,
},
{
id: "enhanced",
surface: "enhanced",
contracts: sources.toolContracts.ENHANCED_TOOL_CONTRACTS,
},
{
id: "native",
surface: "native-provider",
contracts: sources.nativeContracts.NATIVE_TOOL_CONTRACTS,
},
{
id: "artifact",
surface: "artifact-provider",
contracts: sources.artifactContracts.ARTIFACT_TOOL_CONTRACTS,
},
{
id: "managed",
surface: "managed",
contracts: [
...sources.managedContracts.MANAGED_TOOL_CONTRACTS,
...sources.managedWorkflowContracts.MANAGED_WORKFLOW_TOOL_CONTRACTS,
],
},
{
id: "browser",
surface: "browser-provider",
contracts: sources.browserContracts.BROWSER_TOOL_CONTRACTS,
},
{
id: "electron",
surface: "electron-provider",
contracts: sources.electronContracts.ELECTRON_TOOL_CONTRACTS,
},
{
id: "application",
surface: "application-workflow",
contracts: sources.applicationContracts.APPLICATION_TOOL_CONTRACTS,
},
{
id: "session",
surface: "session",
contracts: sources.toolContracts.SESSION_TOOL_CONTRACTS,
},
].map(({ id, surface, contracts }) => ({
id,
surface,
count: contracts.length,
tools: names(contracts),
}));
const familyTotal = families.reduce(
(total, family) => total + family.count,
0,
);
if (
familyTotal !== sources.toolContracts.TOOL_CONTRACTS.length ||
familyTotal !== sources.catalogIdentity.CATALOG_IDENTITY.counts.mcp_tools
)
throw new Error("Tool family inventory does not match TOOL_CONTRACTS");
return { total: familyTotal, families };
};
/** Build provider identities with their sorted capability names. */
export const providerCatalog = (sources) => {
const applicationContracts =
sources.electronContracts.ELECTRON_TOOL_CONTRACTS.filter(
({ name }) => name === "analyze_javascript_application",
);
const reconciliationContracts =
sources.electronContracts.ELECTRON_TOOL_CONTRACTS.filter(
({ name }) => name === "reconcile_javascript_runtime",
);
const observationContracts =
sources.electronContracts.ELECTRON_TOOL_CONTRACTS.filter(
({ name }) =>
name !== "analyze_javascript_application" &&
name !== "reconcile_javascript_runtime",
);
if (
applicationContracts.length !== 1 ||
reconciliationContracts.length !== 1 ||
observationContracts.length !== 2
)
throw new Error("Electron provider capability ownership drifted");
return [
{
identity: sources.hopperProvider.HOPPER_PROVIDER_IDENTITY,
contracts: sources.hopperProvider.HOPPER_PROVIDER_TOOL_CONTRACTS,
},
{
identity: sources.ghidraProvider.GHIDRA_PROVIDER_IDENTITY,
contracts: sources.ghidraProvider.GHIDRA_PROVIDER_TOOL_CONTRACTS,
},
{
identity: sources.nativeProvider.NATIVE_MACOS_PROVIDER_IDENTITY,
contracts: sources.nativeContracts.NATIVE_TOOL_CONTRACTS,
},
{
identity: sources.artifactProviders.ARTIFACT_GRAPH_PROVIDER,
contracts: sources.artifactContracts.ARTIFACT_TOOL_CONTRACTS,
},
{
identity: sources.artifactProviders.MANAGED_STATIC_PROVIDER,
contracts: sources.managedContracts.MANAGED_TOOL_CONTRACTS,
},
{
identity: sources.artifactProviders.MANAGED_WORKFLOW_PROVIDER,
contracts:
sources.managedWorkflowContracts.MANAGED_WORKFLOW_TOOL_CONTRACTS,
},
{
identity: sources.browserProvider.CDP_BROWSER_PROVIDER_IDENTITY,
contracts: sources.browserContracts.BROWSER_TOOL_CONTRACTS,
},
{
identity: sources.electronProvider.CDP_ELECTRON_PROVIDER_IDENTITY,
contracts: observationContracts,
},
{
identity: sources.artifactProviders.JAVASCRIPT_APPLICATION_PROVIDER,
contracts: applicationContracts,
},
{
identity:
sources.artifactProviders.JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
contracts: reconciliationContracts,
},
{
identity:
sources.artifactProviders.JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER,
contracts: sources.applicationContracts.APPLICATION_TOOL_CONTRACTS,
},
]
.map(({ identity, contracts }) => ({
id: identity.id,
name: identity.name,
version: identity.version,
capabilities: names(contracts),
}))
.sort((left, right) => left.id.localeCompare(right.id));
};
+61
View File
@@ -0,0 +1,61 @@
import { Cli } from "incur";
import { z } from "zod";
/** Read primary names and aliases from the actual Incur command router. */
export const createCliInventory = (cli) => {
const commands = Cli.toCommands.get(cli);
if (commands === undefined)
throw new Error("Incur did not expose the registered REA CLI commands");
const primary = [];
const aliases = [];
for (const [name, entry] of commands) {
if ("_alias" in entry) aliases.push({ name, target: entry.target });
else primary.push(name);
}
return {
primary: primary.sort((left, right) => left.localeCompare(right)),
aliases: aliases.sort((left, right) => left.name.localeCompare(right.name)),
};
};
/** Read one primary command's declared option names from the Incur router. */
export const cliCommandOptionNames = (cli, name) => {
const commands = Cli.toCommands.get(cli);
const command = commands?.get(name);
if (
command === undefined ||
"_alias" in command ||
!("options" in command) ||
command.options === undefined
)
return [];
const schema = z.toJSONSchema(command.options);
return Object.keys(schema.properties ?? {}).sort((left, right) =>
left.localeCompare(right),
);
};
/** Report primary CLI fields whose generated JSON Schema lacks help text. */
export const cliCommandDescriptionIssues = (cli) => {
const commands = Cli.toCommands.get(cli);
if (commands === undefined)
throw new Error("Incur did not expose the registered REA CLI commands");
const missing = [];
for (const [commandName, command] of commands) {
if ("_alias" in command) continue;
for (const groupName of ["args", "options"]) {
if (!(groupName in command) || command[groupName] === undefined) continue;
const properties = z.toJSONSchema(command[groupName]).properties ?? {};
for (const [propertyName, property] of Object.entries(properties)) {
if (
typeof property !== "object" ||
property === null ||
typeof property.description !== "string" ||
property.description.trim() === ""
)
missing.push(`${commandName}.${groupName}.${propertyName}`);
}
}
}
return missing;
};
+78
View File
@@ -0,0 +1,78 @@
import { join } from "node:path";
import { pathToFileURL } from "node:url";
const load = (root, path) => import(pathToFileURL(join(root, path)).href);
/** Sort tool/provider names alphabetically. */
export const names = (contracts) =>
contracts
.map(({ name }) => name)
.sort((left, right) => left.localeCompare(right));
/** Throw when two name lists diverge. */
export const assertSameNames = (label, actual, expected) => {
const actualSet = new Set(actual);
const expectedSet = new Set(expected);
const missing = [...expectedSet].filter((name) => !actualSet.has(name));
const extra = [...actualSet].filter((name) => !expectedSet.has(name));
if (missing.length === 0 && extra.length === 0) return;
throw new Error(
`${label} drifted (missing: ${missing.join(", ") || "none"}; extra: ${extra.join(", ") || "none"})`,
);
};
const SOURCE_PATHS = {
packageMetadata: "dist/generatedPackageMetadata.js",
catalogIdentity: "dist/catalogIdentity.js",
cli: "dist/cli.js",
toolContracts: "dist/contracts/toolContracts.js",
nativeContracts: "dist/contracts/nativeToolContracts.js",
artifactContracts: "dist/contracts/artifactToolContracts.js",
managedContracts: "dist/contracts/managedToolContracts.js",
managedWorkflowContracts: "dist/contracts/managedWorkflowToolContracts.js",
browserContracts: "dist/contracts/browserToolContracts.js",
electronContracts: "dist/contracts/electronToolContracts.js",
applicationContracts: "dist/contracts/applicationToolContracts.js",
supportedClients: "dist/application/SupportedClients.js",
hopperProvider: "dist/hopper/HopperProvider.js",
ghidraProvider: "dist/ghidra/GhidraProvider.js",
nativeProvider: "dist/native/NativeMacOSProvider.js",
artifactProviders: "dist/application/InvestigationProviders.js",
browserProvider: "dist/browser/CdpBrowserProvider.js",
electronProvider: "dist/browser/CdpElectronProvider.js",
evidence: "dist/domain/evidence.js",
evidenceBundle: "dist/domain/evidenceBundle.js",
processCapture: "dist/domain/processCapture.js",
analysisSnapshot: "dist/domain/analysisSnapshot.js",
artifactGraph: "dist/domain/artifactGraph.js",
investigationWorkspace: "dist/domain/investigationWorkspace.js",
browserObservation: "dist/domain/browserObservation.js",
browserSession: "dist/domain/browserSession.js",
electronObservation: "dist/domain/electronObservation.js",
webBundleAnalysis: "dist/domain/webBundleAnalysis.js",
webCaptureDiff: "dist/domain/webCaptureDiff.js",
managedArtifact: "dist/domain/managedArtifact.js",
managedComparison: "dist/domain/managedMemberComparison.js",
managedNativeVerification: "dist/domain/managedNativeVerification.js",
webMcpDiscovery: "dist/domain/webMcpDiscovery.js",
webScreenshot: "dist/domain/webScreenshot.js",
javascriptApplicationGraph: "dist/domain/javascriptApplicationGraph.js",
javascriptApplicationAnalysis: "dist/domain/javascriptApplicationAnalysis.js",
javascriptFeatureTrace: "dist/domain/javascriptFeatureTraceSchemas.js",
javascriptVersionComparison:
"dist/domain/javascriptApplicationVersionComparisonSchemas.js",
reconstructionVerification:
"dist/domain/reconstructionVerificationSchemas.js",
residualUnknown: "dist/domain/residualUnknown.js",
};
/** Load every compiled source module referenced by the catalog. */
export const loadSources = async (root) =>
Object.fromEntries(
await Promise.all(
Object.entries(SOURCE_PATHS).map(async ([key, path]) => [
key,
await load(root, path),
]),
),
);
+204
View File
@@ -0,0 +1,204 @@
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 (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), 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"],
],
["evidence", sources.evidence.evidenceSchema, ["schema_version"]],
[
"evidence_bundle",
sources.evidenceBundle.evidenceBundleSchema,
["bundle_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_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 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"],
],
[
"electron_page_inspection",
sources.electronObservation.electronPageInspectionSchema,
["schema_version"],
],
[
"electron_target_list",
sources.electronObservation.electronTargetListSchema,
["schema_version"],
],
[
"javascript_application_analysis",
sources.javascriptApplicationAnalysis
.javascriptApplicationAnalysisResultSchema,
["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));
+12 -482
View File
@@ -1,490 +1,20 @@
import { pathToFileURL } from "node:url";
import { join } from "node:path";
import { Cli } from "incur";
import { format } from "prettier";
import { z } from "zod";
const load = (root, path) => import(pathToFileURL(join(root, path)).href);
const names = (contracts) =>
contracts
.map(({ name }) => name)
.sort((left, right) => left.localeCompare(right));
import { assertSameNames, loadSources } from "./catalog-core.mjs";
import {
createCliInventory,
cliCommandDescriptionIssues,
cliCommandOptionNames,
} from "./catalog-cli.mjs";
import { providerCatalog, toolFamilyCatalog } from "./catalog-builders.mjs";
import { schemaCatalog } from "./catalog-schemas.mjs";
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 (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)
: [];
export {
createCliInventory,
cliCommandDescriptionIssues,
cliCommandOptionNames,
};
const versionAt = (schema, path) => {
const versions = [
...new Set(valuesAt(z.toJSONSchema(schema), 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;
};
/** Read primary names and aliases from the actual Incur command router. */
export const createCliInventory = (cli) => {
const commands = Cli.toCommands.get(cli);
if (commands === undefined)
throw new Error("Incur did not expose the registered REA CLI commands");
const primary = [];
const aliases = [];
for (const [name, entry] of commands) {
if ("_alias" in entry) aliases.push({ name, target: entry.target });
else primary.push(name);
}
return {
primary: primary.sort((left, right) => left.localeCompare(right)),
aliases: aliases.sort((left, right) => left.name.localeCompare(right.name)),
};
};
/** Read one primary command's declared option names from the Incur router. */
export const cliCommandOptionNames = (cli, name) => {
const commands = Cli.toCommands.get(cli);
const command = commands?.get(name);
if (
command === undefined ||
"_alias" in command ||
!("options" in command) ||
command.options === undefined
)
return [];
const schema = z.toJSONSchema(command.options);
return Object.keys(schema.properties ?? {}).sort((left, right) =>
left.localeCompare(right),
);
};
/** Report primary CLI fields whose generated JSON Schema lacks help text. */
export const cliCommandDescriptionIssues = (cli) => {
const commands = Cli.toCommands.get(cli);
if (commands === undefined)
throw new Error("Incur did not expose the registered REA CLI commands");
const missing = [];
for (const [commandName, command] of commands) {
if ("_alias" in command) continue;
for (const groupName of ["args", "options"]) {
if (!(groupName in command) || command[groupName] === undefined) continue;
const properties = z.toJSONSchema(command[groupName]).properties ?? {};
for (const [propertyName, property] of Object.entries(properties)) {
if (
typeof property !== "object" ||
property === null ||
typeof property.description !== "string" ||
property.description.trim() === ""
)
missing.push(`${commandName}.${groupName}.${propertyName}`);
}
}
}
return missing;
};
const assertSameNames = (label, actual, expected) => {
const actualSet = new Set(actual);
const expectedSet = new Set(expected);
const missing = [...expectedSet].filter((name) => !actualSet.has(name));
const extra = [...actualSet].filter((name) => !expectedSet.has(name));
if (missing.length === 0 && extra.length === 0) return;
throw new Error(
`${label} drifted (missing: ${missing.join(", ") || "none"}; extra: ${extra.join(", ") || "none"})`,
);
};
const SOURCE_PATHS = {
packageMetadata: "dist/generatedPackageMetadata.js",
catalogIdentity: "dist/catalogIdentity.js",
cli: "dist/cli.js",
toolContracts: "dist/contracts/toolContracts.js",
nativeContracts: "dist/contracts/nativeToolContracts.js",
artifactContracts: "dist/contracts/artifactToolContracts.js",
managedContracts: "dist/contracts/managedToolContracts.js",
managedWorkflowContracts: "dist/contracts/managedWorkflowToolContracts.js",
browserContracts: "dist/contracts/browserToolContracts.js",
electronContracts: "dist/contracts/electronToolContracts.js",
applicationContracts: "dist/contracts/applicationToolContracts.js",
supportedClients: "dist/application/SupportedClients.js",
hopperProvider: "dist/hopper/HopperProvider.js",
ghidraProvider: "dist/ghidra/GhidraProvider.js",
nativeProvider: "dist/native/NativeMacOSProvider.js",
artifactProviders: "dist/application/InvestigationProviders.js",
browserProvider: "dist/browser/CdpBrowserProvider.js",
electronProvider: "dist/browser/CdpElectronProvider.js",
evidence: "dist/domain/evidence.js",
evidenceBundle: "dist/domain/evidenceBundle.js",
processCapture: "dist/domain/processCapture.js",
analysisSnapshot: "dist/domain/analysisSnapshot.js",
artifactGraph: "dist/domain/artifactGraph.js",
investigationWorkspace: "dist/domain/investigationWorkspace.js",
browserObservation: "dist/domain/browserObservation.js",
browserSession: "dist/domain/browserSession.js",
electronObservation: "dist/domain/electronObservation.js",
webBundleAnalysis: "dist/domain/webBundleAnalysis.js",
webCaptureDiff: "dist/domain/webCaptureDiff.js",
managedArtifact: "dist/domain/managedArtifact.js",
managedComparison: "dist/domain/managedMemberComparison.js",
managedNativeVerification: "dist/domain/managedNativeVerification.js",
webMcpDiscovery: "dist/domain/webMcpDiscovery.js",
webScreenshot: "dist/domain/webScreenshot.js",
javascriptApplicationGraph: "dist/domain/javascriptApplicationGraph.js",
javascriptApplicationAnalysis: "dist/domain/javascriptApplicationAnalysis.js",
javascriptFeatureTrace: "dist/domain/javascriptFeatureTraceSchemas.js",
javascriptVersionComparison:
"dist/domain/javascriptApplicationVersionComparisonSchemas.js",
reconstructionVerification:
"dist/domain/reconstructionVerificationSchemas.js",
residualUnknown: "dist/domain/residualUnknown.js",
};
const loadSources = async (root) =>
Object.fromEntries(
await Promise.all(
Object.entries(SOURCE_PATHS).map(async ([key, path]) => [
key,
await load(root, path),
]),
),
);
const toolFamilyCatalog = (sources) => {
const families = [
{
id: "direct",
surface: "official-proxy",
contracts: sources.toolContracts.OFFICIAL_TOOL_CONTRACTS,
},
{
id: "enhanced",
surface: "enhanced",
contracts: sources.toolContracts.ENHANCED_TOOL_CONTRACTS,
},
{
id: "native",
surface: "native-provider",
contracts: sources.nativeContracts.NATIVE_TOOL_CONTRACTS,
},
{
id: "artifact",
surface: "artifact-provider",
contracts: sources.artifactContracts.ARTIFACT_TOOL_CONTRACTS,
},
{
id: "managed",
surface: "managed",
contracts: [
...sources.managedContracts.MANAGED_TOOL_CONTRACTS,
...sources.managedWorkflowContracts.MANAGED_WORKFLOW_TOOL_CONTRACTS,
],
},
{
id: "browser",
surface: "browser-provider",
contracts: sources.browserContracts.BROWSER_TOOL_CONTRACTS,
},
{
id: "electron",
surface: "electron-provider",
contracts: sources.electronContracts.ELECTRON_TOOL_CONTRACTS,
},
{
id: "application",
surface: "application-workflow",
contracts: sources.applicationContracts.APPLICATION_TOOL_CONTRACTS,
},
{
id: "session",
surface: "session",
contracts: sources.toolContracts.SESSION_TOOL_CONTRACTS,
},
].map(({ id, surface, contracts }) => ({
id,
surface,
count: contracts.length,
tools: names(contracts),
}));
const familyTotal = families.reduce(
(total, family) => total + family.count,
0,
);
if (
familyTotal !== sources.toolContracts.TOOL_CONTRACTS.length ||
familyTotal !== sources.catalogIdentity.CATALOG_IDENTITY.counts.mcp_tools
)
throw new Error("Tool family inventory does not match TOOL_CONTRACTS");
return { total: familyTotal, families };
};
const providerCatalog = (sources) => {
const applicationContracts =
sources.electronContracts.ELECTRON_TOOL_CONTRACTS.filter(
({ name }) => name === "analyze_javascript_application",
);
const reconciliationContracts =
sources.electronContracts.ELECTRON_TOOL_CONTRACTS.filter(
({ name }) => name === "reconcile_javascript_runtime",
);
const observationContracts =
sources.electronContracts.ELECTRON_TOOL_CONTRACTS.filter(
({ name }) =>
name !== "analyze_javascript_application" &&
name !== "reconcile_javascript_runtime",
);
if (
applicationContracts.length !== 1 ||
reconciliationContracts.length !== 1 ||
observationContracts.length !== 2
)
throw new Error("Electron provider capability ownership drifted");
return [
{
identity: sources.hopperProvider.HOPPER_PROVIDER_IDENTITY,
contracts: sources.hopperProvider.HOPPER_PROVIDER_TOOL_CONTRACTS,
},
{
identity: sources.ghidraProvider.GHIDRA_PROVIDER_IDENTITY,
contracts: sources.ghidraProvider.GHIDRA_PROVIDER_TOOL_CONTRACTS,
},
{
identity: sources.nativeProvider.NATIVE_MACOS_PROVIDER_IDENTITY,
contracts: sources.nativeContracts.NATIVE_TOOL_CONTRACTS,
},
{
identity: sources.artifactProviders.ARTIFACT_GRAPH_PROVIDER,
contracts: sources.artifactContracts.ARTIFACT_TOOL_CONTRACTS,
},
{
identity: sources.artifactProviders.MANAGED_STATIC_PROVIDER,
contracts: sources.managedContracts.MANAGED_TOOL_CONTRACTS,
},
{
identity: sources.artifactProviders.MANAGED_WORKFLOW_PROVIDER,
contracts:
sources.managedWorkflowContracts.MANAGED_WORKFLOW_TOOL_CONTRACTS,
},
{
identity: sources.browserProvider.CDP_BROWSER_PROVIDER_IDENTITY,
contracts: sources.browserContracts.BROWSER_TOOL_CONTRACTS,
},
{
identity: sources.electronProvider.CDP_ELECTRON_PROVIDER_IDENTITY,
contracts: observationContracts,
},
{
identity: sources.artifactProviders.JAVASCRIPT_APPLICATION_PROVIDER,
contracts: applicationContracts,
},
{
identity:
sources.artifactProviders.JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
contracts: reconciliationContracts,
},
{
identity:
sources.artifactProviders.JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER,
contracts: sources.applicationContracts.APPLICATION_TOOL_CONTRACTS,
},
]
.map(({ identity, contracts }) => ({
id: identity.id,
name: identity.name,
version: identity.version,
capabilities: names(contracts),
}))
.sort((left, right) => left.id.localeCompare(right.id));
};
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"],
],
["evidence", sources.evidence.evidenceSchema, ["schema_version"]],
[
"evidence_bundle",
sources.evidenceBundle.evidenceBundleSchema,
["bundle_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_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 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"],
],
[
"electron_page_inspection",
sources.electronObservation.electronPageInspectionSchema,
["schema_version"],
],
[
"electron_target_list",
sources.electronObservation.electronTargetListSchema,
["schema_version"],
],
[
"javascript_application_analysis",
sources.javascriptApplicationAnalysis
.javascriptApplicationAnalysisResultSchema,
["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"],
],
];
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));
/** Project current runtime contracts into deterministic, machine-readable facts. */
export const createProductCatalog = async (root) => {
const sources = await loadSources(root);
+84
View File
@@ -0,0 +1,84 @@
import { execFile } from "node:child_process";
import { lstat } from "node:fs/promises";
import { promisify } from "node:util";
/** Promisified child_process execution helper. */
export const exec = promisify(execFile);
/** Run a command and return its stdout. */
export const run = async (command, args, env) =>
(await exec(command, args, { env })).stdout;
/** Run a command and treat exit code 1 as a non-throwing status result. */
export const runWithStatus = async (command, args, env) => {
try {
return { stdout: await run(command, args, env), status: 0 };
} catch (cause) {
if (
typeof cause === "object" &&
cause !== null &&
cause.code === 1 &&
typeof cause.stdout === "string"
)
return { stdout: cause.stdout, status: 1 };
throw cause;
}
};
/** Parse JSON from a command output string. */
export const json = (text) => JSON.parse(text);
/** Check whether a path exists on disk. */
export const pathExists = async (path) => {
try {
await lstat(path);
return true;
} catch (cause) {
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
return false;
throw cause;
}
};
/** 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",
name,
classification: {
external: false,
thunk: false,
thunk_target: null,
provenance: "synthetic-provider",
},
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 },
limitations: [],
};
};
+66
View File
@@ -0,0 +1,66 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { json, run } from "./lib/verify-package-core.mjs";
/** Run inventory-artifact and analyze-javascript-application against packaged fixtures. */
export async function verifyPackageArtifactAndElectron({
cli,
workspace,
environment,
}) {
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 applicationRoot = join(workspace, "electron-app");
await mkdir(applicationRoot);
await writeFile(
join(applicationRoot, "package.json"),
'{"name":"packaged-electron-fixture","main":"main.js"}\n',
);
await writeFile(
join(applicationRoot, "main.js"),
'const { BrowserWindow, ipcMain } = require("electron");\nnew BrowserWindow({ webPreferences: { preload: path.join(__dirname, "preload.js"), contextIsolation: true } });\nipcMain.handle("rea:ping", () => true);\n',
);
await writeFile(
join(applicationRoot, "preload.js"),
'const { contextBridge, ipcRenderer } = require("electron");\ncontextBridge.exposeInMainWorld("rea", { ping: () => ipcRenderer.invoke("rea:ping") });\n',
);
const applicationAnalysis = json(
await run(
cli,
[
"analyze-javascript-application",
applicationRoot,
"--approved",
"--json",
],
environment,
),
);
if (
applicationAnalysis.operation !== "analyze_javascript_application" ||
applicationAnalysis.provider?.id !== "rea-javascript-application" ||
applicationAnalysis.normalized_result?.summary?.browser_windows !== 1 ||
applicationAnalysis.normalized_result?.summary?.ipc
?.paired_renderer_transmissions !== 1
)
throw new Error("packaged JavaScript application analysis CLI failed");
return { artifactArchive };
}
+36
View File
@@ -0,0 +1,36 @@
import { json, run } from "./lib/verify-package-core.mjs";
/** Verify packaged capabilities, providers, and non-Linux search results. */
export async function verifyPackageCapabilitiesAndSearch({ cli, environment }) {
const capabilities = json(
await run(cli, ["capabilities", "--json"], environment),
);
if (!Array.isArray(capabilities.capabilities))
throw new Error("packaged capabilities CLI failed");
const providers = json(await run(cli, ["providers", "--json"], environment));
if (
!Array.isArray(providers.providers) ||
providers.providers.some(({ id }) => typeof id !== "string") ||
providers.analysis_provider_binding !== null ||
providers.analysis_provider_candidates?.find(
({ provider }) => provider?.id === "hopper",
)?.target_support?.status !== "unknown"
)
throw new Error("packaged providers CLI failed");
if (process.platform !== "linux") {
const searchResult = json(
await run(
cli,
["search", process.execPath, "fixture", "--json"],
environment,
),
);
if (
searchResult.operation !== "search_strings" ||
searchResult.normalized_result?.items?.length !== 1
)
throw new Error(
`packaged search CLI failed: ${JSON.stringify(searchResult)}`,
);
}
}
+61
View File
@@ -0,0 +1,61 @@
import { json, run, runWithStatus } from "./lib/verify-package-core.mjs";
const REQUIRED_HELP_COMMANDS = [
"setup",
"upgrade",
"inventory-artifact",
"extract-artifact",
"investigate-versions",
"import-reference-source",
"list-browser-targets",
"inspect-web-page",
"analyze-javascript-application",
"compare",
];
const REQUIRED_LLM_TOPICS = [
"decompile",
"function",
"search",
"inspect",
"xrefs",
"trace",
"capabilities",
"providers",
"inventory-artifact",
"list-browser-targets",
"inspect-web-page",
"analyze-javascript-application",
];
/** Validate --help, --llms, and doctor output and determine host setup support. */
export async function verifyPackageDiscovery({ cli, environment }) {
const help = await run(cli, ["--help"], environment);
const llms = await run(cli, ["--llms"], environment);
const doctorExecution = await runWithStatus(
cli,
["doctor", "--json"],
environment,
);
const doctor = json(doctorExecution.stdout);
const supportedSetupHost =
doctor.checks?.find(({ name }) => name === "host")?.ok === true;
const expectedDoctorHealth = doctor.checks?.every(({ ok }) => ok) === true;
const missingHelp = REQUIRED_HELP_COMMANDS.filter(
(command) => !help.includes(command),
);
const missingLlms = REQUIRED_LLM_TOPICS.filter(
(topic) => !llms.includes(topic),
);
if (
missingHelp.length !== 0 ||
missingLlms.length !== 0 ||
doctor.healthy !== expectedDoctorHealth ||
doctorExecution.status !== (expectedDoctorHealth ? 0 : 1) ||
doctor.checks?.find(({ name }) => name === "hopper")?.ok !== true
)
throw new Error(
`packaged CLI discovery or doctor failed: ${JSON.stringify({ helpSetup: help.includes("setup"), llmsDecompile: llms.includes("decompile"), doctor })}`,
);
return { supportedSetupHost };
}
+96
View File
@@ -0,0 +1,96 @@
import { chmod, mkdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
/** Create an isolated prefix, fake PATH, client configs, and environment. */
export async function verifyPackageEnvironment({
root,
workspace,
evidenceRoot,
referenceRoot,
}) {
const prefix = join(workspace, "prefix");
const home = join(workspace, "home");
const fakeBin = join(workspace, "bin");
await mkdir(fakeBin, { recursive: true });
await Promise.all([
mkdir(evidenceRoot, { recursive: true }),
mkdir(join(referenceRoot, "src"), { recursive: true }),
]);
await Promise.all([
writeFile(
join(referenceRoot, "src", "main.ts"),
'import "./dependency";\n',
),
writeFile(
join(referenceRoot, "src", "dependency.ts"),
"export const value = 1;\n",
),
writeFile(join(referenceRoot, ".env"), "PACKAGE_SECRET_SENTINEL=1\n"),
]);
const brew = join(fakeBin, "brew");
const swVers = join(fakeBin, "sw_vers");
const npx = join(fakeBin, "npx");
const npxLog = join(workspace, "npx.log");
const hopper = join(workspace, "hopper");
await writeFile(
brew,
'#!/bin/sh\nif [ "$1" = "--prefix" ]; then echo /fake/cask; fi\nexit 0\n',
);
await writeFile(swVers, "#!/bin/sh\necho 14.5\n");
await writeFile(
npx,
'#!/bin/sh\nprintf "%s\\n" "$*" > "$REA_NPX_LOG"\necho "│ ✓ Cursor: isolated │"\n',
);
await writeFile(hopper, "#!/bin/sh\nexit 0\n");
await Promise.all([
chmod(brew, 0o755),
chmod(swVers, 0o755),
chmod(hopper, 0o755),
chmod(npx, 0o755),
]);
const claudeDir = join(home, "Library/Application Support/Claude");
const codexDir = join(home, ".codex");
const cursorDir = join(home, ".cursor");
await Promise.all([
mkdir(claudeDir, { recursive: true }),
mkdir(codexDir, { recursive: true }),
mkdir(cursorDir, { recursive: true }),
]);
const claudeConfig = join(claudeDir, "claude_desktop_config.json");
const codexConfig = join(codexDir, "config.toml");
const codexTarget = join(home, "managed-codex.toml");
const cursorConfig = join(cursorDir, "mcp.json");
const cursorTarget = join(home, "managed-cursor.json");
await writeFile(claudeConfig, '{"existing":true}\n');
await writeFile(codexTarget, 'model = "gpt-5"\n');
await writeFile(cursorTarget, '{"existing":true}\n');
await symlink(codexTarget, codexConfig);
await symlink(cursorTarget, cursorConfig);
const environment = {
...process.env,
HOME: home,
XDG_CONFIG_HOME: join(home, ".config"),
PATH: `${fakeBin}:${process.env.PATH ?? ""}`,
REA_ANALYSIS_PROVIDER: "auto",
HOPPER_LAUNCHER_PATH: process.execPath,
HOPPER_LOADER_ARGS_JSON: JSON.stringify([
join(root, "tests/fixtures/fakeLauncher.mjs"),
]),
REA_NPX_LOG: npxLog,
REA_EVIDENCE_ROOTS_JSON: JSON.stringify([evidenceRoot]),
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([workspace]),
REA_REFERENCE_ROOTS_JSON: JSON.stringify([referenceRoot]),
REA_REFERENCE_SECRET_PATTERNS_JSON: JSON.stringify([".env"]),
};
return {
prefix,
home,
npxLog,
claudeConfig,
codexConfig,
codexTarget,
cursorConfig,
cursorTarget,
environment,
};
}
+74
View File
@@ -0,0 +1,74 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createEvidence } from "../dist/domain/evidence.js";
import { json, run } from "./lib/verify-package-core.mjs";
/** Round-trip historical reference import and evidence bundles. */
export async function verifyPackageEvidence({
cli,
evidenceRoot,
referenceRoot,
environment,
}) {
const referenceImport = json(
await run(
cli,
["import-reference-source", referenceRoot, "--json"],
environment,
),
);
if (
referenceImport.authority !== "historical-reference" ||
referenceImport.root_alias !== "$REFERENCE_ROOT" ||
referenceImport.relationships?.[0]?.resolution !== "internal" ||
JSON.stringify(referenceImport).includes("PACKAGE_SECRET_SENTINEL")
)
throw new Error("packaged historical reference import CLI failed");
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,
),
);
const comparedBundle = json(
await run(
cli,
["compare", sourceBundlePath, canonicalBundlePath, "--json"],
environment,
),
);
if (
importedBundle.imported !== 1 ||
importedBundle.total !== 1 ||
exportedBundle.records !== 1 ||
(await readFile(canonicalBundlePath, "utf8")) !==
serializeEvidenceBundle(sourceBundle) ||
comparedBundle.status !== "unchanged" ||
comparedBundle.summary?.records_unchanged !== 1
)
throw new Error(
"packaged CLI evidence bundle comparison round trip failed",
);
}
+101
View File
@@ -0,0 +1,101 @@
import { rm } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { exec, json, run } from "./lib/verify-package-core.mjs";
/** Install the packed CLI globally with and without optional dependencies and verify PTY degradation. */
export async function verifyPackageInstall({
root,
tarball,
prefix,
workspace,
environment,
}) {
await exec(
"npm",
[
"install",
"--global",
"--ignore-scripts",
"--prefix",
prefix,
join(root, tarball),
],
{ env: environment },
);
const cli = join(prefix, "bin", "rea");
const processCaptureCapabilityUrl = pathToFileURL(
join(
prefix,
"lib/node_modules/rea-agents/dist/application/ProcessCaptureCapability.js",
),
).href;
const processCaptureCapability = json(
(
await exec(
process.execPath,
[
"--input-type=module",
"--eval",
`const { probeProcessCaptureCapability } = await import(${JSON.stringify(processCaptureCapabilityUrl)}); process.stdout.write(JSON.stringify(await probeProcessCaptureCapability()));`,
],
{ env: environment },
)
).stdout,
);
if (processCaptureCapability.available !== true)
throw new Error(
`packaged PTY backend failed without lifecycle scripts: ${JSON.stringify(processCaptureCapability)}`,
);
const noOptionalPrefix = join(workspace, "prefix-no-optional");
await exec(
"npm",
[
"install",
"--global",
"--ignore-scripts",
"--omit=optional",
"--prefix",
noOptionalPrefix,
join(root, tarball),
],
{ env: environment },
);
const noOptionalCli = join(noOptionalPrefix, "bin", "rea");
await rm(
join(
noOptionalPrefix,
"lib/node_modules/rea-agents/node_modules/@lydell",
`node-pty-${process.platform}-${process.arch}`,
),
{ recursive: true, force: true },
);
const noOptionalCapabilityUrl = pathToFileURL(
join(
noOptionalPrefix,
"lib/node_modules/rea-agents/dist/application/ProcessCaptureCapability.js",
),
).href;
const noOptionalCapability = json(
(
await exec(
process.execPath,
[
"--input-type=module",
"--eval",
`const { probeProcessCaptureCapability } = await import(${JSON.stringify(noOptionalCapabilityUrl)}); process.stdout.write(JSON.stringify(await probeProcessCaptureCapability()));`,
],
{ env: environment },
)
).stdout,
);
if (
!(await run(noOptionalCli, ["--help"], environment)).includes("setup") ||
noOptionalCapability.available !== false
)
throw new Error(
`packaged CLI did not degrade without the optional PTY binary: ${JSON.stringify(noOptionalCapability)}`,
);
return { cli };
}
+367
View File
@@ -0,0 +1,367 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createEvidence } from "../dist/domain/evidence.js";
import { buildManagedPeFixture } from "./lib/managed-pe-fixture.mjs";
import { functionDossier, json, run } from "./lib/verify-package-core.mjs";
const buildManagedFixtures = async (workspace) => {
const managedPath = join(workspace, "managed-fixture.exe");
const managedRightPath = join(workspace, "managed-fixture-right.exe");
await Promise.all([
writeFile(
managedPath,
buildManagedPeFixture({
pinvoke: {
moduleName: "user32.dll",
importName: "MessageBoxW",
mappingFlags: 0x0345,
},
}),
),
writeFile(
managedRightPath,
buildManagedPeFixture({
mvid: Buffer.from([
0xde, 0xad, 0xbe, 0xef, 0x44, 0x33, 0x66, 0x55, 0xaa, 0xbb, 0xcc,
0xdd, 0xee, 0xff, 0x11, 0x22,
]),
}),
),
]);
return { managedPath, managedRightPath };
};
const verifyManagedArtifact = async ({ cli, managedPath, environment }) => {
const managedArtifact = json(
await run(
cli,
["inspect-managed-artifact", managedPath, "--json"],
environment,
),
);
if (
managedArtifact.operation !== "inspect_managed_artifact" ||
managedArtifact.provider?.id !== "rea-dotnet-static" ||
managedArtifact.normalized_result?.classification?.status !== "managed"
)
throw new Error("packaged managed artifact CLI failed");
return managedArtifact;
};
const verifyManagedMembers = async ({ cli, managedPath, environment }) => {
const managedMembers = json(
await run(
cli,
["inspect-managed-members", managedPath, "--json"],
environment,
),
);
if (
managedMembers.operation !== "inspect_managed_members" ||
managedMembers.normalized_result?.methods?.total !== 1
)
throw new Error("packaged managed member CLI failed");
return managedMembers;
};
const verifyManagedReconstruction = async ({
cli,
managedMembers,
managedMethod,
environment,
}) => {
const managedReconstructionInput = {
static_members: managedMembers,
decompiler: {
name: "ilspycmd",
version: "9.1.0.7988",
family: "ilspy",
executable_sha256: null,
options: ["--type", "Fixture.Program"],
},
methods: [
{
token: managedMethod.token,
signature_sha256: managedMethod.signature.raw_sha256,
normalized_il_sha256: managedMethod.body.normalized_il_sha256,
reconstruction: {
kind: "decompiled-csharp",
language: "csharp",
text: "internal static void Main() { }",
},
},
],
notes: ["packaged synthetic reconstruction import"],
};
const managedReconstruction = json(
await run(
cli,
[
"import-managed-reconstruction",
JSON.stringify(managedReconstructionInput),
"--json",
],
environment,
),
);
if (
managedReconstruction.operation !== "import_managed_reconstruction" ||
managedReconstruction.provider?.id !== "rea-dotnet-workflows" ||
managedReconstruction.normalized_result?.executed !== false ||
managedReconstruction.normalized_result?.methods?.[0]?.validation
?.canonical_observation !== false
)
throw new Error("packaged managed reconstruction import CLI failed");
};
const verifyManagedRuntimePlan = async ({
cli,
managedMembers,
managedMethod,
workspace,
environment,
}) => {
const managedRuntimePlanInput = {
static_members: managedMembers,
method: {
token: managedMethod.token,
signature_sha256: managedMethod.signature.raw_sha256,
normalized_il_sha256: managedMethod.body.normalized_il_sha256,
},
requested_effect: "attach",
host: {
os: "linux",
clr_family: "dotnet",
architecture: "x86_64",
},
bounds: {
timeout_ms: 5_000,
max_threads: 32,
max_output_bytes: 65_536,
allow_network: false,
allow_ui: false,
},
};
const managedRuntimePlan = json(
await run(
cli,
[
"plan-managed-runtime-correlation",
JSON.stringify(managedRuntimePlanInput),
"--json",
],
{
...environment,
REA_MANAGED_RUNTIME_ENABLED: "true",
REA_MANAGED_RUNTIME_ROOTS_JSON: JSON.stringify([workspace]),
REA_MANAGED_RUNTIME_EXECUTABLE_PATH: process.execPath,
},
),
);
if (
managedRuntimePlan.operation !== "plan_managed_runtime_correlation" ||
managedRuntimePlan.provider?.id !== "rea-dotnet-workflows" ||
managedRuntimePlan.normalized_result?.executed !== false ||
managedRuntimePlan.normalized_result?.authority_model?.capability !==
"managed_runtime" ||
managedRuntimePlan.normalized_result?.effect_taxonomy?.attaches_process !==
true ||
managedRuntimePlan.normalized_result?.effect_taxonomy
?.invokes_target_code !== false
)
throw new Error("packaged managed runtime-correlation CLI failed");
};
const verifyManagedBoundaries = async ({ cli, managedPath, environment }) => {
const managedBoundaries = json(
await run(
cli,
["inspect-managed-native-boundaries", managedPath, "--json"],
environment,
),
);
if (
managedBoundaries.operation !== "inspect_managed_native_boundaries" ||
managedBoundaries.normalized_result?.pinvoke_imports?.total !== 1 ||
managedBoundaries.normalized_result?.pinvoke_imports?.items?.[0]
?.verification !== "managed-declaration-only"
)
throw new Error("packaged managed native-boundary CLI failed");
return managedBoundaries;
};
const verifyManagedApplicationGraph = async ({
cli,
managedArtifact,
managedMembers,
managedBoundaries,
environment,
}) => {
const managedApplicationGraphInput = {
managed_artifact: managedArtifact,
managed_members: managedMembers,
managed_native_boundaries: managedBoundaries,
limits: {
max_types: 100,
max_methods: 100,
max_fields: 100,
max_pinvoke_imports: 100,
max_native_implementations: 100,
},
};
const managedApplicationGraph = json(
await run(
cli,
[
"project-managed-application-graph",
JSON.stringify(managedApplicationGraphInput),
"--json",
],
environment,
),
);
if (
managedApplicationGraph.operation !== "project_managed_application_graph" ||
managedApplicationGraph.provider?.id !== "rea-dotnet-workflows" ||
managedApplicationGraph.confidence !== "inferred" ||
managedApplicationGraph.normalized_result?.summary?.pinvoke_imports !== 1 ||
managedApplicationGraph.normalized_result?.graph?.schema !==
"JavaScriptApplicationGraph" ||
!managedApplicationGraph.normalized_result?.graph?.nodes?.some(
({ kind }) => kind === "managed-pinvoke-import",
)
)
throw new Error("packaged managed application-graph CLI failed");
};
const verifyManagedNativeVerification = async ({
cli,
managedBoundaries,
environment,
}) => {
const managedNativeVerificationInput = {
managed_boundaries: managedBoundaries,
native_observations: [
createEvidence(
{
path: "/system/user32.dll",
sha256: "9".repeat(64),
format: "pe",
architecture: "x86",
},
{
id: "ghidra",
name: "Ghidra",
version: "12.1.2",
},
{
operation: "analyze_function",
parameters: { procedure: "MessageBoxW" },
result: functionDossier("MessageBoxW"),
rawResult: null,
limitations: [],
locations: [{ kind: "address", address: "0x401000" }],
},
),
],
limits: {
max_native_observations: 20,
max_candidates_per_import: 25,
},
};
const managedNativeVerification = json(
await run(
cli,
[
"verify-managed-native-boundaries",
JSON.stringify(managedNativeVerificationInput),
"--json",
],
environment,
),
);
if (
managedNativeVerification.operation !==
"verify_managed_native_boundaries" ||
managedNativeVerification.provider?.id !== "rea-dotnet-workflows" ||
managedNativeVerification.normalized_result?.summary?.verified !== 1 ||
managedNativeVerification.normalized_result?.algorithm
?.token_to_address_mapping !== "not-inferred"
)
throw new Error("packaged managed/native verification CLI failed");
};
const verifyManagedComparison = async ({
cli,
managedPath,
managedRightPath,
environment,
}) => {
const managedComparison = json(
await run(
cli,
["compare-managed-members", managedPath, managedRightPath, "--json"],
environment,
),
);
if (
managedComparison.operation !== "compare_managed_members" ||
managedComparison.provider?.id !== "rea-dotnet-workflows" ||
managedComparison.normalized_result?.algorithm?.name_matching !== "not-used"
)
throw new Error("packaged managed comparison CLI failed");
};
/** Exercise all packaged managed static and workflow CLIs. */
export async function verifyManaged({ cli, workspace, environment }) {
const { managedPath, managedRightPath } =
await buildManagedFixtures(workspace);
const managedArtifact = await verifyManagedArtifact({
cli,
managedPath,
environment,
});
const managedMembers = await verifyManagedMembers({
cli,
managedPath,
environment,
});
const managedMethod = managedMembers.normalized_result.methods.items[0];
await verifyManagedReconstruction({
cli,
managedMembers,
managedMethod,
environment,
});
await verifyManagedRuntimePlan({
cli,
managedMembers,
managedMethod,
workspace,
environment,
});
const managedBoundaries = await verifyManagedBoundaries({
cli,
managedPath,
environment,
});
await verifyManagedApplicationGraph({
cli,
managedArtifact,
managedMembers,
managedBoundaries,
environment,
});
await verifyManagedNativeVerification({
cli,
managedBoundaries,
environment,
});
await verifyManagedComparison({
cli,
managedPath,
managedRightPath,
environment,
});
}
+209
View File
@@ -0,0 +1,209 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
import * as prompts from "./verify-package-prompts.mjs";
import { json } from "./lib/verify-package-core.mjs";
const verifyMcpToolsAndPrompts = async (client, mcpOptions) => {
if (
(await client.listTools(undefined, mcpOptions)).tools.length !==
TOOL_CONTRACTS.length
)
throw new Error("packaged MCP tool inventory diverged from contracts");
await prompts.verifyPromptCatalog(client, mcpOptions, prompts.names);
await prompts.verifyPromptCompletion(client, mcpOptions, false);
};
const verifyMcpReplay = async (client, mcpOptions, investigationReplay) => {
const replay = await client.callTool(
{
name: "find_changed_behavior",
arguments: { investigation_run: investigationReplay.arguments },
},
mcpOptions,
);
const replayEvidence = json(prompts.mcpText(replay));
const replayWorkspace = json(
await readFile(investigationReplay.workspacePath, "utf8"),
);
if (
replay.isError === true ||
replayEvidence.evidence_id !== investigationReplay.evidenceId ||
replayWorkspace.revision !== investigationReplay.revision
)
throw new Error(
"packaged MCP did not replay with workspace-only authority",
);
};
const verifyMcpTargetFree = async (client, mcpOptions) => {
const result = await client.callTool(
{ name: "current_document", arguments: {} },
mcpOptions,
);
if (result.isError !== true)
throw new Error("packaged target-free MCP omitted no-target error");
};
const verifyMcpUnknownProvider = async (client, mcpOptions) => {
const unknownProvider = await client.callTool(
{
name: "open_binary",
arguments: {
path: process.execPath,
provider_id: "missing-provider",
},
},
mcpOptions,
);
if (
unknownProvider.isError !== true ||
unknownProvider.structuredContent?.error?.details?.selection_reason !==
"unknown_provider"
)
throw new Error("packaged MCP accepted an unknown analysis provider");
};
const verifyMcpOpenAndBind = async (client, mcpOptions) => {
const opened = await client.callTool(
{
name: "open_binary",
arguments: { path: process.execPath, provider_id: "hopper" },
},
mcpOptions,
);
if (opened.isError === true)
throw new Error("packaged MCP could not open a binary");
const providerStatusEnvelope = json(
prompts.mcpText(
await client.callTool(
{ name: "binary_session", arguments: {} },
mcpOptions,
),
),
);
const providerStatus = providerStatusEnvelope.result;
if (
providerStatus.analysis_provider_binding?.provider?.id !== "hopper" ||
providerStatus.analysis_provider_binding?.selection_source !== "request"
)
throw new Error("packaged MCP omitted its explicit Hopper binding");
};
const verifyMcpLinuxCurrentDocument = async (client, mcpOptions, current) => {
if (
current.isError !== true ||
!prompts
.mcpText(current)
.includes("not supported for unattended Linux analysis")
)
throw new Error("packaged Linux MCP did not reject an unpinned Hopper");
};
const verifyMcpNonLinuxCurrentDocument = async (
client,
mcpOptions,
current,
) => {
if (json(prompts.mcpText(current)).result !== "fixture")
throw new Error("packaged MCP bridge call failed");
const batch = await client.callTool(
{
name: "batch_decompile",
arguments: { addresses: ["0x1000"] },
},
mcpOptions,
);
const batchResult = json(prompts.mcpText(batch)).result;
if (
batch.isError === true ||
batchResult?.total !== 1 ||
batchResult?.succeeded !== 1 ||
batchResult?.failed !== 0 ||
batchResult?.items?.[0]?.status !== "ok" ||
batchResult?.items?.[0]?.pseudocode !== "return 0;"
)
throw new Error("packaged MCP structured batch result failed");
};
const verifyMcpBinaryLifecycle = async (client, mcpOptions) => {
await verifyMcpOpenAndBind(client, mcpOptions);
await prompts.verifyPromptCompletion(
client,
mcpOptions,
process.platform !== "linux",
);
const current = await client.callTool(
{ name: "current_document", arguments: {} },
mcpOptions,
);
if (process.platform === "linux") {
await verifyMcpLinuxCurrentDocument(client, mcpOptions, current);
} else {
await verifyMcpNonLinuxCurrentDocument(client, mcpOptions, current);
}
const closed = await client.callTool(
{ name: "close_binary", arguments: {} },
mcpOptions,
);
if (closed.isError === true)
throw new Error("packaged MCP could not close its binary");
await prompts.verifyPromptCompletion(client, mcpOptions, false);
};
const verifyMcpEvidenceBundle = async (client, mcpOptions, evidenceRoot) => {
const mcpBundlePath = join(evidenceRoot, "mcp.json");
const mcpExport = await client.callTool(
{ name: "export_evidence_bundle", arguments: { path: mcpBundlePath } },
mcpOptions,
);
if (mcpExport.isError === true)
throw new Error("packaged MCP evidence export failed");
const mcpImport = await client.callTool(
{ name: "import_evidence_bundle", arguments: { path: mcpBundlePath } },
mcpOptions,
);
if (mcpImport.isError === true)
throw new Error("packaged MCP evidence import failed");
};
/** Connect to the packaged MCP server and exercise the target-free catalog. */
export async function verifyPackageMcp({
cli,
environment,
evidenceRoot,
investigationReplay,
}) {
const transport = new StdioClientTransport({
command: cli,
args: ["mcp"],
env: {
...environment,
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([]),
},
stderr: "pipe",
});
let mcpStderr = "";
transport.stderr?.on("data", (chunk) => {
mcpStderr += chunk.toString();
});
const client = new Client({ name: "package-smoke", version: "1.0.0" });
try {
await client.connect(transport);
const mcpOptions = { timeout: 15_000 };
await verifyMcpToolsAndPrompts(client, mcpOptions);
await verifyMcpReplay(client, mcpOptions, investigationReplay);
await verifyMcpTargetFree(client, mcpOptions);
await verifyMcpUnknownProvider(client, mcpOptions);
await verifyMcpBinaryLifecycle(client, mcpOptions);
await verifyMcpEvidenceBundle(client, mcpOptions, evidenceRoot);
} catch (cause) {
throw new Error(`packaged MCP smoke failed: ${mcpStderr}`, { cause });
} finally {
await client.close();
await transport.close();
}
}
+33
View File
@@ -0,0 +1,33 @@
import { join } from "node:path";
import { exec } from "./lib/verify-package-core.mjs";
import { verifyPackedBridge } from "./verify-packed-bridge.mjs";
/** Create a tarball and assert production packaging constraints. */
export async function verifyPackagePack({ root, workspace }) {
const tarball = (
await exec("npm", ["pack", "--silent"], { cwd: root })
).stdout.trim();
const packedFiles = (
await exec("tar", ["-tf", join(root, tarball)])
).stdout.split("\n");
const packedManifest = JSON.parse(
(await exec("tar", ["-xOf", join(root, tarball), "package/package.json"]))
.stdout,
);
if (
packedManifest.scripts?.postinstall !== undefined ||
packedManifest.dependencies?.["node-pty"] !== undefined ||
packedManifest.dependencies?.["@lydell/node-pty"] !== "1.1.0"
)
throw new Error("package retained a lifecycle-dependent PTY installation");
if (
packedFiles.some(
(path) => path.includes("__pycache__") || path.endsWith(".pyc"),
)
) {
throw new Error("package contained generated Python bytecode");
}
await verifyPackedBridge({ root, workspace, tarball, packedFiles });
return { tarball };
}
+87
View File
@@ -0,0 +1,87 @@
import { json, run, runWithStatus } from "./lib/verify-package-core.mjs";
/** Run platform-specific deep-analysis smoke tests. */
export async function verifyPackagePlatform({ cli, environment }) {
if (process.platform === "linux") {
const unsupportedExecution = await runWithStatus(
cli,
["analyze", process.execPath, "--json"],
environment,
);
const unsupported = json(unsupportedExecution.stdout);
if (
unsupportedExecution.status !== 1 ||
unsupported.details?.failure_code !== "unsupported_hopper_build"
)
throw new Error(
`packaged Linux Hopper verification did not fail closed: ${JSON.stringify(unsupported)}`,
);
} else {
const overview = json(
await run(cli, ["analyze", process.execPath, "--json"], environment),
);
if (
overview.operation !== "binary_overview" ||
overview.normalized_result?.procedure_count < 1
)
throw new Error(
`packaged Hopper-backed analyze CLI failed: ${JSON.stringify(overview)}`,
);
const inspected = json(
await run(
cli,
[
"inspect",
process.execPath,
"--detail",
"detailed",
"--limit",
"1",
"--json",
],
environment,
),
);
if (
inspected.operation !== "binary_overview" ||
inspected.normalized_result?.detail !== "detailed"
)
throw new Error("packaged inspect CLI failed");
const functionResult = json(
await run(
cli,
["function", process.execPath, "0x1000", "--json"],
environment,
),
);
if (
functionResult.operation !== "analyze_function" ||
functionResult.provider?.id !== "hopper" ||
functionResult.normalized_result?.procedure?.address !== "0x1000"
)
throw new Error(
`packaged function CLI failed: ${JSON.stringify(functionResult)}`,
);
const xrefs = json(
await run(
cli,
["xrefs", process.execPath, "0x1000", "--json"],
environment,
),
);
if (
xrefs.operation !== "xrefs" ||
JSON.stringify(xrefs.normalized_result) !== JSON.stringify(["0x1000"])
)
throw new Error(`packaged xrefs CLI failed: ${JSON.stringify(xrefs)}`);
const trace = json(
await run(
cli,
["trace", process.execPath, "fixture", "--json"],
environment,
),
);
if (trace.operation !== "trace_feature")
throw new Error(`packaged trace CLI failed: ${JSON.stringify(trace)}`);
}
}
+376
View File
@@ -0,0 +1,376 @@
import {
lstat,
mkdir,
readFile,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
import {
json,
pathExists,
run,
runWithStatus,
} from "./lib/verify-package-core.mjs";
const verifyMcpAdd = async ({ cli, environment, npxLog }) => {
await run(cli, ["mcp", "add"], environment);
const mcpRegistration = await readFile(npxLog, "utf8");
if (
!mcpRegistration.includes("add-mcp npx -y rea-agents@latest mcp --name rea")
)
throw new Error("Incur mcp add did not register the latest npx command");
};
const verifySetupPlan = async ({
cli,
environment,
claudeConfig,
cursorConfig,
codexTarget,
supportedSetupHost,
}) => {
const plannedExecution = await runWithStatus(
cli,
["setup", "--json"],
environment,
);
const planned = json(plannedExecution.stdout);
if (supportedSetupHost) {
const plannedClaudeConfig = await readFile(claudeConfig, "utf8");
const plannedCodexConfig = await readFile(codexTarget, "utf8");
const plannedCursorConfig = await readFile(cursorConfig, "utf8");
if (
planned.status !== "needs_confirmation" ||
plannedExecution.status !== 1 ||
planned.appliedActions.length !== 0 ||
!planned.plannedActions.some(({ kind }) => kind === "configure_client") ||
!planned.plannedActions.some(({ kind }) => kind === "install_skill") ||
plannedClaudeConfig !== '{"existing":true}\n' ||
plannedCodexConfig !== 'model = "gpt-5"\n' ||
plannedCursorConfig !== '{"existing":true}\n'
)
throw new Error(
`packaged setup plan was not read-only: ${JSON.stringify({ status: planned.status, exitCode: plannedExecution.status, plannedKinds: planned.plannedActions.map(({ kind }) => kind), appliedKinds: planned.appliedActions.map(({ kind }) => kind), claudeConfig: plannedClaudeConfig, codexConfig: plannedCodexConfig, cursorConfig: plannedCursorConfig })}`,
);
}
return { planned };
};
const verifySetupApply = async ({ cli, environment, supportedSetupHost }) => {
const status = process.platform === "linux" ? "needs_human" : "ready";
const firstExecution = await runWithStatus(
cli,
["setup", "--yes", "--json"],
environment,
);
const first = json(firstExecution.stdout);
const alignedExecution = await runWithStatus(
cli,
["setup", "--json"],
environment,
);
const aligned = json(alignedExecution.stdout);
const secondExecution = await runWithStatus(
cli,
["setup", "--install-hopper", "--json"],
environment,
);
const second = json(secondExecution.stdout);
if (supportedSetupHost) {
if (
first.status !== status ||
second.status !== "needs_confirmation" ||
firstExecution.status !== (status === "ready" ? 0 : 1) ||
secondExecution.status !== 1 ||
aligned.status !== status ||
alignedExecution.status !== (status === "ready" ? 0 : 1) ||
aligned.plannedActions.length !== 0 ||
aligned.appliedActions.length !== 0 ||
!second.plannedActions.some(({ kind }) => kind === "install_hopper") ||
second.appliedActions.length !== 0
)
throw new Error(
`packaged setup did not preserve idempotent defaults and explicit Hopper reinstall behavior: ${JSON.stringify({ first, aligned, second })}`,
);
}
return {
first,
aligned,
second,
firstExecution,
alignedExecution,
secondExecution,
status,
};
};
const assertClientConfig = async (cli, configPath) => {
const config = json(await readFile(configPath, "utf8"));
if (
config.existing !== true ||
config.mcpServers?.rea?.command !== cli ||
JSON.stringify(config.mcpServers?.rea?.args) !== JSON.stringify(["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 assertCodexSymlink = async ({
cli,
codexConfig,
cursorConfig,
codexTarget,
}) => {
const codex = await readFile(codexTarget, "utf8");
if (
!(await lstat(codexConfig)).isSymbolicLink() ||
!(await lstat(cursorConfig)).isSymbolicLink() ||
!codex.includes("[mcp_servers.rea]") ||
!codex.includes(`command = "${cli}"`) ||
(await readFile(`${codexConfig}.rea.backup`, "utf8")) !==
'model = "gpt-5"\n' ||
(await readFile(`${cursorConfig}.rea.backup`, "utf8")) !==
'{"existing":true}\n'
)
throw new Error("packaged setup did not preserve config symlinks");
};
const assertSkill = async ({ skillPath, siblingSkillPath, root }) => {
const skill = await readFile(skillPath, "utf8");
const canonicalSkill = await readFile(
join(root, "skills/reverse-engineer-anything/SKILL.md"),
"utf8",
);
if (skill !== canonicalSkill)
throw new Error("packaged skill did not match its canonical source");
if ((await readFile(siblingSkillPath, "utf8")) !== "unrelated skill\n")
throw new Error("packaged skill installation modified a sibling skill");
};
const assertAlignedDoctor = async (cli, environment) => {
const alignedDoctorExecution = await runWithStatus(
cli,
["doctor", "--json"],
environment,
);
const alignedDoctor = json(alignedDoctorExecution.stdout);
if (
alignedDoctorExecution.status !== (alignedDoctor.healthy ? 0 : 1) ||
alignedDoctor.identity?.skill?.state !== "aligned" ||
alignedDoctor.identity?.skill?.installed_tool_count !==
TOOL_CONTRACTS.length ||
alignedDoctor.checks?.some(({ name }) => name === "skill:identity")
)
throw new Error(
"packaged doctor did not report the upgraded skill aligned",
);
};
const verifyConfigReadback = async ({
cli,
environment,
claudeConfig,
cursorConfig,
codexConfig,
codexTarget,
root,
skillPath,
siblingSkillPath,
}) => {
await assertClientConfig(cli, claudeConfig);
await assertClientConfig(cli, cursorConfig);
await assertCodexSymlink({
cli,
codexConfig,
cursorConfig,
codexTarget,
});
await assertSkill({ skillPath, siblingSkillPath, root });
await assertAlignedDoctor(cli, environment);
};
const verifySetupFailureRecovery = async ({
cli,
environment,
claudeConfig,
cursorConfig,
status,
}) => {
await writeFile(claudeConfig, "malformed");
await writeFile(cursorConfig, '{"existing":true}\n');
const failedExecution = await runWithStatus(
cli,
["setup", "--yes", "--json"],
environment,
);
const failed = json(failedExecution.stdout);
if (
failed.status !== "needs_human" ||
failedExecution.status !== 1 ||
failed.clients?.claude_desktop?.status !== "failed" ||
failed.clients?.cursor?.status !== "configured" ||
!failed.appliedActions.includes("configured_cursor") ||
(await readFile(claudeConfig, "utf8")) !== "malformed" ||
json(await readFile(cursorConfig, "utf8")).mcpServers?.rea?.command !== cli
)
throw new Error(
`packaged setup did not continue after an earlier client failure: ${JSON.stringify(failed)}`,
);
await writeFile(claudeConfig, "{}\n");
const recoveredExecution = await runWithStatus(
cli,
["setup", "--yes", "--json"],
environment,
);
const recovered = json(recoveredExecution.stdout);
if (
recovered.status !== status ||
recoveredExecution.status !== (status === "ready" ? 0 : 1)
)
throw new Error("packaged setup did not recover");
};
const verifyDanglingSymlink = async ({ cli, environment, home }) => {
const geminiDir = join(home, ".gemini");
const geminiConfig = join(geminiDir, "settings.json");
await mkdir(geminiDir, { recursive: true });
await symlink(join(home, "missing-gemini.json"), geminiConfig);
const danglingExecution = await runWithStatus(
cli,
["setup", "--yes", "--json"],
environment,
);
const dangling = json(danglingExecution.stdout);
if (
dangling.status !== "needs_human" ||
danglingExecution.status !== 1 ||
dangling.clients?.gemini_cli?.status !== "failed" ||
dangling.clients?.gemini_cli?.reason !== "path" ||
!(await lstat(geminiConfig)).isSymbolicLink() ||
(await pathExists(`${geminiConfig}.rea.backup`))
)
throw new Error(
`packaged setup did not reject a dangling config symlink before mutation: ${JSON.stringify(dangling)}`,
);
await rm(geminiDir, { recursive: true });
};
const verifyUninstall = async ({
cli,
environment,
cursorConfig,
codexConfig,
cursorTarget,
codexTarget,
}) => {
const uninstallExecution = await runWithStatus(
cli,
["uninstall", "--json"],
environment,
);
const uninstall = json(uninstallExecution.stdout);
const cursorAfterUninstall = json(await readFile(cursorTarget, "utf8"));
const codexAfterUninstall = await readFile(codexTarget, "utf8");
if (
uninstall.status !== "complete" ||
uninstallExecution.status !== 0 ||
uninstall.items?.find(({ name }) => name === "cursor")?.status !==
"removed" ||
uninstall.items?.find(({ name }) => name === "codex")?.status !==
"removed" ||
!(await lstat(cursorConfig)).isSymbolicLink() ||
!(await lstat(codexConfig)).isSymbolicLink() ||
cursorAfterUninstall.existing !== true ||
cursorAfterUninstall.mcpServers?.rea !== undefined ||
!codexAfterUninstall.includes('model = "gpt-5"') ||
codexAfterUninstall.includes("mcp_servers.rea") ||
!(await readFile(`${cursorConfig}.rea.backup`, "utf8")).includes('"rea"') ||
!(await readFile(`${codexConfig}.rea.backup`, "utf8")).includes(
"[mcp_servers.rea]",
)
)
throw new Error(
`packaged uninstall did not preserve config symlinks: ${JSON.stringify(uninstall)}`,
);
};
/** Verify setup transactions, skill installation, and uninstall for supported hosts. */
export async function verifyPackageSetup({
cli,
environment,
home,
npxLog,
claudeConfig,
codexConfig,
cursorConfig,
codexTarget,
cursorTarget,
supportedSetupHost,
root,
}) {
await verifyMcpAdd({ cli, environment, npxLog });
const skillPath = join(
home,
".agents/skills/reverse-engineer-anything/SKILL.md",
);
const siblingSkillPath = join(home, ".agents/skills/unrelated/SKILL.md");
if (supportedSetupHost) {
await mkdir(join(home, ".agents/skills/unrelated"), { recursive: true });
await writeFile(siblingSkillPath, "unrelated skill\n");
}
await verifySetupPlan({
cli,
environment,
claudeConfig,
cursorConfig,
codexTarget,
supportedSetupHost,
});
const apply = await verifySetupApply({
cli,
environment,
supportedSetupHost,
});
if (supportedSetupHost) {
await verifyConfigReadback({
cli,
environment,
claudeConfig,
cursorConfig,
codexConfig,
codexTarget,
root,
skillPath,
siblingSkillPath,
});
await verifySetupFailureRecovery({
cli,
environment,
claudeConfig,
cursorConfig,
status: apply.status,
});
await verifyDanglingSymlink({ cli, environment, home });
await verifyUninstall({
cli,
environment,
cursorConfig,
codexConfig,
cursorTarget,
codexTarget,
});
} else if (
apply.first.status !== "needs_human" ||
apply.aligned.status !== "needs_human" ||
apply.second.status !== "needs_human"
) {
throw new Error("packaged setup did not reject an unsupported host");
}
}
@@ -0,0 +1,19 @@
import { json, runWithStatus } from "./lib/verify-package-core.mjs";
/** Verify that an unknown --provider is rejected by the packaged CLI. */
export async function verifyUnknownProvider({ cli, environment }) {
const unknownProviderExecution = await runWithStatus(
cli,
["analyze", process.execPath, "--provider", "missing-provider", "--json"],
environment,
);
const unknownProvider = json(unknownProviderExecution.stdout);
if (
unknownProviderExecution.status !== 1 ||
unknownProvider.details?.selection_reason !== "unknown_provider" ||
unknownProvider.details?.requested_provider_id !== "missing-provider"
)
throw new Error(
`packaged CLI provider selection failed: ${JSON.stringify(unknownProvider)}`,
);
}
+83 -1190
View File
File diff suppressed because it is too large Load Diff
+17 -19
View File
@@ -20,6 +20,7 @@ import {
} from "../dist/domain/webScreenshot.js";
import { startBrowserVerifierSite } from "./fixtures/browser-verifier-site.mjs";
import { startPageCdpProxy } from "./fixtures/page-cdp-proxy.mjs";
import { sourceMapSummary } from "./lib/browser-verifier-assertions.mjs";
const SECRET_VALUES = [
"network-secret-value",
@@ -334,6 +335,13 @@ async function pageTarget(provider, endpoint, origin) {
}
function assertObservation(result, origin) {
assertObservationInventory(result, origin);
assertObservationEvents(result);
assertObservationPrivacy(result);
assertObservationMetadata(result);
}
function assertObservationInventory(result, origin) {
if (result.target.origin !== origin)
throw new Error("Real Chrome target origin was not preserved exactly");
if (result.frames.length < 1 || result.dom.nodes.length < 1)
@@ -353,6 +361,9 @@ function assertObservation(result, origin) {
throw new Error("Real Chrome script metadata was missing");
if (!result.resources.some((resource) => resource.url.includes("/app.js")))
throw new Error("Real Chrome resource metadata was missing");
}
function assertObservationEvents(result) {
if (!result.network.requests.some((request) => request.url.includes("/api")))
throw new Error(
"Real Chrome attach-window network observation was missing",
@@ -372,6 +383,9 @@ function assertObservation(result, origin) {
);
if (result.network.websocket_events.length < 1)
throw new Error("Real Chrome WebSocket metadata was missing");
}
function assertObservationPrivacy(result) {
if (
result.console.events.some(
(event) => event.text_capture.status !== "not_approved",
@@ -386,6 +400,9 @@ function assertObservation(result, origin) {
throw new Error(
"Sensitive text or payload shapes were retained without approval",
);
}
function assertObservationMetadata(result) {
if (!result.storage.local_storage_keys.includes("rea-storage-key"))
throw new Error("Real Chrome local-storage key inventory was missing");
if (!result.storage.indexed_db_names.includes("rea-browser-db"))
@@ -431,25 +448,6 @@ function assertBundleAnalysis(result) {
);
}
function sourceMapSummary(sourceMaps) {
return {
status: sourceMaps.status,
requested: sourceMaps.requested,
processed: sourceMaps.processed,
dropped: sourceMaps.dropped,
items: sourceMaps.items.map((item) => ({
status: item.status,
declaredUrl: item.declared_url,
sources: item.original_sources.map(({ source }) => source),
edgeSpecifiers: item.original_module_edges.map(({ specifier }) =>
specifier.slice(0, 256),
),
mappings: item.mappings.length,
limitation: item.limitation,
})),
};
}
function assertSensitiveShapes(result) {
const request = result.network.requests.find((item) =>
item.url.includes("/api"),
+349
View File
@@ -0,0 +1,349 @@
import { access } from "node:fs/promises";
import { parseBinaryTarget } from "../dist/domain/binaryTarget.js";
import { SUPPORTED_GHIDRA_VERSION } from "../dist/ghidra/GhidraInstallation.js";
import { GHIDRA_SESSION_CAPABILITIES } from "../dist/ghidra/GhidraSessionValues.js";
export function assertLocalProcedureInfo(info, expectedAddress) {
if (
info.entrypoint !== expectedAddress ||
info.basicblock_count < 1 ||
info.length < 1 ||
typeof info.signature !== "string" ||
info.signature.length === 0 ||
info.classification.external ||
info.classification.provenance !== "ghidra-function-manager"
)
throw new Error(
`Ghidra procedure metadata drifted: ${JSON.stringify(info)}`,
);
}
export function assertProviderText(assembly, pseudocode, expectedAddress) {
if (
typeof assembly !== "string" ||
!assembly.includes(`${expectedAddress}:`) ||
assembly.trim().length === 0
)
throw new Error("Ghidra assembly rendering lost its address-bearing lines");
if (typeof pseudocode !== "string" || pseudocode.trim().length === 0)
throw new Error("Ghidra local function pseudocode is unavailable");
}
export function assertReferenceMetadata(observed) {
if (
observed.instructions_scanned < 1 ||
observed.instruction_scan_truncated ||
observed.references.items.length === 0 ||
!observed.references.items.every(
({ kind }) =>
kind.available && kind.provenance === "ghidra-reference-manager",
) ||
!observed.references.items.some(({ kind }) => kind.call) ||
!observed.references.items.some(({ kind }) => kind.data)
)
throw new Error(
`Ghidra typed reference metadata drifted: ${JSON.stringify(observed)}`,
);
}
export function assertDossier(
dossier,
{
address,
expectedCallees = [],
expectedString = null,
requireAssembly = false,
requireMultiBlock = false,
},
) {
assertDossierProcedure(dossier, address);
assertDossierReferences(dossier);
assertDossierCallees(dossier, expectedCallees);
assertDossierStrings(dossier, expectedString);
assertDossierAssembly(dossier, requireAssembly);
assertDossierMultiBlock(dossier, requireMultiBlock);
}
function assertDossierProcedure(dossier, address) {
if (
dossier.procedure.address !== address ||
dossier.procedure.classification === null ||
dossier.procedure.classification.provenance !== "ghidra-function-manager" ||
dossier.procedure.classification.external ||
dossier.pseudocode.text.trim().length === 0 ||
dossier.pseudocode.returned_chars !== [...dossier.pseudocode.text].length ||
dossier.instruction_scan.scanned < 1 ||
dossier.instruction_scan.truncated ||
!dossier.limitations.some((value) => /indirect|computed/u.test(value)) ||
!dossier.limitations.some((value) => /Ghidra|Hopper|provider/u.test(value))
)
throw new Error(
`Ghidra dossier truthfulness drifted: ${JSON.stringify(dossier)}`,
);
}
function assertDossierReferences(dossier) {
if (
![
...dossier.incoming_references.items,
...dossier.outgoing_references.items,
].every(
({ kind }) =>
kind.available && kind.provenance === "ghidra-reference-manager",
)
)
throw new Error("Ghidra dossier lost typed reference provenance");
}
function assertDossierCallees(dossier, expectedCallees) {
for (const expected of expectedCallees)
if (!dossier.callees.items.some(({ address: value }) => value === expected))
throw new Error(`Ghidra dossier missed callee ${expected}`);
}
function assertDossierStrings(dossier, expectedString) {
if (
expectedString !== null &&
!dossier.referenced_strings.items.some(
({ value }) => value === expectedString,
)
)
throw new Error(
`Ghidra dossier missed referenced string ${expectedString}`,
);
}
function assertDossierAssembly(dossier, requireAssembly) {
if (
requireAssembly &&
(dossier.assembly.items.length === 0 || dossier.assembly.truncated)
)
throw new Error("Ghidra dossier assembly was unavailable or truncated");
}
function assertDossierMultiBlock(dossier, requireMultiBlock) {
if (
requireMultiBlock &&
(dossier.basic_blocks.items.length < 2 ||
!dossier.basic_blocks.items.some(
({ successors }) => successors.length > 0,
))
)
throw new Error(
"Ghidra dossier CFG missed the multi-block branch structure",
);
}
export function dossierSummary(dossier) {
return {
address: dossier.procedure.address,
pseudocode_chars: dossier.pseudocode.total_chars,
instructions: dossier.instruction_scan.scanned,
callees: dossier.callees.returned,
outgoing_references: dossier.outgoing_references.returned,
referenced_strings: dossier.referenced_strings.returned,
basic_blocks: dossier.basic_blocks.returned,
};
}
export async function assertSession(
session,
expectedDigest,
expectedTargetSha256,
) {
if (
session.provider.id !== "ghidra" ||
session.provider.version !== SUPPORTED_GHIDRA_VERSION ||
session.profile_digest !== expectedDigest ||
session.target.sha256 !== expectedTargetSha256 ||
session.read_only !== true ||
session.analysis_complete !== true ||
session.analysis_timed_out !== false ||
session.capabilities.join(",") !== GHIDRA_SESSION_CAPABILITIES.join(",") ||
!/^0x[0-9a-f]+$/u.test(session.target.image_base) ||
session.target.default_address_space.length === 0
)
throw new Error(
`Ghidra session commitment drifted: ${JSON.stringify(session)}`,
);
}
export function assertRuntimeCoordinates(coordinates) {
for (const name of ["runtime_root", "endpoint_path", "project_root"])
if (typeof coordinates[name] !== "string")
throw new Error(`Ghidra verifier did not observe ${name}`);
if (typeof coordinates.process_id !== "number")
throw new Error("Ghidra verifier did not observe its process ID");
}
export async function assertCleanup(coordinates) {
for (const name of ["runtime_root", "endpoint_path", "project_root"]) {
const path = coordinates[name];
if (typeof path === "string" && (await exists(path)))
throw new Error(`Ghidra cleanup left ${name}: ${path}`);
}
const pid = coordinates.process_id;
if (typeof pid === "number" && processExists(pid))
throw new Error(`Ghidra cleanup left process ${String(pid)}`);
}
export function assertDebugFixture(observed) {
if (
!Array.isArray(observed.documents) ||
observed.documents.length !== 1 ||
!observed.documents[0].includes("debug")
)
throw new Error("Ghidra did not expose exactly one debug Program identity");
const entry = findValue(observed.procedures, "rea_ghidra_inventory_entry");
const leaf = findValue(observed.procedures, "rea_ghidra_inventory_leaf");
const external = observed.procedures.find(
(item) => item.procedure.external && symbolTail(item.value) === "puts",
);
if (entry === undefined || leaf === undefined || external === undefined)
throw new Error(
"Ghidra procedure inventory missed local or external functions",
);
if (
!observed.procedures.some(
(item) => item.procedure.thunk && item.procedure.thunk_target !== null,
)
)
throw new Error(
"Ghidra procedure inventory did not distinguish a resolved thunk",
);
const entryName = findValue(observed.names, "rea_ghidra_inventory_entry");
if (entryName === undefined || !entryName.symbol.primary)
throw new Error("Ghidra symbol inventory missed the primary entry symbol");
if (!observed.names.some((item) => item.symbol.external))
throw new Error("Ghidra symbol inventory missed external symbols");
assertStrings(observed.strings);
assertSegments(observed.segments, observed.session.target.image_base);
}
export function assertStrippedFixture(observed) {
if (
observed.procedures.length === 0 ||
observed.names.length === 0 ||
findValue(observed.procedures, "rea_ghidra_inventory_entry") !== undefined
)
throw new Error(
"Stripped Ghidra fixture did not preserve stripped semantics",
);
assertStrings(observed.strings);
assertSegments(observed.segments, observed.session.target.image_base);
}
export function assertCrossFixture(observed) {
if (
observed.procedures.length === 0 ||
observed.names.length === 0 ||
observed.probes === null ||
typeof observed.probes.entry !== "string" ||
observed.probes.string_owner.referenced_strings < 1 ||
observed.probes.branch.basic_blocks < 2
)
throw new Error(
`Cross-format Ghidra semantics drifted: ${JSON.stringify(summary(observed))}`,
);
assertSegments(observed.segments, observed.session.target.image_base);
}
export async function assertMalformedFixture(path) {
const parsed = await parseBinaryTarget(path);
if (parsed.ok || parsed.error._tag !== "BinaryTargetError")
throw new Error(
"Malformed executable was not rejected before provider start",
);
}
export function assertStrings(strings) {
for (const expected of [
"REA_GHIDRA_INVENTORY_ENTRY",
"REA_GHIDRA_LEAF_VALUE",
]) {
const item = strings.find((candidate) => candidate.value === expected);
if (
item === undefined ||
item.value_truncated ||
typeof item.string.encoding !== "string" ||
item.string.byte_length < expected.length
)
throw new Error(`Ghidra string inventory missed ${expected}`);
}
}
export function assertSegments(segments, imageBase) {
if (
!Array.isArray(segments) ||
segments.length === 0 ||
!segments.some((item) => item.executable) ||
!segments.some((item) => item.writable) ||
!segments.every(
(item) =>
item.permissions.available === true &&
item.permissions.source === "ghidra-memory-block" &&
item.image_base === imageBase,
)
)
throw new Error("Ghidra memory-block permissions or image base drifted");
}
export function findValue(items, expected) {
return items.find((item) => symbolTail(item.value) === expected);
}
export function requireProcedure(items, expected) {
const observed = findValue(items, expected);
if (observed === undefined)
throw new Error(`Ghidra procedure probe is unavailable: ${expected}`);
return observed;
}
export function matchesSymbol(value, expected) {
const tail = symbolTail(value);
return tail === expected || tail === `_${expected}`;
}
export function symbolTail(value) {
if (typeof value !== "string") return undefined;
return value.split("::").at(-1);
}
export function summary(observed) {
return {
variant: observed.variant,
target_path: observed.target.path,
target_sha256: observed.target.sha256,
analysis_profile_digest: observed.profile.digest,
language_id: observed.session.target.language_id,
compiler_spec_id: observed.session.target.compiler_spec_id,
image_base: observed.session.target.image_base,
procedures: observed.procedures.length,
names: observed.names.length,
strings: observed.strings.length,
memory_blocks: observed.segments.length,
};
}
async function exists(path) {
try {
await access(path);
return true;
} catch {
return false;
}
}
function processExists(pid) {
try {
process.kill(pid, 0);
return true;
} catch (cause) {
return !(
cause instanceof Error &&
"code" in cause &&
cause.code === "ESRCH"
);
}
}
+422
View File
@@ -0,0 +1,422 @@
import {
parseGhidraFunctionInput,
parseGhidraFunctionResult,
} from "../dist/ghidra/GhidraFunctionValues.js";
import {
assertDossier,
assertLocalProcedureInfo,
assertProviderText,
assertReferenceMetadata,
dossierSummary,
matchesSymbol,
requireProcedure,
} from "./verify-real-ghidra-assertions.mjs";
export async function functionCall(client, operation, parameters) {
const input = parseGhidraFunctionInput(operation, parameters);
if (!input.ok) throw input.error;
const called = await client.callTool(operation, input.value);
if (!called.ok)
throw new Error(
`Ghidra ${operation} failed for ${JSON.stringify(input.value)}: ${called.error.message}`,
{ cause: called.error },
);
const parsed = parseGhidraFunctionResult(operation, called.value);
if (!parsed.ok) throw parsed.error;
return parsed.value;
}
export async function verifyDebugFunctionOperations(
client,
{ procedures, strings, entry },
) {
const leaf = requireProcedure(procedures, "rea_ghidra_inventory_leaf");
const branch = requireProcedure(procedures, "rea_ghidra_inventory_branch");
const indirect = requireProcedure(
procedures,
"rea_ghidra_inventory_indirect",
);
const main = requireProcedure(procedures, "main");
const entryString = strings.find(
(item) => item.value === "REA_GHIDRA_INVENTORY_ENTRY",
);
if (entryString === undefined)
throw new Error("Ghidra debug string function probe is unavailable");
const [info, assembly, pseudocode, callees, callers, outgoing, entryXrefs] =
await collectEntryFunctionData(client, entry);
assertLocalProcedureInfo(info, entry.address);
assertProviderText(assembly, pseudocode, entry.address);
assertEntryCallGraph({ branch, indirect, main, callees, callers });
const { xrefOwners, xrefOwnerFailures } = await resolveXrefOwners(
client,
entryXrefs,
);
assertEntryXrefAttribution({
entryXrefs,
callers,
xrefOwners,
xrefOwnerFailures,
main,
});
assertReferenceMetadata(outgoing);
await assertStringXrefs(client, entryString.address);
const entryDossier = await analyzeEntryDossier(
client,
entry,
branch,
indirect,
);
const branchDossier = await analyzeBranchDossier(client, branch);
const indirectDossier = await analyzeIndirectDossier(client, indirect);
assertIndirectDossier(indirectDossier, leaf.address);
const { cancellation, timeout } = await verifyRequestCancellationAndTimeout(
client,
entry,
);
const concurrent = await verifyConcurrentRequests(client, entry, leaf);
return {
entry: dossierSummary(entryDossier),
branch: dossierSummary(branchDossier),
indirect: dossierSummary(indirectDossier),
cancellation,
timeout,
concurrency: concurrent,
};
}
async function collectEntryFunctionData(client, entry) {
return Promise.all([
functionCall(client, "procedure_info", {
document: null,
procedure: entry.value,
}),
functionCall(client, "procedure_assembly", {
document: null,
procedure: entry.value,
}),
functionCall(client, "procedure_pseudo_code", {
document: null,
procedure: entry.value,
}),
functionCall(client, "procedure_callees", {
document: null,
procedure: entry.value,
}),
functionCall(client, "procedure_callers", {
document: null,
procedure: entry.value,
}),
functionCall(client, "procedure_references", {
document: null,
procedure: entry.value,
direction: "outgoing",
}),
functionCall(client, "xrefs", {
document: null,
address: entry.address,
}),
]);
}
function assertEntryCallGraph({ branch, indirect, main, callees, callers }) {
for (const expected of [branch.address, indirect.address])
if (!callees.includes(expected))
throw new Error(`Ghidra call graph missed ${expected}`);
if (!callers.includes(main.address))
throw new Error("Ghidra caller or xref relation missed main");
}
async function resolveXrefOwners(client, entryXrefs) {
const xrefOwners = [];
const xrefOwnerFailures = [];
for (const address of entryXrefs) {
try {
xrefOwners.push(
await functionCall(client, "resolve_containing_procedure", {
document: null,
address,
}),
);
} catch (cause) {
xrefOwnerFailures.push({
address,
message: cause instanceof Error ? cause.message : String(cause),
});
}
}
return { xrefOwners, xrefOwnerFailures };
}
function assertEntryXrefAttribution({
entryXrefs,
callers,
xrefOwners,
xrefOwnerFailures,
main,
}) {
if (
!xrefOwners.some(
(owner) => owner.found && owner.procedure.address === main.address,
)
)
throw new Error(
`Ghidra entry xrefs were not attributable to main: ${JSON.stringify({ entryXrefs, callers, xrefOwners, xrefOwnerFailures })}`,
);
}
async function assertStringXrefs(client, entryStringAddress) {
const stringXrefs = await functionCall(client, "xrefs", {
document: null,
address: entryStringAddress,
});
if (stringXrefs.length === 0)
throw new Error("Ghidra xrefs missed the entry string");
}
async function analyzeEntryDossier(client, entry, branch, indirect) {
const entryDossier = await functionCall(client, "analyze_function", {
procedure: entry.address,
include_assembly: true,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDossier(entryDossier, {
address: entry.address,
expectedCallees: [branch.address, indirect.address],
expectedString: "REA_GHIDRA_INVENTORY_ENTRY",
requireAssembly: true,
});
return entryDossier;
}
async function analyzeBranchDossier(client, branch) {
const branchDossier = await functionCall(client, "analyze_function", {
procedure: branch.address,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDossier(branchDossier, {
address: branch.address,
requireMultiBlock: true,
});
return branchDossier;
}
async function analyzeIndirectDossier(client, indirect) {
const indirectDossier = await functionCall(client, "analyze_function", {
procedure: indirect.address,
include_assembly: true,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDossier(indirectDossier, {
address: indirect.address,
requireAssembly: true,
});
return indirectDossier;
}
function assertIndirectDossier(indirectDossier, leafAddress) {
if (
indirectDossier.callees.items.some(({ address }) => address === leafAddress)
)
throw new Error(
"Ghidra dossier falsely resolved a targetless callback as the fixture leaf",
);
if (!/\bcall\b/iu.test(indirectDossier.assembly.items.join("\n")))
throw new Error("Ghidra indirect-call fixture lost its computed call site");
}
async function verifyRequestCancellationAndTimeout(client, entry) {
const aborted = new AbortController();
aborted.abort();
const cancelled = await client.callTool(
"procedure_info",
{ document: null, procedure: entry.address },
{ signal: aborted.signal },
);
if (cancelled.ok || cancelled.error.kind !== "cancelled")
throw new Error("Ghidra established-request cancellation drifted");
const timedOut = await client.callTool(
"procedure_info",
{ document: null, procedure: entry.address },
{ timeoutMs: 0 },
);
if (timedOut.ok || timedOut.error.kind !== "timeout")
throw new Error("Ghidra established-request deadline drifted");
return {
cancellation: "cancelled-before-wire",
timeout: "expired-before-wire",
};
}
async function verifyConcurrentRequests(client, entry, leaf) {
const concurrent = await Promise.all([
functionCall(client, "procedure_info", {
document: null,
procedure: entry.address,
}),
functionCall(client, "xrefs", {
document: null,
address: leaf.address,
}),
]);
if (concurrent.length !== 2)
throw new Error("Ghidra serial request queue lost a concurrent result");
return "serialized-two-results";
}
export async function verifyStrippedFunctionOperations(client, entryString) {
const stringXrefs = await functionCall(client, "xrefs", {
document: null,
address: entryString.address,
});
if (stringXrefs.length === 0)
throw new Error("Ghidra stripped string xref probe is unavailable");
const containing = await functionCall(
client,
"resolve_containing_procedure",
{
document: null,
address: stringXrefs[0],
},
);
if (!containing.found)
throw new Error("Ghidra could not recover a stripped containing function");
const procedure = containing.procedure;
const pseudocode = await functionCall(client, "procedure_pseudo_code", {
document: null,
procedure: procedure.address,
});
if (typeof pseudocode !== "string" || pseudocode.trim().length === 0)
throw new Error("Ghidra did not decompile the stripped function");
const dossier = await functionCall(client, "analyze_function", {
procedure: procedure.address,
include_assembly: true,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDossier(dossier, {
address: procedure.address,
expectedString: "REA_GHIDRA_INVENTORY_ENTRY",
requireAssembly: true,
});
if (symbolTail(dossier.procedure.name) === "rea_ghidra_inventory_entry")
throw new Error("Ghidra stripped dossier invented a source symbol");
return dossierSummary(dossier);
}
export async function verifyCrossFormatOperations({
client,
variant,
procedures,
names,
strings,
}) {
const message = strings.find(
(item) => item.value === "REA_GHIDRA_CROSS_FORMAT",
);
if (message === undefined)
throw new Error(`${variant} string inventory missed the source oracle`);
const entry =
procedures.find((item) => matchesSymbol(item.value, "rea_cross_entry")) ??
names.find((item) => matchesSymbol(item.value, "rea_cross_entry"));
if (entry === undefined)
throw new Error(`${variant} did not retain the exported entry symbol`);
const entryAddress = entry.address;
const info = await functionCall(client, "procedure_info", {
document: null,
procedure: entryAddress,
});
assertLocalProcedureInfo(info, entryAddress);
const [pseudocode, assembly, callees, messageXrefs] = await Promise.all([
functionCall(client, "procedure_pseudo_code", {
document: null,
procedure: entryAddress,
}),
functionCall(client, "procedure_assembly", {
document: null,
procedure: entryAddress,
}),
functionCall(client, "procedure_callees", {
document: null,
procedure: entryAddress,
}),
functionCall(client, "xrefs", {
document: null,
address: message.address,
}),
]);
assertProviderText(assembly, pseudocode, entryAddress);
if (callees.length < 2)
throw new Error(`${variant} call graph missed direct fixture calls`);
if (messageXrefs.length === 0)
throw new Error(`${variant} xrefs missed the fixture string`);
const messageOwner = await findCrossStringOwner(client, messageXrefs);
const stringDossier = await functionCall(client, "analyze_function", {
procedure: messageOwner.procedure.address,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDossier(stringDossier, {
address: messageOwner.procedure.address,
expectedString: "REA_GHIDRA_CROSS_FORMAT",
});
const branchAddress = await findCrossBranchAddress(client, variant, callees);
const branchDossier = await functionCall(client, "analyze_function", {
procedure: branchAddress,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDossier(branchDossier, {
address: branchAddress,
requireMultiBlock: true,
});
return {
entry: entryAddress,
exported_symbol: entry.value,
string_owner: dossierSummary(stringDossier),
branch: dossierSummary(branchDossier),
};
}
async function findCrossStringOwner(client, messageXrefs) {
for (const address of messageXrefs) {
const candidate = await functionCall(
client,
"resolve_containing_procedure",
{
document: null,
address,
},
);
if (candidate.found) return candidate;
}
throw new Error("Cross-format did not resolve the string-owning function");
}
async function findCrossBranchAddress(client, variant, callees) {
for (const address of callees) {
const candidate = await functionCall(client, "procedure_info", {
document: null,
procedure: address,
});
if (candidate.basicblock_count > 1) return address;
}
throw new Error(`${variant} did not recover the multi-block callee`);
}
+237
View File
@@ -0,0 +1,237 @@
import { parseGhidraInventoryResult } from "../dist/ghidra/GhidraInventoryValues.js";
import { findValue, symbolTail } from "./verify-real-ghidra-assertions.mjs";
import {
verifyCrossFormatOperations,
verifyDebugFunctionOperations,
verifyStrippedFunctionOperations,
} from "./verify-real-ghidra-function.mjs";
export async function call(client, operation, parameters) {
const called = await client.callTool(operation, parameters);
if (!called.ok)
throw new Error(
`Ghidra ${operation} failed for ${JSON.stringify(parameters)}: ${called.error.message}`,
{ cause: called.error },
);
const parsed = parseGhidraInventoryResult(operation, called.value);
if (!parsed.ok) throw parsed.error;
return parsed.value;
}
export async function allItems(client, operation, parameters) {
const items = [];
let offset = 0;
let total;
while (true) {
const page = await call(client, operation, {
...parameters,
offset,
limit: 500,
});
if (typeof page !== "object" || page === null || Array.isArray(page))
throw new Error(`${operation} did not return a page`);
items.push(...page.items);
total ??= page.total;
if (page.total !== total)
throw new Error(`${operation} total changed during immutable paging`);
if (!page.has_more) break;
if (page.next_offset === null || page.next_offset <= offset)
throw new Error(`${operation} returned a non-advancing page`);
offset = page.next_offset;
}
if (items.length !== total)
throw new Error(`${operation} pagination was not exhaustive`);
return items;
}
export async function expectRemoteFailure(client, operation, parameters, code) {
const result = await client.callTool(operation, parameters);
if (
result.ok ||
result.error.kind !== "remote" ||
result.error.remoteCode !== code ||
result.error.diagnostics.remote_code !== code
)
throw new Error(
`Ghidra ${operation} rejection drifted: ${JSON.stringify(result)}`,
);
return { operation, code };
}
export async function verifyBridgeRejections(client) {
return {
unknownDocument: await expectRemoteFailure(
client,
"list_segments",
{ document: "not-the-imported-program" },
"not_found",
),
malformedParameter: await expectRemoteFailure(
client,
"procedure_address",
{ document: null, procedure: 17 },
"invalid_request",
),
unboundedRegex: await expectRemoteFailure(
client,
"search_strings",
{
pattern: "a+",
mode: "regex",
case_sensitive: true,
offset: 0,
limit: 100,
document: null,
},
"invalid_request",
),
undeclaredMutation: await expectRemoteFailure(
client,
"set_comment",
{},
"method_unavailable",
),
};
}
export async function verifyInventoryOperations({
client,
variant,
procedures,
names,
strings,
}) {
if (variant.startsWith("cross-"))
return verifyCrossFormatOperations({
client,
variant,
procedures,
names,
strings,
});
const rejections =
variant === "debug" ? await verifyBridgeRejections(client) : null;
const stringSearch = await call(client, "search_strings", {
pattern: String.raw`^REA_GHIDRA_(?:INVENTORY_ENTRY|LEAF_VALUE)$`,
mode: "regex",
case_sensitive: true,
offset: 0,
limit: 100,
document: null,
});
if (stringSearch.total !== 2 || stringSearch.items.length !== 2)
throw new Error("Ghidra bounded regex string search drifted");
const stringItem = strings.find(
(item) => item.value === "REA_GHIDRA_INVENTORY_ENTRY",
);
if (stringItem === undefined)
throw new Error("Ghidra string probe address is unavailable");
const filteredStrings = await call(client, "list_strings", {
document: null,
address: stringItem.address,
offset: 0,
limit: 500,
});
if (
filteredStrings.total !== 1 ||
filteredStrings.items[0]?.address !== stringItem.address
)
throw new Error("Ghidra exact-address string filter drifted");
if (variant === "stripped") {
const functionAnalysis = await verifyStrippedFunctionOperations(
client,
stringItem,
);
return { rejections, stringSearch, filteredStrings, functionAnalysis };
}
const entry = findValue(procedures, "rea_ghidra_inventory_entry");
if (entry === undefined)
throw new Error("Ghidra entry procedure probe is unavailable");
const debug = await verifyDebugInventoryCore({
client,
procedures,
names,
strings,
entry,
});
return {
rejections,
stringSearch,
filteredStrings,
...debug,
};
}
async function verifyDebugInventoryCore({
client,
procedures,
names,
strings,
entry,
}) {
const addressName = await call(client, "address_name", {
document: null,
address: entry.address,
});
if (symbolTail(addressName) !== "rea_ghidra_inventory_entry")
throw new Error("Ghidra primary address-name resolution drifted");
const resolvedAddress = await call(client, "procedure_address", {
document: null,
procedure: entry.value,
});
if (resolvedAddress !== entry.address)
throw new Error("Ghidra procedure-name resolution drifted");
const interior = `0x${(BigInt(entry.address) + 1n).toString(16)}`;
const containing = await call(client, "resolve_containing_procedure", {
document: null,
address: interior,
});
if (!containing.found || containing.procedure.address !== entry.address)
throw new Error("Ghidra containing-procedure resolution drifted");
const procedureSearch = await call(client, "search_procedures", {
pattern: "rea_ghidra_inventory_",
mode: "literal",
case_sensitive: true,
offset: 0,
limit: 1,
document: null,
});
if (
procedureSearch.total < 2 ||
procedureSearch.items.length !== 1 ||
!procedureSearch.has_more ||
procedureSearch.next_offset !== 1
)
throw new Error("Ghidra literal procedure-search pagination drifted");
const name = names.find((item) => item.address === entry.address);
if (name === undefined)
throw new Error("Ghidra entry name probe is unavailable");
const filteredNames = await call(client, "list_names", {
document: null,
address: entry.address,
offset: 0,
limit: 500,
});
if (
filteredNames.total < 1 ||
!filteredNames.items.some((item) => item.value === name.value)
)
throw new Error("Ghidra exact-address name filter drifted");
const functionAnalysis = await verifyDebugFunctionOperations(client, {
procedures,
strings,
entry,
});
return {
addressName,
resolvedAddress,
containing,
procedureSearch,
filteredNames,
functionAnalysis,
};
}
+18 -861
View File
@@ -1,28 +1,38 @@
#!/usr/bin/env node
import { execFile } from "node:child_process";
import { access, mkdtemp, rm, writeFile } from "node:fs/promises";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { isAbsolute, join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { parseBinaryTarget } from "../dist/domain/binaryTarget.js";
import { resolveGhidraAnalysisProfile } from "../dist/ghidra/GhidraAnalysisProfile.js";
import { GhidraClient } from "../dist/ghidra/GhidraClient.js";
import { GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS } from "../dist/ghidra/GhidraDefaults.js";
import {
parseGhidraFunctionInput,
parseGhidraFunctionResult,
} from "../dist/ghidra/GhidraFunctionValues.js";
import { parseGhidraInventoryResult } from "../dist/ghidra/GhidraInventoryValues.js";
import {
inspectGhidraInstallation,
SUPPORTED_GHIDRA_VERSION,
} from "../dist/ghidra/GhidraInstallation.js";
import { GhidraHeadlessLauncher } from "../dist/ghidra/GhidraLauncher.js";
import { GHIDRA_PROVIDER_IDENTITY } from "../dist/ghidra/GhidraProvider.js";
import { GHIDRA_SESSION_CAPABILITIES } from "../dist/ghidra/GhidraSessionValues.js";
import { parseBinaryTarget } from "../dist/domain/binaryTarget.js";
import {
assertCleanup,
assertCrossFixture,
assertDebugFixture,
assertMalformedFixture,
assertRuntimeCoordinates,
assertSession,
assertStrippedFixture,
summary,
} from "./verify-real-ghidra-assertions.mjs";
import {
allItems,
call,
verifyInventoryOperations,
} from "./verify-real-ghidra-inventory.mjs";
const exec = promisify(execFile);
const installDir = process.env.GHIDRA_INSTALL_DIR;
@@ -256,856 +266,3 @@ async function verifyTarget(targetPath, variant, expectedTarget = null) {
await assertCleanup(runtimeCoordinates);
}
}
async function verifyInventoryOperations({
client,
variant,
procedures,
names,
strings,
}) {
if (variant.startsWith("cross-"))
return verifyCrossFormatOperations({
client,
variant,
procedures,
names,
strings,
});
const rejections =
variant === "debug" ? await verifyBridgeRejections(client) : null;
const stringSearch = await call(client, "search_strings", {
pattern: String.raw`^REA_GHIDRA_(?:INVENTORY_ENTRY|LEAF_VALUE)$`,
mode: "regex",
case_sensitive: true,
offset: 0,
limit: 100,
document: null,
});
if (stringSearch.total !== 2 || stringSearch.items.length !== 2)
throw new Error("Ghidra bounded regex string search drifted");
const stringItem = strings.find(
(item) => item.value === "REA_GHIDRA_INVENTORY_ENTRY",
);
if (stringItem === undefined)
throw new Error("Ghidra string probe address is unavailable");
const filteredStrings = await call(client, "list_strings", {
document: null,
address: stringItem.address,
offset: 0,
limit: 500,
});
if (
filteredStrings.total !== 1 ||
filteredStrings.items[0]?.address !== stringItem.address
)
throw new Error("Ghidra exact-address string filter drifted");
if (variant === "stripped") {
const functionAnalysis = await verifyStrippedFunctionOperations(
client,
stringItem,
);
return { rejections, stringSearch, filteredStrings, functionAnalysis };
}
const entry = findValue(procedures, "rea_ghidra_inventory_entry");
if (entry === undefined)
throw new Error("Ghidra entry procedure probe is unavailable");
const addressName = await call(client, "address_name", {
document: null,
address: entry.address,
});
if (symbolTail(addressName) !== "rea_ghidra_inventory_entry")
throw new Error("Ghidra primary address-name resolution drifted");
const resolvedAddress = await call(client, "procedure_address", {
document: null,
procedure: entry.value,
});
if (resolvedAddress !== entry.address)
throw new Error("Ghidra procedure-name resolution drifted");
const interior = `0x${(BigInt(entry.address) + 1n).toString(16)}`;
const containing = await call(client, "resolve_containing_procedure", {
document: null,
address: interior,
});
if (!containing.found || containing.procedure.address !== entry.address)
throw new Error("Ghidra containing-procedure resolution drifted");
const procedureSearch = await call(client, "search_procedures", {
pattern: "rea_ghidra_inventory_",
mode: "literal",
case_sensitive: true,
offset: 0,
limit: 1,
document: null,
});
if (
procedureSearch.total < 2 ||
procedureSearch.items.length !== 1 ||
!procedureSearch.has_more ||
procedureSearch.next_offset !== 1
)
throw new Error("Ghidra literal procedure-search pagination drifted");
const name = names.find((item) => item.address === entry.address);
if (name === undefined)
throw new Error("Ghidra entry name probe is unavailable");
const filteredNames = await call(client, "list_names", {
document: null,
address: entry.address,
offset: 0,
limit: 500,
});
if (
filteredNames.total < 1 ||
!filteredNames.items.some((item) => item.value === name.value)
)
throw new Error("Ghidra exact-address name filter drifted");
const functionAnalysis = await verifyDebugFunctionOperations(client, {
procedures,
strings,
entry,
});
return {
rejections,
addressName,
resolvedAddress,
containing,
procedureSearch,
stringSearch,
filteredNames,
filteredStrings,
functionAnalysis,
};
}
async function verifyDebugFunctionOperations(
client,
{ procedures, strings, entry },
) {
const leaf = requireProcedure(procedures, "rea_ghidra_inventory_leaf");
const branch = requireProcedure(procedures, "rea_ghidra_inventory_branch");
const indirect = requireProcedure(
procedures,
"rea_ghidra_inventory_indirect",
);
const main = requireProcedure(procedures, "main");
const entryString = strings.find(
(item) => item.value === "REA_GHIDRA_INVENTORY_ENTRY",
);
if (entryString === undefined)
throw new Error("Ghidra debug string function probe is unavailable");
const [info, assembly, pseudocode, callees, callers, outgoing, entryXrefs] =
await Promise.all([
functionCall(client, "procedure_info", {
document: null,
procedure: entry.value,
}),
functionCall(client, "procedure_assembly", {
document: null,
procedure: entry.value,
}),
functionCall(client, "procedure_pseudo_code", {
document: null,
procedure: entry.value,
}),
functionCall(client, "procedure_callees", {
document: null,
procedure: entry.value,
}),
functionCall(client, "procedure_callers", {
document: null,
procedure: entry.value,
}),
functionCall(client, "procedure_references", {
document: null,
procedure: entry.value,
direction: "outgoing",
}),
functionCall(client, "xrefs", {
document: null,
address: entry.address,
}),
]);
assertLocalProcedureInfo(info, entry.address);
assertProviderText(assembly, pseudocode, entry.address);
for (const expected of [branch.address, indirect.address])
if (!callees.includes(expected))
throw new Error(`Ghidra call graph missed ${expected}`);
if (!callers.includes(main.address) || entryXrefs.length === 0)
throw new Error("Ghidra caller or xref relation missed main");
const xrefOwners = [];
const xrefOwnerFailures = [];
for (const address of entryXrefs) {
try {
xrefOwners.push(
await call(client, "resolve_containing_procedure", {
document: null,
address,
}),
);
} catch (cause) {
xrefOwnerFailures.push({
address,
message: cause instanceof Error ? cause.message : String(cause),
});
}
}
if (
!xrefOwners.some(
(owner) => owner.found && owner.procedure.address === main.address,
)
)
throw new Error(
`Ghidra entry xrefs were not attributable to main: ${JSON.stringify({ entryXrefs, callers, xrefOwners, xrefOwnerFailures })}`,
);
assertReferenceMetadata(outgoing);
const stringXrefs = await functionCall(client, "xrefs", {
document: null,
address: entryString.address,
});
if (stringXrefs.length === 0)
throw new Error("Ghidra xrefs missed the entry string");
const entryDossier = await functionCall(client, "analyze_function", {
procedure: entry.address,
include_assembly: true,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDossier(entryDossier, {
address: entry.address,
expectedCallees: [branch.address, indirect.address],
expectedString: "REA_GHIDRA_INVENTORY_ENTRY",
requireAssembly: true,
});
const branchDossier = await functionCall(client, "analyze_function", {
procedure: branch.address,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDossier(branchDossier, {
address: branch.address,
expectedCallees: [leaf.address],
requireMultiBlock: true,
});
const indirectDossier = await functionCall(client, "analyze_function", {
procedure: indirect.address,
include_assembly: true,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDossier(indirectDossier, {
address: indirect.address,
requireAssembly: true,
});
if (
indirectDossier.callees.items.some(
({ address }) => address === leaf.address,
)
)
throw new Error(
"Ghidra dossier falsely resolved a targetless callback as the fixture leaf",
);
if (!/\bcall\b/iu.test(indirectDossier.assembly.items.join("\n")))
throw new Error("Ghidra indirect-call fixture lost its computed call site");
const aborted = new AbortController();
aborted.abort();
const cancelled = await client.callTool(
"procedure_info",
{ document: null, procedure: entry.address },
{ signal: aborted.signal },
);
if (cancelled.ok || cancelled.error.kind !== "cancelled")
throw new Error("Ghidra established-request cancellation drifted");
const timedOut = await client.callTool(
"procedure_info",
{ document: null, procedure: entry.address },
{ timeoutMs: 0 },
);
if (timedOut.ok || timedOut.error.kind !== "timeout")
throw new Error("Ghidra established-request deadline drifted");
const concurrent = await Promise.all([
functionCall(client, "procedure_info", {
document: null,
procedure: entry.address,
}),
functionCall(client, "xrefs", {
document: null,
address: leaf.address,
}),
]);
if (concurrent.length !== 2)
throw new Error("Ghidra serial request queue lost a concurrent result");
return {
entry: dossierSummary(entryDossier),
branch: dossierSummary(branchDossier),
indirect: dossierSummary(indirectDossier),
cancellation: "cancelled-before-wire",
timeout: "expired-before-wire",
concurrency: "serialized-two-results",
};
}
async function verifyStrippedFunctionOperations(client, entryString) {
const stringXrefs = await functionCall(client, "xrefs", {
document: null,
address: entryString.address,
});
if (stringXrefs.length === 0)
throw new Error("Ghidra stripped string xref probe is unavailable");
const containing = await call(client, "resolve_containing_procedure", {
document: null,
address: stringXrefs[0],
});
if (!containing.found)
throw new Error("Ghidra could not recover a stripped containing function");
const procedure = containing.procedure;
const pseudocode = await functionCall(client, "procedure_pseudo_code", {
document: null,
procedure: procedure.address,
});
if (typeof pseudocode !== "string" || pseudocode.trim().length === 0)
throw new Error("Ghidra did not decompile the stripped function");
const dossier = await functionCall(client, "analyze_function", {
procedure: procedure.address,
include_assembly: true,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDossier(dossier, {
address: procedure.address,
expectedString: "REA_GHIDRA_INVENTORY_ENTRY",
requireAssembly: true,
});
if (symbolTail(dossier.procedure.name) === "rea_ghidra_inventory_entry")
throw new Error("Ghidra stripped dossier invented a source symbol");
return dossierSummary(dossier);
}
async function verifyCrossFormatOperations({
client,
variant,
procedures,
names,
strings,
}) {
const message = strings.find(
(item) => item.value === "REA_GHIDRA_CROSS_FORMAT",
);
if (message === undefined)
throw new Error(`${variant} string inventory missed the source oracle`);
const entry =
procedures.find((item) => matchesSymbol(item.value, "rea_cross_entry")) ??
names.find((item) => matchesSymbol(item.value, "rea_cross_entry"));
if (entry === undefined)
throw new Error(`${variant} did not retain the exported entry symbol`);
const entryAddress = entry.address;
const info = await functionCall(client, "procedure_info", {
document: null,
procedure: entryAddress,
});
assertLocalProcedureInfo(info, entryAddress);
const [pseudocode, assembly, callees, messageXrefs] = await Promise.all([
functionCall(client, "procedure_pseudo_code", {
document: null,
procedure: entryAddress,
}),
functionCall(client, "procedure_assembly", {
document: null,
procedure: entryAddress,
}),
functionCall(client, "procedure_callees", {
document: null,
procedure: entryAddress,
}),
functionCall(client, "xrefs", {
document: null,
address: message.address,
}),
]);
assertProviderText(assembly, pseudocode, entryAddress);
if (callees.length < 2)
throw new Error(`${variant} call graph missed direct fixture calls`);
if (messageXrefs.length === 0)
throw new Error(`${variant} xrefs missed the fixture string`);
let messageOwner = null;
for (const address of messageXrefs) {
const candidate = await call(client, "resolve_containing_procedure", {
document: null,
address,
});
if (candidate.found) {
messageOwner = candidate;
break;
}
}
if (messageOwner === null)
throw new Error(`${variant} did not resolve the string-owning function`);
const stringDossier = await functionCall(client, "analyze_function", {
procedure: messageOwner.procedure.address,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDossier(stringDossier, {
address: messageOwner.procedure.address,
expectedString: "REA_GHIDRA_CROSS_FORMAT",
});
let branchAddress = null;
for (const address of callees) {
const candidate = await functionCall(client, "procedure_info", {
document: null,
procedure: address,
});
if (candidate.basicblock_count > 1) {
branchAddress = address;
break;
}
}
if (branchAddress === null)
throw new Error(`${variant} did not recover the multi-block callee`);
const branchDossier = await functionCall(client, "analyze_function", {
procedure: branchAddress,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDossier(branchDossier, {
address: branchAddress,
requireMultiBlock: true,
});
return {
entry: entryAddress,
exported_symbol: entry.value,
string_owner: dossierSummary(stringDossier),
branch: dossierSummary(branchDossier),
};
}
async function verifyBridgeRejections(client) {
return {
unknownDocument: await expectRemoteFailure(
client,
"list_segments",
{ document: "not-the-imported-program" },
"not_found",
),
malformedParameter: await expectRemoteFailure(
client,
"procedure_address",
{ document: null, procedure: 17 },
"invalid_request",
),
unboundedRegex: await expectRemoteFailure(
client,
"search_strings",
{
pattern: "a+",
mode: "regex",
case_sensitive: true,
offset: 0,
limit: 100,
document: null,
},
"invalid_request",
),
undeclaredMutation: await expectRemoteFailure(
client,
"set_comment",
{},
"method_unavailable",
),
};
}
async function expectRemoteFailure(client, operation, parameters, code) {
const result = await client.callTool(operation, parameters);
if (
result.ok ||
result.error.kind !== "remote" ||
result.error.remoteCode !== code ||
result.error.diagnostics.remote_code !== code
)
throw new Error(
`Ghidra ${operation} rejection drifted: ${JSON.stringify(result)}`,
);
return { operation, code };
}
async function call(client, operation, parameters) {
const called = await client.callTool(operation, parameters);
if (!called.ok)
throw new Error(
`Ghidra ${operation} failed for ${JSON.stringify(parameters)}: ${called.error.message}`,
{ cause: called.error },
);
const parsed = parseGhidraInventoryResult(operation, called.value);
if (!parsed.ok) throw parsed.error;
return parsed.value;
}
async function functionCall(client, operation, parameters) {
const input = parseGhidraFunctionInput(operation, parameters);
if (!input.ok) throw input.error;
const called = await client.callTool(operation, input.value);
if (!called.ok)
throw new Error(
`Ghidra ${operation} failed for ${JSON.stringify(input.value)}: ${called.error.message}`,
{ cause: called.error },
);
const parsed = parseGhidraFunctionResult(operation, called.value);
if (!parsed.ok) throw parsed.error;
return parsed.value;
}
function assertLocalProcedureInfo(info, expectedAddress) {
if (
info.entrypoint !== expectedAddress ||
info.basicblock_count < 1 ||
info.length < 1 ||
typeof info.signature !== "string" ||
info.signature.length === 0 ||
info.classification.external ||
info.classification.provenance !== "ghidra-function-manager"
)
throw new Error(
`Ghidra procedure metadata drifted: ${JSON.stringify(info)}`,
);
}
function assertProviderText(assembly, pseudocode, expectedAddress) {
if (
typeof assembly !== "string" ||
!assembly.includes(`${expectedAddress}:`) ||
assembly.trim().length === 0
)
throw new Error("Ghidra assembly rendering lost its address-bearing lines");
if (typeof pseudocode !== "string" || pseudocode.trim().length === 0)
throw new Error("Ghidra local function pseudocode is unavailable");
}
function assertReferenceMetadata(observed) {
if (
observed.instructions_scanned < 1 ||
observed.instruction_scan_truncated ||
observed.references.items.length === 0 ||
!observed.references.items.every(
({ kind }) =>
kind.available && kind.provenance === "ghidra-reference-manager",
) ||
!observed.references.items.some(({ kind }) => kind.call) ||
!observed.references.items.some(({ kind }) => kind.data)
)
throw new Error(
`Ghidra typed reference metadata drifted: ${JSON.stringify(observed)}`,
);
}
function assertDossier(
dossier,
{
address,
expectedCallees = [],
expectedString = null,
requireAssembly = false,
requireMultiBlock = false,
},
) {
if (
dossier.procedure.address !== address ||
dossier.procedure.classification === null ||
dossier.procedure.classification.provenance !== "ghidra-function-manager" ||
dossier.procedure.classification.external ||
dossier.pseudocode.text.trim().length === 0 ||
dossier.pseudocode.returned_chars !== [...dossier.pseudocode.text].length ||
dossier.instruction_scan.scanned < 1 ||
dossier.instruction_scan.truncated ||
!dossier.limitations.some((value) => /indirect|computed/u.test(value)) ||
!dossier.limitations.some((value) => /Ghidra|Hopper|provider/u.test(value))
)
throw new Error(
`Ghidra dossier truthfulness drifted: ${JSON.stringify(dossier)}`,
);
if (
![
...dossier.incoming_references.items,
...dossier.outgoing_references.items,
].every(
({ kind }) =>
kind.available && kind.provenance === "ghidra-reference-manager",
)
)
throw new Error("Ghidra dossier lost typed reference provenance");
for (const expected of expectedCallees)
if (!dossier.callees.items.some(({ address: value }) => value === expected))
throw new Error(`Ghidra dossier missed callee ${expected}`);
if (
expectedString !== null &&
!dossier.referenced_strings.items.some(
({ value }) => value === expectedString,
)
)
throw new Error(
`Ghidra dossier missed referenced string ${expectedString}`,
);
if (
requireAssembly &&
(dossier.assembly.items.length === 0 || dossier.assembly.truncated)
)
throw new Error("Ghidra dossier assembly was unavailable or truncated");
if (
requireMultiBlock &&
(dossier.basic_blocks.items.length < 2 ||
!dossier.basic_blocks.items.some(
({ successors }) => successors.length > 0,
))
)
throw new Error(
"Ghidra dossier CFG missed the multi-block branch structure",
);
}
function dossierSummary(dossier) {
return {
address: dossier.procedure.address,
pseudocode_chars: dossier.pseudocode.total_chars,
instructions: dossier.instruction_scan.scanned,
callees: dossier.callees.returned,
outgoing_references: dossier.outgoing_references.returned,
referenced_strings: dossier.referenced_strings.returned,
basic_blocks: dossier.basic_blocks.returned,
};
}
async function allItems(client, operation, parameters) {
const items = [];
let offset = 0;
let total;
while (true) {
const page = await call(client, operation, {
...parameters,
offset,
limit: 500,
});
if (typeof page !== "object" || page === null || Array.isArray(page))
throw new Error(`${operation} did not return a page`);
items.push(...page.items);
total ??= page.total;
if (page.total !== total)
throw new Error(`${operation} total changed during immutable paging`);
if (!page.has_more) break;
if (page.next_offset === null || page.next_offset <= offset)
throw new Error(`${operation} returned a non-advancing page`);
offset = page.next_offset;
}
if (items.length !== total)
throw new Error(`${operation} pagination was not exhaustive`);
return items;
}
function assertDebugFixture(observed) {
if (
!Array.isArray(observed.documents) ||
observed.documents.length !== 1 ||
!observed.documents[0].includes("debug")
)
throw new Error("Ghidra did not expose exactly one debug Program identity");
const entry = findValue(observed.procedures, "rea_ghidra_inventory_entry");
const leaf = findValue(observed.procedures, "rea_ghidra_inventory_leaf");
const external = observed.procedures.find(
(item) => item.procedure.external && symbolTail(item.value) === "puts",
);
if (entry === undefined || leaf === undefined || external === undefined)
throw new Error(
"Ghidra procedure inventory missed local or external functions",
);
if (
!observed.procedures.some(
(item) => item.procedure.thunk && item.procedure.thunk_target !== null,
)
)
throw new Error(
"Ghidra procedure inventory did not distinguish a resolved thunk",
);
const entryName = findValue(observed.names, "rea_ghidra_inventory_entry");
if (entryName === undefined || !entryName.symbol.primary)
throw new Error("Ghidra symbol inventory missed the primary entry symbol");
if (!observed.names.some((item) => item.symbol.external))
throw new Error("Ghidra symbol inventory missed external symbols");
assertStrings(observed.strings);
assertSegments(observed.segments, observed.session.target.image_base);
}
function assertStrippedFixture(observed) {
if (
observed.procedures.length === 0 ||
observed.names.length === 0 ||
findValue(observed.procedures, "rea_ghidra_inventory_entry") !== undefined
)
throw new Error(
"Stripped Ghidra fixture did not preserve stripped semantics",
);
assertStrings(observed.strings);
assertSegments(observed.segments, observed.session.target.image_base);
}
function assertCrossFixture(observed) {
if (
observed.procedures.length === 0 ||
observed.names.length === 0 ||
observed.probes === null ||
typeof observed.probes.entry !== "string" ||
observed.probes.string_owner.referenced_strings < 1 ||
observed.probes.branch.basic_blocks < 2
)
throw new Error(
`Cross-format Ghidra semantics drifted: ${JSON.stringify(summary(observed))}`,
);
assertSegments(observed.segments, observed.session.target.image_base);
}
async function assertMalformedFixture(path) {
const parsed = await parseBinaryTarget(path);
if (parsed.ok || parsed.error._tag !== "BinaryTargetError")
throw new Error(
"Malformed executable was not rejected before provider start",
);
}
function assertStrings(strings) {
for (const expected of [
"REA_GHIDRA_INVENTORY_ENTRY",
"REA_GHIDRA_LEAF_VALUE",
]) {
const item = strings.find((candidate) => candidate.value === expected);
if (
item === undefined ||
item.value_truncated ||
typeof item.string.encoding !== "string" ||
item.string.byte_length < expected.length
)
throw new Error(`Ghidra string inventory missed ${expected}`);
}
}
function assertSegments(segments, imageBase) {
if (
!Array.isArray(segments) ||
segments.length === 0 ||
!segments.some((item) => item.executable) ||
!segments.some((item) => item.writable) ||
!segments.every(
(item) =>
item.permissions.available === true &&
item.permissions.source === "ghidra-memory-block" &&
item.image_base === imageBase,
)
)
throw new Error("Ghidra memory-block permissions or image base drifted");
}
function findValue(items, expected) {
return items.find((item) => symbolTail(item.value) === expected);
}
function requireProcedure(items, expected) {
const observed = findValue(items, expected);
if (observed === undefined)
throw new Error(`Ghidra procedure probe is unavailable: ${expected}`);
return observed;
}
function matchesSymbol(value, expected) {
const tail = symbolTail(value);
return tail === expected || tail === `_${expected}`;
}
function symbolTail(value) {
if (typeof value !== "string") return undefined;
return value.split("::").at(-1);
}
function assertSession(session, expectedDigest, expectedTargetSha256) {
if (
session.provider.id !== "ghidra" ||
session.provider.version !== SUPPORTED_GHIDRA_VERSION ||
session.profile_digest !== expectedDigest ||
session.target.sha256 !== expectedTargetSha256 ||
session.read_only !== true ||
session.analysis_complete !== true ||
session.analysis_timed_out !== false ||
session.capabilities.join(",") !== GHIDRA_SESSION_CAPABILITIES.join(",") ||
!/^0x[0-9a-f]+$/u.test(session.target.image_base) ||
session.target.default_address_space.length === 0
)
throw new Error(
`Ghidra session commitment drifted: ${JSON.stringify(session)}`,
);
}
function assertRuntimeCoordinates(coordinates) {
for (const name of ["runtime_root", "endpoint_path", "project_root"])
if (typeof coordinates[name] !== "string")
throw new Error(`Ghidra verifier did not observe ${name}`);
if (typeof coordinates.process_id !== "number")
throw new Error("Ghidra verifier did not observe its process ID");
}
async function assertCleanup(coordinates) {
for (const name of ["runtime_root", "endpoint_path", "project_root"]) {
const path = coordinates[name];
if (typeof path === "string" && (await exists(path)))
throw new Error(`Ghidra cleanup left ${name}: ${path}`);
}
const pid = coordinates.process_id;
if (typeof pid === "number" && processExists(pid))
throw new Error(`Ghidra cleanup left process ${String(pid)}`);
}
function summary(observed) {
return {
variant: observed.variant,
target_path: observed.target.path,
target_sha256: observed.target.sha256,
analysis_profile_digest: observed.profile.digest,
language_id: observed.session.target.language_id,
compiler_spec_id: observed.session.target.compiler_spec_id,
image_base: observed.session.target.image_base,
procedures: observed.procedures.length,
names: observed.names.length,
strings: observed.strings.length,
memory_blocks: observed.segments.length,
};
}
async function exists(path) {
try {
await access(path);
return true;
} catch {
return false;
}
}
function processExists(pid) {
try {
process.kill(pid, 0);
return true;
} catch (cause) {
return !(
cause instanceof Error &&
"code" in cause &&
cause.code === "ESRCH"
);
}
}