diff --git a/.agents/skills/reverse-engineer-anything/references/evidence-workflows.md b/.agents/skills/reverse-engineer-anything/references/evidence-workflows.md index 32a5962d40..f595e51a3a 100644 --- a/.agents/skills/reverse-engineer-anything/references/evidence-workflows.md +++ b/.agents/skills/reverse-engineer-anything/references/evidence-workflows.md @@ -73,6 +73,13 @@ Parent Evidence ID plus source index preserves same-address alternatives. Follow `coverage.next_offset` only as far as the question needs; exhausting retained rows does not establish complete program discovery. +Read a retained `batch_decompile` through its Evidence ID with +`view: {kind: "batch-decompile", collection: "items"}` for body-free rows and +exact `where.indices`, `addresses`, `procedure_addresses` or `statuses`. Add +`include_pseudocode: true` for several chosen bodies, or use +`collection: "pseudocode"` with one row's `index` to page a large body. Batch +limitations aggregate every item, so do not attribute them to one successful row. + Use `record_unknown` to track unresolved questions in the user's investigation and name the authority or environment still required. Supply supporting and contradicting evidence IDs. It updates the session registry directly. diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md index 1898fb7a86..a6f5ed43a7 100644 --- a/docs/mcp-contracts.md +++ b/docs/mcp-contracts.md @@ -620,6 +620,38 @@ never upgrades `trace_coverage`, and graph connectivity does not prove runtime reachability. The CLI keeps complete trace JSON; save it and use `inspect-analysis-view` with an `evidence-file` source. +### Selected batch decompile results + +`batch_decompile` returns every pseudocode body. `inspect_analysis_view` selects +from that completed record, retained in the session, saved as an Evidence file or +imported from a portable bundle, and never repeats decompilation. +`view: {"kind":"summary"}` reports the producer counts, `source_provider` (the +composing workflow), `source_analysis_profile_digest`, `decompiling_provider`, +procedure identity counts, total and largest `pseudocode` size, and +`limitation_count`. + +A `batch-decompile` view selects one `collection` and repeats the batch counts +and provider identities: + +- `items`: rows in retained order with their original `index`, so duplicate + selectors stay distinct. A row keeps the selector in `address`, its `procedure` + identity and `status`, plus `pseudocode_code_units` or its exact `error` and + `limitations`. `where.indices`, `where.addresses`, `where.procedure_addresses` + and `where.statuses` filter exactly and combine; an item with unknown identity + never matches `procedure_addresses`. Omitted filters select all, and empty + arrays select none. `offset` and `limit` default to 0 and 64. + `include_pseudocode: true` adds each selected body. +- `pseudocode`: one `index`'s text in UTF-16 code-unit pages. `offset` and `limit` + default to 0 and 16,384, and `coverage` measures that body. An offset inside a + surrogate pair is refused, and a limit ending inside one stops before it. An + error item has no text and is refused with a pointer to `items`. + +Page `coverage` counts the selection only: exhausting it establishes nothing +about functions outside the batch. Evidence `limitations` aggregate every item's +provider observations and are not attributed to one successful item; only error +items keep their own. The CLI has no batch command; save the Evidence and use +`inspect-analysis-view` with an `evidence-file` source or `--evidence-bundle`. + Completed `inspect_artifact` and atomic `inventory_artifact` Evidence also support summary and inventory views. A summary reports the manifest's expected counts separately from available record counts, observed entry kinds, inventory diff --git a/docs/native-investigation.md b/docs/native-investigation.md index dfd83283de..c823149f08 100644 --- a/docs/native-investigation.md +++ b/docs/native-investigation.md @@ -201,6 +201,10 @@ remains valid. This tool has no dedicated CLI command; the existing `decompile` command remains the single-procedure CLI operation. +`inspect_analysis_view` reads a summary, rows or one body from the retained +record, an Evidence file or a portable bundle without repeating decompilation: +see [selected batch results](mcp-contracts.md#selected-batch-decompile-results). + Each batch schedules one provider read at a time, but has no shared input-count or aggregate retained-output allowance. It retains every requested row and full pseudocode body through Evidence construction. The MCP response budget checks diff --git a/src/application/EnhancedTools.ts b/src/application/EnhancedTools.ts index 08b001b16f..a01fb6546b 100644 --- a/src/application/EnhancedTools.ts +++ b/src/application/EnhancedTools.ts @@ -1,6 +1,10 @@ import { permitsCapabilityFallback } from "./CapabilityFallback.js"; import { withOverviewInventoryCoverage } from "../domain/native/inventoryCoverage.js"; import type { NativeCallGraph } from "../domain/native/nativeCallGraph.js"; +import type { + BatchDecompileItem, + BatchProcedureIdentity, +} from "../domain/native/batchDecompile.js"; import { nativeProcedureInputSchema } from "../domain/native/nativeProcedureInput.js"; import { cleanupStoppedTraversal, @@ -76,18 +80,6 @@ import { import { traceLiteralFeature } from "./EnhancedLiteralTracing.js"; import { projectNativeApiInspection } from "./native/NativeApiInspection.js"; -type BatchProcedureIdentity = - | { - readonly status: "resolved"; - readonly address: string; - readonly name: string | null; - readonly name_error?: ReturnType; - } - | { - readonly status: "unknown"; - readonly error: ReturnType; - }; - type BatchResolution = { readonly address: string; readonly result: Result; @@ -99,16 +91,6 @@ type BatchReadyItem = { readonly providerProcedure: string; }; -type BatchDecompileItem = { - readonly address: string; - readonly procedure: BatchProcedureIdentity; - readonly status: "ok" | "error"; - readonly pseudocode?: string; - readonly error?: ReturnType; - /** Caveats of this item's own observation when it supplied no pseudocode. */ - readonly limitations?: string[]; -}; - /** * Guidance for a batch item whose provider returned null pseudocode, by * whether that observation reported caveats for the item to carry. diff --git a/src/contracts/analysisViewToolContracts.ts b/src/contracts/analysisViewToolContracts.ts index 14ffdf63bb..87fdfec068 100644 --- a/src/contracts/analysisViewToolContracts.ts +++ b/src/contracts/analysisViewToolContracts.ts @@ -17,7 +17,7 @@ export const ANALYSIS_VIEW_TOOL_CONTRACTS = [ ...toolContractMetadata("inspect_analysis_view"), kind: "application", description: - 'Use javascript-routes collections to query route patterns, source-linked occurrences, source status, unknowns or summary counts from retained JavaScript application or web-bundle Evidence. Use web-bundle collections endpoints or inferences to page endpoint observations and inferences from retained analyze_web_bundle Evidence; summary returns target URL, origin, and counts. Inspect selected views of supported completed Evidence without repeating analysis. Choose a view compatible with the parent operation described below. Command summary views preserve ordered GDB records or opaque objdump stdout/stderr once, source parameters, completion facts and parent identity. They do not establish current target state. Historical capture summaries return identity and counts without bodies or archive inventories. Capture views page retained records: view {kind: "capture", detail: "preview" | "complete", offset: 0, limit: 20}; preview selects recorded headline fields and binary descriptors, complete returns exact records with all sidecars. Offsets follow the selected parent record order, preserving original producer ordinals. Paging never reopens the source or reruns the decoder. Native export tables use kind native-exports, collection exports/issues, exact names or original indices, selected fields and matching-row pagination; parent Evidence plus source_index identifies each row. Source coverage stays separate from page coverage. BEAM views use kind beam, collections atoms/exports/imports/lambdas/chunks, exact names/indices/fields and matching-row pages; import modules intersects function names. source_index identifies original parent-and-collection rows, preserving every arity and raw atom index. beam.counts preserves null missing tables versus decoded empty tables; runtime absence remains unknown. PYC views use kind python-pyc, collection code_objects, names/indices/fields and paging; source_index scopes every same-name alternative to the parent, nested_code keeps code-constant references, and pyc.coverage preserves source coverage. Go metadata uses kind go, collection dependencies/settings, exact paths/keys or indices, fields and pagination. Row index refers to the original collection; empty selections return no rows, and dependency coverage remains unknown. Rust metadata uses kind rust, collection packages/edges, exact names/versions or original indices, selected fields, edge from_indices/to_indices and matching-row pagination. Embedded-record coverage is separate from unknown runtime dependencies. For inspect_pcap_capture parents, kind pcap pages endpoints, dns-queries, tls-sni, protocols, http-uris or unattributed-addresses. Select an exact query for dns-addresses, or a tshark/capinfos stream for UTF-16 diagnostics text. Page totals count retained facts; source coverage remains explicit. Qlog summaries keep profile/scope and counts; kind qlog pages traces, streams, loss-declarations, incomplete-records, contributions, ranges or final-sizes. Except traces, select trace_index; stream-specific facets also require exact stream_id and direction. Facts retain all-recorded-events-before-selection scope, and interval overlap or endpoint loss declarations do not prove retransmission or network loss. The api-surface view groups retained HAR requests by method, origin and format-rule path template; templated segments are inferences. It reads no headers or bodies and reports no query values. The environment-manifest view projects the same HAR requests on the primary origin (most JSON-like records) into a replayable tool surface: view {kind: "environment-manifest", template_rules: ["after-uid-literal", "opaque-token", "sibling-variance"], include_query_parameter_names: true}. Each tool has a deterministic name, a path template and parameters from the four format rules plus the selected opt-in rules, observed query parameter names, a value-free body shape for POST/PUT/PATCH, status and content-type sets and record ordinals; records are pointers into the parent, excluded groups carry a reason and three fixed unknowns are always stated. Templates, parameters and names are inferences; the view copies no header, cookie or body values and refuses parents inspected with sensitive values. A capture_browser_scenario parent also supports summary and browser-scenario steps/events/transactions/text pages, preserving step_indices, event_kinds, transaction_ids and selected artifacts. A capture_browser_scenario parent that selected response bodies or header values projects the same way, one record per network transaction in request order; it relies on capture-time redaction of declared secrets instead of that refusal, and a transaction whose URL was redacted is left unrepresented. The environment-state view extracts, from the same parents, the initial state the recorded reads observed: view {kind: "environment-state", template_rules: [...]} with the rules of the manifest it accompanies. It reads response bodies recorded before the first related write and reports entity types with an identity field (proved by a path parameter or inferred from a field name), entities in collection order with per-view values where views differ, documents for non-parameterized reads that are not entities and have one initial request line (item-shaped paths stay recorded), and a render plan per read tool: item and list views reproduce their latest recordings from the state (a list also learns the filters, search, sort and paging its recordings verify, and answers new values of them from the state), and every other read tool is a recorded view with a reason. It also reports a write plan per state-changing tool (create, update, delete or document, built from its first successful call) and write_clock; a plan is served only when replaying the capture shows a later read confirming its effect and none contradicting it. Types and identity are inferences; values are recorded data, so it refuses parents inspected with sensitive values, and a scenario parent must have selected response bodies; its values keep the capture redaction markers, and a write whose URL it redacted ends the state of every type. The environment-coverage view, view {kind: "environment-coverage", template_rules: [...]}, summarizes that state without its entities: reads.state and reads.recorded count read tools answered from the state and replayed (recorded_reasons per view reason), writes.served lists the served write tools, and writes.withheld lists each other write tool with its reason, plan record, contradicting read and a hint about what to record next; it refuses what the environment-state view refuses. For a retained record use source: {kind: "retained-evidence", evidence_id: ""}. Use normalized_result.parent_evidence_id from a summary receipt. Source kind is required. Portable source uses {kind: "inline", evidence: }. A completed Evidence JSON file on this host uses {kind: "evidence-file", path: ""}: REA reads and authenticates it, then projects it like retained Evidence, so a large capture is bounded by the file reader rather than by inline-input accounting. The file may also be an Evidence bundle written by CLI --evidence_output or export_evidence_bundle; select evidence_id when it contains more than one record. For layout, JavaScript, inventory, WASM, Mach-O, Interface Builder, EVM, managed artifact, Android package and Dart AOT sources, request a summary with view: {kind: "summary"}; summary is a view kind and has no facet. The WASM summary gives validation, counts, WAT digest/length, tool profile and execution/network states without reading WAT text. Select a layout mitigations/linkage facet, one section/symbol/module, or a stable page. Module pages include assets, bundled and source modules; use node_id for ambiguous or unavailable paths. Typed module references use view {kind: "javascript", collection: "modules", projection: "references", where: {path: "main.js", kind: "javascript-module"}, offset: 0, limit: 64}; where matches exact retained strings (null selects unavailable paths). Rows include canonical identity, retained source-range count and observation support states. Source coverage and selection remain explicit; exhausting matching rows does not prove runtime loading or complete analysis. For exact file/native facts and processing gaps, use view {kind: "javascript-facts", where: {paths: ["package.json"]}, property_keys: ["name", "operation", "analysis_status"]}. Rows page original observations with canonical identities and Evidence; missing properties remain omitted. Paths match recorded artifact-path/source-range locations; optional kinds filter nodes. To discover field names without values, opt into include_available_property_keys: true with property_keys: []. Canonical identity and Evidence are separate from properties; keep each node_id/observation_id pair together when composing results. Inventory uses view: {kind: "inventory", collection: "occurrences", logical_paths: ["package.json"], offset: 0, limit: 64}. Inventory views page nodes, occurrences, edges or integrity contradictions. Occurrences accept exact logical_paths and occurrence_ids; nodes accept artifact_ids. Batch filters intersect (omitted means all available, [] means none); fields selects columns while retaining identity links. source_complete describes retained graph membership; source_coverage describes producer coverage, including unknown encrypted PCK directories. Page exhaustion does not prove absence in a partial source. WASM views use kind wasm and facet sections/imports/exports/candidates/glue/wat/headers/details/tool_profile; text facets use UTF-16 code units and source forms remain exact. Mach-O views use kind macho and facet entrypoints/architectures/build_metadata/load_commands/dependencies/imports/exports/segments/provenance; source_exhaustive false means unreturned rows may exist. Interface Builder views use kind interface-builder and collection documents/nodes/edges/coverage; nodes and edges accept an exact document relative_path. EVM summary returns all inferred interface candidates, carrier/decoded identities and explicit unknowns without hex or duplicate stdout. EVM views use kind evm and facet functions/bytecode_hex/stdout/stderr; function pages preserve the original candidate rows, and text offsets/limits count UTF-16 code units (hex has two characters per decoded byte). Exhausting candidate pages does not establish global interface completeness. Managed artifact summaries preserve complete identity/classification, metadata status, module/MVID, frameworks, coverage and limitations without unrelated inventories. Managed pages use kind managed and collection references/resources/attributes, retaining source coverage and build-local token scope; page exhaustion does not establish complete metadata. Managed member summaries keep identity, selection with unmatched names, coverage and per-collection counts; managed-members pages use collection types/exported_types/fields/methods/member_refs/call_edges/field_accesses/user_strings. Exact names and declaring_types filters intersect before paging where supported; fields selects columns (distinct from collection: "fields"). Identity/source_index, module MVID, source coverage and unresolved filter counts remain; omit body to avoid IL anchors. Omitted fields preserves full rows. Android package summaries retain all declarations, engine identity and counts without decoded manifest text. Android manifest pages use kind android, facet manifest, offset and limit in UTF-16 code units; source_status preserves partial decoded coverage even when the retained text page is exhausted. Dart AOT summary preserves target/ABI/library identity, snapshot headers and pool lower bounds. String pages use kind dart-aot, collection package_uris/dart_uris/class_like_tokens; source coverage remains partial when the producer says partial. Protobuf views use kind protobuf, collection bodies/frames/fields, with record_ordinals, body_pointers and fields; field pages also select frame_indices, field_ids, field_numbers or schema_names. Byte identity, offset basis and body status remain present. Text and schema_value are opt-in page columns. APK signing views use kind apk-signature and collection signers/digests/lineage, with ids, signer_ids, schemes, fields and paging. Identity links remain when fields is empty. Declared identities and digest matches do not establish signature verification or authenticity. Model views use kind model-artifact and collection metadata (keys), tensors (names/types) or types (derived totals), with indices, fields and paging. Header SHA-256 scopes declarations; full-file identity remains unknown unless full hashing was selected. Arrays retain typed eight-element previews with explicit omissions. IL2CPP metadata views use kind il2cpp-metadata and collection sections/images/types/methods/fields/properties/events/parameters/string_literals/code_gen_modules/method_addresses/return_types/field_types/parameter_types/generic_method_instances/generic_method_issues. Select indices, fields and pages; sections/images/types/methods/fields/properties/events/parameters/return_types/field_types/parameter_types/generic_method_instances accept exact names (native type names match retained rendered values, preserving same-name rows; null names never match), types also accept image_indices/namespaces/declaring_types, and methods/members accept declaring_types. Parameters and parameter_types accept method_indices; code_gen_modules accept image_indices; method_addresses and generic_method_instances accept addresses/states (generic_method_instances also method_indices), preserving every folded alternative; generic_method_issues accept rows. Row index is scoped to the metadata digest; native pages add binary_source. Uncollected native tables have null counts and remain unavailable. Desktop directory views use kind desktop-application and collection files/omissions/candidates/components/next_probes, with fields and pagination; files and omissions accept exact paths or their stable IDs, and candidates accept families. Source coverage and stable row IDs remain available. Native load-image Evidence uses kind native-load-image with collection source_files/mappings/relocations/entry_points/entry_context/checks/sections, original indices, collection-specific fields and offset/limit paging. Null collections remain unrecorded or inapplicable; pages preserve unsupported verification. Native inventory Evidence from list_names, list/search_procedures or list/search_strings uses view: {kind: "native-inventory", offset: 0, limit: 64, fields: ["value"]}. Rows keep source_index and address even with selected fields. Summary counts describe retained rows; provider discovery coverage remains unknown. Native function Evidence accepts kind summary for identity, availability and facet counts, or kind native for selected facts: view: {kind: "native", facet: "procedure"}. Facets select procedure, pseudocode, assembly, basic blocks, comments, callers/callees, references, unresolved calls, referenced strings/names, native API and high-pcode. Use nonnegative offset and a positive caller-selected limit (defaults 0 and 64); pseudocode uses UTF-16 code units, other native pages use rows. Returns artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the complete retained Evidence if needed.', + 'Use javascript-routes collections to query route patterns, source-linked occurrences, source status, unknowns or summary counts from retained JavaScript application or web-bundle Evidence. Use web-bundle collections endpoints or inferences to page endpoint observations and inferences from retained analyze_web_bundle Evidence; summary returns target URL, origin, and counts. Inspect selected views of supported completed Evidence without repeating analysis. Choose a view compatible with the parent operation described below. Command summary views preserve ordered GDB records or opaque objdump stdout/stderr once, source parameters, completion facts and parent identity. They do not establish current target state. Historical capture summaries return identity and counts without bodies or archive inventories. Capture views page retained records: view {kind: "capture", detail: "preview" | "complete", offset: 0, limit: 20}; preview selects recorded headline fields and binary descriptors, complete returns exact records with all sidecars. Offsets follow the selected parent record order, preserving original producer ordinals. Paging never reopens the source or reruns the decoder. Native export tables use kind native-exports, collection exports/issues, exact names or original indices, selected fields and matching-row pagination; parent Evidence plus source_index identifies each row. Source coverage stays separate from page coverage. BEAM views use kind beam, collections atoms/exports/imports/lambdas/chunks, exact names/indices/fields and matching-row pages; import modules intersects function names. source_index identifies original parent-and-collection rows, preserving every arity and raw atom index. beam.counts preserves null missing tables versus decoded empty tables; runtime absence remains unknown. PYC views use kind python-pyc, collection code_objects, names/indices/fields and paging; source_index scopes every same-name alternative to the parent, nested_code keeps code-constant references, and pyc.coverage preserves source coverage. Go metadata uses kind go, collection dependencies/settings, exact paths/keys or indices, fields and pagination. Row index refers to the original collection; empty selections return no rows, and dependency coverage remains unknown. Rust metadata uses kind rust, collection packages/edges, exact names/versions or original indices, selected fields, edge from_indices/to_indices and matching-row pagination. Embedded-record coverage is separate from unknown runtime dependencies. For inspect_pcap_capture parents, kind pcap pages endpoints, dns-queries, tls-sni, protocols, http-uris or unattributed-addresses. Select an exact query for dns-addresses, or a tshark/capinfos stream for UTF-16 diagnostics text. Page totals count retained facts; source coverage remains explicit. Qlog summaries keep profile/scope and counts; kind qlog pages traces, streams, loss-declarations, incomplete-records, contributions, ranges or final-sizes. Except traces, select trace_index; stream-specific facets also require exact stream_id and direction. Facts retain all-recorded-events-before-selection scope, and interval overlap or endpoint loss declarations do not prove retransmission or network loss. The api-surface view groups retained HAR requests by method, origin and format-rule path template; templated segments are inferences. It reads no headers or bodies and reports no query values. The environment-manifest view projects the same HAR requests on the primary origin (most JSON-like records) into a replayable tool surface: view {kind: "environment-manifest", template_rules: ["after-uid-literal", "opaque-token", "sibling-variance"], include_query_parameter_names: true}. Each tool has a deterministic name, a path template and parameters from the four format rules plus the selected opt-in rules, observed query parameter names, a value-free body shape for POST/PUT/PATCH, status and content-type sets and record ordinals; records are pointers into the parent, excluded groups carry a reason and three fixed unknowns are always stated. Templates, parameters and names are inferences; the view copies no header, cookie or body values and refuses parents inspected with sensitive values. A capture_browser_scenario parent also supports summary and browser-scenario steps/events/transactions/text pages, preserving step_indices, event_kinds, transaction_ids and selected artifacts. A capture_browser_scenario parent that selected response bodies or header values projects the same way, one record per network transaction in request order; it relies on capture-time redaction of declared secrets instead of that refusal, and a transaction whose URL was redacted is left unrepresented. The environment-state view extracts, from the same parents, the initial state the recorded reads observed: view {kind: "environment-state", template_rules: [...]} with the rules of the manifest it accompanies. It reads response bodies recorded before the first related write and reports entity types with an identity field (proved by a path parameter or inferred from a field name), entities in collection order with per-view values where views differ, documents for non-parameterized reads that are not entities and have one initial request line (item-shaped paths stay recorded), and a render plan per read tool: item and list views reproduce their latest recordings from the state (a list also learns the filters, search, sort and paging its recordings verify, and answers new values of them from the state), and every other read tool is a recorded view with a reason. It also reports a write plan per state-changing tool (create, update, delete or document, built from its first successful call) and write_clock; a plan is served only when replaying the capture shows a later read confirming its effect and none contradicting it. Types and identity are inferences; values are recorded data, so it refuses parents inspected with sensitive values, and a scenario parent must have selected response bodies; its values keep the capture redaction markers, and a write whose URL it redacted ends the state of every type. The environment-coverage view, view {kind: "environment-coverage", template_rules: [...]}, summarizes that state without its entities: reads.state and reads.recorded count read tools answered from the state and replayed (recorded_reasons per view reason), writes.served lists the served write tools, and writes.withheld lists each other write tool with its reason, plan record, contradicting read and a hint about what to record next; it refuses what the environment-state view refuses. For a retained record use source: {kind: "retained-evidence", evidence_id: ""}. Use normalized_result.parent_evidence_id from a summary receipt. Source kind is required. Portable source uses {kind: "inline", evidence: }. A completed Evidence JSON file on this host uses {kind: "evidence-file", path: ""}: REA reads and authenticates it, then projects it like retained Evidence, so a large capture is bounded by the file reader rather than by inline-input accounting. The file may also be an Evidence bundle written by CLI --evidence_output or export_evidence_bundle; select evidence_id when it contains more than one record. For layout, JavaScript, inventory, WASM, Mach-O, Interface Builder, EVM, managed artifact, Android package and Dart AOT sources, request a summary with view: {kind: "summary"}; summary is a view kind and has no facet. The WASM summary gives validation, counts, WAT digest/length, tool profile and execution/network states without reading WAT text. Select a layout mitigations/linkage facet, one section/symbol/module, or a stable page. Module pages include assets, bundled and source modules; use node_id for ambiguous or unavailable paths. Typed module references use view {kind: "javascript", collection: "modules", projection: "references", where: {path: "main.js", kind: "javascript-module"}, offset: 0, limit: 64}; where matches exact retained strings (null selects unavailable paths). Rows include canonical identity, retained source-range count and observation support states. Source coverage and selection remain explicit; exhausting matching rows does not prove runtime loading or complete analysis. For exact file/native facts and processing gaps, use view {kind: "javascript-facts", where: {paths: ["package.json"]}, property_keys: ["name", "operation", "analysis_status"]}. Rows page original observations with canonical identities and Evidence; missing properties remain omitted. Paths match recorded artifact-path/source-range locations; optional kinds filter nodes. To discover field names without values, opt into include_available_property_keys: true with property_keys: []. Canonical identity and Evidence are separate from properties; keep each node_id/observation_id pair together when composing results. Inventory uses view: {kind: "inventory", collection: "occurrences", logical_paths: ["package.json"], offset: 0, limit: 64}. Inventory views page nodes, occurrences, edges or integrity contradictions. Occurrences accept exact logical_paths and occurrence_ids; nodes accept artifact_ids. Batch filters intersect (omitted means all available, [] means none); fields selects columns while retaining identity links. source_complete describes retained graph membership; source_coverage describes producer coverage, including unknown encrypted PCK directories. Page exhaustion does not prove absence in a partial source. WASM views use kind wasm and facet sections/imports/exports/candidates/glue/wat/headers/details/tool_profile; text facets use UTF-16 code units and source forms remain exact. Mach-O views use kind macho and facet entrypoints/architectures/build_metadata/load_commands/dependencies/imports/exports/segments/provenance; source_exhaustive false means unreturned rows may exist. Interface Builder views use kind interface-builder and collection documents/nodes/edges/coverage; nodes and edges accept an exact document relative_path. EVM summary returns all inferred interface candidates, carrier/decoded identities and explicit unknowns without hex or duplicate stdout. EVM views use kind evm and facet functions/bytecode_hex/stdout/stderr; function pages preserve the original candidate rows, and text offsets/limits count UTF-16 code units (hex has two characters per decoded byte). Exhausting candidate pages does not establish global interface completeness. Managed artifact summaries preserve complete identity/classification, metadata status, module/MVID, frameworks, coverage and limitations without unrelated inventories. Managed pages use kind managed and collection references/resources/attributes, retaining source coverage and build-local token scope; page exhaustion does not establish complete metadata. Managed member summaries keep identity, selection with unmatched names, coverage and per-collection counts; managed-members pages use collection types/exported_types/fields/methods/member_refs/call_edges/field_accesses/user_strings. Exact names and declaring_types filters intersect before paging where supported; fields selects columns (distinct from collection: "fields"). Identity/source_index, module MVID, source coverage and unresolved filter counts remain; omit body to avoid IL anchors. Omitted fields preserves full rows. Android package summaries retain all declarations, engine identity and counts without decoded manifest text. Android manifest pages use kind android, facet manifest, offset and limit in UTF-16 code units; source_status preserves partial decoded coverage even when the retained text page is exhausted. Dart AOT summary preserves target/ABI/library identity, snapshot headers and pool lower bounds. String pages use kind dart-aot, collection package_uris/dart_uris/class_like_tokens; source coverage remains partial when the producer says partial. Protobuf views use kind protobuf, collection bodies/frames/fields, with record_ordinals, body_pointers and fields; field pages also select frame_indices, field_ids, field_numbers or schema_names. Byte identity, offset basis and body status remain present. Text and schema_value are opt-in page columns. APK signing views use kind apk-signature and collection signers/digests/lineage, with ids, signer_ids, schemes, fields and paging. Identity links remain when fields is empty. Declared identities and digest matches do not establish signature verification or authenticity. Model views use kind model-artifact and collection metadata (keys), tensors (names/types) or types (derived totals), with indices, fields and paging. Header SHA-256 scopes declarations; full-file identity remains unknown unless full hashing was selected. Arrays retain typed eight-element previews with explicit omissions. IL2CPP metadata views use kind il2cpp-metadata and collection sections/images/types/methods/fields/properties/events/parameters/string_literals/code_gen_modules/method_addresses/return_types/field_types/parameter_types/generic_method_instances/generic_method_issues. Select indices, fields and pages; sections/images/types/methods/fields/properties/events/parameters/return_types/field_types/parameter_types/generic_method_instances accept exact names (native type names match retained rendered values, preserving same-name rows; null names never match), types also accept image_indices/namespaces/declaring_types, and methods/members accept declaring_types. Parameters and parameter_types accept method_indices; code_gen_modules accept image_indices; method_addresses and generic_method_instances accept addresses/states (generic_method_instances also method_indices), preserving every folded alternative; generic_method_issues accept rows. Row index is scoped to the metadata digest; native pages add binary_source. Uncollected native tables have null counts and remain unavailable. Desktop directory views use kind desktop-application and collection files/omissions/candidates/components/next_probes, with fields and pagination; files and omissions accept exact paths or their stable IDs, and candidates accept families. Source coverage and stable row IDs remain available. Native load-image Evidence uses kind native-load-image with collection source_files/mappings/relocations/entry_points/entry_context/checks/sections, original indices, collection-specific fields and offset/limit paging. Null collections remain unrecorded or inapplicable; pages preserve unsupported verification. Native inventory Evidence from list_names, list/search_procedures or list/search_strings uses view: {kind: "native-inventory", offset: 0, limit: 64, fields: ["value"]}. Rows keep source_index and address even with selected fields. Summary counts describe retained rows; provider discovery coverage remains unknown. Native function Evidence accepts kind summary for identity, availability and facet counts, or kind native for selected facts: view: {kind: "native", facet: "procedure"}. Facets select procedure, pseudocode, assembly, basic blocks, comments, callers/callees, references, unresolved calls, referenced strings/names, native API and high-pcode. Use nonnegative offset and a positive caller-selected limit (defaults 0 and 64); pseudocode uses UTF-16 code units, other native pages use rows. Retained batch_decompile Evidence accepts kind summary for counts and sizes, or view: {kind: "batch-decompile", collection: "items", where: {statuses: ["error"]}} for body-free rows with exact indices, addresses, procedure_addresses or statuses (include_pseudocode adds bodies), or collection "pseudocode" with an index to page one body. Returns artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the complete retained Evidence if needed.', inputSchema: inspectAnalysisViewInputSchema, outputSchema: evidenceResultOf(analysisViewResultSchema), examples: [ diff --git a/src/contracts/toolOutputSchemaGroups.ts b/src/contracts/toolOutputSchemaGroups.ts index 88434a744f..4c43b66f55 100644 --- a/src/contracts/toolOutputSchemaGroups.ts +++ b/src/contracts/toolOutputSchemaGroups.ts @@ -22,6 +22,7 @@ import { byteEntropySchema } from "../domain/native/byteEntropy.js"; import { nativeFunctionMatchingSchema } from "../domain/native/functionMatching.js"; import { nativeByteReadSchema } from "../domain/native/nativeByteRead.js"; import { analysisDetailOutputSchemaOf } from "./analysisDetail.js"; +import { batchDecompileResultSchema } from "../domain/native/batchDecompile.js"; import { functionDossierSchema, functionInstructionWindowSchema, @@ -313,23 +314,6 @@ const callPathTraceOutput = evidenceResultOf( }), ); -/** Identity facts attached to one requested batch selector. */ -const batchProcedureIdentity = z.discriminatedUnion("status", [ - z.object({ - status: z.literal("resolved"), - address: z.string().min(1).describe("Observed canonical procedure entry."), - name: z - .string() - .nullable() - .describe("Provider's entry label, or null when unavailable."), - name_error: analysisErrorProjectionSchema.optional(), - }), - z.object({ - status: z.literal("unknown"), - error: analysisErrorProjectionSchema, - }), -]); - /** Exact structured-content schemas for composed analysis workflows. */ export const enhancedOutputSchemas = { inspect_native_dispatch_metadata: evidenceResultOf( @@ -340,39 +324,7 @@ export const enhancedOutputSchemas = { get_objc_classes: objcClassDiscoveryOutput, get_objc_protocols: symbolDiscoveryOutput("protocols"), decompile_all: evidenceResultOf(decompileDirectoryManifestSchema), - batch_decompile: evidenceResultOf( - z.object({ - items: z.array( - z.discriminatedUnion("status", [ - z.object({ - address: z - .string() - .describe("Original caller-selected symbol or address."), - procedure: batchProcedureIdentity, - status: z.literal("ok"), - pseudocode: z.string().min(1), - }), - z.object({ - address: z - .string() - .describe("Original caller-selected symbol or address."), - procedure: batchProcedureIdentity, - status: z.literal("error"), - error: analysisErrorProjectionSchema, - limitations: z - .array(z.string()) - .optional() - .describe( - "Caveats of this item's own provider observation when it supplied no pseudocode, including any reason the provider reported.", - ), - }), - ]), - ), - total: z.int().min(0), - succeeded: z.int().min(0), - failed: z.int().min(0), - }), - ), + batch_decompile: evidenceResultOf(batchDecompileResultSchema), get_call_graph: analysisDetailOutputSchemaOf( nativeObservationSourceSchemas.get_call_graph, nativeObservationSummaryViewResultSchemas.get_call_graph, diff --git a/src/domain/analysisView/analysisView.ts b/src/domain/analysisView/analysisView.ts index cc69a3505f..026dc9da7a 100644 --- a/src/domain/analysisView/analysisView.ts +++ b/src/domain/analysisView/analysisView.ts @@ -18,6 +18,7 @@ import { projectJavaScriptRoutesView } from "./javascriptRoutesView.js"; import { projectWebBundleView } from "./webBundleView.js"; import { projectSourceToBundleView } from "./sourceToBundleView.js"; import { projectFeatureTraceView } from "./featureTraceView.js"; +import { projectBatchDecompileView } from "./batchDecompileView.js"; import { projectGpuCodeObjectsView } from "./gpuCodeObjectsView.js"; import { projectModelArtifactView } from "./modelArtifactView.js"; import { projectCommandObservationView } from "./commandObservationView.js"; @@ -333,6 +334,7 @@ const retainedViewProjectors = new Map([ retain("match_native_functions", projectNativeFunctionMatchingView), retain("compare_source_to_bundle", projectSourceToBundleView), retain("trace_application_feature", projectFeatureTraceView), + retain("batch_decompile", projectBatchDecompileView), retain("inspect_artifact", projectArtifactInventoryView), retain("inventory_artifact", projectArtifactInventoryView), retain("analyze_web_bundle", projectWebBundleView), @@ -432,6 +434,7 @@ export const projectAnalysisView = ( parent.operation === "match_native_functions" ? NATIVE_FUNCTION_MATCHING_PREDICATE : parent.operation === "analyze_function" || + parent.operation === "batch_decompile" || isNativeObservationOperation(parent.operation) || isNativeInventoryOperation(parent.operation) ? ANALYSIS_EVIDENCE_PREDICATE diff --git a/src/domain/analysisView/analysisViewRequest.ts b/src/domain/analysisView/analysisViewRequest.ts index 8375b84dd9..cfa24c93f6 100644 --- a/src/domain/analysisView/analysisViewRequest.ts +++ b/src/domain/analysisView/analysisViewRequest.ts @@ -11,6 +11,7 @@ import { javaScriptRoutesViewRequestSchema } from "./javascriptRoutesView.js"; import { webBundleViewRequestSchema } from "./webBundleView.js"; import { sourceToBundleViewRequestSchema } from "./sourceToBundleView.js"; import { featureTraceViewRequestSchema } from "./featureTraceView.js"; +import { batchDecompileViewRequestSchema } from "./batchDecompileView.js"; import { gpuCodeObjectsViewRequestSchema } from "./gpuCodeObjectsView.js"; import { modelArtifactViewRequestSchema } from "../model/modelArtifactQuery.js"; import { rustBinaryViewRequestSchema } from "../rust/rustBinaryQuery.js"; @@ -68,6 +69,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [ nativeFunctionMatchingViewRequestSchema, sourceToBundleViewRequestSchema, featureTraceViewRequestSchema, + batchDecompileViewRequestSchema, summaryViewSchema, goBinaryViewRequestSchema, rustBinaryViewRequestSchema, diff --git a/src/domain/analysisView/analysisViewResult.ts b/src/domain/analysisView/analysisViewResult.ts index 7bd99d111b..2866190c8a 100644 --- a/src/domain/analysisView/analysisViewResult.ts +++ b/src/domain/analysisView/analysisViewResult.ts @@ -68,6 +68,11 @@ import { featureTraceViewCollections, featureTraceViewContextSchema, } from "./featureTraceView.js"; +import { + batchDecompileSummarySchema, + batchDecompileViewCollections, + batchDecompileViewContextSchema, +} from "./batchDecompileView.js"; import { gpuCodeObjectsViewRequestSchema, gpuCodeObjectsSummarySchema, @@ -987,6 +992,39 @@ export const featureTraceViewResultSchema = z ]), ); +/** Counts and identities of a retained batch without any pseudocode body. */ +const batchDecompileSummaryViewResultSchema = z.strictObject({ + ...summaryViewResultBase, + artifact: artifactSchema.nullable(), + parent_operation: z.literal("batch_decompile"), + summary: batchDecompileSummarySchema, +}); +const batchDecompilePage = { + ...viewResultBase, + ...batchDecompileViewContextSchema.shape, + kind: z.literal("batch-decompile"), + artifact: artifactSchema.nullable(), + parent_operation: z.literal("batch_decompile"), +}; +// The kind tag keeps dispatch while each collection keeps exactly its own shape. +export const batchDecompileViewResultSchema = z + .object({ kind: z.literal("batch-decompile") }) + .passthrough() + .pipe( + z.union([ + z.strictObject({ + ...batchDecompilePage, + view: batchDecompileViewCollections.items.request, + items: batchDecompileViewCollections.items.rows, + }), + z.strictObject({ + ...batchDecompilePage, + view: batchDecompileViewCollections.pseudocode.request, + item: batchDecompileViewCollections.pseudocode.item, + }), + ]), + ); + /** Bind the existing nested facet selection to its producer-owned rows. */ const machoPage = (facet: Facet) => z.strictObject({ @@ -1026,6 +1064,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [ webBundlePageViewResultSchema, sourceToBundlePageViewResultSchema, featureTraceViewResultSchema, + batchDecompileViewResultSchema, z.strictObject({ ...viewResultBase, ...nativeFunctionMatchingContextSchema.shape, @@ -1116,6 +1155,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [ nativeFunctionSummaryViewResultSchema, sourceToBundleSummaryViewResultSchema, featureTraceSummaryViewResultSchema, + batchDecompileSummaryViewResultSchema, webBundleSummaryViewResultSchema, ]), z.strictObject({ diff --git a/src/domain/analysisView/batchDecompileView.ts b/src/domain/analysisView/batchDecompileView.ts new file mode 100644 index 0000000000..2d0497e4d9 --- /dev/null +++ b/src/domain/analysisView/batchDecompileView.ts @@ -0,0 +1,396 @@ +import { z } from "zod"; +import { + committedProviderSchema, + type CommittedProviderIdentity, +} from "../analysisProfile.js"; +import { digestSchema } from "../digests.js"; +import { providerSchema } from "../evidence.js"; +import { + batchDecompileResultSchema, + batchItemLimitationsSchema, + batchProcedureIdentitySchema, + type BatchDecompileItem, + type BatchDecompileResult, +} from "../native/batchDecompile.js"; +import { analysisErrorProjectionSchema } from "../../contracts/errorSchemas.js"; +import { err, ok } from "../result.js"; +import { + boundedViewMessages, + completeWithinViewCoverage, + pageViewCoverage, +} from "./analysisViewCoverage.js"; +import { analysisViewInputError } from "./analysisViewErrors.js"; +import { + createAnalysisViewResultReader, + type AnalysisViewParent, +} from "./analysisViewParent.js"; +import { + ownedView, + type AdmittedView, + type SummaryAnalysisView, +} from "./analysisViewShape.js"; +import { + analysisTextPage, + analysisTextPageItemSchema, +} from "./analysisViewText.js"; +import { selectViewRows } from "./selectViewRows.js"; + +const OPERATION = "batch_decompile" as const; + +const offset = z.int().nonnegative().default(0); + +const itemsRequestSchema = z.strictObject({ + kind: z.literal("batch-decompile"), + collection: z.literal("items"), + offset, + limit: z.int().positive().default(64), + where: z + .strictObject({ + indices: z + .array(z.int().nonnegative()) + .optional() + .describe( + "Exact zero-based positions in the original batch, which keep duplicate selectors distinct. Omitted selects all; [] selects none.", + ), + addresses: z + .array(z.string()) + .optional() + .describe( + "Exact caller-selected symbols or addresses as submitted. Omitted selects all; [] selects none.", + ), + procedure_addresses: z + .array(z.string()) + .optional() + .describe( + "Exact observed canonical entries. An item with unknown procedure identity never matches. Omitted selects all; [] selects none.", + ), + statuses: z + .array(z.enum(["ok", "error"])) + .optional() + .describe("Item outcomes. Omitted selects all; [] selects none."), + }) + .default({}), + include_pseudocode: z + .boolean() + .default(false) + .describe( + "Opt into each selected successful item's complete pseudocode. Otherwise rows report pseudocode_code_units only.", + ), +}); + +const pseudocodeRequestSchema = z.strictObject({ + kind: z.literal("batch-decompile"), + collection: z.literal("pseudocode"), + index: z.int().nonnegative().describe("Exact item position from a row."), + offset: offset.describe("UTF-16 code-unit offset into this item's text."), + limit: z + .int() + .positive() + .default(16_384) + .describe( + "UTF-16 code units in this page. A page size only: coverage reports the complete body and the next offset.", + ), +}); + +/** Select rows of a completed batch or page one retained pseudocode body. */ +export const batchDecompileViewRequestSchema = z.discriminatedUnion( + "collection", + [itemsRequestSchema, pseudocodeRequestSchema], +); + +type BatchDecompileViewRequest = z.output< + typeof batchDecompileViewRequestSchema +>; + +const itemIdentity = { + index: z.int().nonnegative().describe("Position in the original batch."), + address: z.string().describe("Original caller-selected symbol or address."), + procedure: batchProcedureIdentitySchema, +}; + +const batchDecompileRowSchema = z.discriminatedUnion("status", [ + z.strictObject({ + ...itemIdentity, + status: z.literal("ok"), + pseudocode_code_units: z.int().positive(), + pseudocode: z.string().min(1).exactOptional(), + }), + z.strictObject({ + ...itemIdentity, + status: z.literal("error"), + error: analysisErrorProjectionSchema, + limitations: batchItemLimitationsSchema, + }), +]); + +/** + * Producer counts and identities repeated with every view, so one selected row + * stays traceable to its batch and to the provider that decompiled it. + */ +export const batchDecompileViewContextSchema = z.strictObject({ + batch: z.strictObject({ + total: z.int().nonnegative(), + succeeded: z.int().nonnegative(), + failed: z.int().nonnegative(), + }), + source_provider: providerSchema.nullable(), + source_analysis_profile_digest: digestSchema.nullable(), + decompiling_provider: committedProviderSchema + .nullable() + .describe( + "Provider committed by the batch's upstream analysis profile, or null when the parent records none.", + ), +}); + +/** Summary context adds the facts an analyst needs to choose what to read. */ +export const batchDecompileSummarySchema = + batchDecompileViewContextSchema.extend({ + procedures: z.strictObject({ + distinct_resolved: z.int().nonnegative(), + unknown_identity: z.int().nonnegative(), + label_unavailable: z + .int() + .nonnegative() + .describe( + "Resolved items whose entry label is null, whether the provider had none or its lookup failed.", + ), + }), + pseudocode: z.strictObject({ + code_units: z.int().nonnegative(), + largest: z + .strictObject({ + index: z.int().nonnegative(), + code_units: z.int().positive(), + }) + .nullable(), + }), + limitation_count: z.int().nonnegative(), + }); + +/** Each collection's request bound to its own rows, so a reply cannot mix them. */ +export const batchDecompileViewCollections = { + items: { + request: itemsRequestSchema, + rows: z.array(batchDecompileRowSchema), + }, + pseudocode: { + request: pseudocodeRequestSchema, + item: z.strictObject({ + ...itemIdentity, + ...analysisTextPageItemSchema.shape, + pseudocode_code_units: z.int().positive(), + }), + }, +} as const; + +const checkedBatch = createAnalysisViewResultReader(batchDecompileResultSchema); + +const upstreamProfileSchema = z.object({ + upstream_analysis_profile: z.object({ provider: committedProviderSchema }), +}); + +/** A composed batch's Evidence provider is the workflow; its profile names the decompiler. */ +const decompilingProvider = ( + parent: AnalysisViewParent, +): CommittedProviderIdentity | null => { + const parsed = upstreamProfileSchema.safeParse( + parent.analysisProfile?.parameters, + ); + return parsed.success ? parsed.data.upstream_analysis_profile.provider : null; +}; + +const batchContext = ( + parent: AnalysisViewParent, + { total, succeeded, failed }: BatchDecompileResult, +) => ({ + batch: { total, succeeded, failed }, + source_provider: parent.provider ?? null, + source_analysis_profile_digest: parent.analysisProfile?.digest ?? null, + decompiling_provider: decompilingProvider(parent), +}); + +const summarizeBatch = (items: readonly BatchDecompileItem[]) => { + const resolved = new Set(); + let unknownIdentity = 0; + let labelUnavailable = 0; + let codeUnits = 0; + let largest: { index: number; code_units: number } | null = null; + for (const [index, item] of items.entries()) { + if (item.procedure.status === "unknown") unknownIdentity++; + else { + resolved.add(item.procedure.address); + // Null covers an answer without a label and a failed label lookup alike. + if (item.procedure.name === null) labelUnavailable++; + } + if (item.status !== "ok") continue; + codeUnits += item.pseudocode.length; + if (largest === null || item.pseudocode.length > largest.code_units) + largest = { index, code_units: item.pseudocode.length }; + } + return { + procedures: { + distinct_resolved: resolved.size, + unknown_identity: unknownIdentity, + label_unavailable: labelUnavailable, + }, + pseudocode: { code_units: codeUnits, largest }, + }; +}; + +const batchUnknowns = (items: readonly BatchDecompileItem[]): string[] => { + const unknownIdentity = items.filter( + ({ procedure }) => procedure.status === "unknown", + ).length; + return [ + ...(unknownIdentity === 0 + ? [] + : [ + `${String(unknownIdentity)} items have unknown procedure identity; their address is the caller's selector, not an observed entry.`, + ]), + "Evidence limitations aggregate every item's provider observations and are not attributed to one successful item. A batch covers only its selected procedures, and exhausting a page establishes nothing outside it.", + ]; +}; + +const selected = (values: readonly Value[] | undefined) => + values === undefined ? undefined : new Set(values); + +const itemRow = ( + item: BatchDecompileItem, + index: number, + includePseudocode: boolean, +): z.output => { + const identity = { + index, + address: item.address, + procedure: item.procedure, + }; + if (item.status === "ok") + return { + ...identity, + status: "ok", + pseudocode_code_units: item.pseudocode.length, + ...(includePseudocode ? { pseudocode: item.pseudocode } : {}), + }; + return { + ...identity, + status: "error", + error: item.error, + ...(item.limitations === undefined + ? {} + : { limitations: item.limitations }), + }; +}; + +const pseudocodeRefusal = (message: string) => + err( + analysisViewInputError([ + { path: ["view", "index"], reason: "invalid_value", message }, + ]), + ); + +/** Select retained batch facts without repeating decompilation or changing its record. */ +export const projectBatchDecompileView = ( + parent: AnalysisViewParent, + admitted: AdmittedView, +) => { + const view = ownedView( + admitted, + "summary", + "batch-decompile", + ); + if (view === undefined) + return err( + analysisViewInputError([ + { + path: ["view"], + reason: "invalid_value", + message: + "batch_decompile Evidence supports summary and batch-decompile views of items or pseudocode.", + }, + ]), + ); + const parsed = checkedBatch(parent); + if (!parsed.ok) return parsed; + const batch = parsed.value; + const shared = { + parent_evidence_id: parent.evidenceId, + parent_operation: OPERATION, + parent_digest: parent.evidenceId.slice(3), + artifact: parent.artifact ?? null, + limitations: boundedViewMessages( + parent.limitations, + parent.evidenceId, + "limitations", + ), + unknowns: boundedViewMessages( + [], + parent.evidenceId, + "unknowns", + batchUnknowns(batch.items), + ), + }; + const context = batchContext(parent, batch); + if (view.kind === "summary") + return ok({ + kind: "summary" as const, + view, + ...shared, + summary: { + ...context, + ...summarizeBatch(batch.items), + limitation_count: new Set(parent.limitations).size, + }, + coverage: completeWithinViewCoverage(1, 1), + }); + if (view.collection === "items") { + const indices = selected(view.where.indices); + const addresses = selected(view.where.addresses); + const entries = selected(view.where.procedure_addresses); + const statuses = selected(view.where.statuses); + const { rows, total } = selectViewRows( + batch.items, + view, + (item, index) => + (indices === undefined || indices.has(index)) && + (addresses === undefined || addresses.has(item.address)) && + (statuses === undefined || statuses.has(item.status)) && + (entries === undefined || + (item.procedure.status === "resolved" && + entries.has(item.procedure.address))), + (item, index) => itemRow(item, index, view.include_pseudocode), + ); + return ok({ + kind: "batch-decompile" as const, + view, + ...shared, + ...context, + items: rows, + coverage: pageViewCoverage(view.offset, rows.length, total), + }); + } + const item = batch.items[view.index]; + if (item === undefined) + return pseudocodeRefusal( + `Item ${String(view.index)} is outside this batch of ${String(batch.items.length)}.`, + ); + if (item.status !== "ok") + return pseudocodeRefusal( + `Item ${String(view.index)} has status error and no pseudocode; read its error and limitations through the items collection.`, + ); + const page = analysisTextPage(item.pseudocode, view.offset, view.limit); + if (!page.ok) return page; + return ok({ + kind: "batch-decompile" as const, + view, + ...shared, + ...context, + item: { + index: view.index, + address: item.address, + procedure: item.procedure, + pseudocode_code_units: item.pseudocode.length, + ...page.value.item, + }, + coverage: page.value.coverage, + }); +}; diff --git a/src/domain/native/batchDecompile.ts b/src/domain/native/batchDecompile.ts new file mode 100644 index 0000000000..b1d78a9983 --- /dev/null +++ b/src/domain/native/batchDecompile.ts @@ -0,0 +1,62 @@ +import { z } from "zod"; +import { analysisErrorProjectionSchema } from "../../contracts/errorSchemas.js"; + +/** Identity facts attached to one requested batch selector. */ +export const batchProcedureIdentitySchema = z.discriminatedUnion("status", [ + z.object({ + status: z.literal("resolved"), + address: z.string().min(1).describe("Observed canonical procedure entry."), + name: z + .string() + .nullable() + .describe("Provider's entry label, or null when unavailable."), + name_error: analysisErrorProjectionSchema.exactOptional(), + }), + z.object({ + status: z.literal("unknown"), + error: analysisErrorProjectionSchema, + }), +]); + +const batchSelectorSchema = z + .string() + .describe("Original caller-selected symbol or address."); + +/** Caveats only this item's own provider observation can explain. */ +export const batchItemLimitationsSchema = z + .array(z.string()) + .exactOptional() + .describe( + "Caveats of this item's own provider observation when it supplied no pseudocode, including any reason the provider reported.", + ); + +/** One ordered batch outcome; array position keeps duplicate selectors distinct. */ +export const batchDecompileItemSchema = z.discriminatedUnion("status", [ + z.object({ + address: batchSelectorSchema, + procedure: batchProcedureIdentitySchema, + status: z.literal("ok"), + pseudocode: z.string().min(1), + }), + z.object({ + address: batchSelectorSchema, + procedure: batchProcedureIdentitySchema, + status: z.literal("error"), + error: analysisErrorProjectionSchema, + limitations: batchItemLimitationsSchema, + }), +]); + +/** Provider-independent result owned by the shared batch decompilation workflow. */ +export const batchDecompileResultSchema = z.object({ + items: z.array(batchDecompileItemSchema), + total: z.int().min(0), + succeeded: z.int().min(0), + failed: z.int().min(0), +}); + +export type BatchProcedureIdentity = z.output< + typeof batchProcedureIdentitySchema +>; +export type BatchDecompileItem = z.output; +export type BatchDecompileResult = z.output; diff --git a/tests/boundary/cli/analysisViewCli.test.ts b/tests/boundary/cli/analysisViewCli.test.ts index 2f1d42a2a0..c0c10c3246 100644 --- a/tests/boundary/cli/analysisViewCli.test.ts +++ b/tests/boundary/cli/analysisViewCli.test.ts @@ -46,6 +46,72 @@ import { } from "../../../src/domain/evidenceBundle.js"; import { inspectEvidenceBundle } from "../../../src/application/investigation/InspectEvidenceBundle.js"; +cliTest( + "reads selected batch rows and one body from a saved bundle without a provider", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-batch-view-cli-"); + const path = join(root, "bundle.json"); + const body = "int main(void) { return 0; }"; + const parent = createEvidence( + undefined, + { id: "fixture", name: "Fixture", version: "1" }, + { + operation: "batch_decompile", + parameters: { addresses: ["main", "main"] }, + result: { + items: ["main", "main"].map((address) => ({ + address, + procedure: { status: "resolved", address: "0x1", name: "main" }, + status: "ok", + pseudocode: body, + })), + total: 2, + succeeded: 2, + failed: 0, + }, + confidence: "derived", + authority: "shipped-artifact", + }, + ); + await writeFile(path, JSON.stringify(createEvidenceBundle([parent]))); + const inspect = async (view: JsonValue) => { + const result = await cli.run({ + arguments: [ + "inspect-analysis-view", + JSON.stringify({ + source: { + kind: "retained-evidence", + evidence_id: parent.evidence_id, + }, + view, + }), + "--evidence-bundle", + path, + "--json", + ], + }); + expect(result.exitCode).toBe(0); + return parseEvidence(result.json).normalized_result; + }; + expect( + await inspect({ kind: "batch-decompile", collection: "items" }), + ).toMatchObject({ + batch: { total: 2 }, + items: [ + { index: 0, pseudocode_code_units: body.length }, + { index: 1, pseudocode_code_units: body.length }, + ], + }); + expect( + await inspect({ + kind: "batch-decompile", + collection: "pseudocode", + index: 1, + }), + ).toMatchObject({ item: { index: 1, text: body } }); + }, +); + cliTest( "authenticates an exact portable parent for non-managed views and rejects ambiguous or altered sources", async ({ cli }) => { diff --git a/tests/boundary/mcp/batchDecompileViewsMcp.test.ts b/tests/boundary/mcp/batchDecompileViewsMcp.test.ts new file mode 100644 index 0000000000..4bbd4d9f12 --- /dev/null +++ b/tests/boundary/mcp/batchDecompileViewsMcp.test.ts @@ -0,0 +1,573 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import type { CallToolResult } from "@modelcontextprotocol/server"; +import { afterAll, expect, it, onTestFinished } from "vitest"; +import { z } from "zod"; +import { analysisViewResultSchema } from "../../../src/domain/analysisView/analysisView.js"; +import { + createEvidence, + parseEvidence, + type Evidence, +} from "../../../src/domain/evidence.js"; +import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js"; +import { batchDecompileResultSchema } from "../../../src/domain/native/batchDecompile.js"; +import { err, ok } from "../../../src/domain/result.js"; +import { GhidraSessionError } from "../../../src/ghidra/GhidraSessionError.js"; +import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js"; +import { createTestBinarySession } from "../../fixtures/binarySession.js"; +import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { connectGhidraMcp, ghidraFixtureResult } from "./ghidraMcpHarness.js"; + +const MAIN_BODY = "int main(void) { return 0; }"; +const EMOJI_BODY = `int emoji(void) { return "${"\u{1F600}".repeat(4)}"; }`; +const NO_BODY_REASON = "Thunk has no decompilable body."; + +/** Selectors exercising a duplicate, an interior address, no body and no identity. */ +const SELECTORS = ["main", "0x401005", "main", "emoji", "bodyless", "missing"]; +const ENTRIES: Readonly> = { + main: "0x401000", + "0x401005": "0x401000", + emoji: "0x402000", + bodyless: "0x403000", + unlabeled: "0x404000", + "label-failure": "0x405000", +}; +const LABELS: Readonly> = { + "0x401000": "main", + "0x402000": "emoji", + "0x403000": "bodyless", +}; +const BODIES: Readonly> = { + "0x401000": MAIN_BODY, + "0x402000": EMOJI_BODY, +}; + +const provider = (calls: { count: number }, bodies: typeof BODIES) => + ((operation, input) => { + calls.count++; + if (operation === "procedure_address") { + const selector = String(input.procedure); + const entry = ENTRIES[selector]; + return Promise.resolve( + entry === undefined + ? err( + new GhidraSessionError( + "remote", + `no function: ${selector}`, + {}, + { remoteCode: "not_found" }, + ), + ) + : ok(entry), + ); + } + if (operation === "address_name") + return Promise.resolve( + input.address === "0x405000" + ? err(new GhidraSessionError("remote", "label lookup failed")) + : ok(LABELS[String(input.address)] ?? null), + ); + if (operation === "procedure_pseudo_code") { + const body = bodies[String(input.procedure)]; + return Promise.resolve( + ok( + body === undefined + ? { value: null, limitations: [NO_BODY_REASON] } + : { value: body, limitations: [] }, + ), + ); + } + return Promise.resolve(ok(ghidraFixtureResult(operation, input))); + }) satisfies NonNullable[1]>; + +const schemaValidation = createMcpSchemaValidation(); +afterAll(() => schemaValidation.clear()); + +/** Replies these tools deliver must validate against what they advertise. */ +const ADVERTISED_OUTPUTS = ["batch_decompile", "inspect_analysis_view"]; + +const connect = async (profile: "full" | "compact") => { + const calls = { count: 0 }; + const harness = await connectGhidraMcp( + `batch-decompile-views-${profile}`, + provider(calls, BODIES), + { + environment: { + REA_MCP_INPUT_SCHEMA_PROFILE: profile, + REA_MCP_OUTPUT_SCHEMA_PROFILE: profile, + }, + schemaValidator: schemaValidation, + }, + ); + onTestFinished(() => harness.close()); + const { tools } = await harness.mcp.listTools(); + const outputSchemas = new Map( + ADVERTISED_OUTPUTS.map((name) => { + const advertised = tools.find((tool) => tool.name === name)?.outputSchema; + if (advertised === undefined) + throw new Error(`${name} advertises no output schema`); + const schema: Record = advertised; + return [name, schema] as const; + }), + ); + const reply = async (name: string, args: Record) => + z + .custom() + .parse(await harness.mcp.callTool({ name, arguments: args })); + const call = async (name: string, args: Record) => { + const result = await reply(name, args); + expect(result.isError, JSON.stringify(result)).not.toBe(true); + const schema = outputSchemas.get(name); + if (schema !== undefined) + expect( + schemaValidation.assertions.validate(schema, result.structuredContent), + JSON.stringify(schemaValidation.assertions.errors), + ).toBe(true); + return { evidence: parseEvidence(result.structuredContent), result }; + }; + return { ...harness, calls, reply, call }; +}; + +type Harness = Awaited>; + +const viewOf = (evidence: Evidence) => + z.looseObject({}).parse(evidence.normalized_result); + +const retained = (evidenceId: string) => ({ + kind: "retained-evidence", + evidence_id: evidenceId, +}); + +const view = async ( + { call }: Harness, + parentId: string, + selected: Record, +) => + viewOf( + ( + await call("inspect_analysis_view", { + source: retained(parentId), + view: { kind: "batch-decompile", ...selected }, + }) + ).evidence, + ); + +const rowIndices = (page: Record) => + z + .array(z.looseObject({ index: z.number() })) + .parse(page.items) + .map(({ index }) => index); + +/** Read every text page of one retained body in order. */ +const readBody = async ( + harness: Harness, + parentId: string, + index: number, + limit?: number, +) => { + let text = ""; + let pages = 0; + let offset: number | null = 0; + while (offset !== null) { + const page = await view(harness, parentId, { + collection: "pseudocode", + index, + offset, + ...(limit === undefined ? {} : { limit }), + }); + text += z.looseObject({ text: z.string() }).parse(page.item).text; + offset = z + .looseObject({ next_offset: z.number().nullable() }) + .parse(page.coverage).next_offset; + pages++; + } + return { text, pages }; +}; + +/** A typed refusal whose issue names the rejected selection. */ +const invalidIssue = (message: string) => ({ + code: "invalid_request", + details: { + issues: expect.arrayContaining([ + expect.objectContaining({ message: expect.stringContaining(message) }), + ]), + }, +}); + +it.each(["full", "compact"] as const)( + "selects retained batch rows and bodies without repeating analysis (%s)", + async (profile) => { + const harness = await connect(profile); + const parent = ( + await harness.call("batch_decompile", { addresses: SELECTORS }) + ).evidence; + const parentId = parent.evidence_id; + const reply = await harness.call("inspect_analysis_view", { + source: retained(parentId), + view: { kind: "summary" }, + }); + const summary = viewOf(reply.evidence); + + expect(parent.parameters).toEqual({ addresses: SELECTORS }); + expect( + batchDecompileResultSchema.parse(parent.normalized_result), + ).toMatchObject({ total: 6, succeeded: 4, failed: 2 }); + expect(JSON.stringify(reply.result)).not.toContain("int main"); + expect(reply.evidence.evidence_links).toEqual([parentId]); + expect(reply.evidence.limitations).toEqual( + expect.arrayContaining(parent.limitations), + ); + expect(summary).toMatchObject({ + kind: "summary", + parent_operation: "batch_decompile", + summary: { + batch: { total: 6, succeeded: 4, failed: 2 }, + source_provider: parent.provider, + source_analysis_profile_digest: parent.analysis_profile?.digest, + decompiling_provider: { id: "ghidra", version: "12.1.4" }, + procedures: { + distinct_resolved: 3, + unknown_identity: 1, + label_unavailable: 0, + }, + pseudocode: { + code_units: MAIN_BODY.length * 3 + EMOJI_BODY.length, + largest: { index: 3, code_units: EMOJI_BODY.length }, + }, + }, + }); + expect(summary.unknowns).toEqual( + expect.arrayContaining([ + expect.stringContaining("1 items have unknown procedure identity"), + expect.stringContaining("not attributed to one successful item"), + ]), + ); + const callsAfterBatch = harness.calls.count; + + // The default page is an index without bodies. + const index = await view(harness, parentId, { collection: "items" }); + expect(JSON.stringify(index.items)).not.toContain("int main"); + expect(index).toMatchObject({ + batch: { total: 6, succeeded: 4, failed: 2 }, + coverage: { total: 6, exhausted: true }, + }); + expect(index.items).toMatchObject([ + { + index: 0, + address: "main", + procedure: { status: "resolved", address: "0x401000", name: "main" }, + status: "ok", + pseudocode_code_units: MAIN_BODY.length, + }, + { index: 1, address: "0x401005" }, + { index: 2, address: "main" }, + { index: 3, address: "emoji" }, + { + index: 4, + status: "error", + error: { code: "capability_unavailable" }, + limitations: expect.arrayContaining([NO_BODY_REASON]), + }, + { index: 5, procedure: { status: "unknown" } }, + ]); + + // Filters are exact, compose, and keep original indices. + for (const [where, indices] of [ + [{ addresses: ["main"] }, [0, 2]], + [{ procedure_addresses: ["0x401000"] }, [0, 1, 2]], + // A selector never matches as an observed entry, including an unknown one. + [{ procedure_addresses: ["missing"] }, []], + [{ statuses: ["error"] }, [4, 5]], + [{ indices: [5, 3, 3] }, [3, 5]], + [{ statuses: ["ok"], procedure_addresses: ["0x402000"] }, [3]], + [{ indices: [] }, []], + [{ addresses: [] }, []], + [{ procedure_addresses: [] }, []], + [{ statuses: [] }, []], + ] as const) + expect( + rowIndices( + await view(harness, parentId, { collection: "items", where }), + ), + JSON.stringify(where), + ).toEqual(indices); + + // Coverage counts matches rather than the whole batch. + const paged = await view(harness, parentId, { + collection: "items", + where: { statuses: ["ok"] }, + offset: 1, + limit: 2, + }); + expect(rowIndices(paged)).toEqual([1, 2]); + expect(paged.coverage).toMatchObject({ + status: "page", + examined: 2, + total: 4, + next_offset: 3, + exhausted: false, + }); + + // Bodies are opt-in, and only successful items have one. + const selected = await view(harness, parentId, { + collection: "items", + where: { indices: [3, 4] }, + include_pseudocode: true, + }); + expect(selected.items).toMatchObject([ + { index: 3, pseudocode: EMOJI_BODY }, + { index: 4, status: "error" }, + ]); + expect(JSON.stringify(selected.items)).not.toContain('"pseudocode":null'); + + expect(harness.calls.count).toBe(callsAfterBatch); + expect(harness.session.evidenceById(parentId)).toEqual(parent); + }, +); + +it("counts both forms of an unavailable entry label", async () => { + const harness = await connect("full"); + const parent = ( + await harness.call("batch_decompile", { + addresses: ["main", "unlabeled", "label-failure"], + }) + ).evidence.evidence_id; + const summary = viewOf( + ( + await harness.call("inspect_analysis_view", { + source: retained(parent), + view: { kind: "summary" }, + }) + ).evidence, + ); + expect(summary.summary).toMatchObject({ + procedures: { + distinct_resolved: 3, + unknown_identity: 0, + label_unavailable: 2, + }, + }); + const { items } = await view(harness, parent, { collection: "items" }); + expect(items).toMatchObject([ + { procedure: { name: "main" } }, + { procedure: { name: null } }, + { procedure: { name: null, name_error: { code: expect.any(String) } } }, + ]); + expect(JSON.stringify(z.array(z.unknown()).parse(items)[1])).not.toContain( + "name_error", + ); +}); + +it("pages one body exactly without splitting a Unicode character", async () => { + const harness = await connect("full"); + const { evidence } = await harness.call("batch_decompile", { + addresses: SELECTORS, + }); + const parent = evidence.evidence_id; + // The complete delivery still carries every body by default. + expect(JSON.stringify(evidence.normalized_result)).toContain("int main"); + + // A limit ending inside a surrogate pair stops before it, so pages rebuild the text. + const { text, pages } = await readBody(harness, parent, 3, 30); + expect(text).toBe(EMOJI_BODY); + expect(pages).toBeGreaterThan(1); + expect( + await view(harness, parent, { collection: "pseudocode", index: 3 }), + ).toMatchObject({ + item: { + index: 3, + address: "emoji", + procedure: { status: "resolved", address: "0x402000" }, + pseudocode_code_units: EMOJI_BODY.length, + unit: "utf16-code-units", + }, + coverage: { total: EMOJI_BODY.length, exhausted: true }, + }); + + const refused = async (selected: Record) => + parseMcpToolError( + await harness.reply("inspect_analysis_view", { + source: retained(parent), + view: { + kind: "batch-decompile", + collection: "pseudocode", + ...selected, + }, + }), + ).error; + expect(await refused({ index: 4 })).toMatchObject( + invalidIssue("Item 4 has status error"), + ); + expect(await refused({ index: 6 })).toMatchObject( + invalidIssue("outside this batch of 6"), + ); + expect( + await refused({ index: 3, offset: EMOJI_BODY.indexOf("\u{1F600}") + 1 }), + ).toMatchObject(invalidIssue("splits a UTF-16 surrogate pair")); +}); + +it("reads the same rows from a bundle and an Evidence file without a provider", async () => { + const harness = await connect("full"); + const parent = ( + await harness.call("batch_decompile", { addresses: SELECTORS }) + ).evidence; + const selected = { + kind: "batch-decompile", + collection: "items", + where: { addresses: ["emoji"] }, + include_pseudocode: true, + }; + const { items } = viewOf( + ( + await harness.call("inspect_analysis_view", { + source: retained(parent.evidence_id), + view: selected, + }) + ).evidence, + ); + expect(items).toMatchObject([{ index: 3, pseudocode: EMOJI_BODY }]); + + const root = await createTestTempDirectory("rea-batch-decompile-view-"); + const bundlePath = join(root, "bundle.json"); + const filePath = join(root, "batch.json"); + await writeFile(bundlePath, JSON.stringify(createEvidenceBundle([parent]))); + await writeFile(filePath, JSON.stringify(parent)); + const { client, close } = await createApplicationMcpHarness({ + session: createTestBinarySession(() => { + throw new Error("Retained batch views must not open a provider"); + }), + clientIdentity: { name: "batch-decompile-offline", version: "1.0.0" }, + schemaValidator: schemaValidation, + }); + onTestFinished(close); + const imported = await client.callTool({ + name: "import_evidence_bundle", + arguments: { path: bundlePath }, + }); + expect(imported.isError).not.toBe(true); + for (const source of [ + retained(parent.evidence_id), + { kind: "evidence-file", path: filePath }, + ]) { + const reply = await client.callTool({ + name: "inspect_analysis_view", + arguments: { source, view: selected }, + }); + expect(viewOf(parseEvidence(reply.structuredContent)).items).toEqual(items); + } +}); + +it("binds views to their parent and each page to its own collection", async () => { + const harness = await connect("full"); + const emptyParent = (await harness.call("batch_decompile", { addresses: [] })) + .evidence.evidence_id; + const summary = viewOf( + ( + await harness.call("inspect_analysis_view", { + source: retained(emptyParent), + view: { kind: "summary" }, + }) + ).evidence, + ); + expect(summary.summary).toMatchObject({ + batch: { total: 0, succeeded: 0, failed: 0 }, + procedures: { distinct_resolved: 0, unknown_identity: 0 }, + pseudocode: { code_units: 0, largest: null }, + }); + expect( + await view(harness, emptyParent, { collection: "items" }), + ).toMatchObject({ + items: [], + coverage: { status: "empty", exhausted: true }, + }); + + const parent = ( + await harness.call("batch_decompile", { addresses: ["main"] }) + ).evidence.evidence_id; + const items = await view(harness, parent, { collection: "items" }); + const body = await view(harness, parent, { + collection: "pseudocode", + index: 0, + }); + expect(analysisViewResultSchema.safeParse(items).success).toBe(true); + expect(analysisViewResultSchema.safeParse(body).success).toBe(true); + expect( + analysisViewResultSchema.safeParse({ ...items, view: body.view }).success, + ).toBe(false); + const { item: _item, ...withoutItem } = body; + expect( + analysisViewResultSchema.safeParse({ ...withoutItem, items: items.items }) + .success, + ).toBe(false); + + const inspect = async (source: unknown, selected: unknown) => + harness.reply("inspect_analysis_view", { source, view: selected }); + expect( + parseMcpToolError( + await inspect(retained(parent), { kind: "native-inventory" }), + ).error, + ).toMatchObject(invalidIssue("batch_decompile Evidence supports")); + const inventory = (await harness.call("list_procedures", {})).evidence; + expect( + parseMcpToolError( + await inspect(retained(inventory.evidence_id), { + kind: "batch-decompile", + collection: "items", + }), + ).error.code, + ).toBe("invalid_request"); + + // Inline parents authenticate their predicate and result before selection. + const inline = ( + predicateType: string, + result: Evidence["normalized_result"], + ) => + inspect( + { + kind: "inline", + evidence: createEvidence( + undefined, + { id: "fixture", name: "Fixture", version: "1" }, + { + operation: "batch_decompile", + parameters: {}, + result, + predicateType, + confidence: "derived", + authority: "shipped-artifact", + }, + ), + }, + { kind: "batch-decompile", collection: "items" }, + ); + const valid = { + items: [ + { + address: "main", + procedure: { status: "resolved", address: "0x1", name: null }, + status: "ok", + pseudocode: "x", + }, + ], + total: 1, + succeeded: 1, + failed: 0, + }; + // A parent without a target stays explicit rather than inventing identity. + const accepted = await inline("rea.analysis", valid); + expect(viewOf(parseEvidence(accepted.structuredContent))).toMatchObject({ + artifact: null, + decompiling_provider: null, + source_analysis_profile_digest: null, + }); + for (const rejected of [ + await inline("rea.other", valid), + await inline("rea.analysis", { + ...valid, + items: [{ address: "main", status: "ok" }], + }), + ]) + expect(parseMcpToolError(rejected).error.code).toBe("invalid_request"); +}); diff --git a/tests/boundary/mcp/ghidraMcpHarness.ts b/tests/boundary/mcp/ghidraMcpHarness.ts index 5b6a5c5b3e..2be23aa28e 100644 --- a/tests/boundary/mcp/ghidraMcpHarness.ts +++ b/tests/boundary/mcp/ghidraMcpHarness.ts @@ -3,6 +3,7 @@ import type { GhidraJavaObservation } from "../../../src/ghidra/GhidraJavaProbe. import { expect } from "vitest"; import { parseEvidence } from "../../../src/domain/evidence.js"; import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js"; +import type { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js"; import type { BinarySession } from "../../../src/application/binary/BinarySession.js"; import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js"; @@ -33,6 +34,8 @@ export const connectGhidraMcp = async ( readonly sessionTarget?: GhidraSessionInfo["target"]; readonly attestDosTargetSnapshot?: ReturnType["attestDosTargetSnapshot"]; readonly close?: ReturnType["close"]; + readonly environment?: Readonly>; + readonly schemaValidator?: ReturnType; } = {}, ) => { const calls: GhidraOperation[] = []; @@ -72,11 +75,15 @@ export const connectGhidraMcp = async ( const { client: mcp, close } = await createApplicationMcpHarness({ session, clientIdentity: { name, version: "1.0.0" }, + ...(fixture.schemaValidator === undefined + ? {} + : { schemaValidator: fixture.schemaValidator }), serverOptions: { logger: silentLogger, environment: { ...process.env, REA_MCP_MAX_INPUT_ELEMENTS: process.env.REA_MCP_MAX_INPUT_ELEMENTS, + ...fixture.environment, }, }, });