diff --git a/src/application/analysisView/AnalysisViewService.ts b/src/application/analysisView/AnalysisViewService.ts index 2798efcd26..0b964a0baf 100644 --- a/src/application/analysisView/AnalysisViewService.ts +++ b/src/application/analysisView/AnalysisViewService.ts @@ -230,6 +230,7 @@ const projectResolvedAnalysisView = ( analysisProfile: parent.analysis_profile, authority: parent.authority, environment: parent.environment, + rawResult: parent.raw_result, normalizedResult: immutableJsonSnapshotMember(parent, "normalized_result") ?? parent.normalized_result, diff --git a/src/contracts/analysisViewToolContracts.ts b/src/contracts/analysisViewToolContracts.ts index 46baf75bfc..34bea969f6 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: - 'For inspect_api_contract parents, graphql-contract pages retained SDL types/fields, operation definitions, field references, fragment-spreads or diagnostics with exact filters and selected columns. 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. For retained trace_feature Evidence, kind native-feature-trace pages matches, references or unknowns; matches filter exact address, references filter exact source_address and target_address, source_index identifies each original row, and list_unknowns pages durable question heads. Inspect selected views of supported completed Evidence without repeating analysis. For procedure_pseudo_code Evidence, summary reports text availability and the original selection; kind native with facet pseudocode pages the original UTF-16 text. Other native facets require analyze_function. 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 value-flow observations. For parameter type paths when value flow is recorded, use facet: "value_flow_parameters"; its decompiler-observed path may be passed to inspect_native_data_type, but exact database lookup can be unavailable and does not by itself establish type identity. 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: ["unavailable", "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.', + 'For inspect_api_contract parents, graphql-contract pages retained SDL types/fields, operation definitions, field references, fragment-spreads or diagnostics with exact filters and selected columns. 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. For retained trace_feature Evidence, kind native-feature-trace pages matches, references or unknowns; matches filter exact address, references filter exact source_address and target_address, source_index identifies each original row, and list_unknowns pages durable question heads. Inspect selected views of supported completed Evidence without repeating analysis. Use recorded-array with an exact raw_result object-member path to page a provider-recorded array when the producer supplies that path; rows keep their raw meaning and the parent retains coverage. For procedure_pseudo_code Evidence, summary reports text availability and the original selection; kind native with facet pseudocode pages the original UTF-16 text. Other native facets require analyze_function. 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 value-flow observations. For parameter type paths when value flow is recorded, use facet: "value_flow_parameters"; its decompiler-observed path may be passed to inspect_native_data_type, but exact database lookup can be unavailable and does not by itself establish type identity. 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: ["unavailable", "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/domain/analysisView/analysisView.ts b/src/domain/analysisView/analysisView.ts index acda9f113b..956aa8ccdf 100644 --- a/src/domain/analysisView/analysisView.ts +++ b/src/domain/analysisView/analysisView.ts @@ -5,6 +5,7 @@ import { NATIVE_OBSERVATION_OPERATIONS, } from "../native/nativeObservation.js"; import { projectNativeObservationView } from "./nativeObservationView.js"; +import { projectRecordedArrayView } from "./recordedArrayView.js"; import { projectNativeInstructionReferencesView } from "./nativeInstructionReferencesView.js"; import { projectNativeValueTraceView } from "./nativeValueTraceView.js"; import { projectDevicetreeView } from "./devicetreeView.js"; @@ -497,6 +498,9 @@ export const projectAnalysisView = ( }, ]), ); + if (view.kind === "recorded-array") { + return sealProjected(projectRecordedArrayView(parent, view)); + } if (view.kind === "javascript-routes") { const projected = projectJavaScriptRoutesView(parent, view); return sealProjected(projected); diff --git a/src/domain/analysisView/analysisViewParent.ts b/src/domain/analysisView/analysisViewParent.ts index 9de5108195..37d81426f7 100644 --- a/src/domain/analysisView/analysisViewParent.ts +++ b/src/domain/analysisView/analysisViewParent.ts @@ -12,6 +12,7 @@ export interface AnalysisViewParent { readonly operation: string; readonly predicateType: string; readonly normalizedResult: unknown; + readonly rawResult?: unknown; readonly provider?: Evidence["provider"]; readonly analysisProfile?: Evidence["analysis_profile"]; readonly authority?: Evidence["authority"]; diff --git a/src/domain/analysisView/analysisViewRequest.ts b/src/domain/analysisView/analysisViewRequest.ts index a15c12f1d1..b616ab526f 100644 --- a/src/domain/analysisView/analysisViewRequest.ts +++ b/src/domain/analysisView/analysisViewRequest.ts @@ -63,11 +63,23 @@ import { pageViewSchema, summaryViewSchema, } from "./analysisViewShape.js"; +export const recordedArrayViewSchema = z.strictObject({ + kind: z.literal("recorded-array"), + path: z + .array(z.string()) + .describe( + "Exact object-member path from the parent Evidence raw_result to the recorded array. The provider defines the values and their coverage.", + ), + offset: z.int().nonnegative().default(0), + limit: z.int().positive().default(64), +}); + /** Caller-selected projection of already completed analysis Evidence. */ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [ nativeInstructionReferencesRequestSchema, nativeObservationViewRequestSchema, nativeContextViewRequestSchema, + recordedArrayViewSchema, devicetreeViewRequestSchema, erlangBeamViewRequestSchema, pythonPycViewRequestSchema, diff --git a/src/domain/analysisView/analysisViewResult.ts b/src/domain/analysisView/analysisViewResult.ts index 301e68cbeb..d8dfd28848 100644 --- a/src/domain/analysisView/analysisViewResult.ts +++ b/src/domain/analysisView/analysisViewResult.ts @@ -308,6 +308,8 @@ import { pageViewSchema, summaryViewSchema, } from "./analysisViewShape.js"; +import { recordedArrayViewSchema } from "./analysisViewRequest.js"; + const artifactSchema = z.strictObject({ path: z .string() @@ -1202,6 +1204,20 @@ const machoPageViewResultSchema = z /** Projected facts for one selected view of retained analysis Evidence. */ export const analysisViewResultSchema = z.discriminatedUnion("kind", [ + z.strictObject({ + ...viewResultBase, + ...nativeViewSourceContext, + source_parameters: jsonObjectSchema + .nullable() + .describe( + "Null means source parameters were omitted to fit the page; retrieve the parent Evidence.", + ), + parent_operation: z.string(), + artifact: artifactSchema.nullable(), + kind: z.literal("recorded-array"), + view: recordedArrayViewSchema, + rows: z.array(jsonValueSchema), + }), playwrightTracePageViewResultSchema, z.strictObject({ ...viewResultBase, diff --git a/src/domain/analysisView/recordedArrayView.test.ts b/src/domain/analysisView/recordedArrayView.test.ts new file mode 100644 index 0000000000..e94b817549 --- /dev/null +++ b/src/domain/analysisView/recordedArrayView.test.ts @@ -0,0 +1,123 @@ +import { expect, it } from "vitest"; +import { createEvidence } from "../evidence.js"; +import { MAX_JSON_DEPTH, type JsonValue } from "../jsonValue.js"; +import { projectAnalysisError } from "../analysisErrorProjection.js"; +import type { AnalysisViewParent } from "./analysisViewParent.js"; +import { + analysisViewRequestSchema, + projectAnalysisView, +} from "./analysisView.js"; + +const nested = (levels: number): JsonValue => { + let value: JsonValue = "leaf"; + for (let index = 0; index < levels; index += 1) value = { child: value }; + return value; +}; + +const parent = ( + parameters: JsonValue, + row: JsonValue = "row", +): AnalysisViewParent => ({ + predicateType: "rea.analysis", + evidenceId: `ev_${"b".repeat(64)}`, + operation: "xrefs", + normalizedResult: ["0x10"], + rawResult: { values: [row] }, + sealedResult: true, + provider: { id: "fixture", name: "Fixture", version: "1" }, + artifact: null, + subject: null, + parameters, + limitations: [], +}); + +const project = (source: AnalysisViewParent) => + projectAnalysisView( + source, + analysisViewRequestSchema.parse({ + kind: "recorded-array", + path: ["values"], + offset: 0, + limit: 1, + }), + ); + +it("omits parent parameters that would exceed Evidence depth by one level", () => { + // Parameters are one field below the Evidence root. levels === 999 puts the + // leaf at depth 1000 there, and one level deeper under normalized_result. + const parameters = nested(MAX_JSON_DEPTH - 1); + const admitted = createEvidence( + undefined, + { id: "fixture", name: "Fixture", version: "1" }, + { + operation: "xrefs", + parameters, + result: ["0x10"], + rawResult: { values: ["row"] }, + }, + ); + expect(admitted.parameters).toStrictEqual(parameters); + const projected = project(parent(parameters)); + if (!projected.ok) throw projected.error; + expect(projected.value).toMatchObject({ + kind: "recorded-array", + source_parameters: null, + rows: ["row"], + }); + expect(projected.value.limitations.join("\n")).toContain("JSON depth"); + expect(() => + createEvidence( + undefined, + { id: "view", name: "View", version: "1" }, + { + operation: "inspect_analysis_view", + parameters: { parent_evidence_id: admitted.evidence_id }, + result: projected.value, + rawResult: null, + }, + ), + ).not.toThrow(); +}); + +it("keeps parameters that still fit one level below the Evidence root", () => { + const parameters = nested(MAX_JSON_DEPTH - 2); + const projected = project(parent(parameters)); + if (!projected.ok) throw projected.error; + if (projected.value.kind !== "recorded-array") + throw new Error("expected a recorded-array page"); + expect(projected.value.source_parameters).toEqual(parameters); +}); + +it("returns a typed depth refusal instead of throwing when a row cannot be nested", () => { + const projected = project(parent({}, nested(MAX_JSON_DEPTH - 1))); + expect(projected.ok).toBe(false); + if (projected.ok) return; + expect(projectAnalysisError(projected.error)).toMatchObject({ + code: "resource_constraint", + details: { reported_limits: { maximum_json_depth: MAX_JSON_DEPTH } }, + }); + expect(projectAnalysisError(projected.error).remediation.action).toContain( + "JSON depth", + ); +}); + +it("stops before a later row exceeds the output Evidence depth", () => { + const source = parent({}); + const first = nested(MAX_JSON_DEPTH - 3); + const tooDeep = nested(MAX_JSON_DEPTH - 2); + const projected = projectAnalysisView( + { ...source, rawResult: { values: [first, tooDeep, "later"] } }, + analysisViewRequestSchema.parse({ + kind: "recorded-array", + path: ["values"], + offset: 0, + limit: 3, + }), + ); + if (!projected.ok) throw projected.error; + expect(projected.value).toMatchObject({ + kind: "recorded-array", + rows: [first], + coverage: { examined: 1, total: 3, next_offset: 1 }, + }); +}); diff --git a/src/domain/analysisView/recordedArrayView.ts b/src/domain/analysisView/recordedArrayView.ts new file mode 100644 index 0000000000..a6832425ba --- /dev/null +++ b/src/domain/analysisView/recordedArrayView.ts @@ -0,0 +1,187 @@ +import type { z } from "zod"; +import { + jsonValueValidationIssue, + MAX_JSON_DEPTH, + type JsonValue, +} from "../jsonValue.js"; +import { jsonValueByteLength } from "../jsonValueByteLength.js"; +import { AnalysisResourceConstraintError } from "../analysisErrorCore.js"; +import { err, ok } from "../result.js"; +import type { AnalysisViewParent } from "./analysisViewParent.js"; +import { pageViewCoverage } from "./analysisViewCoverage.js"; +import { analysisViewInputError } from "./analysisViewErrors.js"; +import type { recordedArrayViewSchema } from "./analysisViewRequest.js"; + +const PAGE_BYTES = 1024 * 1024; + +/** + * Parent parameters sit on the Evidence root. This page stores them under + * `normalized_result.source_parameters`, one level deeper. A parent that used + * the whole depth budget is valid and still cannot be copied unchanged. + */ +const exceedsEvidenceResultDepth = (result: JsonValue): boolean => + jsonValueValidationIssue({ normalized_result: result }) !== undefined; + +/** A row is nested under normalized_result.rows in the output Evidence. */ +const exceedsRecordedRowDepth = (row: JsonValue): boolean => + jsonValueValidationIssue({ normalized_result: { rows: [row] } }) !== + undefined; + +const recordedArrayDepthRefusal = () => + err( + new AnalysisResourceConstraintError( + "inspect_analysis_view", + "memory", + `Recorded array view exceeds the maximum JSON nesting depth of ${MAX_JSON_DEPTH}.`, + { maximum_json_depth: MAX_JSON_DEPTH }, + { + retryable: false, + remediationAction: + "A recorded value cannot be nested inside an Evidence page without exceeding the JSON depth limit. Retrieve or export the complete parent Evidence, or read it from the caller-supplied Evidence file or bundle.", + }, + ), + ); + +/** Page an exact array within authenticated provider-recorded raw JSON. */ +export const projectRecordedArrayView = ( + parent: AnalysisViewParent, + view: z.output, +) => { + let value: unknown = parent.rawResult; + for (const key of view.path) { + if ( + typeof value !== "object" || + value === null || + Array.isArray(value) || + !Object.hasOwn(value, key) + ) + return err( + analysisViewInputError([ + { + path: ["view", "path"], + reason: "invalid_value", + message: + "The selected path does not identify an object member in recorded raw data.", + }, + ]), + ); + value = (value as Record)[key]; + } + if (!Array.isArray(value)) + return err( + analysisViewInputError([ + { + path: ["view", "path"], + reason: "invalid_value", + message: "The selected recorded raw value is not an array.", + }, + ]), + ); + const rows: JsonValue[] = []; + let result = { + parent_evidence_id: parent.evidenceId, + parent_operation: parent.operation, + parent_digest: parent.evidenceId.slice(3), + source_provider: parent.provider ?? null, + source_analysis_profile_digest: parent.analysisProfile?.digest ?? null, + source_parameters: (parent.parameters ?? {}) as Record< + string, + JsonValue + > | null, + artifact: parent.artifact ?? null, + kind: "recorded-array" as const, + view, + rows, + coverage: pageViewCoverage(view.offset, 0, value.length), + limitations: [ + "These are raw provider-recorded values; interpretation and provider coverage require the parent Evidence.", + "Raw rows may include values excluded from the parent operation's normalized result; use source parameters and parent caveats to interpret their scope.", + ], + unknowns: [], + }; + // Include the sealed digest and reserve the longest numeric coverage fields + // before adding rows. Output transport may impose a smaller separate limit. + const estimateBase = () => + jsonValueByteLength( + { + ...result, + view_digest: "0".repeat(64), + coverage: { + status: "complete-within-view", + examined: Number.MAX_SAFE_INTEGER, + total: Number.MAX_SAFE_INTEGER, + next_offset: Number.MAX_SAFE_INTEGER, + exhausted: false, + }, + }, + PAGE_BYTES, + ); + const omitParameters = (reason: "bytes" | "depth") => { + result = { + ...result, + source_parameters: null, + limitations: [ + ...result.limitations, + reason === "depth" + ? "Source parameters were omitted because nesting them under this Evidence page exceeds the maximum JSON depth; retrieve the parent Evidence for their complete values." + : "Source parameters were omitted to fit the page allowance; retrieve the parent Evidence for their complete values.", + ], + }; + }; + if (result.source_parameters !== null && exceedsEvidenceResultDepth(result)) + omitParameters("depth"); + let bytes = estimateBase(); + if (bytes > PAGE_BYTES) { + omitParameters("bytes"); + bytes = estimateBase(); + } + const tooLarge = () => + err( + new AnalysisResourceConstraintError( + "inspect_analysis_view", + "memory", + "Recorded array view exceeds the 1 MiB page allowance.", + { maximum_page_bytes: PAGE_BYTES }, + { + retryable: false, + remediationAction: + "The selected path or one recorded value exceeds the 1,048,576-byte analysis-view page allowance. Retrieve or export the complete parent Evidence, or read it from the caller-supplied Evidence file or bundle.", + }, + ), + ); + if (bytes > PAGE_BYTES) return tooLarge(); + const end = Math.min(value.length, view.offset + view.limit); + for (let i = view.offset; i < end; i++) { + const row = value[i] as JsonValue; + const comma = rows.length === 0 ? 0 : 1; + let size = jsonValueByteLength(row, PAGE_BYTES - bytes - comma); + if ( + bytes + comma + size > PAGE_BYTES && + rows.length === 0 && + result.source_parameters !== null + ) { + omitParameters("bytes"); + bytes = estimateBase(); + if (bytes > PAGE_BYTES) return tooLarge(); + size = jsonValueByteLength(row, PAGE_BYTES - bytes); + } + if (bytes + comma + size > PAGE_BYTES) { + if (rows.length === 0) return tooLarge(); + break; + } + // The fixed fields are checked separately. Validate only this row at its + // final nesting depth; previously accepted rows cannot change, so walking + // the growing page for every row repeats the same work quadratically. + if (exceedsRecordedRowDepth(row)) { + if (rows.length === 0) return recordedArrayDepthRefusal(); + break; + } + bytes += comma + size; + rows.push(row); + } + if (exceedsEvidenceResultDepth(result)) return recordedArrayDepthRefusal(); + return ok({ + ...result, + coverage: pageViewCoverage(view.offset, rows.length, value.length), + }); +}; diff --git a/src/kuna/KunaSessionClient.ts b/src/kuna/KunaSessionClient.ts index f9ed36d4ab..b56d93deda 100644 --- a/src/kuna/KunaSessionClient.ts +++ b/src/kuna/KunaSessionClient.ts @@ -1089,6 +1089,12 @@ export class KunaSessionClient implements AnalysisClient { locations, limitations: [ ...limitations, + ...(references.value.pointers !== null && + references.value.pointers.length > 0 + ? [ + 'The recorded pointer rows can be paged from this Evidence with inspect_analysis_view: view {"kind":"recorded-array","path":["references","pointers"]}. These raw Kuna rows may include alias targets; compare each row\'s to_address with the selected address before treating it as an exact-target reference.', + ] + : []), ...(references.value.pointerCoverage === null ? [] : [ diff --git a/src/server/EvidenceMcpServerCore.ts b/src/server/EvidenceMcpServerCore.ts index b0a089172b..a6369dd467 100644 --- a/src/server/EvidenceMcpServerCore.ts +++ b/src/server/EvidenceMcpServerCore.ts @@ -1039,9 +1039,12 @@ class ErrorEvidenceTransport implements Transport { "The MCP tool arguments exceed the configured input element allowance; schema validation and tool execution did not start.", { max_input_elements: this.maximumInputElements }, { - remediationAction: this.evidenceReferenceAlternatives.has(tool) - ? 'If the source Evidence is retained, use {"kind":"retained-evidence","evidence_id":"ev_..."} for declared Evidence fields; use a summary\'s parent_evidence_id for its complete source. Otherwise import the originating Evidence bundle when available. Reduce the arguments, or restart REA with a larger REA_MCP_MAX_INPUT_ELEMENTS allowance.' - : "Reduce the combined array elements and object members in the arguments, or restart REA with a larger REA_MCP_MAX_INPUT_ELEMENTS allowance for this workload.", + remediationAction: + tool === "inspect_analysis_view" + ? 'If using inline Evidence, save the Evidence record as a local JSON file and use source {"kind":"evidence-file","path":"..."}; if it is retained, use its retained-evidence ID. Otherwise reduce the combined array elements and object members, or restart REA with a larger REA_MCP_MAX_INPUT_ELEMENTS allowance.' + : this.evidenceReferenceAlternatives.has(tool) + ? 'If the source Evidence is retained, use {"kind":"retained-evidence","evidence_id":"ev_..."} for declared Evidence fields; use a summary\'s parent_evidence_id for its complete source. Otherwise import the originating Evidence bundle when available. Reduce the arguments, or restart REA with a larger REA_MCP_MAX_INPUT_ELEMENTS allowance.' + : "Reduce the combined array elements and object members in the arguments, or restart REA with a larger REA_MCP_MAX_INPUT_ELEMENTS allowance for this workload.", }, ); const result = this.delivery.toErrorToolResult(error, targetContent); diff --git a/tests/boundary/mcp/analysisViewMcp.test.ts b/tests/boundary/mcp/analysisViewMcp.test.ts index bba6e199ce..69bd684014 100644 --- a/tests/boundary/mcp/analysisViewMcp.test.ts +++ b/tests/boundary/mcp/analysisViewMcp.test.ts @@ -2058,3 +2058,145 @@ it("projects an environment manifest identically from retained, portable and fil expect(JSON.stringify(refused)).not.toContain("/api/folders"); await client.ping(); }); + +it("pages retained raw array rows without losing the parent and refuses an oversized row", async () => { + const { client, session } = await connect(); + const rows = [ + { from_address: "0x10", to_address: "0x20", source: "fixups" }, + { from_address: "0x18", to_address: "0x20", source: "fixups" }, + { from_address: "0x20", name: "x".repeat(1024 * 1024) }, + ]; + const parent = createEvidence( + { path: "/fixtures/raw-native", format: "mach-o", sha256: "e".repeat(64) }, + { id: "fixture", name: "Fixture", version: "1" }, + { + operation: "xrefs", + parameters: { address: "0x20" }, + result: ["0x10", "0x18", "0x20"], + rawResult: { references: { pointers: rows } }, + }, + ); + expect(session.recordEvidence(parent).ok).toBe(true); + const call = (offset: number, limit: number) => + client.callTool({ + name: "inspect_analysis_view", + arguments: { + source: { kind: "retained-evidence", evidence_id: parent.evidence_id }, + view: { + kind: "recorded-array", + path: ["references", "pointers"], + offset, + limit, + }, + }, + }); + const first = await call(0, 10); + expect(first.isError).not.toBe(true); + const parsed = toolContract("inspect_analysis_view").outputSchema.parse( + first.structuredContent, + ); + expect(parsed.normalized_result).toMatchObject({ + kind: "recorded-array", + parent_evidence_id: parent.evidence_id, + source_provider: { id: "fixture", name: "Fixture", version: "1" }, + source_analysis_profile_digest: null, + source_parameters: { address: "0x20" }, + limitations: expect.arrayContaining([ + expect.stringContaining( + "excluded from the parent operation's normalized result", + ), + ]), + rows: rows.slice(0, 2), + coverage: { examined: 2, total: 3, next_offset: 2 }, + }); + expect(parsed.evidence_links).toEqual([parent.evidence_id]); + const oversized = parseMcpToolError(await call(2, 1)).error; + expect(oversized.code).toBe("resource_constraint"); + expect(oversized.remediation.action).toContain("1,048,576-byte"); + expect((await call(0, 1)).isError).not.toBe(true); +}); + +it("directs oversized inline Evidence to a usable file source", async () => { + const { client } = await connect(undefined, undefined, 32); + const parent = analysisViewNativeEvidence(); + const view = { kind: "native", facet: "procedure", offset: 0, limit: 1 }; + const inline = await client.callTool({ + name: "inspect_analysis_view", + arguments: { source: { kind: "inline", evidence: parent }, view }, + }); + const error = parseMcpToolError(inline).error; + expect(error.code).toBe("resource_constraint"); + expect(error.remediation.action).toContain("evidence-file"); + + const root = await createTestTempDirectory("rea-view-input-capacity-"); + const path = join(root, "evidence.json"); + await writeFile(path, JSON.stringify(parent)); + const fromFile = await client.callTool({ + name: "inspect_analysis_view", + arguments: { source: { kind: "evidence-file", path }, view }, + }); + expect(fromFile.isError).not.toBe(true); + const parsed = toolContract("inspect_analysis_view").outputSchema.parse( + fromFile.structuredContent, + ); + expect(parsed.normalized_result).toMatchObject({ + parent_evidence_id: parent.evidence_id, + }); +}); + +it.each([ + { queryBytes: 1024 * 1024, rowBytes: 0 }, + { queryBytes: 600_000, rowBytes: 600_000 }, +])( + "pages a recorded row when its parent parameters do not fit", + async ({ queryBytes, rowBytes }) => { + const { client, session } = await connect(); + const { ajv, outputSchema } = await advertisedMcpToolSchemas( + client, + "inspect_analysis_view", + schemaValidation.assertions, + ); + const parent = createEvidence( + { + path: "/fixtures/large-context", + format: "elf", + sha256: "f".repeat(64), + }, + { id: "fixture", name: "Fixture", version: "1" }, + { + operation: "xrefs", + parameters: { query: "x".repeat(queryBytes) }, + result: ["0x10"], + rawResult: { + values: [{ address: "0x10", data: "y".repeat(rowBytes) }], + }, + }, + ); + expect(session.recordEvidence(parent).ok).toBe(true); + const response = await client.callTool({ + name: "inspect_analysis_view", + arguments: { + source: { kind: "retained-evidence", evidence_id: parent.evidence_id }, + view: { kind: "recorded-array", path: ["values"], offset: 0, limit: 1 }, + }, + }); + expect(response.isError).not.toBe(true); + expect( + ajv.validate(outputSchema, response.structuredContent), + JSON.stringify(ajv.errors), + ).toBe(true); + const parsed = toolContract("inspect_analysis_view").outputSchema.parse( + response.structuredContent, + ); + expect(parsed.normalized_result).toMatchObject({ + kind: "recorded-array", + parent_evidence_id: parent.evidence_id, + source_provider: { id: "fixture", name: "Fixture", version: "1" }, + source_parameters: null, + limitations: expect.arrayContaining([ + expect.stringContaining("omitted to fit the page allowance"), + ]), + rows: [{ address: "0x10", data: "y".repeat(rowBytes) }], + }); + }, +); diff --git a/tests/boundary/providers/kuna/fakeKuna.ts b/tests/boundary/providers/kuna/fakeKuna.ts index 51e68f4f3b..5c2bad9199 100644 --- a/tests/boundary/providers/kuna/fakeKuna.ts +++ b/tests/boundary/providers/kuna/fakeKuna.ts @@ -75,6 +75,8 @@ export interface FakeKunaBehavior { /** Bytes of an extra root member in the graph JSON. */ readonly graphPadding?: number; readonly xrefs?: "ok" | "hang" | "not-json"; + /** Include stored pointers to the selected target and its forwarding alias. */ + readonly pointerAliasReferences?: boolean; /** Additional exact-target incoming call-site addresses. */ readonly extraXrefSources?: readonly number[]; readonly referenceDelayMs?: number; @@ -163,7 +165,9 @@ if (args[0] === "--version") { const row = (from, to, kind) => ({ address: from, address_hex: "0x" + from.toString(16), from_address: from, from_address_hex: "0x" + from.toString(16), to_address: to, to_address_hex: "0x" + to.toString(16), kind, from_function: identity("main", 4096), to_function: null, instruction: "fixture reference" + "x".repeat(behavior.referencePadding ?? 0) }); const rows = [4100, ...(behavior.extraXrefSources ?? [])].map((source) => row(source, parseInt(target, 16), "call")); if (aliases.length) rows.push(row(4164, 12288, "call")); - setTimeout(() => process.stdout.write(JSON.stringify({ binary: args[1], direction: "to", count: rows.length, target: { ...identity(null, parseInt(target, 16)), aliases }, xrefs: rows })), behavior.referenceDelayMs ?? 0); + const pointer = (from, to) => ({ kind: "pointer", from_address: from, from_address_hex: "0x" + from.toString(16), from_name: null, to_address: to, to_address_hex: "0x" + to.toString(16), to_name: null, width: 8, source: "dynamic-relocations" }); + const pointers = behavior.pointerAliasReferences ? [pointer(4352, parseInt(target, 16)), pointer(4368, 12288)] : undefined; + setTimeout(() => process.stdout.write(JSON.stringify({ binary: args[1], direction: "to", count: rows.length, target: { ...identity(null, parseInt(target, 16)), aliases }, xrefs: rows, ...(pointers ? { data_refs: pointers, data_refs_count: pointers.length, data_refs_coverage: "dynamic-relocations" } : {}) })), behavior.referenceDelayMs ?? 0); } } else if (args[0] === "decompile-project") { const input = args[1]; diff --git a/tests/boundary/providers/kuna/kunaReferences.test.ts b/tests/boundary/providers/kuna/kunaReferences.test.ts index 56cd7f2b18..c221e049e8 100644 --- a/tests/boundary/providers/kuna/kunaReferences.test.ts +++ b/tests/boundary/providers/kuna/kunaReferences.test.ts @@ -235,6 +235,30 @@ it("filters forwarding aliases and reuses exact-address xrefs without inventory } }); +it("distinguishes exact xrefs from recorded pointer rows to forwarding aliases", async () => { + const { open } = await session("rea-kuna-pointer-alias-", { + version: { stdout: "kuna 1.990\n" }, + pointerAliasReferences: true, + }); + const client = open(); + try { + const answer = await run(client, "xrefs", { address: "0x2000" }); + expect(answer.result).toEqual(["0x1004", "0x1100"]); + expect(answer.rawResult).toMatchObject({ + references: { + pointers: [{ to_address: "0x2000" }, { to_address: "0x3000" }], + }, + }); + expect(answer.limitations).toEqual( + expect.arrayContaining([ + expect.stringContaining("compare each row's to_address"), + ]), + ); + } finally { + await client.close(); + } +}); + it("resolves an xref procedure name without starting the project export", async () => { const { open, kuna } = await session("rea-kuna-named-xrefs-"); const client = open();