From 123b693f0877181115b8fd7ad800ecfd566f22c0 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:25:18 -0500 Subject: [PATCH] feat(delivery)!: bound default results by an agent result budget (#14252) * feat(delivery)!: bound default results by an agent result budget Omitted detail now returns complete Evidence only when it fits the new delivery.agent_result_budget_bytes runtime setting (default 49152 compact JSON bytes, about 12k tokens at an estimated 4 bytes per token). Larger results are retained and delivered as the producer's summary with a limitation naming the budget and the recovery call; nothing is refused or truncated. inspect_analysis_view gains an evidence-json view that pages the exact JSON text of retained Evidence. The CLI applies the same budget and publishes the complete bundle with --evidence_output. inspect_managed_members type_names now also narrows member_refs and exported_types, and inspect-byte-entropy gains CLI evidence delivery. BREAKING CHANGE: An omitted detail no longer always returns complete Evidence inline on MCP or the CLI for tools with a detail selector (including inspect_managed_members, inspect_managed_artifact, inspect_byte_entropy, inspect_artifact, analyze_javascript_application, list_procedures, list_strings and the other operations listed in src/domain/agentBudgetOperations.ts). Over the budget they return the retained summary; pass detail complete (--detail complete) for complete inline delivery. inspect_managed_members type_names narrows member_refs and exported_types. Fixes #14172 Fixes #14180 Part of #14187 Part of #14156 * test(schemas): record advertised summaries for budgeted detail * fix(delivery): keep budgeted summaries canonical and carry delivery facts beside them Review fixes for the agent result budget: - Deliver the producer's own summary record, identical to detail summary, so its identity holds in summary consumers such as compare_artifacts. The budget, sizes, retention and the exact paging call travel as delivery facts: a second MCP text block and _meta, or a delivery field in CLI output. - Capture the caller's detail for application-validated tools too, so inspect_binary_layout and similar tools are budgeted. - Keep recovery facts when a budgeted summary itself exceeds the frame. - Size an omitted evidence-json limit by escaped UTF-8 bytes and never split a surrogate pair, even in a one-unit page. - Add the REA_AGENT_RESULT_BUDGET_BYTES launch seed; the shared test environment raises it for semantic tests, and budget tests clear it. - Align tool descriptions and verifiers that read complete Evidence. * fix(delivery): retain the budgeted summary like an explicit summary * fix(delivery): read the budget seed from the captured environment and count delivery facts in the frame - The agent result budget seed is read from the environment the server or CLI invocation captured: ToolResultDelivery takes it at construction, and a CLI invocation binds it in its publication context. The ambient process environment is no longer read. - The frame check reserves the bytes of the delivery block and _meta that are added after encoding, so a budgeted response cannot exceed the frame. - Conformance workflows that resend complete Evidence raise the budget through the shared inline-Evidence environment, as do the artifact and binary layout verifiers. * fix(delivery)!: request complete Evidence explicitly and never spill CLI overflow - Shared test and verifier environments no longer raise the agent result budget. Every test and verifier workflow that reads complete Evidence from a budgeted tool now requests it with detail complete or --detail complete, including the real-provider verifiers outside PR CI (Ghidra, Hopper, IDA, Kuna and client verifiers). Default delivery is exercised as shipped. - Budgeting applies only to tools with a detail selector, so every budgeted call has a complete opt-out. - CLI overflow without --evidence_output writes nothing; its delivery facts carry exact rerun argv for --detail complete and --evidence_output, omitted when the command declares sensitive values. * test(delivery): prove captured budget seeds with valid in-range values * test: state complete-detail requests once and fix codemod regressions - Add tests/support/completeDetail.ts with COMPLETE_DETAIL and completeArguments so tests that read complete Evidence request it in one place, keeping functions within max-lines-per-function without raising the limit. - Restore provider-client tests (GhidraClient, Hopper health): their callTool("name", ...) calls are bridge requests, not MCP tools, and take no detail. - Update the game-scale type inventory test for member_refs narrowing. * test: request complete Evidence in shared JavaScript analysis helpers and remaining CLI workflows * test: request complete Evidence by default in the shared test transports The shared MCP client helpers (createTestMcp, connectLocalToolsMcp and the CLI fixture's shared MCP session) and the CLI runners (the cli fixture and the shared CLI session) now apply one named default, completeEvidenceByDefault. A budgeted tool called with neither detail nor view gets detail complete; the CLI does the same with --detail complete, chosen by the command's tool contract. A budgeted operation that resolves to no contract fails loudly at load. Tests whose subject is delivery opt out with delivery "budgeted". This is a test-harness choice; production delivery is unchanged and the budget tests prove the default path. Per-call complete-detail edits are reverted in the 204 test files whose transports all apply the default. Explicit requests remain where a test drives its own SDK client, server, CLI instance or process, and where the detail choice is the test's subject. * test: resolve CLI complete-detail defaults from the CLI registry The Real Apple and browser verifiers read complete Evidence through artifactCliEvidence, which ran the compiled CLI without a detail choice and got the budgeted {summary, delivery} output. The helper now requests complete Evidence for commands that take --detail, read from the compiled CLI's own registry (scripts/lib/complete-evidence-cli.mjs). The test harness default had a sibling bug: it treated every cli-flagged budgeted contract as taking --detail, but only Evidence-delivery commands do (inspect-binary-layout does not). It now reads the source CLI registry too, and covers every command the CLI budgets. * test(verifiers): request complete Evidence at each verifier's SDK client and CLI argv The real-browser failure was the same missing normalized_result as the Apple one: browser-capture-metadata-budget-e2e reads analyze-web-bundle through artifactCliEvidence, fixed in the previous commit. The shared verifier module, scripts/lib/complete-evidence.mjs, now owns both transports: - completeEvidenceClient wraps each verifier's SDK Client once, so every callTool to a budgeted tool with neither detail nor view requests complete Evidence, whatever local call helper a verifier uses (86 clients, including the Ghidra, Hopper, IDA and Kuna verifiers' argument-less list_procedures and inspect_native_load_image calls). - completeEvidenceCliArguments covers the remaining verifier CLI argv that chose no detail, such as function, decompile, analyze and the Android and Apple commands. Commands and tools that are not budgeted are sent as written. * test(delivery): await async completeEvidenceCliArguments helper in boundary test * test(delivery): request complete detail in Electron CLI artifact format test * docs(delivery): document delivery.rerun as add-only argument arrays * test(schemas): record advertised summaries for the unified delivery budget Tool descriptions now name the agent result budget, and the evidence-json default page is derived from the 32 KiB default, which changes the advertised input digests of the 28 affected tools. Recorded from the Build package job's output. * test(delivery): pin the budget boundary and keep failures unbudgeted Main's retainedSummaryDelivery tests pinned the size decision at exactly 32,768 and 32,769 UTF-8 JSON bytes. Unifying that decision into budgetedSummaryBytes deleted them, and their port never landed, so the byte measurement went unchecked. Restore them against budgetedSummaryBytes at the configured budget and one byte over, for the default and a runtime budget, with ASCII, escaped and multibyte text, plus each condition of the decision. Off-by-one mutants (< for <=, a cap one byte short) fail six cases; measuring UTF-16 code units instead of UTF-8 bytes fails the multibyte cases. An MCP case pins that a target failure from a budgeted tool under the minimum budget is identical with detail omitted and complete, with no delivery facts. * test(verifiers): route literal CLI argv for budgeted commands through complete Evidence real-browser failed with "Scenario CLI did not report external disconnect ownership": runScenarioCli ran capture-browser-scenario without --detail, so an over-budget capture came back as its summary, which has no browser.cleanup. The earlier sweep counted these files as covered because their MCP clients were wrapped, but their CLI argv was not. Route the shared runScenarioCli helper (five callers), the local cli helpers in the module, source-map and script-export verifiers, and every other literal argv for a budgeted CLI command without --detail or --view (EVM interface, binary layout, packet capture, devicetree, DOM destinations, Ghidra relocation symbols, WABT cleanup, Termux browser) through completeEvidenceCliArguments. A sweep of scripts/ for budgeted command literals with --json and no detail selection now finds none. * fix(verifiers): leave clients without callTool unwrapped The native verifier cleanup test drives native-value-e2e with a connection double whose Client has only connect and close. completeEvidenceClient bound client.callTool unconditionally, so wrapping threw a TypeError before connect ran. That TypeError replaced the primary connection failure the test asserts is preserved, and all four fault cases failed in Test shard 5 and Portable tests. A client without callTool has no tool call to complete, so the helper now returns it unchanged. Locally all five fault modes of the fixture now exit 0. * fix(delivery): keep the catalog recorder on shipped helpers and expect view-implied summary The verifier sweep wrapped record-mcp-catalog.mjs in completeEvidenceClient, which lives in an unshipped helper. deferredRuntime copies only the package's shipped files plus the recorder, so the recorder failed to load (ERR_MODULE_NOT_FOUND) and its cleanup recorder never wrote. The recorder only lists tools and prompts, so the wrapper had no effect; it is removed. This branch makes a view with no --detail select summary delivery, as MCP does for a view. Three CLI cases still expected the old view refusal; with a view alone the missing input is now the summary bundle, so they expect evidence_output, and a view with --detail complete still refuses the view. * fix(delivery): request complete Evidence where callers need the whole result Budgeted delivery made four callers receive a summary they cannot use: - The GitHub Actions example uploads the analysis as a CI artifact, so it now asks for --detail complete; over budget it had saved a summary. - javascriptIntegrityPolicyCli spawns the CLI itself, outside the test harness default, and reads normalized_result; it now applies the same completeEvidenceCliArguments default. - nativeObservationViewsMcp builds its own client to prove complete observations overflow into a paging continuation; it now applies the harness default so each call asks for complete Evidence. - The CLI parity goldens are re-recorded for the --detail and --evidence_output options the budgeted commands now advertise. * fix(tests): give processes tests spawn the largest agent result budget About 90 tests spawn scripts/rea.mjs or a server directly, outside the harness default that asks for complete Evidence, and read analysis facts from the result. Over the default budget they received a summary instead; javascriptChildHandleOwnership failed this way. The Vitest environment now seeds REA_AGENT_RESULT_BUDGET_BYTES with the largest accepted value, so a spawned CLI or server delivers complete Evidence, as the in-process default does. Delivery tests keep their own budget: agentResultBudgetMcp builds its server without the seed, so its default-budget cases still exercise the shipped default. * fix(tests): give budgeted harness tests the shipped agent result budget The test environment seeds the largest agent result budget so spawned processes deliver complete Evidence. In-memory servers built by createApplicationMcpHarness (and connectGhidraMcp, which uses it) inherit process.env too, so a test that chose testDelivery "budgeted" kept the seed: the 600-row list_procedures case and the omitted-detail web page views returned complete Evidence instead of a summary. testDeliveryEnvironment now owns that choice: a budgeted test's server environment drops the seed and uses the shipped default. The application harness applies it to every server it builds. * fix(tests): expect view-implied summary delivery in the Playwright trace refusal A view with no --detail now selects summary delivery, so its refusal names the missing evidence_output bundle; --detail complete still refuses the view. The trace test still expected a view refusal in both cases. --- docs/guides/managed/managed-code-analysis.md | 24 +- docs/guides/web/browser-observation.md | 2 +- docs/reference/limits-and-recovery.md | 53 ++ docs/reference/mcp-contracts.md | 14 +- docs/reference/rea-limit-inventory.md | 5 + examples/github-actions/rea-analysis.yml | 2 +- scripts/lib/advertised-catalog.mjs | 5 +- scripts/lib/artifact-e2e.mjs | 21 +- .../browser-capture-metadata-budget-e2e.mjs | 7 +- scripts/lib/browser-dom-destinations-e2e.mjs | 24 +- scripts/lib/browser-module-e2e.mjs | 13 +- scripts/lib/browser-nested-source-map-e2e.mjs | 2 + scripts/lib/browser-network-e2e.mjs | 17 +- scripts/lib/browser-popup-e2e.mjs | 12 +- scripts/lib/browser-request-e2e.mjs | 6 +- scripts/lib/browser-runtime-e2e.mjs | 5 +- .../lib/browser-scenario-environment-e2e.mjs | 21 +- ...wser-scenario-storage-fingerprints-e2e.mjs | 19 +- scripts/lib/browser-scenario-verifier.mjs | 24 +- scripts/lib/browser-screenshot-e2e.mjs | 15 +- scripts/lib/browser-script-export-e2e.mjs | 36 +- scripts/lib/browser-source-map-e2e.mjs | 15 +- scripts/lib/browser-url-userinfo-e2e.mjs | 6 +- scripts/lib/complete-evidence.d.mts | 13 + scripts/lib/complete-evidence.mjs | 151 ++++++ scripts/lib/ghidra-reference-snapshot-e2e.mjs | 19 +- scripts/lib/kuna-reference-verifier.mjs | 21 +- scripts/lib/kuna-string-verifier.mjs | 11 +- scripts/lib/large-result-mcp.mjs | 5 +- scripts/lib/mcp-startup-probe.mjs | 21 +- scripts/lib/native-value-e2e.mjs | 36 +- scripts/lib/real-ghidra-batch-identity.mjs | 5 +- scripts/lib/real-ghidra-boundaries.mjs | 92 +++- .../lib/real-ghidra-compact-references.mjs | 6 +- scripts/lib/real-ghidra-entry-aliases.mjs | 56 +- scripts/lib/real-ghidra-file-offsets.mjs | 31 +- scripts/lib/real-ghidra-instruction-flow.mjs | 2 + scripts/lib/real-ghidra-large-results.mjs | 10 +- .../lib/real-ghidra-namespace-annotations.mjs | 2 + scripts/lib/real-ghidra-project-identity.mjs | 30 +- .../lib/real-ghidra-relocation-symbols.mjs | 13 +- scripts/lib/real-ghidra-search-facts.mjs | 1 + scripts/lib/real-ghidra-socket-boundary.mjs | 28 +- scripts/lib/real-ghidra-target-admission.mjs | 8 +- scripts/lib/real-hopper-boundaries.mjs | 72 ++- scripts/lib/real-hopper-function-basics.mjs | 8 +- scripts/lib/real-hopper-owner-exit.mjs | 7 +- scripts/lib/real-hopper-search.mjs | 54 +- scripts/lib/real-hopper-semantic.mjs | 7 +- scripts/lib/real-hopper-workflows.mjs | 30 +- scripts/lib/release-package-canary.mjs | 5 +- scripts/lib/verify-wabt-cleanup.mjs | 18 +- scripts/verify-apk-signature.mjs | 18 +- scripts/verify-binary-layout.mjs | 71 ++- scripts/verify-cline-client.mjs | 5 +- scripts/verify-deno-standalone.mjs | 18 +- scripts/verify-evm-interface.mjs | 50 +- scripts/verify-flutter.mjs | 5 +- scripts/verify-go-binary.mjs | 16 +- scripts/verify-http3-network-captures.mjs | 13 +- scripts/verify-il2cpp-metadata.mjs | 17 +- scripts/verify-package-artifact.mjs | 14 +- scripts/verify-package-managed.mjs | 16 +- scripts/verify-package-mcp.mjs | 9 +- scripts/verify-packaged-ghidra-windows.mjs | 45 +- scripts/verify-packet-capture.mjs | 17 +- scripts/verify-pcap.mjs | 5 +- scripts/verify-qlog-captures.mjs | 15 +- scripts/verify-real-browser.mjs | 5 +- scripts/verify-real-cutter.mjs | 11 +- scripts/verify-real-ghidra-6502.mjs | 75 ++- .../verify-real-ghidra-address-context.mjs | 69 ++- scripts/verify-real-ghidra-checkpoints.mjs | 17 +- scripts/verify-real-ghidra-com.mjs | 22 +- scripts/verify-real-ghidra-cortex-m.mjs | 38 +- scripts/verify-real-ghidra-dol.mjs | 6 +- scripts/verify-real-ghidra-dos.mjs | 12 +- scripts/verify-real-ghidra-m68k.mjs | 24 +- .../verify-real-ghidra-mips-relocatable.mjs | 27 +- scripts/verify-real-ghidra-mips-shared.mjs | 11 +- scripts/verify-real-ghidra-mips.mjs | 67 ++- scripts/verify-real-ghidra-mips32-shared.mjs | 28 +- scripts/verify-real-ghidra-nativeaot.mjs | 17 +- scripts/verify-real-ghidra-ppc.mjs | 23 +- scripts/verify-real-ghidra-ppc64.mjs | 23 +- .../verify-real-ghidra-project-coverage.mjs | 11 +- scripts/verify-real-ghidra-raw.mjs | 25 +- scripts/verify-real-ghidra-riscv.mjs | 37 +- scripts/verify-real-ghidra-swift.mjs | 11 +- scripts/verify-real-ghidra-switch.mjs | 5 +- scripts/verify-real-hopper-callers.mjs | 34 +- scripts/verify-real-hopper-fat.mjs | 5 +- scripts/verify-real-hopper.mjs | 9 +- scripts/verify-real-ida.mjs | 40 +- scripts/verify-real-kuna.mjs | 12 +- scripts/verify-reconstruction-readiness.mjs | 27 +- scripts/verify-signal-recording.mjs | 5 +- scripts/verify-wasm-artifact.mjs | 13 +- scripts/verify-wasm-interface-comparison.mjs | 13 +- scripts/verify-web-network-captures.mjs | 15 +- .../tools/batch_decompile.json | 2 +- .../tools/capture_browser_scenario.json | 2 +- .../advertised-schemas/tools/gdb_console.json | 2 +- .../tools/get_call_graph.json | 2 +- .../tools/inspect_analysis_settings.json | 2 +- .../tools/inspect_binary_layout.json | 2 +- .../tools/inspect_byte_entropy.json | 2 +- .../tools/inspect_devicetree.json | 2 +- .../tools/inspect_elf_dependencies.json | 2 +- .../tools/inspect_evm_interface.json | 2 +- .../tools/inspect_go_binary.json | 2 +- .../tools/inspect_managed_artifact.json | 2 +- .../tools/inspect_managed_members.json | 2 +- .../tools/inspect_native_exports.json | 2 +- .../tools/inspect_native_load_image.json | 2 +- .../tools/inspect_pcap_capture.json | 2 +- .../tools/inspect_wasm_artifact.json | 2 +- .../tools/inspect_web_network_capture.json | 2 +- .../tools/inspect_web_page.json | 2 +- .../tools/inspect_with_objdump.json | 2 +- .../advertised-schemas/tools/list_names.json | 2 +- .../tools/list_procedures.json | 2 +- .../tools/list_strings.json | 2 +- .../tools/procedure_address.json | 2 +- .../tools/procedure_callees.json | 2 +- .../tools/procedure_callers.json | 2 +- .../tools/procedure_pseudo_code.json | 2 +- .../tools/procedure_references.json | 2 +- .../tools/resolve_containing_procedure.json | 2 +- .../tools/search_procedures.json | 2 +- .../tools/search_strings.json | 2 +- .../tools/trace_feature.json | 2 +- .../tools/update_analysis_settings.json | 2 +- scripts/verify/android/analysis.mjs | 20 +- scripts/verify/android/bridge-catalog.mjs | 5 +- scripts/verify/android/cli-cancellation.mjs | 11 +- scripts/verify/android/direct-invokes.mjs | 11 +- scripts/verify/android/external-invokes.mjs | 29 +- scripts/verify/android/failure-recovery.mjs | 30 +- scripts/verify/android/method-bodies.mjs | 33 +- scripts/verify/android/windows-lifecycle.mjs | 34 +- scripts/verify/apple/macho-occurrences.mjs | 2 +- scripts/verify/apple/native-provenance.mjs | 2 +- scripts/verify/electron/tool-contracts.mjs | 6 +- scripts/verify/firmware/analysis.mjs | 12 +- scripts/verify/firmware/devicetree.mjs | 9 +- scripts/verify/firmware/esp-image-tools.mjs | 10 +- scripts/verify/harmony/analysis.mjs | 26 +- .../verify/inspector/runtime-observation.mjs | 11 +- .../verify/javascript/module-references.mjs | 19 +- scripts/verify/javascript/native-handoffs.mjs | 11 +- scripts/verify/javascript/recovery.mjs | 12 +- scripts/verify/javascript/retained-facts.mjs | 11 +- scripts/verify/mcp-client-validation.mjs | 3 +- scripts/verify/recorded-crash/public.mjs | 5 +- scripts/verify/termux/browser.mjs | 9 +- .../analysisView/AnalysisViewService.ts | 24 + .../analysisView/EvidenceJsonView.test.ts | 164 ++++++ src/cli/analysisEvidenceDelivery.ts | 132 ++++- src/cli/analysisEvidenceDeliveryOptions.ts | 14 +- src/cli/binaryDiagnosticsCommands.ts | 7 +- src/cli/cliEvidencePublication.ts | 20 +- src/cli/contractCliDescription.ts | 4 +- src/cli/contractCliDescriptionTypes.ts | 4 +- src/cli/contractCliDocumentDescription.ts | 2 +- src/cli/coreBinaryCommands.ts | 4 +- src/cli/javascriptApplicationAnalysis.ts | 2 +- src/cli/runCliCommand.ts | 50 +- src/config/analysisSettings.ts | 2 + src/contracts/analysisDetail.test.ts | 49 ++ src/contracts/analysisDetail.ts | 26 +- src/contracts/android/androidToolContracts.ts | 6 +- src/contracts/browserScenarioToolContracts.ts | 2 +- src/contracts/browserToolContracts.ts | 8 +- src/contracts/enhancedToolContracts.ts | 13 +- src/contracts/erlang/beamToolContracts.ts | 2 +- src/contracts/flutter/flutterToolContracts.ts | 2 +- src/contracts/fridaToolContracts.ts | 2 +- src/contracts/gdbToolContracts.ts | 2 +- src/contracts/go/goToolContracts.ts | 2 +- src/contracts/managed/managedToolContracts.ts | 4 +- .../native/binaryDiagnosticsToolContracts.ts | 2 +- src/contracts/officialToolContracts.ts | 27 +- src/contracts/pcap/pcapToolContracts.ts | 2 +- .../python/pythonPycToolContracts.ts | 2 +- .../reverseEngineeringToolContracts.ts | 2 +- src/contracts/rust/rustToolContracts.ts | 2 +- src/contracts/wasm/wasmToolContracts.ts | 2 +- .../webNetworkCaptureToolContracts.ts | 2 +- src/domain/agentBudgetOperations.ts | 52 ++ src/domain/agentResultBudget.test.ts | 119 +++++ src/domain/agentResultBudget.ts | 210 ++++++++ src/domain/analysisResourceLimits.ts | 16 + src/domain/analysisSettingDefinitions.ts | 15 + src/domain/analysisSettings.ts | 1 + src/domain/analysisView/analysisView.ts | 3 + src/domain/analysisView/analysisViewParent.ts | 2 + .../analysisView/analysisViewRequest.ts | 2 + src/domain/analysisView/analysisViewResult.ts | 13 + src/domain/analysisView/evidenceJsonView.ts | 242 +++++++++ src/domain/analysisView/managedMemberView.ts | 2 +- src/domain/commandObservation.ts | 4 +- src/domain/go/goBinary.ts | 4 +- src/dotnet/ManagedMemberInspector.test.ts | 22 +- src/dotnet/ManagedMemberInspector.ts | 39 +- src/dotnet/ManagedMemberTypeInventory.test.ts | 11 +- src/main/eagerRuntime.ts | 5 +- src/server/BundleResourcesMcp.test.ts | 2 +- src/server/EvidenceMcpServerCore.ts | 16 +- src/server/McpToolRequest.ts | 11 + .../ToolResultDelivery.agentBudget.test.ts | 157 ++++++ src/server/ToolResultDelivery.ts | 189 ++++++- src/server/browserToolBindings.ts | 21 +- src/server/contractToolBindings.ts | 33 +- src/server/contractToolHandler.ts | 88 +-- src/server/createServer.ts | 2 +- src/server/deliverApplicationExecution.ts | 8 +- src/server/deliverInvestigationWorkflow.ts | 2 + src/server/providerOperationToolHandler.ts | 17 +- src/server/retainedSummaryDelivery.test.ts | 53 -- src/server/retainedSummaryDelivery.ts | 49 +- src/server/serviceToolBindings.ts | 4 +- src/server/toolResult.ts | 5 + .../applicationVersionMatchingCli.test.ts | 17 +- .../applicationWorkflowCli.test.ts | 52 +- .../artifactComparisonCoverage.test.ts | 9 +- .../exportedFunctionBindingsCli.test.ts | 6 +- .../javascriptBuiltinDefaultsCli.test.ts | 3 + .../javascriptCallbackTargets.test.ts | 2 + .../javascriptCapturedParameters.test.ts | 3 +- .../javascriptChildHandleOwnership.test.ts | 1 + .../applications/playwrightTrace.test.ts | 9 +- .../applications/unboundRequires.test.ts | 18 +- ...rowserScenarioReferenceDiagnostics.test.ts | 5 +- .../byteEntropyWindowsIdentity.test.ts | 5 +- tests/acceptance/dotnetBundleJourney.test.ts | 7 +- .../acceptance/harmonyArtifactJourney.test.ts | 11 +- .../acceptance/machoSelectedSliceCli.test.ts | 7 +- .../acceptance/managedMemberRecovery.test.ts | 11 +- tests/acceptance/nonBinaryComposition.test.ts | 11 +- .../providers/idaEndpointFailure.test.ts | 4 +- .../tools/historicalCaptureResources.test.ts | 7 +- tests/acceptance/tools/qlogCapture.test.ts | 20 +- tests/acceptance/uefiFirmware.test.ts | 9 +- tests/acceptance/webRuntimeCli.test.ts | 2 + .../browser/historicalWebCapture.test.ts | 5 + tests/boundary/browser/sazWebCapture.test.ts | 7 + .../cli/browserScenarioSummaryCli.test.ts | 2 + tests/boundary/cli/cliOutput.test.ts | 29 + .../cli/contractCommandViewDelivery.test.ts | 28 +- tests/boundary/cli/electronCli.test.ts | 10 +- .../cli/javascriptIntegrityPolicyCli.test.ts | 7 +- tests/boundary/cli/jsonOutput.test.ts | 9 +- .../cli/managedMemberSummaryCli.test.ts | 65 ++- .../boundary/cli/markdownNestedFacts.test.ts | 3 +- tests/boundary/cli/rawDiskImageCli.test.ts | 14 +- .../reconstructionObligationLedgerCli.test.ts | 3 +- .../cli/sharedJavaScriptCliSession.test.ts | 9 +- .../cli/workflowInputIdentities.test.ts | 2 + .../javascriptSelectedPathEvidence.test.ts | 22 +- .../javascriptSemanticTraceEvidence.test.ts | 29 +- .../mcp/absoluteLocalPathSchema.test.ts | 1 + .../boundary/mcp/agentResultBudgetMcp.test.ts | 501 ++++++++++++++++++ .../mcp/analysisSnapshotProvenanceMcp.test.ts | 4 +- .../mcp/analysisSummaryDetailMcp.test.ts | 2 +- tests/boundary/mcp/analysisViewMcp.test.ts | 6 +- .../mcp/androidLateCompletionMcp.test.ts | 2 +- .../boundary/mcp/artifactArmSlicesMcp.test.ts | 2 +- .../mcp/artifactInspectionCoverageMcp.test.ts | 2 +- .../mcp/artifactMcp.inlineInventory.test.ts | 5 +- tests/boundary/mcp/artifactMcp.test.ts | 18 +- .../mcp/batchSourcePublicationCleanup.test.ts | 1 + .../batchSourcePublicationRecovery.test.ts | 2 +- .../boundary/mcp/binaryDiagnosticsMcp.test.ts | 19 +- tests/boundary/mcp/browserMcp.test.ts | 5 + ...browserScenarioInputDiagnosticsMcp.test.ts | 2 + tests/boundary/mcp/bunStandaloneMcp.test.ts | 5 +- .../mcp/capabilityRemediationMcp.test.ts | 4 +- .../mcp/commandObservationViews.test.ts | 7 +- .../mcp/completeEvidenceByDefault.test.ts | 54 ++ .../mcp/completionInventoryAliasMcp.test.ts | 2 +- ...buggerExternalMutationLifecycleMcp.test.ts | 10 +- .../mcp/desktopApplicationMcp.test.ts | 2 +- tests/boundary/mcp/devicetreeMcp.test.ts | 4 +- tests/boundary/mcp/electronMcp.test.ts | 14 +- tests/boundary/mcp/erlangBeamMcp.test.ts | 8 +- .../mcp/errorEvidenceLifecycleMcp.test.ts | 2 +- tests/boundary/mcp/evmInterfaceMcp.test.ts | 1 - tests/boundary/mcp/flutterMcp.test.ts | 10 +- tests/boundary/mcp/fridaLifecycleMcp.test.ts | 15 +- tests/boundary/mcp/gdbCancellationMcp.test.ts | 25 +- .../boundary/mcp/gdbCloseDisposition.test.ts | 8 +- .../mcp/gdbExecutableSelection.test.ts | 6 +- tests/boundary/mcp/ghidraMcpHarness.ts | 6 + tests/boundary/mcp/ghidraReopen.test.ts | 2 +- .../mcp/ghidraStartupCancellationMcp.test.ts | 7 +- tests/boundary/mcp/goBinaryMcp.test.ts | 20 +- tests/boundary/mcp/goBinaryViews.test.ts | 15 +- .../mcp/javascriptAnalysisResources.test.ts | 1 + .../mcp/javascriptSourceSelection.test.ts | 27 +- .../mcp/keyedArchiveXmlExtensionMcp.test.ts | 2 +- tests/boundary/mcp/kunaCloseRetryMcp.test.ts | 5 +- tests/boundary/mcp/largeToolResult.test.ts | 2 +- .../lateAbortApplicationEvidenceMcp.test.ts | 5 +- .../mcp/managedArtifactSummaryMcp.test.ts | 4 +- .../mcp/managedMemberSummaryMcp.test.ts | 9 +- .../mcp/nativeInventoryViewsMcp.test.ts | 17 +- .../mcp/nativeMachoSummaryMcp.test.ts | 2 +- .../mcp/nativeObservationViewsMcp.test.ts | 17 +- tests/boundary/mcp/ntfsMftAdmission.test.ts | 5 +- tests/boundary/mcp/officialArguments.test.ts | 2 +- tests/boundary/mcp/officialTools.test.ts | 4 +- .../mcp/optionalProviderIsolation.test.ts | 6 +- .../mcp/oversizedErrorDeliveryMcp.test.ts | 4 +- tests/boundary/mcp/pcapMcp.test.ts | 2 +- .../mcp/pcapWorkspaceAllocation.test.ts | 2 +- .../mcp/pseudocodeDeliveryMcp.test.ts | 10 +- .../mcp/pyinstallerArtifactMcp.test.ts | 10 +- tests/boundary/mcp/pythonPycMcp.test.ts | 12 +- .../mcp/reverseEngineeringPartialMcp.test.ts | 6 +- tests/boundary/mcp/serverIdentity.test.ts | 2 +- tests/boundary/mcp/serverLifecycleMcp.test.ts | 2 +- tests/boundary/mcp/serverUnknownsMcp.test.ts | 4 +- tests/boundary/mcp/serverWorkflowMcp.test.ts | 4 +- .../mcp/sessionAvailabilityRecovery.test.ts | 4 +- .../mcp/sessionEvidenceRecovery.test.ts | 1 + .../mcp/sessionEvidenceReuseMcp.test.ts | 15 +- .../stableArtifactSymlinkRecoveryMcp.test.ts | 1 + tests/boundary/mcp/universalSliceMcp.test.ts | 21 +- tests/boundary/mcp/wasmArtifactMcp.test.ts | 2 +- .../mcp/webBundleContainmentMcp.test.ts | 2 + .../boundary/mcp/webNetworkCaptureMcp.test.ts | 11 +- tests/boundary/mcp/webPageViewMcp.test.ts | 5 +- .../boundary/mcp/webSourceLocationMcp.test.ts | 7 +- .../mcp/workflowSnapshotReplayMcp.test.ts | 12 +- .../process/androidAnalysisMcp.test.ts | 7 +- .../process/androidMappingMcp.test.ts | 3 +- tests/boundary/process/jadxStartup.test.ts | 2 +- .../providers/kuna/kunaAliasSearchMcp.test.ts | 6 +- .../kuna/kunaBatchDecompileMcp.test.ts | 2 + .../kuna/kunaMachoInventoryMcp.test.ts | 16 +- .../nativeMachoUuidlessInspection.test.ts | 2 +- tests/fixtures/applicationMcpHarness.ts | 16 +- tests/fixtures/artifactComparisonMcp.ts | 2 +- .../cli-parity/discovery-help-over-schema.txt | 8 +- .../discovery-llms-full-over-llms.txt | 2 + .../cli-parity/help-contract-command.txt | 8 +- .../help-contract-long-description.txt | 2 +- .../cli-parity/llms-full-command-yaml.txt | 15 + .../fixtures/cli-parity/llms-full-command.txt | 2 + .../cli-parity/schema-command-json.txt | 2 +- .../fixtures/cli-parity/schema-command-md.txt | 21 + tests/fixtures/cli-parity/schema-command.txt | 9 + .../terminal-error-refined-number.txt | 8 +- .../cli-parity/terminal-help-command.txt | 8 +- tests/fixtures/javascriptReturnShapes.ts | 4 +- tests/fixtures/localToolsMcp.ts | 14 +- .../browserScenarioCleanup.test.ts | 8 +- .../javascriptAnalysisCancellation.test.ts | 6 +- .../javascriptFilesystemErrors.test.ts | 12 +- .../javascriptRuntimeObservationCli.test.ts | 3 +- .../mcpDeliveryEnvironment.test.ts | 2 +- .../stableArtifactConsumers.test.ts | 6 +- .../windowsNativeControlCapability.test.ts | 2 +- tests/support/cli/cliCommandSession.ts | 20 +- tests/support/cli/cliFixture.ts | 16 +- tests/support/cli/javascriptApplication.ts | 3 + tests/support/completeDetail.ts | 18 + tests/support/completeEvidenceByDefault.ts | 207 ++++++++ tests/support/mcp/mcpFixture.ts | 11 +- vitest.config.ts | 4 + 371 files changed, 5188 insertions(+), 1373 deletions(-) create mode 100644 scripts/lib/complete-evidence.d.mts create mode 100644 scripts/lib/complete-evidence.mjs create mode 100644 src/application/analysisView/EvidenceJsonView.test.ts create mode 100644 src/domain/agentBudgetOperations.ts create mode 100644 src/domain/agentResultBudget.test.ts create mode 100644 src/domain/agentResultBudget.ts create mode 100644 src/domain/analysisView/evidenceJsonView.ts create mode 100644 src/server/ToolResultDelivery.agentBudget.test.ts delete mode 100644 src/server/retainedSummaryDelivery.test.ts create mode 100644 tests/boundary/mcp/agentResultBudgetMcp.test.ts create mode 100644 tests/boundary/mcp/completeEvidenceByDefault.test.ts create mode 100644 tests/support/completeDetail.ts create mode 100644 tests/support/completeEvidenceByDefault.ts diff --git a/docs/guides/managed/managed-code-analysis.md b/docs/guides/managed/managed-code-analysis.md index 9b079977e50..cd5f4cd641d 100644 --- a/docs/guides/managed/managed-code-analysis.md +++ b/docs/guides/managed/managed-code-analysis.md @@ -164,9 +164,12 @@ rejects selected summary before analysis; complete delivery remains available. ### Member summary and retained member rows -Complete `inspect_managed_members` delivery always includes the assembly-wide -`member_refs` and `exported_types`, which `type_names` does not narrow, so even -one selected or unmatched type can return megabytes. In MCP, select +`type_names` narrows every collection: `member_refs` to the MemberRef rows the +selected method bodies use, and `exported_types` to rows whose full name was +selected. Complete delivery of a whole assembly can still be megabytes, so an +omitted `detail` returns complete Evidence only within the +[agent result budget](../../reference/limits-and-recovery.md#agent-result-budget) +and otherwise the retained summary. In MCP, select `{"path":"/absolute/path/Assembly.dll","type_names":["Namespace.Type"],"detail":"summary"}` to keep the complete source in the session and receive identity, metadata status, the selection with its unmatched names, coverage/issues, the separate @@ -242,8 +245,11 @@ prove absence among unresolved or unexamined source rows. #### CLI summary and saved member rows -The CLI accepts the same `complete` and `summary` detail choices. Omitted or -`--detail complete` returns complete Evidence. To receive a summary, choose a +The CLI accepts the same `complete` and `summary` detail choices. +`--detail complete` returns complete Evidence. Omitted, it returns complete +Evidence within the agent result budget and the summary otherwise; with +`--evidence_output` that summary comes with the saved bundle. To always receive +a summary, choose a new Evidence bundle destination so its original complete parent remains available after the command exits: @@ -422,8 +428,8 @@ The result preserves the requested names in `selection.type_names` and reports unmatched names separately. If metadata names are unreadable, limitations retain that uncertainty. With no selection, `selection` is null and whole-assembly inspection keeps its existing resource policy. Selection restricts types, -fields, methods, call edges, field accesses and user strings; member references -remain an assembly-wide inventory, so output size is not guaranteed to be small. +fields, methods, member references, exported types, call edges, field accesses +and user strings. Output size is still not guaranteed to be small. Coverage describes the selected members. Comparisons leave members outside the opposite observation's selection unknown, and application graphs report their @@ -455,8 +461,8 @@ method absence; observed pairs and field inventory comparisons remain available. For MCP callers, request `detail: "summary"` and page the `types` collection using the returned parent Evidence ID. Select one or more returned full names in a subsequent `inspect_managed_members` request. Selection is a recovery path, -not a guarantee: a single type or the assembly-wide member references can still -exhaust the representation budget. A successful command exit means the Evidence +not a guarantee: a single large type can still exhaust the representation +budget. A successful command exit means the Evidence was returned; inspect `coverage.state` and `coverage.issues` before treating any collection as complete. diff --git a/docs/guides/web/browser-observation.md b/docs/guides/web/browser-observation.md index 4a63752797d..48ae8c58132 100644 --- a/docs/guides/web/browser-observation.md +++ b/docs/guides/web/browser-observation.md @@ -24,7 +24,7 @@ authority are validated independently before selection and connection. - `list_browser_targets` / `rea list-browser-targets` discovers all eligible page targets at the endpoint by default, with an optional exact-origin filter. - `inspect_web_page` / `rea inspect-web-page` captures DOM structure, accessibility nodes, scripts, resources, safe response/DOM metadata, attach-window network and console metadata, WebSocket frame sizes, workers, quota, and optionally selected storage key names, redacted storage-content fingerprints, or script sources. An MCP call that omits `detail` returns the capture inline when its Evidence - is at most 32 KiB. A larger capture is retained, and the call returns a + fits the [agent result budget](../../reference/limits-and-recovery.md#agent-result-budget). A larger capture is retained, and the call returns a summary with the small sections and counts. On a local page with 2,000 list rows, 200 buttons and three libraries, the complete result was 4.6 MB, mostly 6,423 DOM nodes and 10,614 accessibility nodes; the summary was 12.5 KB. diff --git a/docs/reference/limits-and-recovery.md b/docs/reference/limits-and-recovery.md index fe73219c571..f612677ce49 100644 --- a/docs/reference/limits-and-recovery.md +++ b/docs/reference/limits-and-recovery.md @@ -296,6 +296,59 @@ same effective setting so readiness changes along with repair and reset. `REA_NATIVE_MATCHING_REPRESENTATION_BYTES` is validated the same way, by `match_native_functions` alone. +## Agent result budget + +`delivery.agent_result_budget_bytes` is a delivery budget, not an admission +limit. It defaults to 32,768 compact JSON bytes. Claude Code moves MCP +results above 25,000 tokens out of context, and dense JSON (addresses, +digests, identifiers) measured about 2.9 bytes per token there, so the +default is about 11,000 tokens: under half the cap, with room for the +delivery facts. Token figures in delivery facts use an estimate of 3 bytes +per token, not a tokenizer measurement. The budget applies to tools with a +`detail` selector when the caller omits `detail`, on MCP and the CLI; it is +the only size that chooses between complete and summary delivery. An MCP +session summarizes only when it retains Evidence and advertises +`inspect_analysis_view`, which pages the summary; otherwise it delivers the +complete Evidence. Its launch seed, `REA_AGENT_RESULT_BUDGET_BYTES`, also +sets it for one-shot CLI invocations; an invalid seed leaves delivery +unbudgeted (complete, as before) rather than falling back to the default, +and settings inspection reports it. The stdio frame limit, +`REA_MCP_MAX_RESPONSE_BYTES`, stays a separate transport safety net. + +When complete Evidence fits, it is delivered inline as before. When it does +not, the work is never refused or truncated: + +- MCP retains the complete Evidence in the session and returns the + operation's summary view, the same record `detail: "summary"` returns, so + its identity holds wherever a summary is accepted. The delivery facts + travel beside it, in a second text block `{"delivery": …}` and in + `_meta["rea/agent-budget-delivery"]`: `budget_bytes`, `budget_source`, the + range, `complete_bytes`, `estimated_complete_tokens`, `evidence_id`, + `retained`, `next` (the exact `inspect_analysis_view` call that pages the + complete record) and a `note` with the recovery. +- `inspect_analysis_view` with view + `{kind: "evidence-json", offset, limit}` pages the exact JSON text of the + retained record in UTF-16 code units. Joining every page in offset order + reproduces it exactly, and no page splits a surrogate pair. With `limit` + omitted a page holds at most 24,576 bytes of escaped UTF-8 text, so with + its view Evidence it fits the default budget for any characters; an explicit `limit` counts code units, + up to 1,048,576. The producer's own views (`managed-members`, `inventory` + and so on) select facts more cheaply. +- The CLI with `--evidence_output` prints + `{"summary", "evidence_bundle", "delivery"}`, whose `delivery.next` names + the bundle as an `evidence-file` source. Without it, the one-shot CLI + writes nothing to disk, no bundle, cache or spill file: it prints + `{"summary", "delivery"}` with `retained: "not-retained"`, and + `delivery.rerun` gives the arguments to add to the original command as argv + arrays for every invocation: `complete` (`["--detail", "complete"]`) and + `retained` (`["--evidence_output", ""]`). Caller inputs are + never echoed, since they can carry access credentials; the note names both. + +Recovery: pass `detail: "complete"` (CLI `--detail complete`) for everything +inline on one call, or raise the setting for the runtime with +`update_analysis_settings`. An operation without a summary view, or with no +retained session, keeps complete delivery. + ## Keep a fixed ceiling honest A fixed ceiling is the exception. Keep one only for a stated format, protocol, diff --git a/docs/reference/mcp-contracts.md b/docs/reference/mcp-contracts.md index 677e814ab3d..0b0573107ee 100644 --- a/docs/reference/mcp-contracts.md +++ b/docs/reference/mcp-contracts.md @@ -338,10 +338,12 @@ framing. `list_procedures`, `search_procedures`, `list_strings`, `search_strings` and `list_names` accept `detail: "complete"` or `detail: "summary"`. These five inventories, `batch_decompile` and `trace_feature` grow with the target, so an -omitted `detail` is size-aware: the complete Evidence is returned inline when -its UTF-8 JSON is at most 32 KiB, and otherwise the session retains it and -returns its summary. A server that retains no Evidence returns the complete -Evidence. On a stripped 1.2 MB ELF (Debian 12 `zstd`), complete MCP results +omitted `detail` follows the +[agent result budget](limits-and-recovery.md#agent-result-budget): the complete +Evidence is returned inline when its UTF-8 JSON fits +`delivery.agent_result_budget_bytes`, and otherwise the session retains it and +returns its summary. A server that retains no Evidence, or a session that does +not advertise `inspect_analysis_view`, returns the complete Evidence. On a stripped 1.2 MB ELF (Debian 12 `zstd`), complete MCP results were 8.2 MB for `list_names` and 3.6 MB for `trace_feature` with `error`. Summary retains the original complete Evidence and returns its row count, provider identity, analysis-profile digest, original query, parent Evidence ID, limitations and explicit unknown discovery coverage. Delivery detail is excluded from provider arguments @@ -889,8 +891,8 @@ reachability. The CLI keeps complete trace JSON; save it and use ### Selected batch decompile results -`batch_decompile` returns every pseudocode body inline when the batch Evidence is -at most 32 KiB; an omitted `detail` summarizes a larger batch, and +`batch_decompile` returns every pseudocode body inline when the batch Evidence +fits the agent result budget; an omitted `detail` summarizes a larger batch, and `detail: "complete"` always returns every body. `detail: "summary"` retains the complete batch in the session first and returns its producer counts, `source_provider` (the composing workflow), `source_analysis_profile_digest`, diff --git a/docs/reference/rea-limit-inventory.md b/docs/reference/rea-limit-inventory.md index fc54d086469..0f047d3740f 100644 --- a/docs/reference/rea-limit-inventory.md +++ b/docs/reference/rea-limit-inventory.md @@ -60,6 +60,11 @@ override is `source: "runtime"`. The structured field is `update_mode: "runtime" | `javascript.max_heap_mb` | none (`max_heap_mb`) | `src/domain/javascript/javascriptAnalysisResourceControls.ts` | 1024 | 128 | 16384 | next worker | | `wasm.command_timeout_ms` | none (`command_timeout_ms`) | `src/domain/wasm/wasmArtifact.ts` | 30000 | 1 | 2147483647 | per operation | | `native.matching_representation_bytes` | `REA_NATIVE_MATCHING_REPRESENTATION_BYTES` | `src/domain/analysisResourceLimits.ts` | 100663296 | 1 | 1073741824 | per operation | +| `delivery.agent_result_budget_bytes` | `REA_AGENT_RESULT_BUDGET_BYTES` | `src/domain/analysisResourceLimits.ts` | 32768 | 4096 | 10485760 | per operation | + +`delivery.agent_result_budget_bytes` is a delivery budget, not an admission +limit: an over-budget result is retained and delivered as its summary with an +`inspect_analysis_view` cursor, never refused. An out-of-range `update_analysis_settings` value is rejected by the setting's schema. Invalid launch seeds that the global environment parser accepts as diff --git a/examples/github-actions/rea-analysis.yml b/examples/github-actions/rea-analysis.yml index d609a79a44c..21510960cb1 100644 --- a/examples/github-actions/rea-analysis.yml +++ b/examples/github-actions/rea-analysis.yml @@ -45,7 +45,7 @@ jobs: REPORT_DIR: ${{ steps.reports.outputs.directory }} run: | set +e - rea analyze-javascript-application "${GITHUB_WORKSPACE}/${ARTIFACT_PATH}" --json --full-output \ + rea analyze-javascript-application "${GITHUB_WORKSPACE}/${ARTIFACT_PATH}" --json --full-output --detail complete \ > "${REPORT_DIR}/analysis.json" 2> "${REPORT_DIR}/analysis.stderr" status=$? set -e diff --git a/scripts/lib/advertised-catalog.mjs b/scripts/lib/advertised-catalog.mjs index 92b1430d13b..0bd70b03365 100644 --- a/scripts/lib/advertised-catalog.mjs +++ b/scripts/lib/advertised-catalog.mjs @@ -4,6 +4,7 @@ import { Client } from "@modelcontextprotocol/client"; import { createOwnedMcpStdioTransport } from "./owned-mcp-stdio.mjs"; import { VerifierFixture, withVerifierFixture } from "./verifier-fixture.mjs"; +import { completeEvidenceClient } from "./complete-evidence.mjs"; const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); @@ -68,7 +69,9 @@ const listPackagedTools = async (profile, packageRoot) => { expectedCommand: null, sweepTokenOwnedProcesses: true, }); - const client = new Client({ name: "rea-advertised-catalog", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-advertised-catalog", version: "1" }), + ); fixture.releaseAfter(() => client.close()); try { await client.connect(transport); diff --git a/scripts/lib/artifact-e2e.mjs b/scripts/lib/artifact-e2e.mjs index 5dd6f742b02..d9a6faeef6d 100644 --- a/scripts/lib/artifact-e2e.mjs +++ b/scripts/lib/artifact-e2e.mjs @@ -6,6 +6,10 @@ import { createOwnedMcpStdioTransport } from "./owned-mcp-stdio.mjs"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "./mcp-verification-environment.mjs"; import { withCanonicalOutputSchema } from "./canonical-output-schema.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./complete-evidence.mjs"; // Bind parsed definitions to this connection. Hot/cold catalogs may add tools; // refresh a missing name once without throwing away already validated bindings. @@ -119,7 +123,7 @@ export async function artifactCli( .normalized_result; } -const executeArtifactCli = ( +const executeArtifactCli = async ( owner, command, target, @@ -130,10 +134,13 @@ const executeArtifactCli = ( process.execPath, [ fileURLToPath(new URL("../rea.mjs", import.meta.url)), - command, - target, - ...arguments_, - "--json", + // These helpers return complete Evidence records, so they request them. + ...(await completeEvidenceCliArguments([ + command, + target, + ...arguments_, + "--json", + ])), ], { env: environment(), @@ -224,7 +231,9 @@ const withOpenedArtifactMcp = async ( signal: options.signal, }); owner.adopt(transport, "artifact MCP process"); - const client = new Client({ name: "artifact-real-e2e", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "artifact-real-e2e", version: "1" }), + ); let clientClose; const closeClient = () => (clientClose ??= Promise.resolve().then(() => client.close())); diff --git a/scripts/lib/browser-capture-metadata-budget-e2e.mjs b/scripts/lib/browser-capture-metadata-budget-e2e.mjs index 498a1adb73b..2a107c391db 100644 --- a/scripts/lib/browser-capture-metadata-budget-e2e.mjs +++ b/scripts/lib/browser-capture-metadata-budget-e2e.mjs @@ -4,6 +4,7 @@ import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { artifactCliEvidence, artifactMcpResult } from "./artifact-e2e.mjs"; import { webSourceMapsSchema } from "../../dist/domain/webBundleAnalysis.js"; +import { completeEvidenceClient } from "./complete-evidence.mjs"; const ANNOTATION_BYTES = 2 * 1024 * 1024; const SCRIPT_COUNT = 5; @@ -112,7 +113,9 @@ export async function verifyBrowserCaptureMetadataBudget(endpoint) { }, stderr: "pipe", }); - const client = new Client({ name: "browser-metadata-e2e", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "browser-metadata-e2e", version: "1" }), + ); try { await client.connect(transport); assertMetadataBudget( @@ -121,8 +124,6 @@ export async function verifyBrowserCaptureMetadataBudget(endpoint) { allowed_origins: [fixtureOrigin], target_id: targetId, observation_ms: 0, - // The assertions read the complete capture, whatever its size. - detail: "complete", }), ); assertBundleMetadataOmissions( diff --git a/scripts/lib/browser-dom-destinations-e2e.mjs b/scripts/lib/browser-dom-destinations-e2e.mjs index 9159d6eb847..47630c3cd01 100644 --- a/scripts/lib/browser-dom-destinations-e2e.mjs +++ b/scripts/lib/browser-dom-destinations-e2e.mjs @@ -8,6 +8,10 @@ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { parseEvidence } from "../../dist/domain/evidence.js"; import { assertFormDestinations } from "./browser-verifier-assertions.mjs"; import { mcpTextValue } from "./mcp-verifier-results.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./complete-evidence.mjs"; /** Verify the real fixture's form destinations through CLI and stdio MCP. */ export async function verifyBrowserDomDestinations( @@ -20,12 +24,14 @@ export async function verifyBrowserDomDestinations( process.execPath, [ entrypoint, - "inspect-web-page", - attachment.cdp_endpoint, - attachment.target_id, - "--observation-ms", - "100", - "--json", + ...(await completeEvidenceCliArguments([ + "inspect-web-page", + attachment.cdp_endpoint, + attachment.target_id, + "--observation-ms", + "100", + "--json", + ])), ], { env, timeout: 60000, maxBuffer: 32 * 1024 * 1024 }, ); @@ -39,12 +45,14 @@ export async function verifyBrowserDomDestinations( env, stderr: "pipe", }); - const client = new Client({ name: "browser-dom-destinations", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "browser-dom-destinations", version: "1" }), + ); try { await client.connect(transport); const result = await client.callTool({ name: "inspect_web_page", - arguments: { ...attachment, observation_ms: 100, detail: "complete" }, + arguments: { ...attachment, observation_ms: 100 }, }); assert.notEqual(result.isError, true, mcpTextValue(result)); assertFormDestinations( diff --git a/scripts/lib/browser-module-e2e.mjs b/scripts/lib/browser-module-e2e.mjs index 53481224b86..6da5b049ca6 100644 --- a/scripts/lib/browser-module-e2e.mjs +++ b/scripts/lib/browser-module-e2e.mjs @@ -15,6 +15,10 @@ import { NativeModuleResolver } from "../../dist/browser/modules/NativeModuleRes import { startBrowserModuleSite } from "../fixtures/browser-module-site.mjs"; import { mcpTextValue } from "./mcp-verifier-results.mjs"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./complete-evidence.mjs"; /** Check native URL resolution against an independently loaded module graph through CLI/MCP. */ export async function verifyBrowserModules( @@ -37,7 +41,10 @@ export async function verifyBrowserModules( const cli = async (...args) => { const { stdout } = await promisify(execFile)( process.execPath, - [entrypoint, ...args, "--json"], + [ + entrypoint, + ...(await completeEvidenceCliArguments([...args, "--json"])), + ], { env, timeout: 45000, maxBuffer: 16 * 1024 * 1024 }, ); return parseEvidence(JSON.parse(stdout)); @@ -48,7 +55,9 @@ export async function verifyBrowserModules( env, stderr: "pipe", }); - client = new Client({ name: "module-real-e2e", version: "1" }); + client = completeEvidenceClient( + new Client({ name: "module-real-e2e", version: "1" }), + ); const oracle = await loadingOracle(executable, site); const scenario = { browser: { mode: "launch", executable_path: executable }, diff --git a/scripts/lib/browser-nested-source-map-e2e.mjs b/scripts/lib/browser-nested-source-map-e2e.mjs index 5976d99d28f..aae21ee9d55 100644 --- a/scripts/lib/browser-nested-source-map-e2e.mjs +++ b/scripts/lib/browser-nested-source-map-e2e.mjs @@ -112,6 +112,8 @@ async function verifyCase(executable, entrypoint, scenario) { [ entrypoint, "analyze-web-bundle", + "--detail", + "complete", endpoint, target.target_id, "--allowed-origins", diff --git a/scripts/lib/browser-network-e2e.mjs b/scripts/lib/browser-network-e2e.mjs index 41ca248d086..d9a88416a9e 100644 --- a/scripts/lib/browser-network-e2e.mjs +++ b/scripts/lib/browser-network-e2e.mjs @@ -16,6 +16,7 @@ import { import { assertBrowserNetworkEvidence } from "./browser-network-assertions.mjs"; import { scenarioProfiles } from "./browser-scenario-verifier.mjs"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; +import { completeEvidenceClient } from "./complete-evidence.mjs"; /** Exercise selected network content through real CLI and stdio MCP, one browser at a time. */ export async function verifyBrowserNetworkEvidence( @@ -74,6 +75,8 @@ export async function verifyBrowserNetworkEvidence( [ entrypoint, "capture-browser-scenario", + "--detail", + "complete", JSON.stringify(scenario), "--json", ], @@ -109,11 +112,16 @@ export async function verifyBrowserNetworkEvidence( env, stderr: "pipe", }); - client = new Client({ name: "network-real-e2e", version: "1" }); + client = completeEvidenceClient( + new Client({ name: "network-real-e2e", version: "1" }), + ); let mcpProof; await client.connect(transport); const result = await client.callTool( - { name: "capture_browser_scenario", arguments: scenario }, + { + name: "capture_browser_scenario", + arguments: { ...scenario, detail: "complete" }, + }, { timeout: 60_000 }, ); assert.notEqual(result.isError, true, JSON.stringify(result)); @@ -131,7 +139,10 @@ export async function verifyBrowserNetworkEvidence( browser: { mode: "connect", ...attachment }, }); const connected = await client.callTool( - { name: "capture_browser_scenario", arguments: connectedScenario }, + { + name: "capture_browser_scenario", + arguments: { ...connectedScenario, detail: "complete" }, + }, { timeout: 60_000 }, ); assert.notEqual(connected.isError, true, JSON.stringify(connected)); diff --git a/scripts/lib/browser-popup-e2e.mjs b/scripts/lib/browser-popup-e2e.mjs index eb557a000a9..27ba34e185e 100644 --- a/scripts/lib/browser-popup-e2e.mjs +++ b/scripts/lib/browser-popup-e2e.mjs @@ -16,6 +16,7 @@ import { browserScenarioSchema } from "../../dist/domain/browserScenario.js"; import { compareBrowserScenarios } from "../../dist/domain/browserScenarioDiff.js"; import { browserScenarioCaptureSchema } from "../../dist/domain/browserScenarioCapture.js"; import { parseEvidence } from "../../dist/domain/evidence.js"; +import { completeEvidenceClient } from "./complete-evidence.mjs"; // Readiness includes descendant document loads, so complete network capture // does not depend on whether an inline script runs before an iframe finishes. @@ -168,6 +169,8 @@ const verifyTransports = async (executable, origin) => { [ entrypoint, "capture-browser-scenario", + "--detail", + "complete", JSON.stringify(scenario), "--json", ], @@ -185,11 +188,16 @@ const verifyTransports = async (executable, origin) => { env, stderr: "pipe", }); - const client = new Client({ name: "popup-real-e2e", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "popup-real-e2e", version: "1" }), + ); try { await client.connect(transport); const captured = await client.callTool( - { name: "capture_browser_scenario", arguments: scenario }, + { + name: "capture_browser_scenario", + arguments: { ...scenario, detail: "complete" }, + }, { timeout: 60_000 }, ); assert.notEqual(captured.isError, true, JSON.stringify(captured)); diff --git a/scripts/lib/browser-request-e2e.mjs b/scripts/lib/browser-request-e2e.mjs index 80ed2f983d2..4bd156c7ea7 100644 --- a/scripts/lib/browser-request-e2e.mjs +++ b/scripts/lib/browser-request-e2e.mjs @@ -17,6 +17,7 @@ import { } from "../fixtures/browser-request-site.mjs"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; import { createPackageVerifierCommands } from "./verify-package-commands.mjs"; +import { completeEvidenceCliArguments } from "./complete-evidence.mjs"; const authenticated = [ { name: "X-CSRFToken", value: { source: "cookie", name: "csrftoken" } }, @@ -125,7 +126,10 @@ const cliOf = (commands, entrypoint) => async (args, maxBuffer) => const captureOf = async (cli, scenario, maxBuffer) => { const stdout = await cli( - ["capture-browser-scenario", JSON.stringify(scenario)], + await completeEvidenceCliArguments([ + "capture-browser-scenario", + JSON.stringify(scenario), + ]), maxBuffer, ); const evidence = parseEvidence(JSON.parse(stdout)); diff --git a/scripts/lib/browser-runtime-e2e.mjs b/scripts/lib/browser-runtime-e2e.mjs index 912b59a185e..63cd841da39 100644 --- a/scripts/lib/browser-runtime-e2e.mjs +++ b/scripts/lib/browser-runtime-e2e.mjs @@ -28,6 +28,7 @@ import { triggerRuntimeFixtureAction, isolatedFixtureUrl, } from "./browser-runtime-world-e2e.mjs"; +import { completeEvidenceClient } from "./complete-evidence.mjs"; // Arming, progress delivery, isolated-world proof and the page action cross // separate transports. Leave time for their round trips on shared CI runners; @@ -104,7 +105,9 @@ export async function verifyBrowserRuntime( env, stderr: "pipe", }); - client = new Client({ name: "web-runtime-real-e2e", version: "1" }); + client = completeEvidenceClient( + new Client({ name: "web-runtime-real-e2e", version: "1" }), + ); await client.connect(transport); const invalidSelectors = await verifyRuntimeInvalidSelectors( client, diff --git a/scripts/lib/browser-scenario-environment-e2e.mjs b/scripts/lib/browser-scenario-environment-e2e.mjs index 79c3f0f5e5f..26153d1eaf4 100644 --- a/scripts/lib/browser-scenario-environment-e2e.mjs +++ b/scripts/lib/browser-scenario-environment-e2e.mjs @@ -12,6 +12,7 @@ import { AnalysisCancelledError } from "../../dist/domain/analysisErrorCore.js"; import { runScenarioCli } from "./browser-scenario-verifier.mjs"; import { requireMcpEvidenceResult } from "./mcp-verifier-results.mjs"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; +import { completeEvidenceClient } from "./complete-evidence.mjs"; const expected = { timezone: "Pacific/Honolulu", @@ -221,10 +222,12 @@ export async function verifyScenarioEnvironment(endpoint, targetId, origin) { env: process.env, stderr: "pipe", }); - const client = new Client({ - name: "browser-environment-e2e", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "browser-environment-e2e", + version: "1", + }), + ); await withVerifierCleanup(async () => { await client.connect(transport); const definition = (await client.listTools()).tools.find( @@ -233,7 +236,10 @@ export async function verifyScenarioEnvironment(endpoint, targetId, origin) { assert.ok(definition, "Scenario tool is absent from the current catalog"); const mcpCapture = requireMcpEvidenceResult( await client.callTool( - { name: "capture_browser_scenario", arguments: scenario }, + { + name: "capture_browser_scenario", + arguments: { ...scenario, detail: "complete" }, + }, { toolDefinition: definition }, ), "capture_browser_scenario", @@ -340,7 +346,10 @@ const verifyConcurrentMcpCapture = async ({ const pendingCalls = []; const callTool = (arguments_, signal) => { const pending = client.callTool( - { name: "capture_browser_scenario", arguments: arguments_ }, + { + name: "capture_browser_scenario", + arguments: { ...arguments_, detail: "complete" }, + }, { signal, timeout: 60_000, toolDefinition: definition }, ); void pending.catch(() => {}); diff --git a/scripts/lib/browser-scenario-storage-fingerprints-e2e.mjs b/scripts/lib/browser-scenario-storage-fingerprints-e2e.mjs index 3d25385477b..5cf318d549a 100644 --- a/scripts/lib/browser-scenario-storage-fingerprints-e2e.mjs +++ b/scripts/lib/browser-scenario-storage-fingerprints-e2e.mjs @@ -12,6 +12,10 @@ import { scenarioProfiles, } from "./browser-scenario-verifier.mjs"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; +import { + completeEvidenceClient, + completeEvidenceToolArguments, +} from "./complete-evidence.mjs"; const secretVariable = "REA_BROWSER_FINGERPRINT_VERIFIER_SECRET"; const secret = "rea-storage-fingerprint-private"; @@ -140,10 +144,12 @@ export async function verifyScenarioStorageFingerprints(executable, origin) { env: process.env, stderr: "pipe", }); - const client = new Client({ - name: "browser-storage-fingerprints-e2e", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "browser-storage-fingerprints-e2e", + version: "1", + }), + ); return withVerifierCleanup(async () => { const cli = await verifyValues( (value) => runScenarioCli(scenarioFor(executable, origin, value)), @@ -166,7 +172,10 @@ export async function verifyScenarioStorageFingerprints(executable, origin) { parseEvidence( await call( "capture_browser_scenario", - scenarioFor(executable, origin, value), + await completeEvidenceToolArguments( + "capture_browser_scenario", + scenarioFor(executable, origin, value), + ), ), ), async (before, after) => diff --git a/scripts/lib/browser-scenario-verifier.mjs b/scripts/lib/browser-scenario-verifier.mjs index aeca987183a..129a2efc6a8 100644 --- a/scripts/lib/browser-scenario-verifier.mjs +++ b/scripts/lib/browser-scenario-verifier.mjs @@ -9,6 +9,10 @@ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { browserScenarioSchema } from "../../dist/domain/browserScenario.js"; import { requireMcpToolError } from "./mcp-verifier-results.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./complete-evidence.mjs"; const execute = promisify(execFile); @@ -134,9 +138,11 @@ export async function runScenarioCli(scenario) { process.execPath, [ "scripts/rea.mjs", - "capture-browser-scenario", - JSON.stringify(scenario), - "--json", + ...(await completeEvidenceCliArguments([ + "capture-browser-scenario", + JSON.stringify(scenario), + "--json", + ])), ], { cwd: process.cwd(), @@ -173,15 +179,17 @@ export async function verifyScenarioFailureEvidence(executable, origin) { env: process.env, stderr: "pipe", }); - const client = new Client({ - name: "browser-scenario-failure-e2e", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "browser-scenario-failure-e2e", + version: "1", + }), + ); try { await client.connect(transport); const result = await client.callTool({ name: "capture_browser_scenario", - arguments: scenario, + arguments: { ...scenario, detail: "complete" }, }); assert.equal(result.isError, true); assertFailedNavigation(requireMcpToolError(result), scenario.start_url.url); diff --git a/scripts/lib/browser-screenshot-e2e.mjs b/scripts/lib/browser-screenshot-e2e.mjs index 73d0f6f970e..16b313c1008 100644 --- a/scripts/lib/browser-screenshot-e2e.mjs +++ b/scripts/lib/browser-screenshot-e2e.mjs @@ -15,6 +15,7 @@ import { webScreenshotSchema } from "../../dist/domain/webScreenshot.js"; import { comparePngScreenshots } from "../../dist/domain/pngVisualDiff.js"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; import { createVerifierCommands } from "./verify-commands.mjs"; +import { completeEvidenceClient } from "./complete-evidence.mjs"; /** Verify a real, large PNG through production CLI and stdio MCP boundaries. */ export async function verifyLargeScreenshotE2e(endpoint, origin) { @@ -96,7 +97,9 @@ export async function verifyLargeScreenshotE2e(endpoint, origin) { // The SDK defaults to a 10 MiB receive buffer; inline PNG output is larger. maxBufferSize, }); - client = new Client({ name: "browser-screenshot-real-e2e", version: "1" }); + client = completeEvidenceClient( + new Client({ name: "browser-screenshot-real-e2e", version: "1" }), + ); await client.connect(transport); const captured = await client.callTool( { @@ -154,10 +157,12 @@ const verifyDefaultScreenshotDelivery = async ({ env: environment, stderr: "pipe", }); - const client = new Client({ - name: "browser-screenshot-default-e2e", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "browser-screenshot-default-e2e", + version: "1", + }), + ); try { await client.connect(transport); const constrained = await client.callTool( diff --git a/scripts/lib/browser-script-export-e2e.mjs b/scripts/lib/browser-script-export-e2e.mjs index f21d1b3a87d..c590f058387 100644 --- a/scripts/lib/browser-script-export-e2e.mjs +++ b/scripts/lib/browser-script-export-e2e.mjs @@ -16,6 +16,11 @@ import { } from "./browser-script-export-assertions.mjs"; import { mcpTextValue } from "./mcp-verifier-results.mjs"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, + completeEvidenceToolArguments, +} from "./complete-evidence.mjs"; /** Verify capture → export → existing analysis through real CLI and stdio MCP. */ export async function verifyBrowserScriptExport( @@ -44,7 +49,9 @@ export async function verifyBrowserScriptExport( env, stderr: "pipe", }); - client = new Client({ name: "web-script-real-e2e", version: "1" }); + client = completeEvidenceClient( + new Client({ name: "web-script-real-e2e", version: "1" }), + ); const cliCapture = await cli( "capture-browser-scenario", JSON.stringify(scenario), @@ -64,6 +71,8 @@ export async function verifyBrowserScriptExport( await cli( "analyze-javascript-application", cliResult.analysis_input.input_path, + "--detail", + "complete", ).then((value) => assertExportedScriptAnalysis(value, 4, true)); assert.deepEqual( site.counts, @@ -76,7 +85,10 @@ export async function verifyBrowserScriptExport( assert.notEqual(result.isError, true, mcpTextValue(result)); return parseEvidence(JSON.parse(mcpTextValue(result))); }; - const mcpCapture = await call("capture_browser_scenario", scenario); + const mcpCapture = await call( + "capture_browser_scenario", + await completeEvidenceToolArguments("capture_browser_scenario", scenario), + ); const mcpInput = await save("mcp", mcpCapture); const mcpCounts = new Map(site.counts); const mcpResult = await assertWebScriptExport( @@ -85,7 +97,10 @@ export async function verifyBrowserScriptExport( site.assets, ); assertExportedScriptAnalysis( - await call("analyze_javascript_application", mcpResult.analysis_input), + await call("analyze_javascript_application", { + ...mcpResult.analysis_input, + detail: "complete", + }), 4, true, ); @@ -125,15 +140,17 @@ const verifyPassiveExport = async (attachment, { cli, call, save }) => { observation_ms: 100, include_script_sources: true, }; - // Export reads the complete capture with its script sources. - const page = await call("inspect_web_page", { ...input, detail: "complete" }); + const page = await call("inspect_web_page", input); const pageInput = await save("passive", page); const exported = await assertWebScriptExport( await call("export_web_scripts", pageInput), page, ); assertExportedScriptAnalysis( - await call("analyze_javascript_application", exported.analysis_input), + await call("analyze_javascript_application", { + ...exported.analysis_input, + detail: "complete", + }), exported.scripts.length, false, ); @@ -158,6 +175,8 @@ const verifyPassiveExport = async (attachment, { cli, call, save }) => { await cli( "analyze-javascript-application", pageCliResult.analysis_input.input_path, + "--detail", + "complete", ), pageCliResult.scripts.length, false, @@ -170,7 +189,10 @@ const exportCli = async (...args) => { const { stdout } = await promisify(execFile)( process.execPath, - [entrypoint, ...args, "--json"], + [ + entrypoint, + ...(await completeEvidenceCliArguments([...args, "--json"])), + ], { env, timeout: 60000, maxBuffer: 32 * 1024 * 1024 }, ); return parseEvidence(JSON.parse(stdout)); diff --git a/scripts/lib/browser-source-map-e2e.mjs b/scripts/lib/browser-source-map-e2e.mjs index 504a981b7bd..f56d36d7278 100644 --- a/scripts/lib/browser-source-map-e2e.mjs +++ b/scripts/lib/browser-source-map-e2e.mjs @@ -13,6 +13,10 @@ import { mcpTextValue } from "./mcp-verifier-results.mjs"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; import { createPackageVerifierCommands } from "./verify-package-commands.mjs"; import { importVerifierSource } from "./verifier-source-loader.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./complete-evidence.mjs"; const { BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS } = await importVerifierSource( new URL("./browser-process-startup.mts", import.meta.url).href, @@ -52,7 +56,10 @@ export async function verifyBrowserSourceMap( const cli = async (...args) => { const { stdout } = await commands.exec( process.execPath, - [entrypoint, ...args, "--json"], + [ + entrypoint, + ...(await completeEvidenceCliArguments([...args, "--json"])), + ], // Allow the shared cold-start budget plus capture, cleanup and delivery. { env, timeout: 120_000, maxBuffer: 16 * 1024 * 1024 }, ); @@ -64,7 +71,9 @@ export async function verifyBrowserSourceMap( env, stderr: "pipe", }); - client = new Client({ name: "source-map-real-e2e", version: "1" }); + client = completeEvidenceClient( + new Client({ name: "source-map-real-e2e", version: "1" }), + ); const capture = await cli( "capture-browser-scenario", JSON.stringify({ @@ -207,7 +216,7 @@ async function assertPublicPair(cli, client, oracle) { const expected = assertPoint(evidence, oracle); const response = await client.callTool({ name: "trace_web_source_location", - arguments: input, + arguments: { ...input, detail: "complete" }, }); assert.notEqual(response.isError, true, mcpTextValue(response)); const mcpEvidence = parseEvidence(JSON.parse(mcpTextValue(response))); diff --git a/scripts/lib/browser-url-userinfo-e2e.mjs b/scripts/lib/browser-url-userinfo-e2e.mjs index 939997adb07..a025dafc9c4 100644 --- a/scripts/lib/browser-url-userinfo-e2e.mjs +++ b/scripts/lib/browser-url-userinfo-e2e.mjs @@ -8,6 +8,7 @@ import { CdpConnection } from "../../dist/browser/CdpConnection.js"; import { parseEvidence } from "../../dist/domain/evidence.js"; import { artifactCliEvidence } from "./artifact-e2e.mjs"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; +import { completeEvidenceClient } from "./complete-evidence.mjs"; /** Verify real V8 source labels, which retain spelling that navigation normalizes. */ export async function verifyBrowserUrlUserInfo(endpoint, origin) { @@ -96,7 +97,9 @@ export async function verifyBrowserUrlUserInfo(endpoint, origin) { env: { ...process.env, REA_LOG_LEVEL: "silent" }, stderr: "pipe", }); - client = new Client({ name: "browser-url-userinfo-e2e", version: "1" }); + client = completeEvidenceClient( + new Client({ name: "browser-url-userinfo-e2e", version: "1" }), + ); await client.connect(transport); const mcp = await client.callTool({ name: "inspect_web_page", @@ -106,7 +109,6 @@ export async function verifyBrowserUrlUserInfo(endpoint, origin) { target_id: target.id, include_script_sources: true, observation_ms: 0, - detail: "complete", }, }); assert.notEqual(mcp.isError, true, JSON.stringify(mcp)); diff --git a/scripts/lib/complete-evidence.d.mts b/scripts/lib/complete-evidence.d.mts new file mode 100644 index 00000000000..0ac0e6437eb --- /dev/null +++ b/scripts/lib/complete-evidence.d.mts @@ -0,0 +1,13 @@ +export function completeEvidenceCliArguments( + arguments_: readonly string[], + cwd?: string, +): Promise; + +export function completeEvidenceToolArguments( + name: string, + arguments_: Record | undefined, +): Promise | undefined>; + +export function completeEvidenceClient( + client: Client, +): Client; diff --git a/scripts/lib/complete-evidence.mjs b/scripts/lib/complete-evidence.mjs new file mode 100644 index 00000000000..630857de25b --- /dev/null +++ b/scripts/lib/complete-evidence.mjs @@ -0,0 +1,151 @@ +import { resolve } from "node:path"; + +/** + * Verifier helpers that read complete Evidence from the compiled CLI or MCP + * request it explicitly, so the shipped budgeted default stays the default. + * A CLI command whose `--detail` accepts `"complete"`, given neither `--detail` + * nor `--view` (and selecting a route that accepts `--detail` when routed, + * such as `analyze` on a JavaScript target), gets `--detail complete` after + * the command word. An MCP tool whose omitted detail is budgeted, called with + * neither `detail` nor `view`, gets `detail: "complete"`. + */ +let cliMetadata; +let budgetedOperations; + +const loadCliMetadata = async () => { + if (cliMetadata !== undefined) return cliMetadata; + const [ + { createCli }, + { cliCommands }, + { parseCliGlobalArguments }, + { parseCliArgv }, + { isJavaScriptApplicationPath }, + ] = await Promise.all([ + import("../../dist/cli.js"), + import("../../dist/cli/commandRegistry.js"), + import("../../dist/cliBuiltinArguments.js"), + import("../../dist/cli/argvParser.js"), + import("../../dist/cli/coreBinaryCommands.js"), + ]); + const commands = new Map( + cliCommands(createCli({})).map((entry) => [entry.name, entry]), + ); + const detailCommands = new Set( + [...commands.values()] + .filter((entry) => { + const detail = entry.definition.options?.shape?.detail; + return detail !== undefined && detail.safeParse("complete").success; + }) + .map(({ name }) => name), + ); + const analyzeEntry = commands.get("analyze"); + const jsOptionKeys = new Set( + Object.keys( + commands.get("analyze-javascript-application")?.definition.options + ?.shape ?? {}, + ), + ); + cliMetadata = { + detailCommands, + analyzeEntry, + jsOptionKeys, + parseCliGlobalArguments, + parseCliArgv, + isJavaScriptApplicationPath, + }; + return cliMetadata; +}; + +/** Whether an `analyze` invocation selects the JavaScript route (which takes `--detail`). */ +const selectsAnalyzeJavaScriptRoute = async (metadata, commandArgs, cwd) => { + if (metadata.analyzeEntry === undefined) return false; + const parsed = metadata.parseCliArgv( + commandArgs, + metadata.analyzeEntry.definition, + ); + if (!parsed.ok) return false; + const suppliedOptions = Object.entries(parsed.value.options) + .filter(([, value]) => value !== undefined) + .map(([key]) => key); + if (!suppliedOptions.every((key) => metadata.jsOptionKeys.has(key))) + return false; + const target = parsed.value.args.path; + if (typeof target !== "string" || target.length === 0) return false; + return metadata.isJavaScriptApplicationPath( + resolve(cwd ?? process.cwd(), target), + ); +}; + +/** The argv for one CLI invocation that reads complete Evidence. */ +export const completeEvidenceCliArguments = async (arguments_, cwd) => { + const [command, ...rest] = arguments_; + if ( + typeof command !== "string" || + !rest.every((argument) => typeof argument === "string") + ) + return arguments_; + const metadata = await loadCliMetadata(); + if (!metadata.detailCommands.has(command)) return arguments_; + const global = metadata.parseCliGlobalArguments(arguments_); + if ( + global.flags.has("--help") || + global.flags.has("-h") || + global.flags.has("--schema") + ) + return arguments_; + const selects = (flag) => + rest.some( + (argument) => argument === flag || argument.startsWith(`${flag}=`), + ); + if (selects("--detail") || selects("--view")) return arguments_; + if ( + command === "analyze" && + !(await selectsAnalyzeJavaScriptRoute( + metadata, + global.command.slice(1), + cwd, + )) + ) + return arguments_; + return [command, "--detail", "complete", ...rest]; +}; + +/** The arguments for one MCP tool call that reads complete Evidence. */ +export const completeEvidenceToolArguments = async (name, arguments_) => { + budgetedOperations ??= new Set( + (await import("../../dist/domain/agentBudgetOperations.js")) + .AGENT_BUDGET_OPERATIONS, + ); + if (!budgetedOperations.has(name)) return arguments_; + const selected = arguments_ ?? {}; + return Object.hasOwn(selected, "detail") || Object.hasOwn(selected, "view") + ? arguments_ + : { ...selected, detail: "complete" }; +}; + +const wrapped = new WeakSet(); + +/** + * Apply the complete-Evidence request to every `callTool` on a verifier's + * SDK client. Calls to tools that are not budgeted, including other servers' + * tools, are sent as written. + */ +export const completeEvidenceClient = (client) => { + // A client without callTool, such as a cleanup test's connection double, + // has no tool call to request complete Evidence for. + if (wrapped.has(client) || typeof client.callTool !== "function") + return client; + wrapped.add(client); + const callTool = client.callTool.bind(client); + client.callTool = async (params, ...rest) => { + const arguments_ = await completeEvidenceToolArguments( + params.name, + params.arguments, + ); + return callTool( + arguments_ === undefined ? params : { ...params, arguments: arguments_ }, + ...rest, + ); + }; + return client; +}; diff --git a/scripts/lib/ghidra-reference-snapshot-e2e.mjs b/scripts/lib/ghidra-reference-snapshot-e2e.mjs index 1a03257fb52..fecf5f85f82 100644 --- a/scripts/lib/ghidra-reference-snapshot-e2e.mjs +++ b/scripts/lib/ghidra-reference-snapshot-e2e.mjs @@ -14,6 +14,7 @@ import { parseBinaryTarget } from "../../dist/application/BinaryTargetResolver.j import { createAnalysisProfile } from "../../dist/domain/analysisProfile.js"; import { serializeAnalysisSnapshot } from "../../dist/domain/analysisSnapshot.js"; import { createLegacyGhidraSnapshot } from "./ghidra-legacy-snapshot-e2e.mjs"; +import { completeEvidenceCliArguments } from "./complete-evidence.mjs"; /** Reject a valid older snapshot whose instruction-only collector omitted a real edge. */ export async function verifyLegacyGhidraReferenceSnapshot( @@ -124,14 +125,16 @@ export async function verifyLegacyGhidraReferenceSnapshot( process.execPath, [ entrypoint, - "function", - target.path, - procedure, - "--provider", - "ghidra", - "--snapshot", - path, - "--json", + ...(await completeEvidenceCliArguments([ + "function", + target.path, + procedure, + "--provider", + "ghidra", + "--snapshot", + path, + "--json", + ])), ], { env, timeout: 240000, maxBuffer: 72 * 1024 * 1024 }, ), diff --git a/scripts/lib/kuna-reference-verifier.mjs b/scripts/lib/kuna-reference-verifier.mjs index 96f1c6ddcce..dbc0112d1a9 100644 --- a/scripts/lib/kuna-reference-verifier.mjs +++ b/scripts/lib/kuna-reference-verifier.mjs @@ -28,8 +28,14 @@ export const verifyKunaReferences = async ({ entries(join(cacheRoot, "projects")), entries(join(cacheRoot, "staging")), ]); - const callers = await call("procedure_callers", { procedure: address }); - const callees = await call("procedure_callees", { procedure: address }); + const callers = await call("procedure_callers", { + detail: "complete", + procedure: address, + }); + const callees = await call("procedure_callees", { + detail: "complete", + procedure: address, + }); const incoming = await call("xrefs", { address }); for (const [label, result] of [ ["callers", callers], @@ -72,6 +78,7 @@ export const verifyKunaReferences = async ({ `${name} incoming references differ from exact-target native sites`, ); const graph = await call("get_call_graph", { + detail: "complete", address: expectedCaller, direction: "forward", }); @@ -84,7 +91,10 @@ export const verifyKunaReferences = async ({ assert.equal(path.value.goal_status, "reached"); let traceMs; if (verifyNamedTrace) { - const trace = await call("trace_feature", { query: name }); + const trace = await call("trace_feature", { + detail: "complete", + query: name, + }); traceMs = trace.ms; assert.ok( trace.value.matches.some( @@ -169,7 +179,10 @@ export const verifyKunaReferences = async ({ before, "A reference-only workflow started a C project export", ); - const repeated = await call("procedure_callees", { procedure: address }); + const repeated = await call("procedure_callees", { + detail: "complete", + procedure: address, + }); assert.deepEqual(repeated.value, callees.value); return { callers: callers.value.length, diff --git a/scripts/lib/kuna-string-verifier.mjs b/scripts/lib/kuna-string-verifier.mjs index 3642edffbab..61b8a19c874 100644 --- a/scripts/lib/kuna-string-verifier.mjs +++ b/scripts/lib/kuna-string-verifier.mjs @@ -107,7 +107,7 @@ export const verifyKunaStrings = async ({ entries(join(cacheRoot, "projects")), entries(join(cacheRoot, "staging")), ]); - const cold = await call("search_strings", { pattern }); + const cold = await call("search_strings", { detail: "complete", pattern }); assert.deepEqual( cold.value, selected, @@ -129,18 +129,22 @@ export const verifyKunaStrings = async ({ `Required string ${JSON.stringify(value)} was not recovered`, ); assert.equal(complete.structured.raw_result.strings.sha256, source.sha256); - const repeated = await call("search_strings", { pattern }); + const repeated = await call("search_strings", { + detail: "complete", + pattern, + }); assert.deepEqual(repeated.value, selected); let exact; if (selected.length > 0) { const address = selected[0].address; - exact = await call("list_strings", { address }); + exact = await call("list_strings", { detail: "complete", address }); assert.deepEqual( exact.value, expected.filter((item) => item.address === address), ); } const regex = await call("search_strings", { + detail: "complete", pattern: "^.{5,12}$", mode: "regex", case_sensitive: true, @@ -150,6 +154,7 @@ export const verifyKunaStrings = async ({ expected.filter(({ value }) => /^.{5,12}$/u.test(value)), ); const missing = await call("search_strings", { + detail: "complete", pattern: "\u0000REA-negative-string-query\u0000", }); assert.deepEqual(missing.value, []); diff --git a/scripts/lib/large-result-mcp.mjs b/scripts/lib/large-result-mcp.mjs index 2d304110ed4..f508641dad2 100644 --- a/scripts/lib/large-result-mcp.mjs +++ b/scripts/lib/large-result-mcp.mjs @@ -1,12 +1,15 @@ import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { completeEvidenceClient } from "./complete-evidence.mjs"; /** Own one SDK client with an explicit receive budget for a large complete result. */ export const withLargeResultMcp = async ( { entrypoint, environment, maxBufferSize }, useClient, ) => { - const client = new Client({ name: "large-result-verifier", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "large-result-verifier", version: "1" }), + ); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], diff --git a/scripts/lib/mcp-startup-probe.mjs b/scripts/lib/mcp-startup-probe.mjs index 518b22004a6..9f5507fd34b 100644 --- a/scripts/lib/mcp-startup-probe.mjs +++ b/scripts/lib/mcp-startup-probe.mjs @@ -4,6 +4,7 @@ import { performance } from "node:perf_hooks"; import { Client, SdkError, SdkErrorCode } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { mcpPhaseBudgetRecovery } from "../../dist/config/mcpStartupBudgets.js"; +import { completeEvidenceClient } from "./complete-evidence.mjs"; const RSS_SAMPLE_INTERVAL_MS = 10; const MAXIMUM_PROFILE_BUFFER_BYTES = 2 * 1_024 * 1_024; @@ -29,10 +30,12 @@ export async function measureMcpStartup({ stderr = boundedAppend(stderr, chunk.toString()); }); const rss = createLinuxRssSampler(() => transport.pid); - const client = new Client({ - name: "package-startup-probe", - version: "1.0.0", - }); + const client = completeEvidenceClient( + new Client({ + name: "package-startup-probe", + version: "1.0.0", + }), + ); const startedAt = performance.now(); // One deadline for both phases. Each request also uses the time still left, // so a shorter first-catalog budget stops a pending initialize or tools/list @@ -96,10 +99,12 @@ export async function profileMcpModuleLoading({ stderr: "pipe", }); transport.stderr?.on("data", (chunk) => profile.append(chunk.toString())); - const client = new Client({ - name: "package-module-profile", - version: "1.0.0", - }); + const client = completeEvidenceClient( + new Client({ + name: "package-module-profile", + version: "1.0.0", + }), + ); try { await withPhaseBudget(policy.doctor, () => client.connect(transport, { diff --git a/scripts/lib/native-value-e2e.mjs b/scripts/lib/native-value-e2e.mjs index 63aa53b9bb6..64fabdc3583 100644 --- a/scripts/lib/native-value-e2e.mjs +++ b/scripts/lib/native-value-e2e.mjs @@ -23,6 +23,10 @@ import { verifyGhidraBoundaries } from "./real-ghidra-boundaries.mjs"; import { verifyLegacyValueScopeSnapshot } from "./ghidra-value-scope-snapshot-e2e.mjs"; import { verifyGhidraProjectIdentity } from "./real-ghidra-project-identity.mjs"; import { verifyGhidraSocketBoundary } from "./real-ghidra-socket-boundary.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./complete-evidence.mjs"; const defaultEntrypoint = fileURLToPath(new URL("../rea.mjs", import.meta.url)); const environment = () => ({ @@ -199,18 +203,20 @@ async function verifyNativeValueAdapters( process.execPath, [ entrypoint, - "trace-native-values", - target.path, - procedure, - "--provider", - "ghidra", - "--max-depth", - "2", - "--max-functions", - "8", - "--limit", - "5000", - "--json", + ...(await completeEvidenceCliArguments([ + "trace-native-values", + target.path, + procedure, + "--provider", + "ghidra", + "--max-depth", + "2", + "--max-functions", + "8", + "--limit", + "5000", + "--json", + ])), ], { env, timeout: 240000, maxBuffer: 72 * 1024 * 1024 }, ); @@ -241,7 +247,9 @@ async function verifyNativeValueAdapters( expectedCommand: null, sweepTokenOwnedProcesses: true, }); - const client = new Client({ name: "native-values-real-e2e", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "native-values-real-e2e", version: "1" }), + ); for (const [resource, owner] of [ ["native value MCP client", client], ["native value MCP transport", transport], @@ -473,7 +481,7 @@ async function verifyNativeValueAdapters( async function verifyUnresolvedCallEvidence(client) { const inventory = await client.callTool({ name: "list_procedures", - arguments: {}, + arguments: { detail: "complete" }, }); assert.notEqual(inventory.isError, true, JSON.stringify(inventory)); assert.notEqual(inventory.structuredContent, undefined); diff --git a/scripts/lib/real-ghidra-batch-identity.mjs b/scripts/lib/real-ghidra-batch-identity.mjs index a8d2935f698..9a9bfdfd3da 100644 --- a/scripts/lib/real-ghidra-batch-identity.mjs +++ b/scripts/lib/real-ghidra-batch-identity.mjs @@ -13,7 +13,10 @@ export async function verifyGhidraBatchIdentity(call, names) { assert.ok(interior, "Source fixture lacks an interior instruction"); const name = await call("address_name", { address: leaf.address }); const selectors = [leaf.address, interior, leaf.value, "0x0"]; - const result = await call("batch_decompile", { addresses: selectors }); + const result = await call("batch_decompile", { + detail: "complete", + addresses: selectors, + }); assert.equal(result.total, 4); assert.equal(result.succeeded, 3); assert.equal(result.failed, 1); diff --git a/scripts/lib/real-ghidra-boundaries.mjs b/scripts/lib/real-ghidra-boundaries.mjs index 08747cfa288..86a9e0b4549 100644 --- a/scripts/lib/real-ghidra-boundaries.mjs +++ b/scripts/lib/real-ghidra-boundaries.mjs @@ -175,6 +175,7 @@ export async function verifyGhidraBoundaries( available: true, }); const externalEntry = await call("resolve_containing_procedure", { + detail: "complete", address: external.address, }); assert.equal(externalEntry.found, true); @@ -196,7 +197,10 @@ export async function verifyGhidraBoundaries( .reduce((maximum, offset) => (offset > maximum ? offset : maximum), 0n); const unknownExternal = `${externalSpace}:0x${(lastExternalOffset + 1n).toString(16)}`; assert.deepEqual( - await call("resolve_containing_procedure", { address: unknownExternal }), + await call("resolve_containing_procedure", { + detail: "complete", + address: unknownExternal, + }), { query_address: unknownExternal, found: false, @@ -239,6 +243,7 @@ export async function verifyGhidraBoundaries( ), ); const incoming = await call("procedure_references", { + detail: "complete", procedure: leaf.address, direction: "incoming", }); @@ -290,7 +295,10 @@ export async function verifyGhidraBoundaries( /Unknown|invalid/u, ); assert.equal( - await call("procedure_address", { procedure: address }), + await call("procedure_address", { + detail: "complete", + procedure: address, + }), address, "Invalid selectors must preserve the live provider connection", ); @@ -332,12 +340,19 @@ export async function verifyGhidraBoundaries( ); assert.equal(await call("address_name", { address: spelling }), name); assert.equal( - await call("procedure_address", { procedure: spelling }), + await call("procedure_address", { + detail: "complete", + procedure: spelling, + }), address, ); assert.equal( - (await call("resolve_containing_procedure", { address: spelling })) - .procedure.address, + ( + await call("resolve_containing_procedure", { + detail: "complete", + address: spelling, + }) + ).procedure.address, address, ); } @@ -396,6 +411,7 @@ export async function verifyGhidraBoundaries( ); assert.ok(indirectProcedure); const references = await call("procedure_references", { + detail: "complete", procedure: indirectProcedure.address, }); assert.ok( @@ -413,7 +429,10 @@ export async function verifyGhidraBoundaries( const strings = await call("list_strings"); assert.ok(strings.length > 0); assert.deepEqual( - await call("list_strings", { address: strings[0].address }), + await call("list_strings", { + detail: "complete", + address: strings[0].address, + }), [strings[0]], ); const marker = strings.find( @@ -427,12 +446,16 @@ export async function verifyGhidraBoundaries( }); assert.ok( ( - await call("search_strings", { pattern: marker.value.toLowerCase() }) + await call("search_strings", { + detail: "complete", + pattern: marker.value.toLowerCase(), + }) ).some((item) => item.address === marker.address), ); assert.equal( ( await call("search_strings", { + detail: "complete", pattern: marker.value.toLowerCase(), case_sensitive: true, }) @@ -441,6 +464,7 @@ export async function verifyGhidraBoundaries( ); assert.deepEqual( await call("search_strings", { + detail: "complete", pattern: `REA_GHIDRA_ABSENT_${randomUUID()}`, }), [], @@ -559,7 +583,7 @@ export async function verifyGhidraBoundaries( const regexFailure = await client.callTool( { name: "search_strings", - arguments: { pattern: regexPattern, mode: "regex" }, + arguments: { detail: "complete", pattern: regexPattern, mode: "regex" }, }, options, ); @@ -585,7 +609,7 @@ export async function verifyGhidraBoundaries( const compileFailure = await client.callTool( { name: "search_procedures", - arguments: { pattern: nestedPattern, mode: "regex" }, + arguments: { detail: "complete", pattern: nestedPattern, mode: "regex" }, }, options, ); @@ -608,15 +632,21 @@ export async function verifyGhidraBoundaries( true, ); assert.ok( - (await call("search_procedures", { pattern: changes.name })).some( - (item) => item.address === address, - ), + ( + await call("search_procedures", { + detail: "complete", + pattern: changes.name, + }) + ).some((item) => item.address === address), "Regex compiler exhaustion must preserve edited names and search availability", ); const longLiteral = "a".repeat(3 * 16 ** 3) + "!"; const longString = strings.find((item) => item.value === longLiteral); assert.ok(longString, "The provider must retain the full regression literal"); - const literalMatches = await call("search_strings", { pattern: longLiteral }); + const literalMatches = await call("search_strings", { + detail: "complete", + pattern: longLiteral, + }); assert.deepEqual(literalMatches, [longString]); assert.deepEqual(await cli("search", longLiteral), literalMatches); await assert.rejects( @@ -637,7 +667,10 @@ export async function verifyGhidraBoundaries( }); assert.equal(updated.dossier.procedure.name, changes.name); assert.equal( - await call("procedure_address", { procedure: changes.name }), + await call("procedure_address", { + detail: "complete", + procedure: changes.name, + }), address, ); assert.equal( @@ -667,7 +700,11 @@ export async function verifyGhidraBoundaries( ); assert.ok( ( - await call("search_procedures", { pattern: "dead", case_sensitive: true }) + await call("search_procedures", { + detail: "complete", + pattern: "dead", + case_sensitive: true, + }) ).some((item) => item.address === address), ); @@ -760,7 +797,10 @@ export async function verifyGhidraBoundaries( name: renamed, }); assert.equal( - await call("procedure_address", { procedure: renamed }), + await call("procedure_address", { + detail: "complete", + procedure: renamed, + }), address, ); assert.equal(await call("address_name", { address }), renamed); @@ -782,7 +822,10 @@ export async function verifyGhidraBoundaries( "Ambiguity diagnostics must retain every matching entry address", ); assert.equal( - await call("procedure_address", { procedure: selected }), + await call("procedure_address", { + detail: "complete", + procedure: selected, + }), selected, ); } @@ -825,10 +868,16 @@ export async function verifyGhidraBoundaries( }); await assert.rejects(access(socketRoot), { code: "ENOENT" }); await assert.rejects(access(runtimeRoot), { code: "ENOENT" }); - assert.equal(await call("procedure_address", { procedure: name }), address); + assert.equal( + await call("procedure_address", { detail: "complete", procedure: name }), + address, + ); assert.equal(await call("address_name", { address }), name); assert.equal( - await call("procedure_address", { procedure: indirectProcedure.value }), + await call("procedure_address", { + detail: "complete", + procedure: indirectProcedure.value, + }), indirectProcedure.address, ); assert.deepEqual( @@ -884,7 +933,10 @@ async function verifyStartupCancellation(client, call, target, env, options) { // so persisted immutable snapshots cannot bypass actual provider startup. const request = { name: "search_procedures", - arguments: { pattern: `startup-cancellation-${randomUUID()}` }, + arguments: { + detail: "complete", + pattern: `startup-cancellation-${randomUUID()}`, + }, }; const controller = new AbortController(); let settled = false; diff --git a/scripts/lib/real-ghidra-compact-references.mjs b/scripts/lib/real-ghidra-compact-references.mjs index 8d5c49a6823..19be9051778 100644 --- a/scripts/lib/real-ghidra-compact-references.mjs +++ b/scripts/lib/real-ghidra-compact-references.mjs @@ -10,6 +10,7 @@ export async function verifyGhidraCompactReferences(call, x86, cli) { ["write", x86 ? 0x102a : 0x102d, 0x2004], ]; const full = await call("procedure_references", { + detail: "complete", procedure: address(0x1020), }); const inspected = {}; @@ -138,7 +139,10 @@ async function verifyDirectCall(call, entry, callee) { targets.targets[0].references, direct.references.filter((item) => item.call), ); - const full = await call("procedure_references", { procedure: entry }); + const full = await call("procedure_references", { + detail: "complete", + procedure: entry, + }); for (const reference of direct.references) assertReference(reference, entry, full.references); const incoming = await call("inspect_native_instruction", { diff --git a/scripts/lib/real-ghidra-entry-aliases.mjs b/scripts/lib/real-ghidra-entry-aliases.mjs index 55f10fe7c70..2e9585cd282 100644 --- a/scripts/lib/real-ghidra-entry-aliases.mjs +++ b/scripts/lib/real-ghidra-entry-aliases.mjs @@ -5,6 +5,10 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; +import { + completeEvidenceCliArguments, + completeEvidenceToolArguments, +} from "./complete-evidence.mjs"; /** Verify imported entry aliases through CLI/MCP without admitting interior labels. */ export async function verifyGhidraEntryAliases({ @@ -69,7 +73,7 @@ export async function verifyGhidraEntryAliases({ alias.address, ]) { assert.equal( - await call("procedure_address", { procedure }), + await call("procedure_address", { detail: "complete", procedure }), alias.address, ); assert.equal( @@ -78,8 +82,11 @@ export async function verifyGhidraEntryAliases({ alias.address, ); assert.equal( - await call("procedure_pseudo_code", { procedure }), - await call("procedure_pseudo_code", { procedure: alias.address }), + await call("procedure_pseudo_code", { detail: "complete", procedure }), + await call("procedure_pseudo_code", { + detail: "complete", + procedure: alias.address, + }), ); } // Leaf and qualified forms of the primary name must not duplicate a match. @@ -95,7 +102,12 @@ export async function verifyGhidraEntryAliases({ { pattern: `^${escaped}$`, mode: "regex", case_sensitive: true }, ]) { assert.deepEqual( - (await call("search_procedures", query)) + ( + await call( + "search_procedures", + await completeEvidenceToolArguments("search_procedures", query), + ) + ) .filter(({ address }) => address === alias.address) .map(({ value, matched_aliases }) => ({ value, matched_aliases })), [{ value: canonical.value, matched_aliases: [alias.value] }], @@ -108,7 +120,10 @@ export async function verifyGhidraEntryAliases({ ), "Listings must not report search matches", ); - const traced = await call("trace_feature", { query: alias.value }); + const traced = await call("trace_feature", { + detail: "complete", + query: alias.value, + }); assert.ok( traced.matches.some( ({ type, address, matched_aliases }) => @@ -124,7 +139,12 @@ export async function verifyGhidraEntryAliases({ assert.ok(interior); assert.notEqual(interior.address, alias.address); assert.ok( - (await call("search_procedures", { pattern: interior.value })).every( + ( + await call("search_procedures", { + detail: "complete", + pattern: interior.value, + }) + ).every( ({ address, matched_aliases = [] }) => address !== interior.address && !matched_aliases.includes(interior.value), @@ -152,7 +172,10 @@ export async function verifyGhidraEntryAliases({ /Unknown Ghidra procedure name or address/u, ); assert.equal( - await call("procedure_address", { procedure: interior.address }), + await call("procedure_address", { + detail: "complete", + procedure: interior.address, + }), alias.address, "Explicit interior addresses keep their existing containment semantics", ); @@ -175,7 +198,10 @@ export async function verifyGhidraEntryAliases({ "Selected by imported entry alias", ); assert.equal( - await call("procedure_address", { procedure: alias.value }), + await call("procedure_address", { + detail: "complete", + procedure: alias.value, + }), alias.address, ); await call("close_binary"); @@ -183,12 +209,14 @@ export async function verifyGhidraEntryAliases({ process.execPath, [ entrypoint, - "function", - path, - alias.value, - "--provider", - "ghidra", - "--json", + ...(await completeEvidenceCliArguments([ + "function", + path, + alias.value, + "--provider", + "ghidra", + "--json", + ])), ], { env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 }, ); diff --git a/scripts/lib/real-ghidra-file-offsets.mjs b/scripts/lib/real-ghidra-file-offsets.mjs index 99faeda05ab..0c5b2adeb19 100644 --- a/scripts/lib/real-ghidra-file-offsets.mjs +++ b/scripts/lib/real-ghidra-file-offsets.mjs @@ -23,6 +23,7 @@ import { requireMcpToolError, mcpTextValue, } from "./mcp-verifier-results.mjs"; +import { completeEvidenceClient } from "./complete-evidence.mjs"; /** Exercise file coordinates through public CLI/MCP using the source-owned PE fixture. */ export async function verifyGhidraFileOffsets( @@ -47,7 +48,9 @@ export async function verifyGhidraFileOffsets( TMP: runtime, TMPDIR: runtime, }; - const client = new Client({ name: "rea-file-offsets", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-file-offsets", version: "1" }), + ); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -76,15 +79,19 @@ export async function verifyGhidraFileOffsets( const offset = mapping.normalized_result.file_offset; const coordinate = `0x${offset.toString(16)}`; const expected = parseEvidence( - await call("procedure_pseudo_code", { procedure }), + await call("procedure_pseudo_code", { detail: "complete", procedure }), ); const explicit = parseEvidence( await call("procedure_pseudo_code", { + detail: "complete", procedure: `file-offset:${coordinate}`, }), ); const automatic = parseEvidence( - await call("procedure_pseudo_code", { procedure: coordinate }), + await call("procedure_pseudo_code", { + detail: "complete", + procedure: coordinate, + }), ); for (const actual of [explicit, automatic]) { assert.equal(actual.normalized_result, expected.normalized_result); @@ -99,12 +106,15 @@ export async function verifyGhidraFileOffsets( } const invalid = await mcp.callTool({ name: "procedure_pseudo_code", - arguments: { procedure: "file-offset:0x20000000000000" }, + arguments: { + detail: "complete", + procedure: "file-offset:0x20000000000000", + }, }); assert.equal(requireMcpToolError(invalid).code, "invalid_request"); const unmapped = await mcp.callTool({ name: "procedure_pseudo_code", - arguments: { procedure: "file-offset:0x100000" }, + arguments: { detail: "complete", procedure: "file-offset:0x100000" }, }); assert.ok( JSON.stringify(requireMcpToolError(unmapped)).includes( @@ -131,7 +141,7 @@ export async function verifyGhidraFileOffsets( const missing = requireMcpToolError( await mcp.callTool({ name: "procedure_pseudo_code", - arguments: { procedure: selector }, + arguments: { detail: "complete", procedure: selector }, }), ); assertMissingMappedProcedure(missing, headerMapping.start); @@ -148,6 +158,8 @@ export async function verifyGhidraFileOffsets( [ entrypoint, "decompile", + "--detail", + "complete", targetPath, `--file-offset=${coordinate}`, "--provider", @@ -165,6 +177,8 @@ export async function verifyGhidraFileOffsets( [ entrypoint, "decompile", + "--detail", + "complete", targetPath, "--file-offset=0x0", "--provider", @@ -192,7 +206,10 @@ export async function verifyGhidraFileOffsets( await call("open_binary", { path: ambiguousPath, provider_id: "ghidra" }); const ambiguous = await mcp.callTool({ name: "procedure_pseudo_code", - arguments: { procedure: `file-offset:${coordinate}` }, + arguments: { + detail: "complete", + procedure: `file-offset:${coordinate}`, + }, }); assert.ok( JSON.stringify(requireMcpToolError(ambiguous)).includes( diff --git a/scripts/lib/real-ghidra-instruction-flow.mjs b/scripts/lib/real-ghidra-instruction-flow.mjs index bafbc13b2f3..f2a521b1f30 100644 --- a/scripts/lib/real-ghidra-instruction-flow.mjs +++ b/scripts/lib/real-ghidra-instruction-flow.mjs @@ -44,6 +44,7 @@ export async function verifyGhidraInstructionFlow(call, names, cli, target) { ); if (procedure === undefined) continue; const before = await call("resolve_containing_procedure", { + detail: "complete", address: procedure.address, }); const instructions = await inspectFunction(call, procedure.address); @@ -65,6 +66,7 @@ export async function verifyGhidraInstructionFlow(call, names, cli, target) { } assert.deepEqual( await call("resolve_containing_procedure", { + detail: "complete", address: procedure.address, }), before, diff --git a/scripts/lib/real-ghidra-large-results.mjs b/scripts/lib/real-ghidra-large-results.mjs index 1b2c6550ee7..a0bdd80dd0c 100644 --- a/scripts/lib/real-ghidra-large-results.mjs +++ b/scripts/lib/real-ghidra-large-results.mjs @@ -81,7 +81,10 @@ export async function verifyGhidraLargeResults({ "invalid_request", ); assert.equal( - await call("procedure_address", { procedure: entry.address }), + await call("procedure_address", { + detail: "complete", + procedure: entry.address, + }), entry.address, ); @@ -107,7 +110,10 @@ export async function verifyGhidraLargeResults({ "annotate_native_function", ); assert.equal( - await call("procedure_address", { procedure: "rea_frame_probe" }), + await call("procedure_address", { + detail: "complete", + procedure: "rea_frame_probe", + }), entry.address, "A delivery constraint must preserve the successfully committed edit", ); diff --git a/scripts/lib/real-ghidra-namespace-annotations.mjs b/scripts/lib/real-ghidra-namespace-annotations.mjs index 2e4736a9cd2..2e179719709 100644 --- a/scripts/lib/real-ghidra-namespace-annotations.mjs +++ b/scripts/lib/real-ghidra-namespace-annotations.mjs @@ -71,6 +71,7 @@ export async function verifyGhidraNamespaceAnnotations({ // Search accepts the leaf spelling exact lookup accepts, keeping each // procedure as one row under its qualified primary name. const leafMatches = await call("search_procedures", { + detail: "complete", pattern: "^same$", mode: "regex", case_sensitive: true, @@ -106,6 +107,7 @@ export async function verifyGhidraNamespaceAnnotations({ } assert.equal( await call("procedure_address", { + detail: "complete", procedure: qualified.annotations.name, }), address, diff --git a/scripts/lib/real-ghidra-project-identity.mjs b/scripts/lib/real-ghidra-project-identity.mjs index 1c068ab2ede..6bc4fe84a6e 100644 --- a/scripts/lib/real-ghidra-project-identity.mjs +++ b/scripts/lib/real-ghidra-project-identity.mjs @@ -15,6 +15,10 @@ import { promisify } from "node:util"; import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { requireMcpToolError } from "./mcp-verifier-results.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./complete-evidence.mjs"; const exec = promisify(execFile); @@ -118,13 +122,15 @@ public class ClearImportDigest extends GhidraScript { process.execPath, [ entrypoint, - "decompile", - input, - "0x0", - "--provider", - "ghidra", - "--format", - "json", + ...(await completeEvidenceCliArguments([ + "decompile", + input, + "0x0", + "--provider", + "ghidra", + "--format", + "json", + ])), ], { env: selectedEnv, timeout: 180000, maxBuffer: 8 * 1024 * 1024 }, ); @@ -166,10 +172,12 @@ async function selectedProjectMcp({ matching, expected, }) { - const client = new Client({ - name: "rea-project-identity-verifier", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "rea-project-identity-verifier", + version: "1", + }), + ); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], diff --git a/scripts/lib/real-ghidra-relocation-symbols.mjs b/scripts/lib/real-ghidra-relocation-symbols.mjs index 2dac131d2c3..616f608093f 100644 --- a/scripts/lib/real-ghidra-relocation-symbols.mjs +++ b/scripts/lib/real-ghidra-relocation-symbols.mjs @@ -7,6 +7,7 @@ import { parseEvidence } from "../../dist/domain/evidence.js"; import { PrivateRuntimeRoot } from "../../dist/process/PrivateRuntimeRoot.js"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; import { createVerifierCommands } from "./verify-commands.mjs"; +import { completeEvidenceCliArguments } from "./complete-evidence.mjs"; const source = fileURLToPath( new URL( @@ -53,11 +54,13 @@ export async function verifyGhidraRelocationSymbols({ clang, lld, env }) { const before = await hash(); const { stdout } = await run(process.execPath, [ "scripts/rea.mjs", - "inspect-native-load-image", - target, - "--provider", - "ghidra", - "--json", + ...(await completeEvidenceCliArguments([ + "inspect-native-load-image", + target, + "--provider", + "ghidra", + "--json", + ])), ]); const evidence = parseEvidence(JSON.parse(stdout)); assert.equal(evidence.subject?.identity.sha256, before); diff --git a/scripts/lib/real-ghidra-search-facts.mjs b/scripts/lib/real-ghidra-search-facts.mjs index 2d275c637ae..ceed925a3f0 100644 --- a/scripts/lib/real-ghidra-search-facts.mjs +++ b/scripts/lib/real-ghidra-search-facts.mjs @@ -39,6 +39,7 @@ export async function verifyGhidraSearchFacts( `${operation} must preserve inventory facts for ${row.value}`, ); const trace = await call("trace_feature", { + detail: "complete", query: row.value, case_sensitive: true, }); diff --git a/scripts/lib/real-ghidra-socket-boundary.mjs b/scripts/lib/real-ghidra-socket-boundary.mjs index 4d9699c3569..b547b1183b8 100644 --- a/scripts/lib/real-ghidra-socket-boundary.mjs +++ b/scripts/lib/real-ghidra-socket-boundary.mjs @@ -16,6 +16,10 @@ import { promisify } from "node:util"; import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./complete-evidence.mjs"; const exec = promisify(execFile); @@ -62,10 +66,12 @@ export async function verifyGhidraSocketBoundary({ assert.equal(Buffer.byteLength(parent) + suffixBytes, proposedBytes); if (unicode) assert.ok(Buffer.byteLength(parent) > parent.length); const sessionEnv = { ...env, TMPDIR: parent }; - const client = new Client({ - name: "rea-ghidra-socket-boundary", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "rea-ghidra-socket-boundary", + version: "1", + }), + ); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -162,12 +168,14 @@ export async function verifyGhidraSocketBoundary({ process.execPath, [ entrypoint, - "function", - target.path, - procedure, - "--provider", - "ghidra", - "--json", + ...(await completeEvidenceCliArguments([ + "function", + target.path, + procedure, + "--provider", + "ghidra", + "--json", + ])), ], { env: sessionEnv, timeout: 240000, maxBuffer: 72 * 1024 * 1024 }, ); diff --git a/scripts/lib/real-ghidra-target-admission.mjs b/scripts/lib/real-ghidra-target-admission.mjs index d2c2fb76889..15c3e01e096 100644 --- a/scripts/lib/real-ghidra-target-admission.mjs +++ b/scripts/lib/real-ghidra-target-admission.mjs @@ -109,8 +109,12 @@ export async function verifyGhidraTargetAdmission({ instruction, ); assert.equal( - (await call("resolve_containing_procedure", { address })).procedure - .address, + ( + await call("resolve_containing_procedure", { + detail: "complete", + address, + }) + ).procedure.address, entry, ); } diff --git a/scripts/lib/real-hopper-boundaries.mjs b/scripts/lib/real-hopper-boundaries.mjs index 55c3f6c964c..56ecf7965d2 100644 --- a/scripts/lib/real-hopper-boundaries.mjs +++ b/scripts/lib/real-hopper-boundaries.mjs @@ -20,6 +20,7 @@ import { verifyHopperSearch, verifyHopperRegexIsolation, } from "./real-hopper-search.mjs"; +import { completeEvidenceCliArguments } from "./complete-evidence.mjs"; const dispatcher = fileURLToPath(new URL("../rea.mjs", import.meta.url)); @@ -228,6 +229,7 @@ export async function verifyHopperBoundaryContracts( ); assert.equal(await call("address_name", { address }), renamed); const matches = await call("search_procedures", { + detail: "complete", pattern: renamed, case_sensitive: true, }); @@ -250,7 +252,7 @@ export async function verifyHopperBoundaryContracts( true, ); assert.equal( - await call("procedure_address", { procedure: "add" }), + await call("procedure_address", { detail: "complete", procedure: "add" }), address, ); assert.equal( @@ -262,7 +264,10 @@ export async function verifyHopperBoundaryContracts( address, ); assert.equal( - await call("procedure_address", { procedure: address.slice(2) }), + await call("procedure_address", { + detail: "complete", + procedure: address.slice(2), + }), address, ); @@ -480,7 +485,10 @@ export async function verifyHopperLifecycleAndCli( }); await call("open_binary", { path: primary }); const query = "REA_C_LEAF __rea_missing_phrase__"; - const expectedTrace = await call("trace_feature", { query }); + const expectedTrace = await call("trace_feature", { + detail: "complete", + query, + }); assert.deepEqual(expectedTrace.matches, []); await call("close_binary"); @@ -505,26 +513,30 @@ export async function verifyHopperLifecycleAndCli( assert.deepEqual(evidence.normalized_result, expected); const traced = await runCli([ dispatcher, - "trace", - primary, - query, - "--provider", - "hopper", - "--format", - "json", + ...(await completeEvidenceCliArguments([ + "trace", + primary, + query, + "--provider", + "hopper", + "--format", + "json", + ])), ]); const traceEvidence = JSON.parse(traced.stdout); assert.equal(traceEvidence.subject.local_path, primary); assert.deepEqual(traceEvidence.normalized_result, expectedTrace); const analyzed = await runCli([ dispatcher, - "function", - primary, - entry.value, - "--provider", - "hopper", - "--format", - "json", + ...(await completeEvidenceCliArguments([ + "function", + primary, + entry.value, + "--provider", + "hopper", + "--format", + "json", + ])), ]); assert.deepEqual( JSON.parse(analyzed.stdout).normalized_result, @@ -548,13 +560,15 @@ export async function verifyHopperLifecycleAndCli( await call("close_binary"); const analyzed = await runCli([ dispatcher, - "function", - objc, - delegate.address, - "--provider", - "hopper", - "--format", - "json", + ...(await completeEvidenceCliArguments([ + "function", + objc, + delegate.address, + "--provider", + "hopper", + "--format", + "json", + ])), ]); assert.deepEqual(JSON.parse(analyzed.stdout).normalized_result, expected); cliTerminalFunctionParity = true; @@ -615,7 +629,10 @@ const verifyBatchCancellation = async (client, options, procedures) => { client.callTool( { name: "batch_decompile", - arguments: { addresses: procedures.map((item) => item.address) }, + arguments: { + detail: "complete", + addresses: procedures.map((item) => item.address), + }, }, { ...options, @@ -634,7 +651,10 @@ const verifyBatchCancellation = async (client, options, procedures) => { ); assert.ok(cancelled, "cancellation did not follow a real Hopper response"); const recovered = requireMcpEvidenceResult( - await client.callTool({ name: "list_procedures", arguments: {} }, options), + await client.callTool( + { name: "list_procedures", arguments: { detail: "complete" } }, + options, + ), "list_procedures", ); assert.deepEqual(recovered, procedures); diff --git a/scripts/lib/real-hopper-function-basics.mjs b/scripts/lib/real-hopper-function-basics.mjs index 04ad28f1227..de438c94dec 100644 --- a/scripts/lib/real-hopper-function-basics.mjs +++ b/scripts/lib/real-hopper-function-basics.mjs @@ -10,7 +10,7 @@ export const verifyHopperFunctionBasics = async ( await client.callTool( { name: "resolve_containing_procedure", - arguments: { address: procedure }, + arguments: { detail: "complete", address: procedure }, }, options, ), @@ -29,10 +29,7 @@ export const verifyHopperFunctionBasics = async ( await client.callTool( { name: "procedure_references", - arguments: { - procedure, - direction: "outgoing", - }, + arguments: { detail: "complete", procedure, direction: "outgoing" }, }, options, ), @@ -80,6 +77,7 @@ export async function verifyHopperTerminalInstructions(call) { let terminalCalls = 0; for (const { address } of selected) { const references = await call("procedure_references", { + detail: "complete", procedure: address, direction: "outgoing", }); diff --git a/scripts/lib/real-hopper-owner-exit.mjs b/scripts/lib/real-hopper-owner-exit.mjs index 6f6784e7beb..551fa06f253 100644 --- a/scripts/lib/real-hopper-owner-exit.mjs +++ b/scripts/lib/real-hopper-owner-exit.mjs @@ -16,6 +16,7 @@ import { requireMcpEvidenceResult, requireMcpLifecycleResult, } from "./mcp-verifier-results.mjs"; +import { completeEvidenceClient } from "./complete-evidence.mjs"; /** Prove actual MCP owner exit releases the demo singleton for subsequent CLI/MCP sessions. */ export async function verifyLinuxHopperOwnerExit({ @@ -47,7 +48,9 @@ export async function verifyLinuxHopperOwnerExit({ }); // Drain launcher diagnostics even on the deliberately interrupted owner. transport.stderr?.resume(); - const client = new Client({ name: "hopper-owner-exit", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "hopper-owner-exit", version: "1" }), + ); const options = { timeout: 180_000 }; try { await client.connect(transport); @@ -80,7 +83,7 @@ export async function verifyLinuxHopperOwnerExit({ ); const procedures = requireMcpEvidenceResult( await client.callTool( - { name: "list_procedures", arguments: {} }, + { name: "list_procedures", arguments: { detail: "complete" } }, options, ), "list_procedures", diff --git a/scripts/lib/real-hopper-search.mjs b/scripts/lib/real-hopper-search.mjs index 6decda4ad5e..3acd6d8e7c2 100644 --- a/scripts/lib/real-hopper-search.mjs +++ b/scripts/lib/real-hopper-search.mjs @@ -16,6 +16,7 @@ export async function verifyHopperSearch(call, invalid, procedure) { } assert.deepEqual( await call("search_procedures", { + detail: "complete", pattern: original, mode: "literal", case_sensitive: true, @@ -39,21 +40,30 @@ async function verifySymbolNames(call, invalid, address) { for (const name of ["REA_a.b[0]", unicode, ...extentNames]) { assert.equal(await call("set_address_name", { address, name }), true); assert.equal(await call("address_name", { address }), name); - assert.deepEqual(await call("list_names", { address }), [ - { address, value: name }, - ]); + assert.deepEqual( + await call("list_names", { detail: "complete", address }), + [{ address, value: name }], + ); assert.deepEqual( await call("search_procedures", { + detail: "complete", pattern: name, mode: "literal", case_sensitive: true, }), [{ address, value: name }], ); - assert.equal(await call("procedure_address", { procedure: name }), address); + assert.equal( + await call("procedure_address", { detail: "complete", procedure: name }), + address, + ); } assert.deepEqual( - await call("search_procedures", { pattern: unicode, mode: "literal" }), + await call("search_procedures", { + detail: "complete", + pattern: unicode, + mode: "literal", + }), [], ); const other = (await call("list_procedures")).find( @@ -83,6 +93,7 @@ async function verifySearchModes(call, address) { await call("set_address_name", { address, name: "REA_Search_Upper" }); assert.deepEqual( await call("search_procedures", { + detail: "complete", pattern: "rea_search_upper", mode: "literal", case_sensitive: false, @@ -91,6 +102,7 @@ async function verifySearchModes(call, address) { ); assert.deepEqual( await call("search_procedures", { + detail: "complete", pattern: "rea_search_upper", mode: "literal", case_sensitive: true, @@ -99,6 +111,7 @@ async function verifySearchModes(call, address) { ); assert.deepEqual( await call("search_procedures", { + detail: "complete", pattern: "^REA_Search_(?:Upper|Lower)$", mode: "regex", case_sensitive: true, @@ -148,6 +161,7 @@ async function verifySearchModes(call, address) { assert.deepEqual( await call("search_strings", { + detail: "complete", pattern: "fragment_tail", mode: "literal", case_sensitive: true, @@ -160,6 +174,7 @@ async function verifySearchModes(call, address) { assert.equal(expected.length, 2); assert.deepEqual( await call("search_strings", { + detail: "complete", pattern: "^REA_C_(?:ENTRY|LEAF)$", mode: "regex", case_sensitive: true, @@ -340,11 +355,13 @@ export async function verifyHopperStringObjects( })); assert.equal(bytes.complete, true); assert.equal(bytes.bytes_hex, expectedBytes.toString("hex")); - assert.deepEqual(await call("list_strings", { address: item.address }), [ - item, - ]); + assert.deepEqual( + await call("list_strings", { detail: "complete", address: item.address }), + [item], + ); assert.deepEqual( await call("search_strings", { + detail: "complete", pattern: value, mode: "literal", case_sensitive: true, @@ -353,7 +370,11 @@ export async function verifyHopperStringObjects( ); } assert.deepEqual( - await call("search_strings", { pattern: "\\xC3\\xA9", mode: "literal" }), + await call("search_strings", { + detail: "complete", + pattern: "\\xC3\\xA9", + mode: "literal", + }), [], ); return { @@ -377,7 +398,12 @@ export async function verifyHopperRegexIsolation( const reply = await client.callTool( { name: "search_procedures", - arguments: { pattern: "(a+)+$", mode: "regex", case_sensitive: true }, + arguments: { + detail: "complete", + pattern: "(a+)+$", + mode: "regex", + case_sensitive: true, + }, }, options, ); @@ -391,7 +417,12 @@ export async function verifyHopperRegexIsolation( const pending = client.callTool( { name: "search_procedures", - arguments: { pattern: "(a+)+$", mode: "regex", case_sensitive: true }, + arguments: { + detail: "complete", + pattern: "(a+)+$", + mode: "regex", + case_sensitive: true, + }, }, { ...options, signal: controller.signal }, ); @@ -404,6 +435,7 @@ export async function verifyHopperRegexIsolation( assert.equal(await call("address_name", { address }), pathological); assert.deepEqual( await call("search_procedures", { + detail: "complete", pattern: pathological, mode: "literal", case_sensitive: true, diff --git a/scripts/lib/real-hopper-semantic.mjs b/scripts/lib/real-hopper-semantic.mjs index 11ca07c0e67..2ccab730998 100644 --- a/scripts/lib/real-hopper-semantic.mjs +++ b/scripts/lib/real-hopper-semantic.mjs @@ -148,7 +148,11 @@ export async function verifyRealHopperFixture({ await client.callTool( { name: "procedure_references", - arguments: { procedure: entry.address, direction: "outgoing" }, + arguments: { + detail: "complete", + procedure: entry.address, + direction: "outgoing", + }, }, options, ), @@ -282,6 +286,7 @@ export async function resolveFixtureProcedure( { name: "search_procedures", arguments: { + detail: "complete", pattern: expectedName, mode: "literal", case_sensitive: true, diff --git a/scripts/lib/real-hopper-workflows.mjs b/scripts/lib/real-hopper-workflows.mjs index 9c71353adf0..b095cce689a 100644 --- a/scripts/lib/real-hopper-workflows.mjs +++ b/scripts/lib/real-hopper-workflows.mjs @@ -4,7 +4,10 @@ import assert from "node:assert/strict"; export async function verifyHopperWorkflows(call, invalid, procedure) { const address = procedure.address; const originalName = await call("address_name", { address }); - const callees = await call("procedure_callees", { procedure: address }); + const callees = await call("procedure_callees", { + detail: "complete", + procedure: address, + }); assert.ok(callees.length > 0, "fixture omitted a reachable call target"); const goal = callees[0]; const goalName = await call("address_name", { address: goal }); @@ -22,13 +25,16 @@ export async function verifyHopperWorkflows(call, invalid, procedure) { }), canonicalPath, ); - const graph = await call("get_call_graph", { address }); + const graph = await call("get_call_graph", { detail: "complete", address }); assert.deepEqual( - await call("get_call_graph", { address: originalName }), + await call("get_call_graph", { detail: "complete", address: originalName }), graph, ); assert.deepEqual( - await call("get_call_graph", { address: address.toUpperCase() }), + await call("get_call_graph", { + detail: "complete", + address: address.toUpperCase(), + }), graph, ); const procedures = await call("list_procedures"); @@ -36,7 +42,10 @@ export async function verifyHopperWorkflows(call, invalid, procedure) { /rea_cycle_[ab]$/u.test(item.value), ); assert.equal(cycle.length, 2, "fixture omitted its source-owned call cycle"); - const cycleGraph = await call("get_call_graph", { address: cycle[0].value }); + const cycleGraph = await call("get_call_graph", { + detail: "complete", + address: cycle[0].value, + }); const cycleNodes = Object.values(cycleGraph.graph).flat(); assert.equal(cycleNodes.length, 2); assert.deepEqual( @@ -59,6 +68,7 @@ export async function verifyHopperWorkflows(call, invalid, procedure) { "procedure_address", ); const missingPhrase = await call("trace_feature", { + detail: "complete", query: "REA_C_LEAF __rea_missing_phrase__", }); assert.deepEqual(missingPhrase.matches, []); @@ -66,11 +76,17 @@ export async function verifyHopperWorkflows(call, invalid, procedure) { const phrase = "REA boundary phrase"; try { await call("set_address_name", { address, name: phrase }); - const traced = await call("trace_feature", { query: phrase }); + const traced = await call("trace_feature", { + detail: "complete", + query: phrase, + }); assert.deepEqual(traced.matches, [ { type: "procedure", address, value: phrase }, ]); - const spaced = await call("trace_feature", { query: ` ${phrase} ` }); + const spaced = await call("trace_feature", { + detail: "complete", + query: ` ${phrase} `, + }); assert.deepEqual(spaced.matches, []); assert.deepEqual(spaced.references, []); } finally { diff --git a/scripts/lib/release-package-canary.mjs b/scripts/lib/release-package-canary.mjs index 2a8637c29d6..f0f90587562 100644 --- a/scripts/lib/release-package-canary.mjs +++ b/scripts/lib/release-package-canary.mjs @@ -9,6 +9,7 @@ import { DEFAULT_CATALOG_IDENTITY } from "../../dist/contracts/catalog/catalogId import { MCP_TARGET_FREE_ENVIRONMENT_OVERRIDES } from "../../dist/config/mcpTargetEnvironment.js"; import { mergeEnvironmentOverrides } from "../../dist/process/snapshotEnvironment.js"; import { verifyCompleteToolCatalog } from "./verify-package-core.mjs"; +import { completeEvidenceClient } from "./complete-evidence.mjs"; /** Install the selected archive or registry specifier with an owned ten-minute deadline. */ export async function installCanaryPackage( @@ -86,7 +87,9 @@ export async function verifyCanaryMcp( env: targetFreeEnvironment, stderr: "pipe", }); - const client = new Client({ name: "release-package-canary", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "release-package-canary", version: "1" }), + ); let stderr = ""; transport.stderr?.on("data", (chunk) => { if (stderr.length < 16_384) diff --git a/scripts/lib/verify-wabt-cleanup.mjs b/scripts/lib/verify-wabt-cleanup.mjs index 8d4b3424d8c..8f449a49ed4 100644 --- a/scripts/lib/verify-wabt-cleanup.mjs +++ b/scripts/lib/verify-wabt-cleanup.mjs @@ -17,6 +17,10 @@ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { requireMcpToolError } from "./mcp-verifier-results.mjs"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; import { WABT_OPERATION_TIMEOUT_MS } from "./wabt-verifier-timeouts.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./complete-evidence.mjs"; const execute = promisify(execFile); /** Real WABT inspection with authored cleanup denials and same-connection recovery. */ export async function verifyWabtCleanup(entrypoint, environment, parent) { @@ -83,9 +87,11 @@ export async function verifyWabtCleanup(entrypoint, environment, parent) { "--import", preload, entrypoint, - "inspect-wasm-artifact", - input, - "--json", + ...(await completeEvidenceCliArguments([ + "inspect-wasm-artifact", + input, + "--json", + ])), ], { env: c.env, @@ -155,7 +161,9 @@ export async function verifyWabtCleanup(entrypoint, environment, parent) { } for (const mode of ["runtime-once", "runtime-until-allowed"]) { const c = await setup("mcp-" + mode, mode, valid); - const client = new Client({ name: "wabt-cleanup-probe", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "wabt-cleanup-probe", version: "1" }), + ); const transport = new StdioClientTransport({ command: process.execPath, args: ["--import", preload, entrypoint, "mcp"], @@ -167,7 +175,7 @@ export async function verifyWabtCleanup(entrypoint, environment, parent) { await client.connect(transport); const request = { name: "inspect_wasm_artifact", - arguments: { path: valid }, + arguments: { detail: "complete", path: valid }, }; const call = () => client.callTool(request, { timeout: WABT_OPERATION_TIMEOUT_MS }); diff --git a/scripts/verify-apk-signature.mjs b/scripts/verify-apk-signature.mjs index f0815080b83..059c99a47b7 100644 --- a/scripts/verify-apk-signature.mjs +++ b/scripts/verify-apk-signature.mjs @@ -28,6 +28,10 @@ import { import { VerifierFixture } from "./lib/verifier-fixture.mjs"; import { mcpTextValue, requireMcpOutput } from "./lib/mcp-verifier-results.mjs"; import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; const execute = promisify(execFile); const environment = Object.fromEntries( @@ -208,10 +212,12 @@ const inspectCli = async (path) => { ( await run(process.execPath, [ entrypoint, - "inspect-apk-signature", - path, - "--format", - "json", + ...(await completeEvidenceCliArguments([ + "inspect-apk-signature", + path, + "--format", + "json", + ])), ]) ).stdout, ); @@ -227,7 +233,9 @@ const fixture = await VerifierFixture.open({ prefix: "rea-apk-signature-verifier-", }); const workspace = fixture.path; -const client = new Client({ name: "apk-signature-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "apk-signature-verifier", version: "1" }), +); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], diff --git a/scripts/verify-binary-layout.mjs b/scripts/verify-binary-layout.mjs index c0355e08e26..3f51fc44422 100644 --- a/scripts/verify-binary-layout.mjs +++ b/scripts/verify-binary-layout.mjs @@ -31,6 +31,10 @@ import { createVerifierCommands } from "./lib/verify-commands.mjs"; import { sectionNameFixtures } from "./lib/elf-section-name-fixtures.mjs"; import { withLargeResultMcp } from "./lib/large-result-mcp.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; const verifyLargeMcp = process.env.REA_VERIFY_LARGE_ELF_MCP === "1"; const python = process.env.REA_PWNTOOLS_PYTHON; @@ -68,7 +72,9 @@ const limitedEnvironment = (option) => ({ REA_VERIFY_LIMITED_PYTHON: python, REA_VERIFY_LIMIT_OPTION: option, }); -const client = new Client({ name: "binary-layout-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "binary-layout-verifier", version: "1" }), +); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -1163,10 +1169,12 @@ try { ["--fsize=33554432", '"file_size_bytes": 33554432'], ]) { const selectedEnvironment = limitedEnvironment(option); - const limitedClient = new Client({ - name: "limited-layout-verifier", - version: "1", - }); + const limitedClient = completeEvidenceClient( + new Client({ + name: "limited-layout-verifier", + version: "1", + }), + ); const limitedTransport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -1242,10 +1250,12 @@ try { // Resource limits are result-affecting inputs: upstream PLT emulation may be // incomplete under this address-space budget. Compare adapters at that budget. const memoryEnvironment = limitedEnvironment("--as=100663296"); - const memoryClient = new Client({ - name: "memory-layout-verifier", - version: "1", - }); + const memoryClient = completeEvidenceClient( + new Client({ + name: "memory-layout-verifier", + version: "1", + }), + ); const memoryTransport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -1311,7 +1321,9 @@ try { const cpuHeavyPath = join(root.path, "cpu-section-heavy.o"); await writeFile(cpuHeavyPath, cpuHeavy); const cpuEnvironment = limitedEnvironment("--cpu=1:"); - const cpuClient = new Client({ name: "cpu-layout-verifier", version: "1" }); + const cpuClient = completeEvidenceClient( + new Client({ name: "cpu-layout-verifier", version: "1" }), + ); const cpuTransport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -1344,10 +1356,12 @@ try { } for (const limit of [1024, 1]) { const fileEnvironment = limitedEnvironment(`--fsize=${limit}:`); - const fileClient = new Client({ - name: "file-size-layout-verifier", - version: "1", - }); + const fileClient = completeEvidenceClient( + new Client({ + name: "file-size-layout-verifier", + version: "1", + }), + ); const fileTransport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -1461,10 +1475,12 @@ try { ...environment, REA_PWNTOOLS_PYTHON: configuredPython, }; - const selectedClient = new Client({ - name: "unavailable-layout-verifier", - version: "1", - }); + const selectedClient = completeEvidenceClient( + new Client({ + name: "unavailable-layout-verifier", + version: "1", + }), + ); const selectedTransport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -1520,9 +1536,11 @@ try { trace, process.execPath, entrypoint, - "inspect-binary-layout", - join(root.path, name), - "--json", + ...(await completeEvidenceCliArguments([ + "inspect-binary-layout", + join(root.path, name), + "--json", + ])), ], { env: { ...environment, PATH: "/usr/bin:/bin" }, @@ -1639,7 +1657,7 @@ async function inspect( const response = await selectedClient.callTool( { name: "inspect_binary_layout", - arguments: { path }, + arguments: { detail: "complete", path }, }, { timeout: 300_000 }, ); @@ -1654,7 +1672,14 @@ async function inspect( try { response = await commands.exec( process.execPath, - [entrypoint, "inspect-binary-layout", path, "--json"], + [ + entrypoint, + ...(await completeEvidenceCliArguments([ + "inspect-binary-layout", + path, + "--json", + ])), + ], { env: selectedEnvironment, timeout: 40_000, diff --git a/scripts/verify-cline-client.mjs b/scripts/verify-cline-client.mjs index 712d7697098..573c13575e1 100644 --- a/scripts/verify-cline-client.mjs +++ b/scripts/verify-cline-client.mjs @@ -10,6 +10,7 @@ import { createVerifierMcpOwner } from "./lib/verifier-mcp-owner.mjs"; import { withVerifierCleanup } from "./lib/verifier-cleanup.mjs"; import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; /** Verify default-path CLI registration, client parsing and owned MCP discovery. */ const repo = fileURLToPath(new URL("..", import.meta.url)); @@ -107,7 +108,9 @@ const report = await withVerifierCleanup(async () => { expectedCommand: null, sweepTokenOwnedProcesses: true, }); - const client = new Client({ name: "rea-cline-verifier", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-cline-verifier", version: "1" }), + ); // The SDK keeps stdin open through delayed initialization and tool discovery. const connection = await mcp.open(client, transport); assert.equal( diff --git a/scripts/verify-deno-standalone.mjs b/scripts/verify-deno-standalone.mjs index 9fea16ca365..e73981988bf 100644 --- a/scripts/verify-deno-standalone.mjs +++ b/scripts/verify-deno-standalone.mjs @@ -120,7 +120,13 @@ await withVerifierFixture(root, async () => { ]); const hostOutput = await producedBinary(hostBinary); const inspectedText = JSON.stringify( - await cli(["inspect-artifact", hostOutput, "--json"]), + await cli([ + "inspect-artifact", + "--detail", + "complete", + hostOutput, + "--json", + ]), ); assert.ok(inspectedText.includes(secret)); const graph = inventoryOf(JSON.parse(inspectedText)); @@ -203,7 +209,7 @@ await withVerifierFixture(root, async () => { continue; } const crossGraph = inventoryOf( - await cli(["inspect-artifact", output, "--json"]), + await cli(["inspect-artifact", "--detail", "complete", output, "--json"]), ); assert.equal(crossGraph.manifest.root_format, "deno-standalone"); const metadata = crossGraph.occurrences.find( @@ -240,7 +246,13 @@ await withVerifierFixture(root, async () => { const damaged = join(root.path, "damaged-native-elf"); await writeFile(damaged, image); nativeElfRootFormat = inventoryOf( - await cli(["inspect-artifact", damaged, "--json"]), + await cli([ + "inspect-artifact", + "--detail", + "complete", + damaged, + "--json", + ]), ).manifest.root_format; assert.notEqual(nativeElfRootFormat, "deno-standalone"); } diff --git a/scripts/verify-evm-interface.mjs b/scripts/verify-evm-interface.mjs index 92e19f3720a..7cd6ee250f8 100644 --- a/scripts/verify-evm-interface.mjs +++ b/scripts/verify-evm-interface.mjs @@ -20,6 +20,10 @@ import { completeVerifierRun, } from "./lib/verifier-run.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; const manifest = JSON.parse( await readFile(new URL("../package.json", import.meta.url), "utf8"), @@ -63,7 +67,9 @@ const environment = Object.fromEntries( Object.entries(process.env).filter(([, value]) => typeof value === "string"), ); const root = await VerifierFixture.open({ prefix: "rea-evm-verifier-" }); -const client = new Client({ name: "evm-interface-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "evm-interface-verifier", version: "1" }), +); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -94,10 +100,12 @@ try { [ ...scope.prefix, entrypoint, - "inspect-evm-interface", - path, - encoding, - "--json", + ...(await completeEvidenceCliArguments([ + "inspect-evm-interface", + path, + encoding, + "--json", + ])), ], { env: scope.environment ?? environment, @@ -113,7 +121,7 @@ try { } else { const reply = await scope.client.callTool({ name: "inspect_evm_interface", - arguments: { path, encoding }, + arguments: { detail: "complete", path, encoding }, }); value = expectedCategory !== undefined @@ -351,10 +359,12 @@ try { process.execPath, "--disable-wasm-trap-handler", ]; - const limitedClient = new Client({ - name: "limited-evm-verifier", - version: "1", - }); + const limitedClient = completeEvidenceClient( + new Client({ + name: "limited-evm-verifier", + version: "1", + }), + ); const limitedTransport = new StdioClientTransport({ command: limiter, args: [...prefix, entrypoint, "mcp"], @@ -416,10 +426,12 @@ try { ...environment, REA_EVM_PRLIMIT_COMMAND: limiter, }; - const selectedClient = new Client({ - name: "unavailable-evm-limiter-verifier", - version: "1", - }); + const selectedClient = completeEvidenceClient( + new Client({ + name: "unavailable-evm-limiter-verifier", + version: "1", + }), + ); const selectedTransport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -493,10 +505,12 @@ try { join(root.path, `offline.trace.${name}`), process.execPath, entrypoint, - "inspect-evm-interface", - join(root.path, name), - encoding, - "--json", + ...(await completeEvidenceCliArguments([ + "inspect-evm-interface", + join(root.path, name), + encoding, + "--json", + ])), ], { env: { ...environment, PATH: "/usr/bin:/bin" }, diff --git a/scripts/verify-flutter.mjs b/scripts/verify-flutter.mjs index 474c558b961..35cd75f0691 100644 --- a/scripts/verify-flutter.mjs +++ b/scripts/verify-flutter.mjs @@ -14,6 +14,7 @@ import { VerifierFixture, withVerifierFixture, } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const options = parseArguments(process.argv.slice(2)); if (options.help) { @@ -48,7 +49,9 @@ Object.assign(environment, { TMP: root, TEMP: root, }); -const client = new Client({ name: "flutter-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "flutter-verifier", version: "1" }), +); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], diff --git a/scripts/verify-go-binary.mjs b/scripts/verify-go-binary.mjs index 6b60423c0e8..fe4c6f77f3a 100644 --- a/scripts/verify-go-binary.mjs +++ b/scripts/verify-go-binary.mjs @@ -16,6 +16,7 @@ import { createVerifierCommands } from "./lib/verify-commands.mjs"; import { createOwnedMcpStdioTransport } from "./lib/owned-mcp-stdio.mjs"; import { closeVerifierResources } from "./lib/verifier-cleanup.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const commands = await createVerifierCommands(); const compiler = process.env.REA_VERIFY_GO_COMMAND ?? "go"; @@ -77,7 +78,9 @@ const verified = []; const omittedCoverage = []; const failures = []; try { - client = new Client({ name: "go-binary-verifier", version: "1" }); + client = completeEvidenceClient( + new Client({ name: "go-binary-verifier", version: "1" }), + ); transport = await createOwnedMcpStdioTransport({ command: process.execPath, arguments: [entrypoint, "mcp"], @@ -368,6 +371,8 @@ async function inspect(mode, path, includeStringLiterals = false) { "inspect-go-binary", path, ...(includeStringLiterals ? ["--include-string-literals"] : []), + "--detail", + "complete", "--json", ]; const { stdout } = await commands.exec(process.execPath, args, { @@ -378,11 +383,14 @@ async function inspect(mode, path, includeStringLiterals = false) { envelope = JSON.parse(stdout); } else { const argumentsPayload = includeStringLiterals - ? { path, include_string_literals: true } - : { path }; + ? { path, include_string_literals: true, detail: "complete" } + : { path, detail: "complete" }; const response = await artifactMcpCall( client, - { name: "inspect_go_binary", arguments: argumentsPayload }, + { + name: "inspect_go_binary", + arguments: { ...argumentsPayload, detail: "complete" }, + }, { timeout: 30_000 }, ); envelope = requireMcpOutput(response, "inspect_go_binary"); diff --git a/scripts/verify-http3-network-captures.mjs b/scripts/verify-http3-network-captures.mjs index 05c2aa26689..79b2fc4d3f7 100644 --- a/scripts/verify-http3-network-captures.mjs +++ b/scripts/verify-http3-network-captures.mjs @@ -29,6 +29,7 @@ import { requireMcpEvidenceBundle, requireMcpOutput, } from "./lib/mcp-verifier-results.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const root = process.argv[2]; const inspectExisting = process.argv[3] === "--inspect-existing"; @@ -58,10 +59,12 @@ const entrypoint = fileURLToPath(new URL("./rea.mjs", import.meta.url)); const environment = Object.fromEntries( Object.entries(process.env).filter(([, value]) => typeof value === "string"), ); -const client = new Client({ - name: "real-http3-capture-verifier", - version: "1", -}); +const client = completeEvidenceClient( + new Client({ + name: "real-http3-capture-verifier", + version: "1", + }), +); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -103,6 +106,8 @@ async function cli(input, name) { arguments: [ entrypoint, "inspect-web-network-capture", + "--detail", + "complete", input.capture_path, input.format, "--json", diff --git a/scripts/verify-il2cpp-metadata.mjs b/scripts/verify-il2cpp-metadata.mjs index 5d27eb1c1e4..a22505b76ca 100644 --- a/scripts/verify-il2cpp-metadata.mjs +++ b/scripts/verify-il2cpp-metadata.mjs @@ -14,6 +14,10 @@ import { } from "./lib/mcp-verifier-results.mjs"; import { withVerifierCleanup } from "./lib/verifier-cleanup.mjs"; import { hashVerifierFile } from "./lib/verifier-file-resources.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; const args = process.argv.slice(2); if (args.includes("--help") || args.includes("-h")) { @@ -29,7 +33,9 @@ const operation = "inspect_il2cpp_metadata"; const contract = toolContract(operation); const entrypoint = resolve("scripts/rea.mjs"); const execute = promisify(execFile); -const client = new Client({ name: "il2cpp-metadata-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "il2cpp-metadata-verifier", version: "1" }), +); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -60,7 +66,14 @@ await withVerifierCleanup(async () => { const started = performance.now(); const { stdout } = await execute( process.execPath, - [entrypoint, "inspect-il2cpp-metadata", path, "--json"], + [ + entrypoint, + ...(await completeEvidenceCliArguments([ + "inspect-il2cpp-metadata", + path, + "--json", + ])), + ], { timeout: 120_000, maxBuffer: 128 * 1024 * 1024 }, ); const cliMs = Math.round(performance.now() - started); diff --git a/scripts/verify-package-artifact.mjs b/scripts/verify-package-artifact.mjs index ef87ce11051..7bf3224a3e7 100644 --- a/scripts/verify-package-artifact.mjs +++ b/scripts/verify-package-artifact.mjs @@ -38,14 +38,14 @@ const verifyPackagedArtifact = async ({ const artifactInspection = JSON.parse( await commands.run( cli, - ["inspect-artifact", artifactArchive, "--json"], + ["inspect-artifact", "--detail", "complete", artifactArchive, "--json"], environment, ), ); const repeatedArtifactInspection = JSON.parse( await commands.run( cli, - ["inspect-artifact", artifactArchive, "--json"], + ["inspect-artifact", "--detail", "complete", artifactArchive, "--json"], environment, ), ); @@ -96,7 +96,13 @@ const verifyPackagedElectronApplication = async ({ const applicationAnalysis = JSON.parse( await commands.run( cli, - ["analyze-javascript-application", applicationRoot, "--json"], + [ + "analyze-javascript-application", + applicationRoot, + "--detail", + "complete", + "--json", + ], environment, ), ); @@ -111,7 +117,7 @@ const verifyPackagedElectronApplication = async ({ const routedApplicationAnalysis = JSON.parse( await commands.run( cli, - ["analyze", applicationRoot, "--json"], + ["analyze", applicationRoot, "--detail", "complete", "--json"], environment, ), ); diff --git a/scripts/verify-package-managed.mjs b/scripts/verify-package-managed.mjs index 3d37462c40d..b51cbbbcfc8 100644 --- a/scripts/verify-package-managed.mjs +++ b/scripts/verify-package-managed.mjs @@ -46,7 +46,13 @@ const verifyManagedArtifact = async ({ const managedArtifact = JSON.parse( await commands.run( cli, - ["inspect-managed-artifact", managedPath, "--json"], + [ + "inspect-managed-artifact", + "--detail", + "complete", + managedPath, + "--json", + ], environment, ), ); @@ -68,7 +74,13 @@ const verifyManagedMembers = async ({ const managedMembers = JSON.parse( await commands.run( cli, - ["inspect-managed-members", managedPath, "--json"], + [ + "inspect-managed-members", + "--detail", + "complete", + managedPath, + "--json", + ], environment, ), ); diff --git a/scripts/verify-package-mcp.mjs b/scripts/verify-package-mcp.mjs index 6487f7b3f9f..3c3690ba7e1 100644 --- a/scripts/verify-package-mcp.mjs +++ b/scripts/verify-package-mcp.mjs @@ -16,6 +16,7 @@ import { parseEvidence } from "../dist/domain/evidence.js"; import * as prompts from "./verify-package-prompts.mjs"; import { verifyCompleteToolCatalog } from "./lib/verify-package-core.mjs"; import { withVerifierCleanup } from "./lib/verifier-cleanup.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const verifyMcpToolsAndPrompts = async (client, mcpOptions) => { await verifyCompleteToolCatalog(client, mcpOptions); @@ -103,7 +104,7 @@ const verifyMcpNonLinuxCurrentDocument = async ( const batch = await client.callTool( { name: "batch_decompile", - arguments: { addresses: ["0x1000"] }, + arguments: { detail: "complete", addresses: ["0x1000"] }, }, mcpOptions, ); @@ -171,7 +172,7 @@ const verifyMcpInlineArtifactEvidence = async ( let outputRoot; try { const inspected = await client.callTool( - { name: "inspect_artifact", arguments: {} }, + { name: "inspect_artifact", arguments: { detail: "complete" } }, mcpOptions, ); assert.notEqual(inspected.structuredContent, undefined); @@ -278,7 +279,9 @@ export async function verifyPackageMcp({ transport.stderr?.on("data", (chunk) => { mcpStderr += chunk.toString(); }); - const client = new Client({ name: "package-smoke", version: "1.0.0" }); + const client = completeEvidenceClient( + new Client({ name: "package-smoke", version: "1.0.0" }), + ); await withVerifierCleanup(async () => { try { await client.connect(transport); diff --git a/scripts/verify-packaged-ghidra-windows.mjs b/scripts/verify-packaged-ghidra-windows.mjs index cc9d2f69792..cebc445dc2b 100644 --- a/scripts/verify-packaged-ghidra-windows.mjs +++ b/scripts/verify-packaged-ghidra-windows.mjs @@ -24,6 +24,7 @@ import { withVerifierCleanup, } from "./lib/verifier-cleanup.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; if (process.platform !== "win32" || process.arch !== "x64") throw new Error( @@ -298,10 +299,12 @@ try { cwd: callerDirectory, stderr: "pipe", }); - const client = new Client({ - name: "rea-packaged-windows-ghidra", - version: "1.0.0", - }); + const client = completeEvidenceClient( + new Client({ + name: "rea-packaged-windows-ghidra", + version: "1.0.0", + }), + ); const closeClient = async () => { try { await client.close(); @@ -363,12 +366,13 @@ try { ); report.bundleActivator = "ReaGhidraBundleActivator"; assert.equal((await call("list_documents", {})).length, 1); - await call("list_names", {}); - const procedures = await call("list_procedures", {}); + await call("list_names", { detail: "complete" }); + const procedures = await call("list_procedures", { detail: "complete" }); assert.ok(procedures.length > 0); if (targetArgument === undefined) { const calleeAddress = fixture.calleeAddress; const calleeCode = await call("procedure_pseudo_code", { + detail: "complete", procedure: calleeAddress, }); assert.match(calleeCode, /\b(?:42|0x2a)\b/iu); @@ -376,22 +380,30 @@ try { const callerAddress = fixture.callerAddress; assert.ok( ( - await call("procedure_callees", { procedure: callerAddress }) + await call("procedure_callees", { + detail: "complete", + procedure: callerAddress, + }) ).includes(calleeAddress), ); assert.match( - await call("procedure_pseudo_code", { procedure: callerAddress }), + await call("procedure_pseudo_code", { + detail: "complete", + procedure: callerAddress, + }), /\+\s*1\b/u, ); } } assert.ok((await call("list_segments", {})).length > 0); - await call("list_strings", {}); + await call("list_strings", { detail: "complete" }); const procedure = procedures.find((item) => item.procedure?.external === false) ?? procedures[0]; assert.ok(procedure !== undefined); - const loadImage = await call("inspect_native_load_image", {}); + const loadImage = await call("inspect_native_load_image", { + detail: "complete", + }); assert.equal( loadImage.status, "unsupported", @@ -416,14 +428,21 @@ try { ); await call("address_name", { address: procedure.address }); assert.equal( - await call("procedure_address", { procedure: procedure.value }), + await call("procedure_address", { + detail: "complete", + procedure: procedure.value, + }), procedure.address, ); await call("resolve_containing_procedure", { + detail: "complete", address: procedure.address, }); - await call("search_procedures", { pattern: procedure.value }); - await call("search_strings", { pattern: "rea" }); + await call("search_procedures", { + detail: "complete", + pattern: procedure.value, + }); + await call("search_strings", { detail: "complete", pattern: "rea" }); report.byteSearch = await verifyWindowsGhidraByteSearch({ invoke: call, sourceBytes, diff --git a/scripts/verify-packet-capture.mjs b/scripts/verify-packet-capture.mjs index f63fba2fa18..e704491e737 100644 --- a/scripts/verify-packet-capture.mjs +++ b/scripts/verify-packet-capture.mjs @@ -22,6 +22,10 @@ import { VerifierFixture, withVerifierFixture, } from "./lib/verifier-fixture.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; if (process.platform !== "linux") throw new Error( @@ -44,7 +48,9 @@ const environment = { TMP: root.path, TEMP: root.path, }; -const client = new Client({ name: "packet-capture-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "packet-capture-verifier", version: "1" }), +); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -346,7 +352,14 @@ await withVerifierFixture(root, async () => { ( await execute( process.execPath, - [entrypoint, "inspect-pcap-capture", capturePath, "--json"], + [ + entrypoint, + ...(await completeEvidenceCliArguments([ + "inspect-pcap-capture", + capturePath, + "--json", + ])), + ], { env: environment, timeout: 60000, maxBuffer: 16 * 1024 * 1024 }, ) ).stdout, diff --git a/scripts/verify-pcap.mjs b/scripts/verify-pcap.mjs index b41e54f2ca0..01fc5654fc3 100644 --- a/scripts/verify-pcap.mjs +++ b/scripts/verify-pcap.mjs @@ -13,6 +13,7 @@ import { VerifierFixture, withVerifierFixture, } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const args = process.argv.slice(2); if (args.includes("--help") || args.includes("-h")) { @@ -42,7 +43,9 @@ Object.assign(environment, { }); const entrypoint = resolve("scripts/rea.mjs"); const execute = promisify(execFile); -const client = new Client({ name: "pcap-real-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "pcap-real-verifier", version: "1" }), +); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], diff --git a/scripts/verify-qlog-captures.mjs b/scripts/verify-qlog-captures.mjs index fcea83edfb1..b45ac55f088 100644 --- a/scripts/verify-qlog-captures.mjs +++ b/scripts/verify-qlog-captures.mjs @@ -20,6 +20,7 @@ import { requireMcpOutput, requireMcpToolError, } from "./lib/mcp-verifier-results.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; // Caller-supplied producer evidence stays local; no fixture capture or secrets are bundled. const [controlPath, lossPath, reportPath] = process.argv.slice(2); @@ -32,7 +33,9 @@ if ( "Usage: node scripts/verify-qlog-captures.mjs /absolute/control/origin.qlog /absolute/loss/origin.qlog /absolute/new-report.json", ); const entrypoint = fileURLToPath(new URL("./rea.mjs", import.meta.url)); -const client = new Client({ name: "qlog-producer-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "qlog-producer-verifier", version: "1" }), +); const environment = { PATH: process.env.PATH ?? "/usr/bin:/bin", REA_LOG_LEVEL: "silent", @@ -88,7 +91,15 @@ const report = await withVerifierCleanup(async () => { ); const completed = await promisify(execFile)( process.execPath, - [entrypoint, "inspect-web-network-capture", path, "qlog", "--json"], + [ + entrypoint, + "inspect-web-network-capture", + "--detail", + "complete", + path, + "qlog", + "--json", + ], { env: environment, timeout: 40_000, maxBuffer: 96 * 1024 * 1024 }, ); const cli = parseEvidence(JSON.parse(completed.stdout)); diff --git a/scripts/verify-real-browser.mjs b/scripts/verify-real-browser.mjs index b6f73f2c220..f395a8fe5bb 100644 --- a/scripts/verify-real-browser.mjs +++ b/scripts/verify-real-browser.mjs @@ -51,6 +51,7 @@ import { verifyScenarioStorage } from "./lib/browser-scenario-storage-e2e.mjs"; import { verifyScenarioStorageFingerprints } from "./lib/browser-scenario-storage-fingerprints-e2e.mjs"; import { verifyScenarioServiceWorkers } from "./lib/browser-scenario-service-workers-e2e.mjs"; import { verifyBrowserUrlUserInfo } from "./lib/browser-url-userinfo-e2e.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const SCENARIO_SECRET_VALUE = "rea-browser-verifier-secret"; const SCENARIO_URL_SECRET_VALUE = "rea-browser-url-verifier-secret"; @@ -453,7 +454,9 @@ async function verifyPublicBundle(endpoint, target, origin) { }, stderr: "pipe", }); - const client = new Client({ name: "browser-bundle-e2e", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "browser-bundle-e2e", version: "1" }), + ); try { await client.connect(transport); const result = await artifactMcpResult(client, "analyze_web_bundle", { diff --git a/scripts/verify-real-cutter.mjs b/scripts/verify-real-cutter.mjs index a676ef0854e..663da83d9b4 100644 --- a/scripts/verify-real-cutter.mjs +++ b/scripts/verify-real-cutter.mjs @@ -11,6 +11,7 @@ import { access, constants, readFile, writeFile } from "node:fs/promises"; import { join, resolve } from "node:path"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const cli = resolve("scripts/rea.mjs"); const runCli = async (...arguments_) => { @@ -111,10 +112,12 @@ await withVerifierCleanup(async () => { providerEnvironment: process.env, }, ); - const mcpClient = new Client({ - name: "rea-cutter-upstream-smoke", - version: "1", - }); + const mcpClient = completeEvidenceClient( + new Client({ + name: "rea-cutter-upstream-smoke", + version: "1", + }), + ); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const mcpOwner = { diff --git a/scripts/verify-real-ghidra-6502.mjs b/scripts/verify-real-ghidra-6502.mjs index 59738794fc0..4006dd4955d 100644 --- a/scripts/verify-real-ghidra-6502.mjs +++ b/scripts/verify-real-ghidra-6502.mjs @@ -30,6 +30,10 @@ import { VerifierFixture, withVerifierFixture, } from "./lib/verifier-fixture.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; if (process.argv.length !== 2) throw new Error("Usage: node scripts/verify-real-ghidra-6502.mjs"); @@ -101,7 +105,9 @@ const transport = new StdioClientTransport({ env, stderr: "pipe", }); -const client = new Client({ name: "rea-real-6502-proof", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "rea-real-6502-proof", version: "1" }), +); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -199,12 +205,18 @@ await withVerifierFixture(workspaceFixture, async () => { ), ); const pseudo = evidence( - await call("procedure_pseudo_code", { procedure: "0x8010" }), + await call("procedure_pseudo_code", { + detail: "complete", + procedure: "0x8010", + }), sha256, ); assert.match(pseudo.normalized_result, /\+\s*(?:3|0x3|'\\x03')/u); const filePseudo = evidence( - await call("procedure_pseudo_code", { procedure: "file-offset:0xf" }), + await call("procedure_pseudo_code", { + detail: "complete", + procedure: "file-offset:0xf", + }), sha256, ); assert.equal(filePseudo.normalized_result, pseudo.normalized_result); @@ -243,6 +255,8 @@ await withVerifierFixture(workspaceFixture, async () => { [ entrypoint, "inspect-native-load-image", + "--detail", + "complete", path, "--target-format", "raw-binary", @@ -265,6 +279,8 @@ await withVerifierFixture(workspaceFixture, async () => { [ entrypoint, "decompile", + "--detail", + "complete", path, "--file-offset=0xf", "--target-format", @@ -378,6 +394,8 @@ await withVerifierFixture(workspaceFixture, async () => { [ entrypoint, "inspect-native-load-image", + "--detail", + "complete", lowPath, "--target-format", "raw-binary", @@ -437,7 +455,10 @@ await withVerifierFixture(workspaceFixture, async () => { }); // open_binary selects a lazy session; the first analysis admits the snapshot. const linkedImage = await client.callTool( - { name: "inspect_native_load_image", arguments: {} }, + { + name: "inspect_native_load_image", + arguments: { detail: "complete" }, + }, { timeout: 240000 }, ); // Native Windows admission refuses the junction before Ghidra imports it. @@ -460,27 +481,33 @@ await withVerifierFixture(workspaceFixture, async () => { ); await call("close_binary"); const snapshotPath = join(workspace, "direct-snapshot.json"); - const cliArgs = (selectedPath) => [ + const cliArgs = async (selectedPath) => [ entrypoint, - "analyze", - selectedPath, - "--target-format", - "raw-binary", - "--architecture", - "6502", - "--entry-point", - "0x8001", - "--provider", - "ghidra", - "--snapshot", - snapshotPath, - "--json", + ...(await completeEvidenceCliArguments([ + "analyze", + selectedPath, + "--target-format", + "raw-binary", + "--architecture", + "6502", + "--entry-point", + "0x8001", + "--provider", + "ghidra", + "--snapshot", + snapshotPath, + "--json", + ])), ]; - const saved = await commands.exec(process.execPath, cliArgs(path), { - env, - timeout: 240000, - maxBuffer: 16 * 1024 * 1024, - }); + const saved = await commands.exec( + process.execPath, + await cliArgs(path), + { + env, + timeout: 240000, + maxBuffer: 16 * 1024 * 1024, + }, + ); assert.equal( evidence(JSON.parse(saved.stdout), sha256).operation, "binary_overview", @@ -494,7 +521,7 @@ await withVerifierFixture(workspaceFixture, async () => { assert.deepEqual(await readdir(runtime), []); // Replaying a matching snapshot must still reach native path admission. await assert.rejects( - commands.exec(process.execPath, cliArgs(linkedPath), { + commands.exec(process.execPath, await cliArgs(linkedPath), { env, timeout: 240000, maxBuffer: 16 * 1024 * 1024, diff --git a/scripts/verify-real-ghidra-address-context.mjs b/scripts/verify-real-ghidra-address-context.mjs index 087934e5805..002b5b26d67 100644 --- a/scripts/verify-real-ghidra-address-context.mjs +++ b/scripts/verify-real-ghidra-address-context.mjs @@ -18,6 +18,10 @@ import { } from "./lib/verifier-run.mjs"; import { createVerifierCommands } from "./lib/verify-commands.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; if (process.argv.length !== 2 || process.platform !== "linux") throw new Error("Run this ELF verifier on Linux without arguments."); @@ -49,7 +53,9 @@ const transport = new StdioClientTransport({ env, stderr: "pipe", }); -const client = new Client({ name: "rea-real-address-context", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "rea-real-address-context", version: "1" }), +); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -154,6 +160,7 @@ try { ); const fromOffset = parseEvidence( await call("procedure_pseudo_code", { + detail: "complete", procedure: `file-offset:0x${offset.toString(16)}`, }), ); @@ -166,6 +173,7 @@ try { assert.equal(fromOffset.raw_result.selection.mapped_address, entry.address); const fromNumericOffset = parseEvidence( await call("procedure_pseudo_code", { + detail: "complete", procedure: `0x${offset.toString(16)}`, }), ); @@ -177,7 +185,7 @@ try { const missingName = await client.callTool( { name: "procedure_pseudo_code", - arguments: { procedure: missingProcedure }, + arguments: { detail: "complete", procedure: missingProcedure }, }, { timeout: 240000 }, ); @@ -193,7 +201,10 @@ try { const unmappedOffset = await client.callTool( { name: "procedure_pseudo_code", - arguments: { procedure: "file-offset:0x1fffffffffffff" }, + arguments: { + detail: "complete", + procedure: "file-offset:0x1fffffffffffff", + }, }, { timeout: 240000 }, ); @@ -207,7 +218,10 @@ try { assert.equal(unmappedError.recovery, undefined); const missingAddress = "ram:0xffffffff"; const rejected = await client.callTool( - { name: "procedure_pseudo_code", arguments: { procedure: missingAddress } }, + { + name: "procedure_pseudo_code", + arguments: { detail: "complete", procedure: missingAddress }, + }, { timeout: 240000 }, ); // procedure_not_found keeps the caller-selected procedure and the inventory tools. @@ -229,7 +243,10 @@ try { }); assert.equal(rejectedError.recovery, undefined); const pseudo = parseEvidence( - await call("procedure_pseudo_code", { procedure: addition.address }), + await call("procedure_pseudo_code", { + detail: "complete", + procedure: addition.address, + }), ); assert.match(pseudo.normalized_result, /\+\s*(?:7|0x7)\b/u); const retained = await call("binary_session"); @@ -242,12 +259,16 @@ try { { env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 }, ); const cliOverview = parseEvidence( - JSON.parse((await cli(["analyze", path])).stdout), + JSON.parse( + (await cli(await completeEvidenceCliArguments(["analyze", path]))).stdout, + ), ); assert.deepEqual(cliOverview.normalized_result, overview.normalized_result); let cliFailure; try { - await cli(["decompile", path, missingAddress]); + await cli( + await completeEvidenceCliArguments(["decompile", path, missingAddress]), + ); } catch (cause) { cliFailure = cause; } @@ -283,16 +304,42 @@ try { assert.ok(cliEntry); assert.equal(cliEntry.address, entry.address); const cliImage = parseEvidence( - JSON.parse((await cli(["inspect-native-load-image", path])).stdout), + JSON.parse( + ( + await cli( + await completeEvidenceCliArguments([ + "inspect-native-load-image", + path, + ]), + ) + ).stdout, + ), ); assert.equal(cliImage.normalized_result.observations.image_base, base); const cliPseudo = parseEvidence( - JSON.parse((await cli(["decompile", path, cliEntry.address])).stdout), + JSON.parse( + ( + await cli( + await completeEvidenceCliArguments([ + "decompile", + path, + cliEntry.address, + ]), + ) + ).stdout, + ), ); const cliOffset = parseEvidence( JSON.parse( - (await cli(["decompile", path, `--file-offset=0x${offset.toString(16)}`])) - .stdout, + ( + await cli( + await completeEvidenceCliArguments([ + "decompile", + path, + `--file-offset=0x${offset.toString(16)}`, + ]), + ) + ).stdout, ), ); assert.equal(cliOffset.normalized_result, fromOffset.normalized_result); diff --git a/scripts/verify-real-ghidra-checkpoints.mjs b/scripts/verify-real-ghidra-checkpoints.mjs index fcf27abf416..1d2547b9173 100644 --- a/scripts/verify-real-ghidra-checkpoints.mjs +++ b/scripts/verify-real-ghidra-checkpoints.mjs @@ -29,6 +29,7 @@ import { assertVerifierCleanupComplete, } from "./lib/verifier-run.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; if (process.platform === "win32") throw new Error( @@ -103,6 +104,8 @@ async function cli(procedure, flags = [], path = target) { [ entrypoint, "decompile", + "--detail", + "complete", path, procedure, "--provider", @@ -124,10 +127,12 @@ async function cli(procedure, flags = [], path = target) { } async function connect(environment = {}) { const owner = createVerifierMcpOwner(); - const client = new Client({ - name: "rea-ghidra-checkpoint-verifier", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "rea-ghidra-checkpoint-verifier", + version: "1", + }), + ); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -193,6 +198,7 @@ int main(void) { CheckpointRecord record = { 3, 11 }; return rea_checkpoint_leaf try { await cold.call("open_binary", { path: target, provider_id: "ghidra" }); await cold.call("procedure_pseudo_code", { + detail: "complete", procedure: "rea_checkpoint_leaf", }); const id = (await cold.call("binary_session")).analysis_run.run_id; @@ -206,6 +212,7 @@ int main(void) { CheckpointRecord record = { 3, 11 }; return rea_checkpoint_leaf id, ); const current = await cold.call("procedure_pseudo_code", { + detail: "complete", procedure: "rea_checkpoint_leaf", }); assert.match(JSON.stringify(current), /cold-session unsaved comment/); @@ -288,6 +295,7 @@ int main(void) { CheckpointRecord record = { 3, 11 }; return rea_checkpoint_leaf provider_id: "ghidra", }); await active.call("procedure_pseudo_code", { + detail: "complete", procedure: "rea_checkpoint_leaf", }); const id = (await active.call("binary_session")).analysis_run.run_id; @@ -388,6 +396,7 @@ int main(void) { CheckpointRecord record = { 3, 11 }; return rea_checkpoint_leaf provider_id: "ghidra", }); const result = await active.call("procedure_pseudo_code", { + detail: "complete", procedure: "rea_checkpoint_retained", }); assert.match(JSON.stringify(result), /saved during alias switch/); diff --git a/scripts/verify-real-ghidra-com.mjs b/scripts/verify-real-ghidra-com.mjs index 4c68a70912c..a1261278e03 100644 --- a/scripts/verify-real-ghidra-com.mjs +++ b/scripts/verify-real-ghidra-com.mjs @@ -37,6 +37,7 @@ import { createVerifierMcpOwner, VerifierStdioTransport, } from "./lib/verifier-mcp-owner.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; // This lane intentionally has no game paths, binary seeds or compiler dependency. if (process.argv.length !== 2) @@ -107,7 +108,9 @@ const transport = new StdioClientTransport({ env: env, stderr: "pipe", }); -const client = new Client({ name: "rea-real-com-proof", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "rea-real-com-proof", version: "1" }), +); let stderr = ""; let connected = false; let verifierRun; @@ -406,7 +409,10 @@ await withVerifierFixture(workspaceFixture, async () => { assert.equal(outside.comment.state, "unavailable"); assert.match(outside.comment.remediation, /binary_session/u); assert.equal( - await call("procedure_address", { procedure: changes.name }), + await call("procedure_address", { + detail: "complete", + procedure: changes.name, + }), fixture.entry, ); assert.equal( @@ -565,10 +571,12 @@ async function verifyRejectedCom() { await writeFile(rejectedPath, rejectedFixture.bytes, { mode: 0o600 }); const fallbackOwner = createVerifierMcpOwner(); workspaceFixture.releaseAfter(() => fallbackOwner.close()); - const rejectedClient = new Client({ - name: "rea-real-com-fallback", - version: "1", - }); + const rejectedClient = completeEvidenceClient( + new Client({ + name: "rea-real-com-fallback", + version: "1", + }), + ); const rejectedTransport = new VerifierStdioTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -594,7 +602,7 @@ async function verifyRejectedCom() { const session = requireMcpLifecycleResult(opened, "open_binary"); assert.equal(session.format, "dos-com"); const response = await rejectedClient.callTool( - { name: "inspect_native_load_image", arguments: {} }, + { name: "inspect_native_load_image", arguments: { detail: "complete" } }, { timeout: 240000 }, ); const evidence = parseEvidence( diff --git a/scripts/verify-real-ghidra-cortex-m.mjs b/scripts/verify-real-ghidra-cortex-m.mjs index bc763afe781..faebec3b144 100644 --- a/scripts/verify-real-ghidra-cortex-m.mjs +++ b/scripts/verify-real-ghidra-cortex-m.mjs @@ -36,6 +36,10 @@ import { completeVerifierRun, createVerifierRun, } from "./lib/verifier-run.mjs"; +import { + completeEvidenceClient, + completeEvidenceCliArguments, +} from "./lib/complete-evidence.mjs"; import { createVerifierCommands } from "./lib/verify-commands.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; @@ -97,7 +101,9 @@ const transport = new StdioClientTransport({ env, stderr: "pipe", }); -const client = new Client({ name: "rea-real-cortex-m-proof", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "rea-real-cortex-m-proof", version: "1" }), +); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -506,20 +512,22 @@ async function verifyOddEntryAndCli(fixture, selection, image, path) { process.execPath, [ entrypoint, - "inspect-native-load-image", - path, - "--target-format", - "raw-binary", - "--architecture", - "arm", - "--architecture-variant", - fixture.variant, - "--base-address", - hex(fixture.base), - ...(prefix === 0 ? [] : ["--vector-table-address", address(0)]), - "--provider", - "ghidra", - "--json", + ...(await completeEvidenceCliArguments([ + "inspect-native-load-image", + path, + "--target-format", + "raw-binary", + "--architecture", + "arm", + "--architecture-variant", + fixture.variant, + "--base-address", + hex(fixture.base), + ...(prefix === 0 ? [] : ["--vector-table-address", address(0)]), + "--provider", + "ghidra", + "--json", + ])), ], { env, timeout: 240_000, maxBuffer: 16 * 1024 * 1024 }, ) diff --git a/scripts/verify-real-ghidra-dol.mjs b/scripts/verify-real-ghidra-dol.mjs index 4f0c3869687..79dd6e3269b 100644 --- a/scripts/verify-real-ghidra-dol.mjs +++ b/scripts/verify-real-ghidra-dol.mjs @@ -38,6 +38,7 @@ import { withVerifierCleanup } from "./lib/verifier-cleanup.mjs"; import { createVerifierCommands } from "./lib/verify-commands.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; import { requireLaneToolchain } from "../tests/conformance/ghidra/fixture-toolchain.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; // Optional cross-target lane. No tool acquisition and no target execution. if (process.argv.length !== 2) @@ -120,7 +121,9 @@ async function runPass({ fixture, languageOverride, label, layout }) { env, stderr: "pipe", }); - const client = new Client({ name: "rea-real-dol-proof", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-real-dol-proof", version: "1" }), + ); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -168,6 +171,7 @@ async function runPass({ fixture, languageOverride, label, layout }) { "Leaf function missing from real Ghidra inventory", ); const callees = await call("procedure_callees", { + detail: "complete", procedure: entry.address, }); assert.ok( diff --git a/scripts/verify-real-ghidra-dos.mjs b/scripts/verify-real-ghidra-dos.mjs index 9f9b362dedd..f951276b349 100644 --- a/scripts/verify-real-ghidra-dos.mjs +++ b/scripts/verify-real-ghidra-dos.mjs @@ -28,6 +28,7 @@ import { VerifierFixture, withVerifierFixture, } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; // This lane intentionally has no game paths, binary seeds or compiler dependency. if (process.argv.length !== 2) @@ -101,7 +102,9 @@ const transport = new StdioClientTransport({ env, stderr: "pipe", }); -const client = new Client({ name: "rea-real-dos-proof", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "rea-real-dos-proof", version: "1" }), +); let stderr = ""; let connected = false; let verifierRun; @@ -272,7 +275,10 @@ await withVerifierFixture(workspaceFixture, async () => { for (const [key, identity] of Object.entries(identities)) { const procedure = identity.address; // Use returned addresses, never symbol-name heuristics. assert.match(procedure, /^0x[0-9a-f]+$/u); - const resolved = await call("procedure_address", { procedure }); + const resolved = await call("procedure_address", { + detail: "complete", + procedure, + }); assert.equal(resolved, procedure, "Flat address round-trip drifted"); const info = await call("procedure_info", { procedure }); const dossierResult = await evidenceCall("analyze_function", { @@ -290,6 +296,7 @@ await withVerifierFixture(workspaceFixture, async () => { const containingQueries = [procedure, info.body.ranges.at(-1).end]; for (const query of containingQueries) { const containing = await call("resolve_containing_procedure", { + detail: "complete", address: query, }); assert.equal(containing.found, true); @@ -299,6 +306,7 @@ await withVerifierFixture(workspaceFixture, async () => { } if (key === "entry") { const gap = await call("resolve_containing_procedure", { + detail: "complete", address: address(0x10), }); assert.equal( diff --git a/scripts/verify-real-ghidra-m68k.mjs b/scripts/verify-real-ghidra-m68k.mjs index 2fe34cc58a3..845c3951245 100644 --- a/scripts/verify-real-ghidra-m68k.mjs +++ b/scripts/verify-real-ghidra-m68k.mjs @@ -20,6 +20,7 @@ import { import { closeVerifierResources } from "./lib/verifier-cleanup.mjs"; import { createVerifierCommands } from "./lib/verify-commands.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; if (process.argv.length !== 2) throw new Error("Usage: node scripts/verify-real-ghidra-m68k.mjs"); @@ -84,7 +85,9 @@ const transport = new StdioClientTransport({ env, stderr: "pipe", }); -const client = new Client({ name: "rea-real-m68k-proof", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "rea-real-m68k-proof", version: "1" }), +); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -147,17 +150,26 @@ try { ), ); const pseudo = evidence( - await call("procedure_pseudo_code", { procedure: "0x1012" }), + await call("procedure_pseudo_code", { + detail: "complete", + procedure: "0x1012", + }), ); assert.match(pseudo.normalized_result, /\+\s*(?:3|0x3)\b/u); const caller = evidence( - await call("procedure_pseudo_code", { procedure: "0x1000" }), + await call("procedure_pseudo_code", { + detail: "complete", + procedure: "0x1000", + }), ); assert.match(caller.normalized_result, /==\s*(?:10|0xa)\b/iu); assert.match(caller.normalized_result, /return\s+(?:42|0x2a)\s*;/iu); assert.match(caller.normalized_result, /return\s+0\s*;/u); const filePseudo = evidence( - await call("procedure_pseudo_code", { procedure: "file-offset:0x12" }), + await call("procedure_pseudo_code", { + detail: "complete", + procedure: "file-offset:0x12", + }), ); assert.equal(filePseudo.normalized_result, pseudo.normalized_result); assert.ok( @@ -203,6 +215,8 @@ try { [ entrypoint, "inspect-native-load-image", + "--detail", + "complete", path, "--target-format", "raw-binary", @@ -224,6 +238,8 @@ try { [ entrypoint, "decompile", + "--detail", + "complete", path, "--file-offset=0x12", "--target-format", diff --git a/scripts/verify-real-ghidra-mips-relocatable.mjs b/scripts/verify-real-ghidra-mips-relocatable.mjs index 36a78fffa39..15df1ef14c3 100755 --- a/scripts/verify-real-ghidra-mips-relocatable.mjs +++ b/scripts/verify-real-ghidra-mips-relocatable.mjs @@ -26,6 +26,10 @@ import { } from "./lib/verifier-run.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; import { requireLaneToolchain } from "../tests/conformance/ghidra/fixture-toolchain.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; // Optional cross-target lane for ET_REL objects. No tool acquisition, no // linking and no target execution. @@ -136,7 +140,9 @@ async function verifyFixture(byteOrder, kernelModule) { env, stderr: "pipe", }); - const client = new Client({ name: "rea-real-mips-rel-proof", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-real-mips-rel-proof", version: "1" }), + ); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -204,7 +210,10 @@ async function verifyFixture(byteOrder, kernelModule) { return found[0].address; }; const entry = named("rea_mips_rel_entry"); - const callees = await call("procedure_callees", { procedure: entry }); + const callees = await call("procedure_callees", { + detail: "complete", + procedure: entry, + }); for (const callee of [ named("rea_mips_rel_leaf"), named("rea_mips_rel_far"), @@ -281,12 +290,14 @@ async function verifyFixture(byteOrder, kernelModule) { process.execPath, [ entrypoint, - "function", - fixture.path, - "rea_mips_rel_entry", - "--provider", - "ghidra", - "--json", + ...(await completeEvidenceCliArguments([ + "function", + fixture.path, + "rea_mips_rel_entry", + "--provider", + "ghidra", + "--json", + ])), ], { env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 }, ); diff --git a/scripts/verify-real-ghidra-mips-shared.mjs b/scripts/verify-real-ghidra-mips-shared.mjs index 951fa84f61e..768c970966e 100644 --- a/scripts/verify-real-ghidra-mips-shared.mjs +++ b/scripts/verify-real-ghidra-mips-shared.mjs @@ -21,6 +21,7 @@ import { } from "./lib/verifier-run.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; import { requireLaneToolchain } from "../tests/conformance/ghidra/fixture-toolchain.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; if ( process.env.GHIDRA_INSTALL_DIR === undefined || @@ -110,10 +111,12 @@ try { env, stderr: "pipe", }); - const client = new Client({ - name: "rea-mips16-shared-conformance", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "rea-mips16-shared-conformance", + version: "1", + }), + ); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-262144); diff --git a/scripts/verify-real-ghidra-mips.mjs b/scripts/verify-real-ghidra-mips.mjs index 4ca8bfebb8b..deb6febe83a 100644 --- a/scripts/verify-real-ghidra-mips.mjs +++ b/scripts/verify-real-ghidra-mips.mjs @@ -50,6 +50,10 @@ import { createVerifierCommands } from "./lib/verify-commands.mjs"; import { runOwnedCommand } from "../dist/process/OwnedCommand.js"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; import { requireLaneToolchain } from "../tests/conformance/ghidra/fixture-toolchain.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; // Optional cross-target lane. No tool acquisition and no target execution. const mode = process.argv[2]; @@ -169,7 +173,9 @@ async function verifyExistingMipsProject(fixture, byteOrder) { }, stderr: "pipe", }); - const client = new Client({ name: "rea-existing-mips-proof", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-existing-mips-proof", version: "1" }), + ); try { await client.connect(transport); const opened = await client.callTool( @@ -181,7 +187,7 @@ async function verifyExistingMipsProject(fixture, byteOrder) { ); requireMcpOperationResult(opened, "open_binary"); const result = await client.callTool( - { name: "list_procedures", arguments: {} }, + { name: "list_procedures", arguments: { detail: "complete" } }, { timeout: 180000 }, ); const observation = parseEvidence( @@ -295,10 +301,12 @@ try { env, stderr: "pipe", }); - const client = new Client({ - name: "rea-real-mips-legacy-proof", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "rea-real-mips-legacy-proof", + version: "1", + }), + ); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -468,7 +476,9 @@ try { env, stderr: "pipe", }); - const client = new Client({ name: "rea-real-mips-proof", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-real-mips-proof", version: "1" }), + ); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -498,12 +508,14 @@ try { process.execPath, [ entrypoint, - "function", - fixture.path, - `${prefix}_entry`, - "--provider", - "ghidra", - "--json", + ...(await completeEvidenceCliArguments([ + "function", + fixture.path, + `${prefix}_entry`, + "--provider", + "ghidra", + "--json", + ])), ], { env, timeout: 60000, maxBuffer: 1024 * 1024 }, ); @@ -629,6 +641,7 @@ try { ).toString("hex"), ); const callees = await call("procedure_callees", { + detail: "complete", procedure: entry.address, }); assert.ok( @@ -771,12 +784,14 @@ try { process.execPath, [ entrypoint, - "function", - fixture.path, - `${prefix}_entry`, - "--provider", - "ghidra", - "--json", + ...(await completeEvidenceCliArguments([ + "function", + fixture.path, + `${prefix}_entry`, + "--provider", + "ghidra", + "--json", + ])), ], { env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 }, ); @@ -829,12 +844,14 @@ try { process.execPath, [ entrypoint, - "function", - carvedPath, - independent.symbols.rea_mips_entry, - "--provider", - "ghidra", - "--json", + ...(await completeEvidenceCliArguments([ + "function", + carvedPath, + independent.symbols.rea_mips_entry, + "--provider", + "ghidra", + "--json", + ])), ], { env, timeout: 60000, maxBuffer: 1024 * 1024 }, ); diff --git a/scripts/verify-real-ghidra-mips32-shared.mjs b/scripts/verify-real-ghidra-mips32-shared.mjs index c530fd5f2aa..5513299e42c 100755 --- a/scripts/verify-real-ghidra-mips32-shared.mjs +++ b/scripts/verify-real-ghidra-mips32-shared.mjs @@ -27,6 +27,10 @@ import { } from "./lib/verifier-run.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; import { requireLaneToolchain } from "../tests/conformance/ghidra/fixture-toolchain.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; // Optional cross-target lane for plain MIPS32 PIC shared libraries (ET_DYN). // No tool acquisition, no dynamic loading and no target execution. @@ -160,10 +164,12 @@ async function verifyFixture(byteOrder, softFloat) { env, stderr: "pipe", }); - const client = new Client({ - name: "rea-real-mips32-shared-proof", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "rea-real-mips32-shared-proof", + version: "1", + }), + ); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -291,12 +297,14 @@ async function verifyFixture(byteOrder, softFloat) { process.execPath, [ entrypoint, - "function", - fixture.path, - "rea_mips_so_entry", - "--provider", - "ghidra", - "--json", + ...(await completeEvidenceCliArguments([ + "function", + fixture.path, + "rea_mips_so_entry", + "--provider", + "ghidra", + "--json", + ])), ], { env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 }, ); diff --git a/scripts/verify-real-ghidra-nativeaot.mjs b/scripts/verify-real-ghidra-nativeaot.mjs index cb30b885f6c..f1e4873f379 100644 --- a/scripts/verify-real-ghidra-nativeaot.mjs +++ b/scripts/verify-real-ghidra-nativeaot.mjs @@ -26,6 +26,7 @@ import { VerifierFixture, withVerifierFixture, } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const run = createVerifierRun(); const mode = process.argv[2] ?? "symbols"; if ( @@ -158,7 +159,9 @@ const transport = new StdioClientTransport({ env, stderr: "pipe", }); -const client = new Client({ name: "rea-nativeaot-proof", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "rea-nativeaot-proof", version: "1" }), +); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -207,7 +210,10 @@ await withVerifierFixture(workspaceFixture, async () => { if (failure.isError !== true) { opened = true; failure = await client.callTool( - { name: "inspect_native_load_image", arguments: {} }, + { + name: "inspect_native_load_image", + arguments: { detail: "complete" }, + }, { timeout: 360000, signal: commandInterruption.signal }, ); } @@ -353,7 +359,12 @@ await withVerifierFixture(workspaceFixture, async () => { assert.ok(dispatch.pseudocode.trim()); for (const literal of oracle.expected_strings) assert.ok( - (await call("search_strings", { pattern: literal })).length > 0, + ( + await call("search_strings", { + detail: "complete", + pattern: literal, + }) + ).length > 0, `Frozen string missing: ${literal}`, ); const observed = await call("read_bytes", { diff --git a/scripts/verify-real-ghidra-ppc.mjs b/scripts/verify-real-ghidra-ppc.mjs index ca990ba6dba..94e24400428 100644 --- a/scripts/verify-real-ghidra-ppc.mjs +++ b/scripts/verify-real-ghidra-ppc.mjs @@ -28,6 +28,10 @@ import { createVerifierCommands } from "./lib/verify-commands.mjs"; import { withVerifierCleanup } from "./lib/verifier-cleanup.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; import { requireLaneToolchain } from "../tests/conformance/ghidra/fixture-toolchain.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; // Optional cross-target lane. No tool acquisition and no target execution. if (process.argv.length !== 2) @@ -96,7 +100,9 @@ try { env, stderr: "pipe", }); - const client = new Client({ name: "rea-real-ppc-proof", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-real-ppc-proof", version: "1" }), + ); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -194,6 +200,7 @@ try { Buffer.from("rea-ppc-source-owned-fixture\0").toString("hex"), ); const callees = await call("procedure_callees", { + detail: "complete", procedure: entry.address, }); assert.ok( @@ -257,12 +264,14 @@ try { process.execPath, [ entrypoint, - "function", - fixture.path, - "rea_ppc_entry", - "--provider", - "ghidra", - "--json", + ...(await completeEvidenceCliArguments([ + "function", + fixture.path, + "rea_ppc_entry", + "--provider", + "ghidra", + "--json", + ])), ], { env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 }, ); diff --git a/scripts/verify-real-ghidra-ppc64.mjs b/scripts/verify-real-ghidra-ppc64.mjs index ef2585602eb..de7d362d1a5 100644 --- a/scripts/verify-real-ghidra-ppc64.mjs +++ b/scripts/verify-real-ghidra-ppc64.mjs @@ -31,6 +31,10 @@ import { fixtureCommand, requireLaneToolchain, } from "../tests/conformance/ghidra/fixture-toolchain.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; // Optional cross-target lane. No tool acquisition and no target execution. if (process.argv.length !== 2) @@ -116,7 +120,9 @@ try { env, stderr: "pipe", }); - const client = new Client({ name: "rea-real-ppc64-proof", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-real-ppc64-proof", version: "1" }), + ); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -232,6 +238,7 @@ try { const local = await dossier(entry.local); assertPowerPc64EntryPair(await dossier(entry.global), local, entry); const callees = await call("procedure_callees", { + detail: "complete", procedure: entry.local, }); assert.ok( @@ -295,12 +302,14 @@ try { process.execPath, [ entrypoint, - "function", - fixture.path, - "rea_ppc64_entry", - "--provider", - "ghidra", - "--json", + ...(await completeEvidenceCliArguments([ + "function", + fixture.path, + "rea_ppc64_entry", + "--provider", + "ghidra", + "--json", + ])), ], { env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 }, ); diff --git a/scripts/verify-real-ghidra-project-coverage.mjs b/scripts/verify-real-ghidra-project-coverage.mjs index 47e585ef633..50bc7a88b6c 100644 --- a/scripts/verify-real-ghidra-project-coverage.mjs +++ b/scripts/verify-real-ghidra-project-coverage.mjs @@ -28,6 +28,7 @@ import { requireMcpOutput, requireMcpToolError, } from "./lib/mcp-verifier-results.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; export async function verifyProjectCoverage(run) { const installDir = process.env.GHIDRA_INSTALL_DIR; @@ -86,10 +87,12 @@ export async function verifyProjectCoverage(run) { return files.flat().sort((a, b) => a[0].localeCompare(b[0])); } async function connect(environment) { - const client = new Client({ - name: "selected-project-coverage-verifier", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "selected-project-coverage-verifier", + version: "1", + }), + ); const transport = new VerifierStdioTransport({ command: process.execPath, args: [entrypoint, "mcp"], diff --git a/scripts/verify-real-ghidra-raw.mjs b/scripts/verify-real-ghidra-raw.mjs index bc6715334c8..0bec49321ac 100644 --- a/scripts/verify-real-ghidra-raw.mjs +++ b/scripts/verify-real-ghidra-raw.mjs @@ -35,6 +35,7 @@ import { VerifierFixture, withVerifierFixture, } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; if (process.argv.length !== 2) throw new Error("Usage: node scripts/verify-real-ghidra-raw.mjs"); @@ -111,7 +112,9 @@ const transport = new StdioClientTransport({ env: env, stderr: "pipe", }); -const client = new Client({ name: "rea-real-raw-proof", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "rea-real-raw-proof", version: "1" }), +); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -286,6 +289,8 @@ await withVerifierFixture(workspaceFixture, async () => { [ entrypoint, "inspect-native-load-image", + "--detail", + "complete", path, "--target-format", "raw-binary", @@ -317,7 +322,11 @@ await withVerifierFixture(workspaceFixture, async () => { architecture, entry_point: "0x1000", }); - const image = await call("inspect_native_load_image", {}, x86Sha256); + const image = await call( + "inspect_native_load_image", + { detail: "complete" }, + x86Sha256, + ); assert.equal( image.normalized_result.status, "verified", @@ -340,7 +349,7 @@ await withVerifierFixture(workspaceFixture, async () => { ); const pseudo = await call( "procedure_pseudo_code", - { procedure: "0x1000" }, + { detail: "complete", procedure: "0x1000" }, x86Sha256, ); assert.match(pseudo.normalized_result, /\b(?:42|0x2a)\b/iu); @@ -815,10 +824,12 @@ async function verifyCrossBlockProject(target, targetSha256) { }, stderr: "pipe", }); - const projectClient = new Client({ - name: "rea-cross-block-project-proof", - version: "1", - }); + const projectClient = completeEvidenceClient( + new Client({ + name: "rea-cross-block-project-proof", + version: "1", + }), + ); try { await untilInterrupted( projectClient.connect(projectTransport, { diff --git a/scripts/verify-real-ghidra-riscv.mjs b/scripts/verify-real-ghidra-riscv.mjs index 441da13aade..f768310ec28 100644 --- a/scripts/verify-real-ghidra-riscv.mjs +++ b/scripts/verify-real-ghidra-riscv.mjs @@ -42,6 +42,10 @@ import { } from "./lib/verifier-run.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; import { requireLaneToolchain } from "../tests/conformance/ghidra/fixture-toolchain.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; if (process.argv.length !== 2) throw new Error("Usage: node scripts/verify-real-ghidra-riscv.mjs"); @@ -99,7 +103,9 @@ const transport = new StdioClientTransport({ env: env, stderr: "pipe", }); -const client = new Client({ name: "rea-real-riscv-proof", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "rea-real-riscv-proof", version: "1" }), +); let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); @@ -551,6 +557,7 @@ try { }); assert.equal(global.bytes_hex, "07000000"); const callees = await call("procedure_callees", { + detail: "complete", procedure: addressFor("rea_riscv_entry"), }); for (const name of abi @@ -657,12 +664,14 @@ try { process.execPath, [ entrypoint, - command, - fixture.path, - ...arguments_, - "--provider", - "ghidra", - "--json", + ...(await completeEvidenceCliArguments([ + command, + fixture.path, + ...arguments_, + "--provider", + "ghidra", + "--json", + ])), ], { env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 }, ); @@ -759,12 +768,14 @@ try { ); const cliArguments = [ entrypoint, - "function", - mutatedPath, - "rea_riscv_entry", - "--provider", - "ghidra", - "--json", + ...(await completeEvidenceCliArguments([ + "function", + mutatedPath, + "rea_riscv_entry", + "--provider", + "ghidra", + "--json", + ])), ]; const cliOptions = { env, diff --git a/scripts/verify-real-ghidra-swift.mjs b/scripts/verify-real-ghidra-swift.mjs index 46c1153ea5c..1f7c3f8f738 100644 --- a/scripts/verify-real-ghidra-swift.mjs +++ b/scripts/verify-real-ghidra-swift.mjs @@ -24,6 +24,7 @@ import { VerifierFixture, withVerifierFixture, } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const run = createVerifierRun(); const installation = await inspectVerifierGhidraInstallation({ @@ -64,7 +65,9 @@ const rootFixture = await VerifierFixture.open({ private: false, }); const root = rootFixture.path; -const client = new Client({ name: "ghidra-swift-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "ghidra-swift-verifier", version: "1" }), +); const transport = new StdioClientTransport({ command: process.execPath, args: [fileURLToPath(new URL("./rea.mjs", import.meta.url)), "mcp"], @@ -155,7 +158,9 @@ await withVerifierFixture(rootFixture, async () => { ]) { await call("open_binary", { path, provider_id: "ghidra" }); await withVerifierCleanup(async () => { - const procedures = await call("list_procedures", {}); + const procedures = await call("list_procedures", { + detail: "complete", + }); const inventory = await call("analyze_swift_types", {}); assert( inventory.total > 0, @@ -288,7 +293,7 @@ async function call(name, arguments_) { async function verifyStringLiterals() { await call("open_binary", { path: literalBinary, provider_id: "ghidra" }); return withVerifierCleanup(async () => { - const procedures = await call("list_procedures", {}); + const procedures = await call("list_procedures", { detail: "complete" }); const expected = { smallLiteral: [["SleepDisabled", "small"]], largeLiteral: [["The power setting could not be changed.", "large"]], diff --git a/scripts/verify-real-ghidra-switch.mjs b/scripts/verify-real-ghidra-switch.mjs index bdd7a4a3bb4..590e5bab68b 100644 --- a/scripts/verify-real-ghidra-switch.mjs +++ b/scripts/verify-real-ghidra-switch.mjs @@ -39,6 +39,7 @@ import { VerifierFixture, withVerifierFixture, } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; // Narrow compiler-shape lane; no cross compiler or game artifact prerequisites. const { values } = parseArgs({ @@ -298,7 +299,9 @@ async function verifyTarget(path, sha256, fixtures, variant) { env, stderr: "pipe", }); - const client = new Client({ name: "rea-real-switch-proof", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-real-switch-proof", version: "1" }), + ); let opened = false; let stderr = ""; const observations = []; diff --git a/scripts/verify-real-hopper-callers.mjs b/scripts/verify-real-hopper-callers.mjs index ed6fe35509c..ab690f38828 100644 --- a/scripts/verify-real-hopper-callers.mjs +++ b/scripts/verify-real-hopper-callers.mjs @@ -19,6 +19,10 @@ import { } from "./lib/verifier-run.mjs"; import { HOPPER_TARGET_LEASE_DIRECTORY } from "../dist/process/HopperLease.js"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { + completeEvidenceClient, + completeEvidenceToolArguments, +} from "./lib/complete-evidence.mjs"; const verifierRun = createVerifierRun(); // xcrun resolves the compiler before a workspace exists. A failed probe must @@ -103,7 +107,9 @@ const digest = async (path) => const sessionsBefore = ( await snapshotHopperRuntime("/tmp", HOPPER_TARGET_LEASE_DIRECTORY) ).paths; -const client = new Client({ name: "hopper-callers-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "hopper-callers-verifier", version: "1" }), +); const transport = new StdioClientTransport({ command: process.execPath, args: ["dist/main.js"], @@ -204,7 +210,7 @@ try { ); assert( ( - await call("procedure_callees", { procedure: from }) + await call("procedure_callees", { detail: "complete", procedure: from }) ).normalized_result.includes(to), ); const callers = await call("procedure_callers", { @@ -220,7 +226,11 @@ try { "forward caller provenance missing", ); const refs = ( - await call("procedure_references", { procedure: to, direction: "incoming" }) + await call("procedure_references", { + detail: "complete", + procedure: to, + direction: "incoming", + }) ).normalized_result.references; assert( refs.some((x) => matchingRef(x, site, from, to)), @@ -282,10 +292,17 @@ try { detail: "complete", }; const count = notifications; - await call("get_call_graph", query); + await call( + "get_call_graph", + await completeEvidenceToolArguments("get_call_graph", query), + ); assert.equal(notifications, count, "unsolicited progress without token"); const progress = []; - await call("get_call_graph", query, { onprogress: (x) => progress.push(x) }); + await call( + "get_call_graph", + await completeEvidenceToolArguments("get_call_graph", query), + { onprogress: (x) => progress.push(x) }, + ); assert( progress.every((x, i) => i === 0 || x.progress > progress[i - 1].progress), "progress not monotonic", @@ -302,7 +319,7 @@ try { try { await artifactMcpCall( client, - { name: "get_call_graph", arguments: query }, + { name: "get_call_graph", arguments: { ...query, detail: "complete" } }, { timeout: 120000, signal: controller.signal, @@ -326,7 +343,10 @@ try { "did not observe cancellation after partial scan progress; cancellation coverage unavailable on this host", ); await client.ping(); - const retry = await call("get_call_graph", query); + const retry = await call( + "get_call_graph", + await completeEvidenceToolArguments("get_call_graph", query), + ); assert(retry.normalized_result.graph, "retry did not return graph"); await call("close_binary", {}); assert.equal(await digest(large), beforeLarge); diff --git a/scripts/verify-real-hopper-fat.mjs b/scripts/verify-real-hopper-fat.mjs index 0e6f70c0a53..f6b2d8883b2 100644 --- a/scripts/verify-real-hopper-fat.mjs +++ b/scripts/verify-real-hopper-fat.mjs @@ -30,6 +30,7 @@ import { relocateSingleFatSlice, } from "./lib/real-hopper-source-binding.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const verifierRun = createVerifierRun(); // xcrun resolves clang and lipo before a workspace exists. A failed probe must @@ -119,7 +120,9 @@ let preparedImagePath; const before = ( await snapshotHopperRuntime("/tmp", HOPPER_TARGET_LEASE_DIRECTORY) ).paths; -const client = new Client({ name: "hopper-fat-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "hopper-fat-verifier", version: "1" }), +); const transport = new StdioClientTransport({ command: process.execPath, args: ["dist/main.js"], diff --git a/scripts/verify-real-hopper.mjs b/scripts/verify-real-hopper.mjs index ada8fa5fd12..aa6737d8d3d 100644 --- a/scripts/verify-real-hopper.mjs +++ b/scripts/verify-real-hopper.mjs @@ -52,6 +52,7 @@ import { import { startUnrelatedHopperSentinel } from "./lib/unrelated-hopper-sentinel.mjs"; import { snapshotHopperRuntime } from "./lib/real-hopper-cleanup.mjs"; import { verifyLinuxHopperOwnerExit } from "./lib/real-hopper-owner-exit.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const verifierRun = createVerifierRun(); // ps and any later host commands share one owner, created before a tool or // workspace exists. A failed workspace allocation still closes the owner. @@ -181,7 +182,7 @@ try { const verifyCurrentTarget = async (client, options) => { const procedures = requireMcpEvidenceResult( await client.callTool( - { name: "list_procedures", arguments: {} }, + { name: "list_procedures", arguments: { detail: "complete" } }, options, ), "list_procedures", @@ -202,7 +203,7 @@ try { await client.callTool( { name: "batch_decompile", - arguments: { addresses: [firstAddress] }, + arguments: { detail: "complete", addresses: [firstAddress] }, }, options, ), @@ -289,7 +290,9 @@ try { stderrBytes += chunk.length; stderrChunks.push(chunk.toString("utf8")); }); - const client = new Client({ name: "real-hopper-verifier", version: "1.0.0" }); + const client = completeEvidenceClient( + new Client({ name: "real-hopper-verifier", version: "1.0.0" }), + ); const unrelatedHopper = await startUnrelatedHopperSentinel(); try { diff --git a/scripts/verify-real-ida.mjs b/scripts/verify-real-ida.mjs index 14c3af1c1a8..9dd1c111bdd 100644 --- a/scripts/verify-real-ida.mjs +++ b/scripts/verify-real-ida.mjs @@ -21,6 +21,10 @@ import { parseArgs } from "node:util"; import { Client } from "@modelcontextprotocol/client"; import { createOwnedMcpStdioTransport } from "./lib/owned-mcp-stdio.mjs"; import { createVerifierCommands } from "./lib/verify-commands.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "./lib/complete-evidence.mjs"; const { values } = parseArgs({ options: { @@ -189,17 +193,19 @@ const cli = async () => { phase = "production CLI function analysis"; const commands = await createVerifierCommands(); const { stdout } = await withVerifierCleanup( - () => + async () => commands.exec( process.execPath, [ entry, - "function", - target, - values.procedure, - "--provider", - "ida", - "--json", + ...(await completeEvidenceCliArguments([ + "function", + target, + values.procedure, + "--provider", + "ida", + "--json", + ])), ], { env: environment, @@ -286,7 +292,9 @@ const verifyPeerCleanup = async (analysis, closeWithPeer, retryClose) => { }; const mcp = async (cliDossier) => { - const client = new Client({ name: "rea-real-ida-verifier", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-real-ida-verifier", version: "1" }), + ); const transport = await createOwnedMcpStdioTransport({ command: process.execPath, arguments: [entry, "mcp"], @@ -399,7 +407,12 @@ const mcp = async (cliDossier) => { "list_documents reported the private workspace copy.", ); const resolveAt = async (address) => - observe(await call("resolve_containing_procedure", { address })); + observe( + await call("resolve_containing_procedure", { + detail: "complete", + address, + }), + ); const instructionAddresses = dossier.assembly .map((line) => /^(0x[0-9a-f]+)/iu.exec(line)?.[1]) .filter((address) => address !== undefined); @@ -416,7 +429,9 @@ const mcp = async (cliDossier) => { const unmapped = await resolveAt("0xffffffffffffff00"); assert.equal(unmapped.found, false); assert.equal(unmapped.reason, "outside_segments"); - const strings = observe(await call("list_strings", {})); + const strings = observe( + await call("list_strings", { detail: "complete" }), + ); const mappedString = await findMappedNonFunction(strings, resolveAt); if (mappedString === undefined) report.unverified.push( @@ -436,7 +451,7 @@ const mcp = async (cliDossier) => { ); const traced = await client.callTool({ name: "trace_feature", - arguments: { query: dossier.procedure.name }, + arguments: { detail: "complete", query: dossier.procedure.name }, }); assert.notEqual(traced.isError, true); const trace = traced.structuredContent.normalized_result; @@ -461,12 +476,14 @@ const mcp = async (cliDossier) => { if (values["second-procedure"] !== undefined) { const secondAddress = observe( await call("procedure_address", { + detail: "complete", procedure: values["second-procedure"], }), ); assert.notEqual(secondAddress, dossier.procedure.address); const secondCode = observe( await call("procedure_pseudo_code", { + detail: "complete", procedure: values["second-procedure"], }), ); @@ -482,6 +499,7 @@ const mcp = async (cliDossier) => { ); const restored = observe( await call("procedure_pseudo_code", { + detail: "complete", procedure: dossier.procedure.address, }), ); diff --git a/scripts/verify-real-kuna.mjs b/scripts/verify-real-kuna.mjs index 17791c8acae..8c4273303de 100644 --- a/scripts/verify-real-kuna.mjs +++ b/scripts/verify-real-kuna.mjs @@ -45,6 +45,7 @@ import { } from "./lib/verifier-run.mjs"; import { createVerifierCommands } from "./lib/verify-commands.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const { values } = parseArgs({ options: { targets: { type: "string" }, @@ -217,7 +218,9 @@ const openServer = async (provider, kunaSettings = {}) => { }, stderr: "ignore", }); - const client = new Client({ name: "rea-real-kuna", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-real-kuna", version: "1" }), + ); let peakKiB = 0; const cpu = new Map(); const sampleOnce = async () => { @@ -478,6 +481,7 @@ const verifyKuna = async ( assert.ok(missing.message.includes("rea_missing_xref_inventory_name")); assert.equal(missing.recovery, undefined); const procedure = await cold.callError("procedure_address", { + detail: "complete", procedure: "rea_missing_procedure_name", }); assert.equal(procedure.code, "invalid_request"); @@ -489,6 +493,7 @@ const verifyKuna = async ( ), ); const missingAddress = await cold.callError("procedure_address", { + detail: "complete", procedure: "0x00000001", }); assert.equal(missingAddress.code, "invalid_request"); @@ -525,6 +530,7 @@ const verifyKuna = async ( }), }); const pseudocode = await cold.call("procedure_pseudo_code", { + detail: "complete", procedure: address, }); assert.equal(pseudocode.structured.subject.identity.sha256, sha256); @@ -546,6 +552,7 @@ const verifyKuna = async ( ); assert.match(assembly.value, new RegExp(`: ; ${address}\\n`, "u")); const exported = await cold.call("procedure_pseudo_code", { + detail: "complete", procedure: address, }); const recorded = exported.structured.raw_result.source; @@ -640,6 +647,7 @@ const verifyKuna = async ( for (const answer of answers) if (answer.address !== undefined) { const reread = await warm.call("procedure_pseudo_code", { + detail: "complete", procedure: answer.address, }); assert.equal( @@ -664,9 +672,11 @@ const measureGhidra = async (path, functions) => { try { for (const [name, address] of functions) { const cold = await server.call("procedure_pseudo_code", { + detail: "complete", procedure: address, }); const warm = await server.call("procedure_pseudo_code", { + detail: "complete", procedure: address, }); answers.push({ diff --git a/scripts/verify-reconstruction-readiness.mjs b/scripts/verify-reconstruction-readiness.mjs index 99b5d0bc400..2e555fbcd94 100644 --- a/scripts/verify-reconstruction-readiness.mjs +++ b/scripts/verify-reconstruction-readiness.mjs @@ -12,6 +12,7 @@ import { requireMcpOutput } from "./lib/mcp-verifier-results.mjs"; import { parseEvidence } from "../dist/domain/evidence.js"; import { createEvidenceBundle } from "../dist/domain/evidenceBundle.js"; import { withVerifierCleanup } from "./lib/verifier-cleanup.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const [ { RECONSTRUCTION_READINESS_EXAMPLE }, @@ -43,15 +44,25 @@ const environment = { ...process.env, }; await access(nativePath); -const nativeEvidence = await runCli(["inspect-artifact", nativePath, "--json"]); +const nativeEvidence = await runCli([ + "inspect-artifact", + nativePath, + "--detail", + "complete", + "--json", +]); const javascriptCliEvidence = await runCli([ "analyze-javascript-application", javascriptPath, + "--detail", + "complete", "--json", ]); const electronCliEvidence = await runCli([ "analyze-javascript-application", electronPath, + "--detail", + "complete", "--json", ]); @@ -62,11 +73,13 @@ const transport = new StdioClientTransport({ env: environment, stderr: "pipe", }); -const client = new Client({ - name: "rea-readiness-verifier", - version: "1", - capabilities: { elicitation: {} }, -}); +const client = completeEvidenceClient( + new Client({ + name: "rea-readiness-verifier", + version: "1", + capabilities: { elicitation: {} }, + }), +); let verificationReport; await withVerifierCleanup(async () => { @@ -190,7 +203,7 @@ async function runCli(arguments_) { async function analyzeMcp(client_, inputPath) { const response = await client_.callTool({ name: "analyze_javascript_application", - arguments: { input_path: inputPath }, + arguments: { input_path: inputPath, detail: "complete" }, }); assert.notEqual(response.structuredContent, undefined); return parseEvidence( diff --git a/scripts/verify-signal-recording.mjs b/scripts/verify-signal-recording.mjs index 5abc58e5c9a..2873aa3997c 100644 --- a/scripts/verify-signal-recording.mjs +++ b/scripts/verify-signal-recording.mjs @@ -22,6 +22,7 @@ import { withVerifierFixture, } from "./lib/verifier-fixture.mjs"; import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; if (process.platform !== "linux") throw new Error( @@ -59,7 +60,9 @@ const environment = { TMP: root.path, TEMP: root.path, }; -const client = new Client({ name: "signal-recording-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "signal-recording-verifier", version: "1" }), +); // Real sigrok refusals of an unknown decoder ID must name the caller's field. const assertRejectedSelector = ( response, diff --git a/scripts/verify-wasm-artifact.mjs b/scripts/verify-wasm-artifact.mjs index 8e6ecd12d72..1028b676bf6 100644 --- a/scripts/verify-wasm-artifact.mjs +++ b/scripts/verify-wasm-artifact.mjs @@ -23,6 +23,7 @@ import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs"; import { WABT_OPERATION_TIMEOUT_MS } from "./lib/wabt-verifier-timeouts.mjs"; import { verifyWabtCleanup } from "./lib/verify-wabt-cleanup.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const directory = process.env.REA_WABT_BIN_DIRECTORY; if (!isAbsolute(directory ?? "")) { @@ -97,7 +98,9 @@ try { throw cause; } const childTempRoot = childTemp.path; -const client = new Client({ name: "wabt-artifact-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "wabt-artifact-verifier", version: "1" }), +); const callTool = (request) => client.callTool(request, { timeout: WABT_OPERATION_TIMEOUT_MS }); const transport = new StdioClientTransport({ @@ -289,7 +292,7 @@ try { const cli = parseEvidence(cliValue); const reply = await callTool({ name: "inspect_wasm_artifact", - arguments: input, + arguments: { ...input, detail: "complete" }, }); assert.notEqual(reply.isError, true, mcpTextValue(reply)); assert.ok( @@ -435,7 +438,7 @@ try { const error = requireMcpToolError( await callTool({ name: "inspect_wasm_artifact", - arguments: invalidInput, + arguments: { ...invalidInput, detail: "complete" }, }), ); assert.equal(error.category, "invalid_input"); @@ -533,7 +536,7 @@ try { const cli = parseEvidence(await inspectCli(input)); const reply = await callTool({ name: "inspect_wasm_artifact", - arguments: input, + arguments: { ...input, detail: "complete" }, }); assert.notEqual(reply.isError, true, mcpTextValue(reply)); assert.ok( @@ -602,7 +605,7 @@ try { const cli = parseEvidence(await inspectCli(input)); const reply = await callTool({ name: "inspect_wasm_artifact", - arguments: input, + arguments: { ...input, detail: "complete" }, }); assert.notEqual(reply.isError, true, mcpTextValue(reply)); assert.ok( diff --git a/scripts/verify-wasm-interface-comparison.mjs b/scripts/verify-wasm-interface-comparison.mjs index c3f35916a8f..a34467a2c3b 100644 --- a/scripts/verify-wasm-interface-comparison.mjs +++ b/scripts/verify-wasm-interface-comparison.mjs @@ -11,6 +11,7 @@ import { VerifierFixture, withVerifierFixture, } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const execute = promisify(execFile); const bin = process.env.REA_WABT_BIN_DIRECTORY; @@ -32,10 +33,12 @@ const command = async (file, args) => maxBuffer: 64 * 1024 * 1024, }) ).stdout; -const client = new Client({ - name: "wasm-interface-real-verifier", - version: "1", -}); +const client = completeEvidenceClient( + new Client({ + name: "wasm-interface-real-verifier", + version: "1", + }), +); const transport = new StdioClientTransport({ command: process.execPath, args: [cli, "mcp"], @@ -58,7 +61,7 @@ const assemble = async (name, wat) => { const inspect = async (path) => { const result = await client.callTool({ name: "inspect_wasm_artifact", - arguments: { path }, + arguments: { detail: "complete", path }, }); assert.notEqual(result.isError, true, JSON.stringify(result)); assert.notEqual(result.structuredContent, undefined); diff --git a/scripts/verify-web-network-captures.mjs b/scripts/verify-web-network-captures.mjs index 1088a2cdfe1..85ae085050f 100644 --- a/scripts/verify-web-network-captures.mjs +++ b/scripts/verify-web-network-captures.mjs @@ -24,6 +24,7 @@ import { } from "./lib/mcp-verifier-results.mjs"; import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; const executable = process.env.REA_MITMDUMP_COMMAND; if ( @@ -44,10 +45,12 @@ const runtime = await VerifierFixture.open({ const environment = Object.fromEntries( Object.entries(process.env).filter(([, value]) => typeof value === "string"), ); -const client = new Client({ - name: "historical-web-capture-verifier", - version: "1", -}); +const client = completeEvidenceClient( + new Client({ + name: "historical-web-capture-verifier", + version: "1", + }), +); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], @@ -953,7 +956,7 @@ async function inspect(mode, input, errorCategory) { if (mode === "mcp") { const result = await client.callTool({ name: "inspect_web_network_capture", - arguments: input, + arguments: { ...input, detail: "complete" }, }); if (errorCategory !== undefined) { const error = requireMcpToolError(result); @@ -1018,6 +1021,8 @@ async function inspect(mode, input, errorCategory) { const args = [ entrypoint, "inspect-web-network-capture", + "--detail", + "complete", input.capture_path, input.format, "--json", diff --git a/scripts/verify/advertised-schemas/tools/batch_decompile.json b/scripts/verify/advertised-schemas/tools/batch_decompile.json index 70daf4d66fe..9d7d04d2c43 100644 --- a/scripts/verify/advertised-schemas/tools/batch_decompile.json +++ b/scripts/verify/advertised-schemas/tools/batch_decompile.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "070aaba8b50aeb20", + "input compact": "38d5b1c230543ed8", "output compact": "4bda7c3651bfc579" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/capture_browser_scenario.json b/scripts/verify/advertised-schemas/tools/capture_browser_scenario.json index 696fd32a147..a1a5895689c 100644 --- a/scripts/verify/advertised-schemas/tools/capture_browser_scenario.json +++ b/scripts/verify/advertised-schemas/tools/capture_browser_scenario.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "555f59d540be07ce", + "input compact": "11b8c13561b47f60", "output compact": "4bda7c3651bfc579" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/gdb_console.json b/scripts/verify/advertised-schemas/tools/gdb_console.json index 8cc8ba05864..1db040896cc 100644 --- a/scripts/verify/advertised-schemas/tools/gdb_console.json +++ b/scripts/verify/advertised-schemas/tools/gdb_console.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "3a493db9e13845e2", + "input compact": "71d7ad04aa702db9", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/get_call_graph.json b/scripts/verify/advertised-schemas/tools/get_call_graph.json index 070d16de91d..4a39ffe1a94 100644 --- a/scripts/verify/advertised-schemas/tools/get_call_graph.json +++ b/scripts/verify/advertised-schemas/tools/get_call_graph.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "da18a434d32e16db", + "input compact": "d8bc42e72c3d6756", "output compact": "4bda7c3651bfc579" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/inspect_analysis_settings.json b/scripts/verify/advertised-schemas/tools/inspect_analysis_settings.json index f79d092fc6c..bee75c22bbd 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_analysis_settings.json +++ b/scripts/verify/advertised-schemas/tools/inspect_analysis_settings.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "71360cba238d0c73", + "input compact": "d6d7f69220a75505", "output compact": "b3a429110120aff1" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/inspect_binary_layout.json b/scripts/verify/advertised-schemas/tools/inspect_binary_layout.json index f73ea207979..bc172433ed3 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_binary_layout.json +++ b/scripts/verify/advertised-schemas/tools/inspect_binary_layout.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "76a620fb6276d952", + "input compact": "23e5246e6a440825", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_byte_entropy.json b/scripts/verify/advertised-schemas/tools/inspect_byte_entropy.json index e4ce90b6528..45efecd7018 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_byte_entropy.json +++ b/scripts/verify/advertised-schemas/tools/inspect_byte_entropy.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "a994241bc7cb700d", + "input compact": "3fe6fb83f79175c6", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_devicetree.json b/scripts/verify/advertised-schemas/tools/inspect_devicetree.json index 89a912fe065..ac572cba986 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_devicetree.json +++ b/scripts/verify/advertised-schemas/tools/inspect_devicetree.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "02a13a32cf55d458", + "input compact": "e54c173fcbf15a51", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_elf_dependencies.json b/scripts/verify/advertised-schemas/tools/inspect_elf_dependencies.json index 3f6850d78ff..0031ab55d4f 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_elf_dependencies.json +++ b/scripts/verify/advertised-schemas/tools/inspect_elf_dependencies.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "6ecf88aeaa9d79da", + "input compact": "30fb8db090aa6071", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_evm_interface.json b/scripts/verify/advertised-schemas/tools/inspect_evm_interface.json index 67c1ce76884..c6ceca8a410 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_evm_interface.json +++ b/scripts/verify/advertised-schemas/tools/inspect_evm_interface.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "1e5fbc1c470c2a23", + "input compact": "432b9d1cce8cbaa1", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_go_binary.json b/scripts/verify/advertised-schemas/tools/inspect_go_binary.json index 7e21572f2d7..e9080567931 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_go_binary.json +++ b/scripts/verify/advertised-schemas/tools/inspect_go_binary.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "caedaefd2eef892b", + "input compact": "801e80c517f9408e", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_managed_artifact.json b/scripts/verify/advertised-schemas/tools/inspect_managed_artifact.json index d7f9a68d39a..7b93062f22e 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_managed_artifact.json +++ b/scripts/verify/advertised-schemas/tools/inspect_managed_artifact.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "26391ae9478bdad4", + "input compact": "f7bf3f8936afcd55", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_managed_members.json b/scripts/verify/advertised-schemas/tools/inspect_managed_members.json index 3f6d512df21..ef3fa93cfc6 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_managed_members.json +++ b/scripts/verify/advertised-schemas/tools/inspect_managed_members.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "54859945355f676d", + "input compact": "273b3dc42f7bd1f5", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_native_exports.json b/scripts/verify/advertised-schemas/tools/inspect_native_exports.json index d18a6401fad..9d25d640546 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_native_exports.json +++ b/scripts/verify/advertised-schemas/tools/inspect_native_exports.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "70adce0beddda5eb", + "input compact": "9116de2eff349249", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_native_load_image.json b/scripts/verify/advertised-schemas/tools/inspect_native_load_image.json index 5a4f10095b2..aa9a41c1cf7 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_native_load_image.json +++ b/scripts/verify/advertised-schemas/tools/inspect_native_load_image.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "f23a678531aa373a", + "input compact": "1e3af2bde466363b", "output compact": "4bda7c3651bfc579" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/inspect_pcap_capture.json b/scripts/verify/advertised-schemas/tools/inspect_pcap_capture.json index 5fc295508c6..bce948de32b 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_pcap_capture.json +++ b/scripts/verify/advertised-schemas/tools/inspect_pcap_capture.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "5b4526bbca7cfaa7", + "input compact": "5d8db1d69f56b939", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_wasm_artifact.json b/scripts/verify/advertised-schemas/tools/inspect_wasm_artifact.json index b48fd4cc247..f29e8010b89 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_wasm_artifact.json +++ b/scripts/verify/advertised-schemas/tools/inspect_wasm_artifact.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "284eab844f7b23e8", + "input compact": "4d6179b4d0d694c1", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_web_network_capture.json b/scripts/verify/advertised-schemas/tools/inspect_web_network_capture.json index 42c2489d715..3249a69d3ee 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_web_network_capture.json +++ b/scripts/verify/advertised-schemas/tools/inspect_web_network_capture.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "72d51d50e5a963a0", + "input compact": "e30c9b8ea56dc0da", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_web_page.json b/scripts/verify/advertised-schemas/tools/inspect_web_page.json index f79cb9443aa..87a067adaa4 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_web_page.json +++ b/scripts/verify/advertised-schemas/tools/inspect_web_page.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "6694e7a2135fc387", + "input compact": "37c2c73ee2d1c5e6", "output compact": "4bda7c3651bfc579" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/inspect_with_objdump.json b/scripts/verify/advertised-schemas/tools/inspect_with_objdump.json index e4e56e5e779..7d999b4a75d 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_with_objdump.json +++ b/scripts/verify/advertised-schemas/tools/inspect_with_objdump.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "3f51a78954949124", + "input compact": "f2ac113b26052065", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/list_names.json b/scripts/verify/advertised-schemas/tools/list_names.json index c35f02fe8d7..7904d2b0ea9 100644 --- a/scripts/verify/advertised-schemas/tools/list_names.json +++ b/scripts/verify/advertised-schemas/tools/list_names.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "dae8bb143805b9d8", + "input compact": "ad6deeb69e540106", "output compact": "dedfba10a6cd6ea4" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/list_procedures.json b/scripts/verify/advertised-schemas/tools/list_procedures.json index 59f4cc0991b..12c00acdbc3 100644 --- a/scripts/verify/advertised-schemas/tools/list_procedures.json +++ b/scripts/verify/advertised-schemas/tools/list_procedures.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "ae31b56060e2cf2a", + "input compact": "e6c23cc150ea72d5", "output compact": "dedfba10a6cd6ea4" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/list_strings.json b/scripts/verify/advertised-schemas/tools/list_strings.json index c35f02fe8d7..7904d2b0ea9 100644 --- a/scripts/verify/advertised-schemas/tools/list_strings.json +++ b/scripts/verify/advertised-schemas/tools/list_strings.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "dae8bb143805b9d8", + "input compact": "ad6deeb69e540106", "output compact": "dedfba10a6cd6ea4" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/procedure_address.json b/scripts/verify/advertised-schemas/tools/procedure_address.json index ee61113c725..0bb7e65e570 100644 --- a/scripts/verify/advertised-schemas/tools/procedure_address.json +++ b/scripts/verify/advertised-schemas/tools/procedure_address.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "69b78eac500c94b7", + "input compact": "e91653898083fedc", "output compact": "fbd287539efb521d" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/procedure_callees.json b/scripts/verify/advertised-schemas/tools/procedure_callees.json index 50e33f23aec..07770664f90 100644 --- a/scripts/verify/advertised-schemas/tools/procedure_callees.json +++ b/scripts/verify/advertised-schemas/tools/procedure_callees.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "69b78eac500c94b7", + "input compact": "e91653898083fedc", "output compact": "6ea8063881cbb7c7" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/procedure_callers.json b/scripts/verify/advertised-schemas/tools/procedure_callers.json index 50e33f23aec..07770664f90 100644 --- a/scripts/verify/advertised-schemas/tools/procedure_callers.json +++ b/scripts/verify/advertised-schemas/tools/procedure_callers.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "69b78eac500c94b7", + "input compact": "e91653898083fedc", "output compact": "6ea8063881cbb7c7" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/procedure_pseudo_code.json b/scripts/verify/advertised-schemas/tools/procedure_pseudo_code.json index 006c32011db..1dae3922693 100644 --- a/scripts/verify/advertised-schemas/tools/procedure_pseudo_code.json +++ b/scripts/verify/advertised-schemas/tools/procedure_pseudo_code.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "b2cba7a6e5a97f9a", + "input compact": "7bd3d5206ada19ea", "output compact": "4750323a9e43caee" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/procedure_references.json b/scripts/verify/advertised-schemas/tools/procedure_references.json index 1f0421e8e6d..cfc45e65819 100644 --- a/scripts/verify/advertised-schemas/tools/procedure_references.json +++ b/scripts/verify/advertised-schemas/tools/procedure_references.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "3f5be054a5907bc6", + "input compact": "07541a0e1a862339", "output compact": "4bda7c3651bfc579" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/resolve_containing_procedure.json b/scripts/verify/advertised-schemas/tools/resolve_containing_procedure.json index fc3f6c263b7..f2a27893fd2 100644 --- a/scripts/verify/advertised-schemas/tools/resolve_containing_procedure.json +++ b/scripts/verify/advertised-schemas/tools/resolve_containing_procedure.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "1178f3ac840bf5c1", + "input compact": "5ead352a637a24da", "output compact": "4bda7c3651bfc579" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/search_procedures.json b/scripts/verify/advertised-schemas/tools/search_procedures.json index d6aa17a67bd..0e18304afdb 100644 --- a/scripts/verify/advertised-schemas/tools/search_procedures.json +++ b/scripts/verify/advertised-schemas/tools/search_procedures.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "cdf541808cd3a978", + "input compact": "9f4f41150e61f0dc", "output compact": "dedfba10a6cd6ea4" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/search_strings.json b/scripts/verify/advertised-schemas/tools/search_strings.json index d6aa17a67bd..0e18304afdb 100644 --- a/scripts/verify/advertised-schemas/tools/search_strings.json +++ b/scripts/verify/advertised-schemas/tools/search_strings.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "cdf541808cd3a978", + "input compact": "9f4f41150e61f0dc", "output compact": "dedfba10a6cd6ea4" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/trace_feature.json b/scripts/verify/advertised-schemas/tools/trace_feature.json index 64d9bf6cc58..93ee41bbbb0 100644 --- a/scripts/verify/advertised-schemas/tools/trace_feature.json +++ b/scripts/verify/advertised-schemas/tools/trace_feature.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "77cb1c33810a1267", + "input compact": "ef7bf3f41eddd3cd", "output compact": "4bda7c3651bfc579" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/update_analysis_settings.json b/scripts/verify/advertised-schemas/tools/update_analysis_settings.json index 1a5f16f2602..c3d95d4e70f 100644 --- a/scripts/verify/advertised-schemas/tools/update_analysis_settings.json +++ b/scripts/verify/advertised-schemas/tools/update_analysis_settings.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "3c58bca74c60f033", + "input compact": "08ab92d3c25f2d0c", "output compact": "39446aa1012006cc" }, "patterns": {} diff --git a/scripts/verify/android/analysis.mjs b/scripts/verify/android/analysis.mjs index 7363ed52d09..361cd0f4e38 100644 --- a/scripts/verify/android/analysis.mjs +++ b/scripts/verify/android/analysis.mjs @@ -20,6 +20,10 @@ import { resolveJadxConfigurationInputs } from "../../../dist/android/JadxConfig import { HOST_PLATFORM } from "../../../dist/platform/HostPlatform.js"; import { validateVerifierJadxConfiguration } from "../../lib/jadx-configuration-inspection.mjs"; import { verifyWindowsAndroidLifecycle } from "./windows-lifecycle.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "../../lib/complete-evidence.mjs"; const repository = resolve(dirname(fileURLToPath(import.meta.url)), "../../.."); const apk = process.env.REA_ANDROID_TEST_APK; @@ -82,7 +86,7 @@ await verifyAndroidBridgeCatalog({ const tasks = [ { name: "inspect_android_package", - args: ["inspect-android-package", path], + args: await completeEvidenceCliArguments(["inspect-android-package", path]), input: { path }, }, { @@ -92,17 +96,21 @@ const tasks = [ }, { name: "inspect_android_class", - args: ["inspect-android-class", path, fixture.class_name], + args: await completeEvidenceCliArguments([ + "inspect-android-class", + path, + fixture.class_name, + ]), input: { path, class_name: fixture.class_name }, }, { name: "inspect_android_method", - args: [ + args: await completeEvidenceCliArguments([ "inspect-android-method", path, fixture.class_name, fixture.method_name, - ], + ]), input: { path, class_name: fixture.class_name, @@ -154,7 +162,9 @@ let stderr = ""; transport.stderr?.on("data", (chunk) => { stderr += chunk.toString(); }); -const client = new Client({ name: "rea-real-android-verifier", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "rea-real-android-verifier", version: "1" }), +); try { await client.connect(transport, { timeout: 30_000 }); for (const task of tasks) { diff --git a/scripts/verify/android/bridge-catalog.mjs b/scripts/verify/android/bridge-catalog.mjs index d8e9203bfe6..cb70c900cd3 100644 --- a/scripts/verify/android/bridge-catalog.mjs +++ b/scripts/verify/android/bridge-catalog.mjs @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { jadxBridgeIdentity } from "../../../dist/android/JadxRelease.js"; +import { completeEvidenceClient } from "../../lib/complete-evidence.mjs"; /** Retained Java diagnostics tail; a failing bridge can be arbitrarily noisy. */ const STDERR_TAIL_BYTES = 64 * 1024; @@ -76,7 +77,9 @@ export const verifyAndroidBridgeCatalog = async ({ transport.stderr?.on("data", (chunk) => { diagnostics = `${diagnostics}${chunk}`.slice(-STDERR_TAIL_BYTES); }); - const client = new Client({ name: "rea-bridge-catalog", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-bridge-catalog", version: "1" }), + ); try { await client.connect(transport); assert.deepEqual( diff --git a/scripts/verify/android/cli-cancellation.mjs b/scripts/verify/android/cli-cancellation.mjs index bc75e8aa141..23e3de1089a 100644 --- a/scripts/verify/android/cli-cancellation.mjs +++ b/scripts/verify/android/cli-cancellation.mjs @@ -4,6 +4,7 @@ import { cleanupOwnedProcessGroup, readProcessRunId, } from "../../../dist/process/ProcessOwnership.js"; +import { completeEvidenceCliArguments } from "../../lib/complete-evidence.mjs"; /** Exercise a real CLI signal while the owned Java engine is still running. */ export const verifyAndroidCliCancellation = async ({ @@ -18,7 +19,15 @@ export const verifyAndroidCliCancellation = async ({ await readProcessRunId(process.pid); const child = spawn( process.execPath, - [entrypoint, "inspect-android-package", path, "--format", "json"], + [ + entrypoint, + ...(await completeEvidenceCliArguments([ + "inspect-android-package", + path, + "--format", + "json", + ])), + ], { cwd: repository, env: environment, stdio: ["ignore", "pipe", "pipe"] }, ); let stdout = ""; diff --git a/scripts/verify/android/direct-invokes.mjs b/scripts/verify/android/direct-invokes.mjs index 3bf4168ed46..6f13f56c894 100644 --- a/scripts/verify/android/direct-invokes.mjs +++ b/scripts/verify/android/direct-invokes.mjs @@ -3,6 +3,7 @@ import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { parseEvidence } from "../../../dist/domain/evidence.js"; import { sha256File } from "../../lib/verifier-file-sha256.mjs"; +import { completeEvidenceClient } from "../../lib/complete-evidence.mjs"; /** The public result keeps one using node and exposes its two raw DEX invokes. */ export const verifyAndroidDirectInvokes = async ({ @@ -73,10 +74,12 @@ export const verifyAndroidDirectInvokes = async ({ transport.stderr?.on("data", (chunk) => { stderr += chunk.toString(); }); - const client = new Client({ - name: "rea-real-android-direct-invokes", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "rea-real-android-direct-invokes", + version: "1", + }), + ); try { await client.connect(transport, { timeout: 30_000 }); const response = await client.callTool( diff --git a/scripts/verify/android/external-invokes.mjs b/scripts/verify/android/external-invokes.mjs index ef13af63208..833b30b267c 100644 --- a/scripts/verify/android/external-invokes.mjs +++ b/scripts/verify/android/external-invokes.mjs @@ -11,6 +11,10 @@ import { requireMcpToolError, } from "../../lib/mcp-verifier-results.mjs"; import { sha256File } from "../../lib/verifier-file-sha256.mjs"; +import { + completeEvidenceClient, + completeEvidenceToolArguments, +} from "../../lib/complete-evidence.mjs"; const operation = "trace_android_references"; const className = "android.app.NotificationManager"; @@ -110,10 +114,12 @@ const verifyApk = async (options, path, dexEntry) => { }, stderr: "pipe", }); - const client = new Client({ - name: "rea-real-external-references", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "rea-real-external-references", + version: "1", + }), + ); await withVerifierCleanup(async () => { await client.connect(transport, { timeout: 30_000 }); const call = (name, args) => @@ -132,10 +138,13 @@ const verifyApk = async (options, path, dexEntry) => { for (const caller of result.normalized_result.references) { const body = parseEvidence( requireMcpOutput( - await call("inspect_android_method", { - path, - ...caller.source_selector, - }), + await call( + "inspect_android_method", + await completeEvidenceToolArguments("inspect_android_method", { + path, + ...caller.source_selector, + }), + ), "inspect_android_method", ), ); @@ -259,7 +268,9 @@ const verifySiteBudget = async (options, path, control) => { }, stderr: "pipe", }); - const client = new Client({ name: "rea-external-site-budget", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-external-site-budget", version: "1" }), + ); await withVerifierCleanup(async () => { await client.connect(transport, { timeout: 30_000 }); const call = (args) => diff --git a/scripts/verify/android/failure-recovery.mjs b/scripts/verify/android/failure-recovery.mjs index 43bcce8acba..ee939e01528 100644 --- a/scripts/verify/android/failure-recovery.mjs +++ b/scripts/verify/android/failure-recovery.mjs @@ -14,6 +14,7 @@ import { VerifierFixture, withVerifierFixture, } from "../../lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "../../lib/complete-evidence.mjs"; /** Real unusable Java runtimes and selectors must lead to applicable recovery. */ export async function verifyAndroidFailureRecovery({ @@ -164,7 +165,14 @@ export async function verifyAndroidFailureRecovery({ try { await execute( process.execPath, - [entrypoint, "inspect-android-package", path, "--json"], + [ + entrypoint, + "inspect-android-package", + "--detail", + "complete", + path, + "--json", + ], { cwd: repository, env: scenario.env, @@ -213,10 +221,12 @@ export async function verifyAndroidFailureRecovery({ env: environment, stderr: "pipe", }); - const client = new Client({ - name: "rea-real-android-failures", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "rea-real-android-failures", + version: "1", + }), + ); try { await client.connect(transport); for (const name of [ @@ -253,6 +263,7 @@ export async function verifyAndroidFailureRecovery({ { name: "inspect_android_method", arguments: { + detail: "complete", path, class_name: fixture.class_name, method_name: "noSuchMethod", @@ -266,7 +277,10 @@ export async function verifyAndroidFailureRecovery({ ]); await client.ping(); const control = await client.callTool( - { name: "inspect_android_package", arguments: { path } }, + { + name: "inspect_android_package", + arguments: { detail: "complete", path }, + }, { timeout: 150_000 }, ); assert.notEqual(control.isError, true, JSON.stringify(control)); @@ -297,7 +311,9 @@ const verifyAndroidReadiness = async ({ env: environment, stderr: "pipe", }); - const client = new Client({ name: "rea-android-readiness", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "rea-android-readiness", version: "1" }), + ); try { await client.connect(transport); const catalog = await client.listTools(); diff --git a/scripts/verify/android/method-bodies.mjs b/scripts/verify/android/method-bodies.mjs index fee27aa10bd..6f1bb5a2b92 100644 --- a/scripts/verify/android/method-bodies.mjs +++ b/scripts/verify/android/method-bodies.mjs @@ -3,6 +3,10 @@ import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { parseEvidence } from "../../../dist/domain/evidence.js"; import { sha256File } from "../../lib/verifier-file-sha256.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "../../lib/complete-evidence.mjs"; const initializers = [ { @@ -127,14 +131,16 @@ export const verifyAndroidMethodBodies = async ({ process.execPath, [ entrypoint, - "inspect-android-method", - apk, - scenario.class_name, - scenario.method_name, - "--overload-index", - String(scenario.overload_index), - "--format", - "json", + ...(await completeEvidenceCliArguments([ + "inspect-android-method", + apk, + scenario.class_name, + scenario.method_name, + "--overload-index", + String(scenario.overload_index), + "--format", + "json", + ])), ], { cwd: repository, @@ -156,10 +162,12 @@ export const verifyAndroidMethodBodies = async ({ transport.stderr?.on("data", (chunk) => { stderr += chunk.toString(); }); - const client = new Client({ - name: "rea-real-android-method-bodies", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "rea-real-android-method-bodies", + version: "1", + }), + ); try { await client.connect(transport, { timeout: 30_000 }); for (const scenario of cases) { @@ -167,6 +175,7 @@ export const verifyAndroidMethodBodies = async ({ { name: "inspect_android_method", arguments: { + detail: "complete", path: apk, class_name: scenario.class_name, method_name: scenario.method_name, diff --git a/scripts/verify/android/windows-lifecycle.mjs b/scripts/verify/android/windows-lifecycle.mjs index d16ffda705a..38f8f352ca6 100644 --- a/scripts/verify/android/windows-lifecycle.mjs +++ b/scripts/verify/android/windows-lifecycle.mjs @@ -14,6 +14,10 @@ import { VerifierFixture, withVerifierFixture, } from "../../lib/verifier-fixture.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "../../lib/complete-evidence.mjs"; /** Verify real Windows cancellation, disconnect and abrupt CLI owner exit. */ export async function verifyWindowsAndroidLifecycle(options) { @@ -99,10 +103,12 @@ async function verifyMcp({ entrypoint, environment, path, repository }, mode) { transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); }); - const client = new Client({ - name: `rea-windows-android-${mode}`, - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: `rea-windows-android-${mode}`, + version: "1", + }), + ); let observer; try { await client.connect(transport); @@ -111,7 +117,10 @@ async function verifyMcp({ entrypoint, environment, path, repository }, mode) { const controller = new AbortController(); const pending = client .callTool( - { name: "inspect_android_package", arguments: { path } }, + { + name: "inspect_android_package", + arguments: { detail: "complete", path }, + }, { timeout: 150000, signal: controller.signal }, ) .then( @@ -144,7 +153,10 @@ async function verifyMcp({ entrypoint, environment, path, repository }, mode) { ); await client.ping(); const next = await client.callTool( - { name: "inspect_android_package", arguments: { path } }, + { + name: "inspect_android_package", + arguments: { detail: "complete", path }, + }, { timeout: 150000 }, ); assert.notEqual(next.isError, true, JSON.stringify(next)); @@ -170,7 +182,15 @@ async function verifyCliOwnerExit({ const baseline = new Set(await runtimeRoots()); const child = spawn( process.execPath, - [entrypoint, "inspect-android-package", path, "--format", "json"], + [ + entrypoint, + ...(await completeEvidenceCliArguments([ + "inspect-android-package", + path, + "--format", + "json", + ])), + ], { cwd: repository, env: environment, stdio: ["ignore", "pipe", "pipe"] }, ); let output = ""; diff --git a/scripts/verify/apple/macho-occurrences.mjs b/scripts/verify/apple/macho-occurrences.mjs index d1719af43bd..9458748b7f4 100644 --- a/scripts/verify/apple/macho-occurrences.mjs +++ b/scripts/verify/apple/macho-occurrences.mjs @@ -56,7 +56,7 @@ export async function verifyMachOOccurrences(app, executable) { await withArtifactMcp(app, async (client) => { const reply = await artifactMcpCall(client, { name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); assert.notEqual(reply.isError, true, JSON.stringify(reply)); assert.deepEqual( diff --git a/scripts/verify/apple/native-provenance.mjs b/scripts/verify/apple/native-provenance.mjs index f3e745a5f80..b4796280d22 100644 --- a/scripts/verify/apple/native-provenance.mjs +++ b/scripts/verify/apple/native-provenance.mjs @@ -272,7 +272,7 @@ async function verifyInstallNames() { await withArtifactMcp(consumer, async (client) => { const response = await artifactMcpCall(client, { name: "inspect_macho", - arguments: {}, + arguments: { detail: "complete" }, }); assert.notEqual(response.isError, true, JSON.stringify(response)); const mcp = toolContract("inspect_macho").outputSchema.parse( diff --git a/scripts/verify/electron/tool-contracts.mjs b/scripts/verify/electron/tool-contracts.mjs index 3154c7b6d4e..5a63b41a1fc 100644 --- a/scripts/verify/electron/tool-contracts.mjs +++ b/scripts/verify/electron/tool-contracts.mjs @@ -20,6 +20,7 @@ import { cleanupOwnedProcessGroup, readProcessRunId, } from "../../../dist/process/ProcessOwnership.js"; +import { completeEvidenceClient } from "../../lib/complete-evidence.mjs"; const execute = promisify(execFile); @@ -112,7 +113,9 @@ bridge.exposeInMainWorld("fixture", { }, stderr: "pipe", }); - const client = new Client({ name: "electron-real-e2e", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "electron-real-e2e", version: "1" }), + ); let serverStderr = ""; transport.stderr?.on("data", (chunk) => { serverStderr += chunk.toString(); @@ -213,6 +216,7 @@ bridge.exposeInMainWorld("fixture", { ), ); const staticAnalysis = await call("analyze_javascript_application", { + detail: "complete", input_path: applicationRoot, }); assert.equal(staticAnalysis.normalized_result.summary.browser_windows, 1); diff --git a/scripts/verify/firmware/analysis.mjs b/scripts/verify/firmware/analysis.mjs index 47f5cf8b4ff..8a15ffd1bd6 100644 --- a/scripts/verify/firmware/analysis.mjs +++ b/scripts/verify/firmware/analysis.mjs @@ -14,6 +14,7 @@ import { VerifierFixture, withVerifierFixture, } from "../../lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "../../lib/complete-evidence.mjs"; const execFileAsync = promisify(execFile); const { join, resolve, dirname } = nodePath; @@ -92,10 +93,12 @@ const workDir = workFixture.path; const baseEnv = Object.fromEntries( Object.entries(process.env).filter(([, v]) => v !== undefined), ); -const mcpClient = new Client({ - name: "rea-real-firmware-verifier", - version: "1", -}); +const mcpClient = completeEvidenceClient( + new Client({ + name: "rea-real-firmware-verifier", + version: "1", + }), +); // --------------------------------------------------------------------------- // Invocation helpers @@ -365,6 +368,7 @@ async function stageGhidra(mcpFiles) { ); const pseudoRaw = await callTool("procedure_pseudo_code", { + detail: "complete", procedure: "firmware_probe", }); assert.equal(parseEvidence(pseudoRaw).provider.id, "ghidra"); diff --git a/scripts/verify/firmware/devicetree.mjs b/scripts/verify/firmware/devicetree.mjs index 75c9d833700..cbc725f69e1 100644 --- a/scripts/verify/firmware/devicetree.mjs +++ b/scripts/verify/firmware/devicetree.mjs @@ -4,6 +4,7 @@ import { withVerifierCleanup } from "../../lib/verifier-cleanup.mjs"; import { VerifierFixture } from "../../lib/verifier-fixture.mjs"; import { readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import { completeEvidenceCliArguments } from "../../lib/complete-evidence.mjs"; // Optional verification tool only; the runtime inspector never starts dtc. const dtc = process.env.REA_DTC_PATH ?? "dtc"; @@ -50,9 +51,11 @@ await withVerifierCleanup(async () => { const evidence = JSON.parse( await exec(process.execPath, [ "scripts/rea.mjs", - "inspect-devicetree", - blob, - "--json", + ...(await completeEvidenceCliArguments([ + "inspect-devicetree", + blob, + "--json", + ])), ]), ); const report = evidence.normalized_result; diff --git a/scripts/verify/firmware/esp-image-tools.mjs b/scripts/verify/firmware/esp-image-tools.mjs index 66a39a65e72..53698e050b9 100644 --- a/scripts/verify/firmware/esp-image-tools.mjs +++ b/scripts/verify/firmware/esp-image-tools.mjs @@ -215,7 +215,15 @@ export const imageInfo = async (file, chip) => { const inspectArtifact = (file, flags) => execute( process.execPath, - [entrypoint, "inspect-artifact", file, ...flags, "--json"], + [ + entrypoint, + "inspect-artifact", + "--detail", + "complete", + file, + ...flags, + "--json", + ], { ...options, env: { ...process.env, REA_LOG_LEVEL: "silent" } }, ); diff --git a/scripts/verify/harmony/analysis.mjs b/scripts/verify/harmony/analysis.mjs index 79661c750fd..0711e28b3d6 100644 --- a/scripts/verify/harmony/analysis.mjs +++ b/scripts/verify/harmony/analysis.mjs @@ -17,6 +17,10 @@ import { VerifierFixture, withVerifierFixture, } from "../../lib/verifier-fixture.mjs"; +import { + completeEvidenceCliArguments, + completeEvidenceClient, +} from "../../lib/complete-evidence.mjs"; const repository = resolve(dirname(fileURLToPath(import.meta.url)), "../../.."); const hap = process.env.REA_HARMONY_TEST_HAP; @@ -42,7 +46,15 @@ const workspace = workspaceFixture.path; await withVerifierFixture(workspaceFixture, async () => { const inspectResponse = await execute( process.execPath, - [entrypoint, "inspect-artifact", path, "--format", "json"], + [ + entrypoint, + ...(await completeEvidenceCliArguments([ + "inspect-artifact", + path, + "--format", + "json", + ])), + ], { cwd: repository, timeout: 150_000, maxBuffer: 64 * 1024 * 1024 }, ); const inspection = parseEvidence(JSON.parse(inspectResponse.stdout)); @@ -148,10 +160,12 @@ await withVerifierFixture(workspaceFixture, async () => { transport.stderr?.on("data", (chunk) => { stderr += chunk.toString(); }); - const client = new Client({ - name: "rea-real-harmony-verifier", - version: "1", - }); + const client = completeEvidenceClient( + new Client({ + name: "rea-real-harmony-verifier", + version: "1", + }), + ); try { await client.connect(transport, { timeout: 30_000 }); await client.listTools(); @@ -170,7 +184,7 @@ await withVerifierFixture(workspaceFixture, async () => { assert.equal(status.structuredContent?.result?.open, true); assert.equal(status.structuredContent?.result?.format, "hap"); const inspected = await client.callTool( - { name: "inspect_artifact", arguments: {} }, + { name: "inspect_artifact", arguments: { detail: "complete" } }, { timeout: 150_000 }, ); assert.notEqual(inspected.structuredContent, undefined); diff --git a/scripts/verify/inspector/runtime-observation.mjs b/scripts/verify/inspector/runtime-observation.mjs index 329bc1a6601..b66a405b3b1 100644 --- a/scripts/verify/inspector/runtime-observation.mjs +++ b/scripts/verify/inspector/runtime-observation.mjs @@ -14,6 +14,7 @@ import { promisify } from "node:util"; import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { completeEvidenceClient } from "../../lib/complete-evidence.mjs"; const execute = promisify(execFile); const repository = resolve(dirname(fileURLToPath(import.meta.url)), "../../.."); @@ -26,10 +27,12 @@ const root = rootFixture.path; const environment = { ...process.env, }; -const client = new Client({ - name: "rea-inspector-conformance", - version: "1.0.0", -}); +const client = completeEvidenceClient( + new Client({ + name: "rea-inspector-conformance", + version: "1.0.0", + }), +); const transport = new StdioClientTransport({ command: process.execPath, args: ["scripts/rea.mjs", "mcp"], diff --git a/scripts/verify/javascript/module-references.mjs b/scripts/verify/javascript/module-references.mjs index 31ecf9b59ee..839600b7a33 100644 --- a/scripts/verify/javascript/module-references.mjs +++ b/scripts/verify/javascript/module-references.mjs @@ -12,6 +12,10 @@ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { artifactCliEvidence } from "../../lib/artifact-e2e.mjs"; import { withVerifierCleanup } from "../../lib/verifier-cleanup.mjs"; import { VerifierFixture } from "../../lib/verifier-fixture.mjs"; +import { + completeEvidenceClient, + completeEvidenceToolArguments, +} from "../../lib/complete-evidence.mjs"; import { OwnedCommandFailure, runOwnedCommand, @@ -54,10 +58,12 @@ const transport = new StdioClientTransport({ }, stderr: "pipe", }); -const client = new Client({ - name: "javascript-module-reference-verifier", - version: "1", -}); +const client = completeEvidenceClient( + new Client({ + name: "javascript-module-reference-verifier", + version: "1", + }), +); const serialize = (value) => JSON.stringify(value); const bytes = (value) => Buffer.byteLength(serialize(value)); const digest = (value) => @@ -114,7 +120,10 @@ await withVerifierCleanup(async () => { }; const summary = await call( "analyze_javascript_application", - preparationRequest, + await completeEvidenceToolArguments( + "analyze_javascript_application", + preparationRequest, + ), ); const source = { kind: "retained-evidence", diff --git a/scripts/verify/javascript/native-handoffs.mjs b/scripts/verify/javascript/native-handoffs.mjs index 7c3d3a5896d..a911bfed8c3 100644 --- a/scripts/verify/javascript/native-handoffs.mjs +++ b/scripts/verify/javascript/native-handoffs.mjs @@ -18,6 +18,7 @@ import { } from "../../../dist/process/OwnedCommand.js"; import { withVerifierCleanup } from "../../lib/verifier-cleanup.mjs"; import { importVerifierSource } from "../../lib/verifier-source-loader.mjs"; +import { completeEvidenceClient } from "../../lib/complete-evidence.mjs"; const { matchesStructuredScopeExpectation, structuredScopeExpectationsSchema } = await importVerifierSource( @@ -97,10 +98,12 @@ const transport = new StdioClientTransport({ env: environment, stderr: "pipe", }); -const client = new Client({ - name: "javascript-native-handoff-verifier", - version: "1", -}); +const client = completeEvidenceClient( + new Client({ + name: "javascript-native-handoff-verifier", + version: "1", + }), +); const serialize = (value) => JSON.stringify(value); const digest = (value) => createHash("sha256").update(serialize(value)).digest("hex"); diff --git a/scripts/verify/javascript/recovery.mjs b/scripts/verify/javascript/recovery.mjs index 30729c73660..41ae832ec41 100644 --- a/scripts/verify/javascript/recovery.mjs +++ b/scripts/verify/javascript/recovery.mjs @@ -16,6 +16,7 @@ import { parseEvidence } from "../../../dist/domain/evidence.js"; import { javascriptRecoveryResultSchema } from "../../../dist/domain/javascript/javascriptRecovery.js"; import { buildRecoveryFixtures } from "../../fixtures/javascript-recovery/build.mjs"; import { mcpTextValue } from "../../lib/mcp-verifier-results.mjs"; +import { completeEvidenceClient } from "../../lib/complete-evidence.mjs"; const OFFICIAL_BINARY_SHA256 = "664fa06782a61eda7ed15885134b52525fd565dd77607e642062ceb6cd927c38"; @@ -36,7 +37,9 @@ const transport = new StdioClientTransport({ env: environment, stderr: "pipe", }); -const client = new Client({ name: "real-recovery", version: "1" }); +const client = completeEvidenceClient( + new Client({ name: "real-recovery", version: "1" }), +); const run = promisify(execFile); const cli = async (...args) => { const { stdout } = await run( @@ -108,8 +111,13 @@ await withVerifierFixture(rootFixture, async () => { ? await cli( "analyze-javascript-application", result.analysis_input.input_path, + "--detail", + "complete", ) - : await call("analyze_javascript_application", result.analysis_input); + : await call("analyze_javascript_application", { + ...result.analysis_input, + detail: "complete", + }); assert.equal(analysis.normalized_result.statistics.parse_failures, 0); assert.equal( analysis.normalized_result.statistics.parsed_javascript_files, diff --git a/scripts/verify/javascript/retained-facts.mjs b/scripts/verify/javascript/retained-facts.mjs index 90e77a71019..2954d332b06 100644 --- a/scripts/verify/javascript/retained-facts.mjs +++ b/scripts/verify/javascript/retained-facts.mjs @@ -17,6 +17,7 @@ import { } from "../../../dist/process/OwnedCommand.js"; import { withVerifierCleanup } from "../../lib/verifier-cleanup.mjs"; import { selectExportedJavaScriptFacts } from "../../lib/javascript-facts-reference.mjs"; +import { completeEvidenceClient } from "../../lib/complete-evidence.mjs"; const { values } = parseArgs({ options: { @@ -51,10 +52,12 @@ const transport = new StdioClientTransport({ env: environment, stderr: "pipe", }); -const client = new Client({ - name: "javascript-retained-facts-verifier", - version: "1", -}); +const client = completeEvidenceClient( + new Client({ + name: "javascript-retained-facts-verifier", + version: "1", + }), +); let temporary; let report; const serialize = (value) => JSON.stringify(value); diff --git a/scripts/verify/mcp-client-validation.mjs b/scripts/verify/mcp-client-validation.mjs index 87f4f8421f1..346ece715eb 100644 --- a/scripts/verify/mcp-client-validation.mjs +++ b/scripts/verify/mcp-client-validation.mjs @@ -1,4 +1,5 @@ import { tokenize } from "./source-tokens.mjs"; +import { completeEvidenceClient } from "../lib/complete-evidence.mjs"; // CI runs the architecture guards before installing dependencies, so this // reads the call from scripts/verify/source-tokens.mjs tokens rather than a @@ -84,7 +85,7 @@ const callNamesValidator = (source, tokens, open) => { }; /** - * Number of `new Client(...)` calls in `content` whose own arguments do not + * Number of `completeEvidenceClient(new Client(...))` calls in `content` whose own arguments do not * pass a `jsonSchemaValidator` property. The source is tokenized, so the * option is read from the second argument's own object literal. Comments, * client metadata and neighbouring calls cannot stand in for options. diff --git a/scripts/verify/recorded-crash/public.mjs b/scripts/verify/recorded-crash/public.mjs index 6ebe7172acb..f2eaae6dc82 100644 --- a/scripts/verify/recorded-crash/public.mjs +++ b/scripts/verify/recorded-crash/public.mjs @@ -8,12 +8,15 @@ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { parseEvidence } from "../../../dist/domain/evidence.js"; import { recordedCrashSchema } from "../../../dist/domain/native/recordedCrash.js"; import { mcpTextValue } from "../../lib/mcp-verifier-results.mjs"; +import { completeEvidenceClient } from "../../lib/complete-evidence.mjs"; const execute = promisify(execFile); /** Exercise the public installed CLI and SDK transport with the same selected environment. */ export async function connectRecordedCrash({ entrypoint, environment }) { - const client = new Client({ name: "recorded-crash-verifier", version: "1" }); + const client = completeEvidenceClient( + new Client({ name: "recorded-crash-verifier", version: "1" }), + ); const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], diff --git a/scripts/verify/termux/browser.mjs b/scripts/verify/termux/browser.mjs index ab9dfe0d077..53d5c16ab4d 100644 --- a/scripts/verify/termux/browser.mjs +++ b/scripts/verify/termux/browser.mjs @@ -4,6 +4,7 @@ import assert from "node:assert/strict"; import { execFile } from "node:child_process"; import { createServer } from "node:http"; import { promisify } from "node:util"; +import { completeEvidenceCliArguments } from "../../lib/complete-evidence.mjs"; const execute = promisify(execFile); assert.equal(process.platform, "android", "Run this verifier inside Termux"); @@ -48,9 +49,11 @@ try { process.execPath, [ "scripts/rea.mjs", - "capture-browser-scenario", - JSON.stringify(scenario), - "--json", + ...(await completeEvidenceCliArguments([ + "capture-browser-scenario", + JSON.stringify(scenario), + "--json", + ])), ], { timeout: 180_000, maxBuffer: 16 * 1024 * 1024 }, ); diff --git a/src/application/analysisView/AnalysisViewService.ts b/src/application/analysisView/AnalysisViewService.ts index 9012f1a59bb..818381ee79d 100644 --- a/src/application/analysisView/AnalysisViewService.ts +++ b/src/application/analysisView/AnalysisViewService.ts @@ -251,6 +251,7 @@ const projectResolvedAnalysisView = ( limitations: parent.limitations, parameters: parent.parameters, artifact: viewArtifact(presentation), + evidence: parent, }); if (!projected.ok) return projected; const identity = validateAnalysisViewSubject( @@ -261,6 +262,29 @@ const projectResolvedAnalysisView = ( return ok(createAnalysisViewEvidence(input, presentation, projected.value)); }; +/** + * The summary an over-budget delivery returns in place of complete Evidence + * the caller can already reach. It is the same record `detail: "summary"` + * delivers, so its identity holds wherever a summary is accepted. An + * operation without a summary view fails here, and the caller keeps + * delivering its complete Evidence. + */ +export const summarizeOverBudgetEvidence = ( + evidence: Evidence, +): Result => { + const view = { kind: "summary" } as const; + const source = { + kind: "retained-evidence" as const, + evidence_id: evidence.evidence_id, + }; + return projectResolvedAnalysisView( + { source, view }, + prepareAnalysisViewProjection(view), + evidence, + evidenceSubjectTarget(evidence.subject), + ); +}; + /** * Retain complete analysis Evidence in the session, then project its summary * with this observation's subject path. Callers page or select the rest through diff --git a/src/application/analysisView/EvidenceJsonView.test.ts b/src/application/analysisView/EvidenceJsonView.test.ts new file mode 100644 index 00000000000..78d38d02bfa --- /dev/null +++ b/src/application/analysisView/EvidenceJsonView.test.ts @@ -0,0 +1,164 @@ +import { describe, expect, it } from "vitest"; + +import { createEvidence, type Evidence } from "../../domain/evidence.js"; +import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; +import { EvidenceLedger } from "../investigation/EvidenceLedger.js"; +import { inspectAnalysisViewValidated } from "./AnalysisViewService.js"; +import { DEFAULT_EVIDENCE_JSON_PAGE_BYTES } from "../../domain/analysisView/evidenceJsonView.js"; +import { DEFAULT_AGENT_RESULT_BUDGET_BYTES } from "../../domain/analysisResourceLimits.js"; + +const parentEvidence = (): Evidence => + createEvidence( + { path: "/fixture/sample.bin", sha256: "c".repeat(64), format: "elf" }, + { id: "fixture", name: "Fixture", version: "1" }, + { + operation: "inspect_byte_entropy", + parameters: {}, + // A non-BMP character makes a page boundary able to split a surrogate pair. + result: { + rows: Array.from({ length: 200 }, (_, index) => ({ + index, + label: `row ${String(index)} \u{1F600}`, + })), + }, + limitations: ["fixture limitation"], + }, + ); + +type PageResult = { + readonly text: string; + readonly coverage: { + readonly next_offset: number | null; + readonly total: number; + readonly exhausted: boolean; + }; +}; + +const page = ( + ledger: EvidenceLedger, + evidenceId: string, + offset: number, + limit: number, +): PageResult => { + const projected = inspectAnalysisViewValidated( + { + source: { kind: "retained-evidence", evidence_id: evidenceId }, + view: { kind: "evidence-json", offset, limit }, + }, + (id) => ledger.forAnalysis(id), + ); + if (!projected.ok) throw projected.error; + return projected.value.normalized_result as unknown as PageResult; +}; + +describe("evidence-json view", () => { + it("reproduces the complete retained Evidence when every page is joined", () => { + const parent = parentEvidence(); + const ledger = new EvidenceLedger(); + expect(ledger.record(parent).ok).toBe(true); + const retained = ledger.forAnalysis(parent.evidence_id)!; + const expected = JSON.stringify(retained); + + const pages: string[] = []; + let offset: number | null = 0; + let calls = 0; + while (offset !== null) { + const result = page(ledger, parent.evidence_id, offset, 257); + expect(result.coverage.total).toBe(expected.length); + pages.push(result.text); + offset = result.coverage.next_offset; + calls += 1; + expect(calls).toBeLessThan(10_000); + } + const joined = pages.join(""); + expect(joined).toBe(expected); + expect(JSON.parse(joined)).toEqual(JSON.parse(JSON.stringify(parent))); + // No page ends between the halves of a surrogate pair. + for (const text of pages.slice(0, -1)) { + const last = text.charCodeAt(text.length - 1); + expect(last >= 0xd800 && last <= 0xdbff).toBe(false); + } + }); + + it("keeps a surrogate pair whole even in a one-unit page", () => { + const parent = parentEvidence(); + const ledger = new EvidenceLedger(); + expect(ledger.record(parent).ok).toBe(true); + const text = JSON.stringify(ledger.forAnalysis(parent.evidence_id)); + const pair = text.indexOf("\u{1F600}"); + const result = page(ledger, parent.evidence_id, pair, 1); + expect(result.text).toBe("\u{1F600}"); + expect(result.coverage.next_offset).toBe(pair + 2); + }); + + it("sizes an omitted limit by escaped UTF-8 bytes, not code units", () => { + // Three-byte characters and quotes would overflow a code-unit page. + const parent = createEvidence( + { path: "/fixture/wide.bin", sha256: "d".repeat(64), format: "elf" }, + { id: "fixture", name: "Fixture", version: "1" }, + { + operation: "inspect_byte_entropy", + parameters: {}, + result: { text: '中"'.repeat(40_000) }, + }, + ); + const ledger = new EvidenceLedger(); + expect(ledger.record(parent).ok).toBe(true); + const projected = inspectAnalysisViewValidated( + { + source: { kind: "retained-evidence", evidence_id: parent.evidence_id }, + view: { kind: "evidence-json", offset: 0 }, + }, + (id) => ledger.forAnalysis(id), + ); + if (!projected.ok) throw projected.error; + const { text } = projected.value.normalized_result as unknown as PageResult; + expect(Buffer.byteLength(JSON.stringify(text)) - 2).toBeLessThanOrEqual( + DEFAULT_EVIDENCE_JSON_PAGE_BYTES, + ); + expect(Buffer.byteLength(JSON.stringify(projected.value))).toBeLessThan( + DEFAULT_AGENT_RESULT_BUDGET_BYTES, + ); + }); + + it("rejects a starting offset inside a surrogate pair", () => { + const parent = parentEvidence(); + const ledger = new EvidenceLedger(); + expect(ledger.record(parent).ok).toBe(true); + const text = JSON.stringify(ledger.forAnalysis(parent.evidence_id)); + const pair = text.indexOf("\u{1F600}"); + const projected = inspectAnalysisViewValidated( + { + source: { kind: "retained-evidence", evidence_id: parent.evidence_id }, + view: { kind: "evidence-json", offset: pair + 1, limit: 8 }, + }, + (id) => ledger.forAnalysis(id), + ); + expect(projected.ok).toBe(false); + if (projected.ok) return; + expect(projectAnalysisError(projected.error)).toMatchObject({ + code: "invalid_request", + details: { + issues: [ + expect.objectContaining({ + path: ["view", "offset"], + reason: "invalid_value", + }), + ], + }, + }); + }); + + it("reports an exhausted empty page past the end", () => { + const parent = parentEvidence(); + const ledger = new EvidenceLedger(); + expect(ledger.record(parent).ok).toBe(true); + const total = JSON.stringify(ledger.forAnalysis(parent.evidence_id)).length; + const result = page(ledger, parent.evidence_id, total + 10, 64); + expect(result.text).toBe(""); + expect(result.coverage).toMatchObject({ + next_offset: null, + exhausted: true, + }); + }); +}); diff --git a/src/cli/analysisEvidenceDelivery.ts b/src/cli/analysisEvidenceDelivery.ts index 258d7b1054a..a998da0fb26 100644 --- a/src/cli/analysisEvidenceDelivery.ts +++ b/src/cli/analysisEvidenceDelivery.ts @@ -1,5 +1,8 @@ import { explicitValuesOccurIn } from "../domain/explicitSensitiveValues.js"; -import { recordCliEvidencePublication } from "./cliEvidencePublication.js"; +import { + cliPublicationInvocation, + recordCliEvidencePublication, +} from "./cliEvidencePublication.js"; import { recordCliDeliveredEvidence } from "./cliResultControls.js"; import type { AnalysisViewRequest } from "../domain/analysisView/analysisViewRequest.js"; import { @@ -15,7 +18,17 @@ import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { redactExplicitFailure } from "../domain/explicitSensitiveFailure.js"; import { err, ok, type Result } from "../domain/result.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; -import { cliEvidenceDeliveryInputError } from "./analysisEvidenceDeliveryOptions.js"; +import { + cliEvidenceDeliveryInputError, + type CliDeliveryDetail, +} from "./analysisEvidenceDeliveryOptions.js"; +import { + agentBudgetDelivery, + budgetedSummaryBytes, + currentAgentResultBudget, + type AgentBudgetDelivery, + type AgentBudgetRecovery, +} from "../domain/agentResultBudget.js"; import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; import { isObject, @@ -29,7 +42,8 @@ interface CliEvidencePublication { readonly view?: AnalysisViewRequest; readonly operation: string; readonly signal: AbortSignal; - readonly detail: "complete" | "summary"; + /** Undefined leaves delivery to the agent result budget. */ + readonly detail: CliDeliveryDetail; readonly evidenceOutput: string | undefined; /** Exact one-shot CLI target spelling, when this invocation selects a file. */ readonly callerInputPath?: string; @@ -169,11 +183,23 @@ export const publishCliAnalysisEvidence = async ( inputError.retainPartialObservation(complete); return projectFailure(inputError); } - if (evidenceOutput === undefined) return complete; + const overBudget = budgetDelivery(complete, input); + if (evidenceOutput === undefined) { + if (overBudget === undefined) return complete; + const summary = await overBudgetSummary(complete); + return summary === undefined + ? complete + : { + summary, + delivery: deliveryJson(overBudget({ kind: "not-retained" })), + }; + } + const outputPath = absoluteCallerPath(evidenceOutput); const published = await publishDeliveredEvidence( complete, evidenceOutput, closureInput, + overBudget !== undefined, ); if (!published.ok) { const failure = projectFailure(published.error.error); @@ -181,26 +207,107 @@ export const publishCliAnalysisEvidence = async ( ? failure : withUndeliveredSourceClosure(failure, closureInput); } - return detail === "summary" + const delivery = + published.value.budgeted && overBudget !== undefined + ? overBudget({ + kind: "evidence-file", + path: revealsSensitiveValue(outputPath, input) + ? undefined + : outputPath, + }) + : undefined; + return published.value.summarized ? { summary: published.value.delivered, evidence_bundle: published.value.receipt, + ...(delivery === undefined ? {} : { delivery: deliveryJson(delivery) }), } : published.value.delivered; }; +/** Delivery facts are plain JSON by construction. */ +const deliveryJson = (delivery: AgentBudgetDelivery): JsonValue => + delivery as unknown as JsonValue; + +/** + * For a caller that left `--detail` to the agent result budget, the + * delivery facts an over-budget result carries for each place the complete + * Evidence can be; undefined when complete Evidence fits or was chosen. + */ +const budgetDelivery = ( + complete: Evidence, + input: CliEvidencePublication, +): ((recovery: AgentBudgetRecovery) => AgentBudgetDelivery) | undefined => { + const invocation = cliPublicationInvocation(); + // An explicit --filter-output selects fields directly from the command's + // Evidence; replacing it with {summary, delivery} would drop those paths. + if (invocation.hasFilterOutput === true) return undefined; + const budget = currentAgentResultBudget(invocation.agentBudgetSeed); + // The one-shot CLI can always publish and page the complete record: with + // --evidence_output through the bundle, without it by a rerun. + const completeBytes = budgetedSummaryBytes({ + detail: input.detail, + evidence: complete, + budget, + retained: true, + pageable: true, + }); + return completeBytes === undefined || budget === undefined + ? undefined + : (recovery) => + agentBudgetDelivery({ + operation: complete.operation, + evidenceId: complete.evidence_id, + completeBytes, + budget, + recovery, + }); +}; + +/** + * The summary that replaces over-budget complete Evidence, answering this + * same invocation; undefined when the operation has no summary view, which + * keeps complete delivery. + */ +const overBudgetSummary = async ( + complete: Evidence, +): Promise => { + const { summarizeOverBudgetEvidence } = + await import("../application/analysisView/AnalysisViewService.js"); + const summary = summarizeOverBudgetEvidence(complete); + if (!summary.ok) return undefined; + return complete.caller_input_path !== undefined || + complete.caller_input_paths !== undefined + ? withEvidenceCallerInputPath( + summary.value, + complete.caller_input_path, + complete.caller_input_paths, + ) + : summary.value; +}; + /** * Project the requested view, then publish the complete bundle. Projection * runs first so a view failure cannot commit an unreported bundle; - * publication then owns every post-commit outcome. + * publication then owns every post-commit outcome. An over-budget delivery + * publishes its summary when the operation has one, and complete Evidence + * otherwise. */ const publishDeliveredEvidence = async ( complete: Evidence, evidenceOutput: string, input: CliEvidencePublication, + overBudget = false, ): Promise< Result< - { readonly delivered: Evidence; readonly receipt: JsonValue }, + { + readonly delivered: Evidence; + readonly receipt: JsonValue; + /** Whether `delivered` is a summary of the published complete record. */ + readonly summarized: boolean; + /** Whether that summary replaced over-budget complete Evidence. */ + readonly budgeted: boolean; + }, { readonly error: AnalysisError; readonly committed: boolean; @@ -209,6 +316,8 @@ const publishDeliveredEvidence = async ( } > > => { + const budgeted = overBudget ? await overBudgetSummary(complete) : undefined; + const summarized = input.detail === "summary" || budgeted !== undefined; const delivered = input.detail === "summary" ? ( @@ -217,7 +326,7 @@ const publishDeliveredEvidence = async ( source: { kind: "inline", evidence: complete }, view: input.view ?? { kind: "summary" }, }) - : ok(complete); + : ok(budgeted ?? complete); if (!delivered.ok) return err({ error: delivered.error.retainPartialObservation(complete), @@ -280,7 +389,12 @@ const publishDeliveredEvidence = async ( const { path, bytes } = published.value.evidenceBundle; const receipt = bundleReceipt(path, bytes, input); recordCliEvidencePublication(receipt); - return ok({ delivered: published.value.delivered, receipt }); + return ok({ + delivered: published.value.delivered, + receipt, + summarized, + budgeted: budgeted !== undefined, + }); }; /** Whether a caller-selected path contains an excluded sensitive literal. */ diff --git a/src/cli/analysisEvidenceDeliveryOptions.ts b/src/cli/analysisEvidenceDeliveryOptions.ts index c5ce8d4207a..b51d15bff4d 100644 --- a/src/cli/analysisEvidenceDeliveryOptions.ts +++ b/src/cli/analysisEvidenceDeliveryOptions.ts @@ -6,8 +6,10 @@ import { localPathStringSchema } from "../domain/localPath.js"; export const analysisEvidenceDeliveryOptions = { detail: z .enum(["complete", "summary"]) - .default("complete") - .describe("Deliver complete Evidence, or a summary with --evidence_output"), + .optional() + .describe( + "Omit for complete Evidence when it fits the agent result budget (32768 compact JSON bytes by default, about 11k tokens) and its summary otherwise; complete always delivers everything; summary needs --evidence_output", + ), evidence_output: localPathStringSchema .optional() .describe( @@ -15,12 +17,18 @@ export const analysisEvidenceDeliveryOptions = { ), }; +/** + * The caller's `--detail`; undefined leaves delivery to the agent result + * budget: complete Evidence when it fits, its summary otherwise. + */ +export type CliDeliveryDetail = "complete" | "summary" | undefined; + /** * Refuse a delivery that cannot keep complete source Evidence available: a * summary needs a bundle, and a selected page is cut from a retained summary. */ export const cliEvidenceDeliveryInputError = (input: { - readonly detail: "complete" | "summary"; + readonly detail: CliDeliveryDetail; readonly evidenceOutput: string | undefined; readonly operation: string; readonly view?: AnalysisViewRequest | undefined; diff --git a/src/cli/binaryDiagnosticsCommands.ts b/src/cli/binaryDiagnosticsCommands.ts index 316ac4fa497..02a5aadb3af 100644 --- a/src/cli/binaryDiagnosticsCommands.ts +++ b/src/cli/binaryDiagnosticsCommands.ts @@ -283,6 +283,7 @@ export const registerBinaryDiagnosticsCommands = ( "Inspect file-wide and block byte entropy without executing the file", positionals: ["path"], callerPaths: ["path"], + evidenceDelivery: true, fields: { path: { description: "Local file" }, block_size: { @@ -293,12 +294,8 @@ export const registerBinaryDiagnosticsCommands = ( description: "Window length in bytes; omit to extend through EOF", }, }, - omit: { - detail: - "One-shot output is complete Evidence; this command has no summary delivery", - }, }, - inspectWithService( + deliverWithService( async () => ( await import("../composition/binaryDiagnostics/byteEntropy.js") diff --git a/src/cli/cliEvidencePublication.ts b/src/cli/cliEvidencePublication.ts index 62dfcf065f5..c6a58d233fe 100644 --- a/src/cli/cliEvidencePublication.ts +++ b/src/cli/cliEvidencePublication.ts @@ -8,12 +8,28 @@ export interface PublishedEvidenceReceipt { interface PublicationContext { receipt?: PublishedEvidenceReceipt; + readonly invocation?: CliPublicationInvocation; } const publication = new AsyncLocalStorage(); +/** What one CLI invocation captured that its delivery reads. */ +export interface CliPublicationInvocation { + /** REA_AGENT_RESULT_BUDGET_BYTES from the environment this invocation captured. */ + readonly agentBudgetSeed?: string | undefined; + /** Whether the caller selected specific output fields with `--filter-output`. */ + readonly hasFilterOutput?: boolean | undefined; +} + /** Keep publication state in the invocation that owns delivery and formatting. */ -export const withCliEvidencePublication = (run: () => Value): Value => - publication.run({}, run); +export const withCliEvidencePublication = ( + run: () => Value, + invocation?: CliPublicationInvocation, +): Value => + publication.run(invocation === undefined ? {} : { invocation }, run); + +/** What this invocation captured; nothing outside one. */ +export const cliPublicationInvocation = (): CliPublicationInvocation => + publication.getStore()?.invocation ?? {}; export const recordCliEvidencePublication = ( receipt: PublishedEvidenceReceipt, diff --git a/src/cli/contractCliDescription.ts b/src/cli/contractCliDescription.ts index 7d0b4e41981..7ff59228a9d 100644 --- a/src/cli/contractCliDescription.ts +++ b/src/cli/contractCliDescription.ts @@ -876,7 +876,7 @@ export const describeContractCommand = < | undefined; const refused = cliEvidenceDeliveryInputError({ operation: contract.name, - detail: detail ?? (view === undefined ? "complete" : "summary"), + detail: detail ?? (view === undefined ? undefined : "summary"), evidenceOutput: decoded.value.evidence_output as string | undefined, view, }); @@ -1111,7 +1111,7 @@ const admitInvocation = ( if (!evidenceDelivery) return ok({ input, parsed, parseWholeInput, delivery: undefined }); const delivery: CliEvidenceDeliveryChoice = { - detail: detail ?? (view === undefined ? "complete" : "summary"), + detail: detail ?? (view === undefined ? undefined : "summary"), evidenceOutput: decoded.evidence_output as string | undefined, ...(view === undefined ? {} diff --git a/src/cli/contractCliDescriptionTypes.ts b/src/cli/contractCliDescriptionTypes.ts index 7d6839c331d..3c12357a014 100644 --- a/src/cli/contractCliDescriptionTypes.ts +++ b/src/cli/contractCliDescriptionTypes.ts @@ -1,3 +1,4 @@ +import type { CliDeliveryDetail } from "./analysisEvidenceDeliveryOptions.js"; import type { z } from "zod"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; @@ -431,7 +432,8 @@ export interface CliOnlyOption { /** The Evidence delivery a command invocation selected. */ export interface CliEvidenceDeliveryChoice { - readonly detail: "complete" | "summary"; + /** Undefined leaves delivery to the agent result budget. */ + readonly detail: CliDeliveryDetail; readonly evidenceOutput: string | undefined; /** The admitted view, for a projection with `viewDelivery`. */ readonly view?: AnalysisViewRequest; diff --git a/src/cli/contractCliDocumentDescription.ts b/src/cli/contractCliDocumentDescription.ts index 71be8f86850..4a8e0bb653d 100644 --- a/src/cli/contractCliDocumentDescription.ts +++ b/src/cli/contractCliDocumentDescription.ts @@ -230,7 +230,7 @@ const admitDocumentDelivery = ( } const detail = (values.detail as "complete" | "summary" | undefined) ?? - (view === undefined ? "complete" : "summary"); + (view === undefined ? undefined : "summary"); const delivery: CliEvidenceDeliveryChoice = { detail, evidenceOutput: values.evidence_output as string | undefined, diff --git a/src/cli/coreBinaryCommands.ts b/src/cli/coreBinaryCommands.ts index 138f54dcc72..250dd6d18bd 100644 --- a/src/cli/coreBinaryCommands.ts +++ b/src/cli/coreBinaryCommands.ts @@ -261,7 +261,9 @@ const registerDecompileCommand = ( }; /** Select static JavaScript analysis only when no binary-analysis option applies. */ -const isJavaScriptApplicationPath = async (path: string): Promise => { +export const isJavaScriptApplicationPath = async ( + path: string, +): Promise => { try { const canonical = await realpath(path); if (canonical.toLowerCase().endsWith(".asar")) return true; diff --git a/src/cli/javascriptApplicationAnalysis.ts b/src/cli/javascriptApplicationAnalysis.ts index c3abab09ef2..7516448a3dd 100644 --- a/src/cli/javascriptApplicationAnalysis.ts +++ b/src/cli/javascriptApplicationAnalysis.ts @@ -105,7 +105,7 @@ export const runCliJavaScriptApplicationAnalysis = async ( environment: Readonly>, signal?: AbortSignal, delivery?: { - readonly detail: "complete" | "summary"; + readonly detail: "complete" | "summary" | undefined; readonly evidenceOutput: string | undefined; readonly view?: AnalysisViewRequest; }, diff --git a/src/cli/runCliCommand.ts b/src/cli/runCliCommand.ts index 8f6e5972b0d..de1ecb3671a 100644 --- a/src/cli/runCliCommand.ts +++ b/src/cli/runCliCommand.ts @@ -1,3 +1,4 @@ +import { AGENT_RESULT_BUDGET_ENVIRONMENT } from "../domain/agentResultBudget.js"; import { Writable } from "node:stream"; import { @@ -123,29 +124,34 @@ export const runCliCommand = async ( report(cliArgumentFailure(cli.name, entry.name, parsed.error)); return; } - await withCliEvidencePublication(() => - withCliResultControls(async () => { - const rawValue = await entry.definition.run({ - ...parsed.value, - formatExplicit: controls.formatExplicit, - }); - const value = projectCliCommandOutput(rawValue, { - operations: entry.operations, - commands: cliCommands(cli), - cliName: cli.name, - recordedCommands: RECORDED_CLI_COMMAND_REGISTRATIONS, - }); - rebindLoggedCliFailure(rawValue, value); - if (!output.handled) - await output.write(value, { - command: entry.name, - duration: `${Math.round(performance.now() - started)}ms`, - renderOutput: - !human || entry.definition.outputPolicy !== "agent-only", - collectCliControls: cliResultControls, - cta, + await withCliEvidencePublication( + () => + withCliResultControls(async () => { + const rawValue = await entry.definition.run({ + ...parsed.value, + formatExplicit: controls.formatExplicit, }); - }), + const value = projectCliCommandOutput(rawValue, { + operations: entry.operations, + commands: cliCommands(cli), + cliName: cli.name, + recordedCommands: RECORDED_CLI_COMMAND_REGISTRATIONS, + }); + rebindLoggedCliFailure(rawValue, value); + if (!output.handled) + await output.write(value, { + command: entry.name, + duration: `${Math.round(performance.now() - started)}ms`, + renderOutput: + !human || entry.definition.outputPolicy !== "agent-only", + collectCliControls: cliResultControls, + cta, + }); + }), + { + agentBudgetSeed: environment.variables[AGENT_RESULT_BUDGET_ENVIRONMENT], + hasFilterOutput: controls.filterOutput !== undefined, + }, ); if (output.error !== undefined) exit(options, 1); } catch (cause: unknown) { diff --git a/src/config/analysisSettings.ts b/src/config/analysisSettings.ts index e9092996b49..3a6ee81d183 100644 --- a/src/config/analysisSettings.ts +++ b/src/config/analysisSettings.ts @@ -35,6 +35,7 @@ import { } from "./windowsChangeTimeSettle.js"; import { pwntoolsInputBytesSchema } from "./pwntoolsInputLimit.js"; import { zstandardMaxFramesSchema } from "../domain/compression/zstandardFrameAllowance.js"; +import { agentResultBudgetBytesSchema } from "../domain/agentResultBudget.js"; const environmentSchemas: Readonly>> = { REA_ASAR_MAX_HEADER_BYTES: asarMaxHeaderBytesSchema, @@ -69,6 +70,7 @@ const environmentSchemas: Readonly>> = REA_WINDOWS_CHANGE_TIME_SETTLE_MAX_POLLS: windowsChangeTimeSettleMaxPollsSchema, REA_ZSTD_MAX_FRAMES: zstandardMaxFramesSchema, + REA_AGENT_RESULT_BUDGET_BYTES: agentResultBudgetBytesSchema, }; export const launchAnalysisSetting = ( id: AnalysisSettingId, diff --git a/src/contracts/analysisDetail.test.ts b/src/contracts/analysisDetail.test.ts index faa3ca126cf..eb1fd41009d 100644 --- a/src/contracts/analysisDetail.test.ts +++ b/src/contracts/analysisDetail.test.ts @@ -133,3 +133,52 @@ it("advertises only that operation's summary from analysis detail outputs", () = ).toBe(false); } }); + +/** The `detail` alternatives an input JSON Schema declares, with their defaults. */ +const detailAlternatives = ( + schema: unknown, +): { + readonly values: readonly unknown[]; + readonly defaults: readonly unknown[]; +} => { + const values: unknown[] = []; + const defaults: unknown[] = []; + const visit = (node: unknown): void => { + if (typeof node !== "object" || node === null) return; + const record = node as Record; + const detail = (record.properties as Record | undefined) + ?.detail as Record | undefined; + if (detail !== undefined) { + if (Array.isArray(detail.enum)) values.push(...detail.enum); + if ("const" in detail) values.push(detail.const); + if ("default" in detail) defaults.push(detail.default); + } + for (const key of ["anyOf", "oneOf", "allOf"]) + if (Array.isArray(record[key])) + for (const child of record[key]) visit(child); + }; + visit(schema); + return { values, defaults }; +}; + +it("registers the agent result budget for every contract whose omitted detail is budgeted", async () => { + const [{ TOOL_CONTRACTS }, { AGENT_BUDGET_OPERATIONS }, { z }] = + await Promise.all([ + import("./toolContracts.js"), + import("../domain/agentBudgetOperations.js"), + import("zod"), + ]); + const budgeted = TOOL_CONTRACTS.flatMap((contract) => { + if (contract.name === "get_evidence_bundle") return []; + const { values, defaults } = detailAlternatives( + z.toJSONSchema(contract.inputSchema, { + io: "input", + unrepresentable: "any", + }), + ); + return values.includes("summary") && !defaults.includes("summary") + ? [contract.name] + : []; + }); + expect([...AGENT_BUDGET_OPERATIONS].sort()).toEqual(budgeted.sort()); +}); diff --git a/src/contracts/analysisDetail.ts b/src/contracts/analysisDetail.ts index aa0d7c94684..4aa2a458e2a 100644 --- a/src/contracts/analysisDetail.ts +++ b/src/contracts/analysisDetail.ts @@ -4,36 +4,12 @@ import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; /** Caller-selected delivery of completed analysis Evidence that supports retained views. */ export const analysisDetailSchema = z - .enum(["complete", "summary"]) - .default("complete") - .describe( - "complete returns the complete analysis Evidence inline. summary retains that complete Evidence in this session and returns its inspect_analysis_view summary; inspect pages, items or facets through normalized_result.parent_evidence_id.", - ); - -/** - * Largest complete Evidence, in UTF-8 JSON bytes, that an omitted size-aware - * detail delivers inline. Claude Code moves MCP results above about 25,000 - * tokens out of context into a file, and a 120-row inventory page of 73K - * characters already crossed that line; 32 KiB stays well inside it. - */ -export const SIZE_AWARE_INLINE_EVIDENCE_BYTES = 32 * 1024; - -/** - * Delivery for operations whose complete Evidence grows with the target, such - * as whole-binary inventories. Omitted, the result size selects the shape. - */ -export const analysisDetailSizeAwareSchema = z .enum(["complete", "summary"]) .optional() .describe( - "Omitted: the complete analysis Evidence inline when its JSON is at most 32 KiB, otherwise this session retains it and returns its inspect_analysis_view summary. complete always returns it inline; summary always retains it and returns the summary. Page a summary through normalized_result.parent_evidence_id.", + "Omitted: complete Evidence inline when its JSON fits the agent result budget (delivery.agent_result_budget_bytes, default 32768 bytes) and this session can page a summary; otherwise the retained summary, with delivery facts naming the budget and the inspect_analysis_view recovery. complete always returns the complete analysis Evidence inline. summary retains that complete Evidence in this session and returns its inspect_analysis_view summary; inspect pages, items or facets through normalized_result.parent_evidence_id.", ); -/** A contract opts into size-aware delivery by declaring that detail schema. */ -export const declaresSizeAwareDetail = (inputSchema: z.ZodType): boolean => - inputSchema instanceof z.ZodObject && - inputSchema.shape.detail === analysisDetailSizeAwareSchema; - /** * analyze_function delivery. Defaults to the token-frugal summary because a * complete native dossier can reach several megabytes of value-flow and diff --git a/src/contracts/android/androidToolContracts.ts b/src/contracts/android/androidToolContracts.ts index 24fc212b272..0d9191a8db1 100644 --- a/src/contracts/android/androidToolContracts.ts +++ b/src/contracts/android/androidToolContracts.ts @@ -69,7 +69,7 @@ export const ANDROID_TOOL_CONTRACTS = [ }), ), description: - "Inspect APK package/SDK/permission declarations, decoded manifest, static components and class/resource counts without executing it or verifying signatures. Requires caller-supplied JADX MCP JAR and JDK. Default complete returns full Evidence; detail summary retains it and omits manifest text/raw duplicates. With summary, view kind android selects facet components (exact filters, fields, paging), component-summary or manifest (UTF-16 text pages); complete detail rejects view. Use normalized_result.parent_evidence_id with inspect_analysis_view for later views. Component source_index identifies the original declaration, and declaration_coverage marks partial declarations.", + "Inspect APK package/SDK/permission declarations, decoded manifest, static components and class/resource counts without executing it or verifying signatures. Requires caller-supplied JADX MCP JAR and JDK. Omitted detail returns full Evidence within the agent result budget, else the retained summary; detail summary retains it and omits manifest text/raw duplicates. With summary, view kind android selects facet components (exact filters, fields, paging), component-summary or manifest (UTF-16 text pages); complete detail rejects view. Use normalized_result.parent_evidence_id with inspect_analysis_view for later views. Component source_index identifies the original declaration, and declaration_coverage marks partial declarations.", kind: "android-provider", inputSchema: androidPackageInspectionInputSchema, outputSchema: evidenceResultOf( @@ -146,7 +146,7 @@ export const ANDROID_TOOL_CONTRACTS = [ }), ), description: - "Inspect one exact Android class's methods, fields, inner classes, DEX prototypes and encoded static final values without generating source. Select an overload_index from these results for inspect_android_method; indices are artifact/engine-session scoped and prototypes are not complete raw method IDs. Optional mapping_path adds verified R8/ProGuard names separately; observed names remain primary. detail summary retains complete Evidence and returns normalized symbols without duplicate raw calls; complete remains the default.", + "Inspect one exact Android class's methods, fields, inner classes, DEX prototypes and encoded static final values without generating source. Select an overload_index from these results for inspect_android_method; indices are artifact/engine-session scoped and prototypes are not complete raw method IDs. Optional mapping_path adds verified R8/ProGuard names separately; observed names remain primary. detail summary retains complete Evidence and returns normalized symbols without duplicate raw calls; omitted detail is complete within the agent result budget, else the retained summary.", kind: "android-provider", inputSchema: androidSymbolInspectionInputSchemas.inspect_android_class, outputSchema: evidenceResultOf( @@ -183,7 +183,7 @@ export const ANDROID_TOOL_CONTRACTS = [ }), ), description: - "Decompile one Android method, with explicit overload_index when names collide and smali fallback when needed. Reports DEX prototype, representation, fallback markers and source truncation; display signatures may be aliases. Optional mapping_path annotates R8/ProGuard names without replacing observed names. detail summary retains complete Evidence and returns the selected body without duplicate class metadata; complete remains the default. Use inspect_android_class to choose the overload.", + "Decompile one Android method, with explicit overload_index when names collide and smali fallback when needed. Reports DEX prototype, representation, fallback markers and source truncation; display signatures may be aliases. Optional mapping_path annotates R8/ProGuard names without replacing observed names. detail summary retains complete Evidence and returns the selected body without duplicate class metadata; omitted detail is complete within the agent result budget, else the retained summary. Use inspect_android_class to choose the overload.", kind: "android-provider", inputSchema: androidSymbolInspectionInputSchemas.inspect_android_method, outputSchema: evidenceResultOf( diff --git a/src/contracts/browserScenarioToolContracts.ts b/src/contracts/browserScenarioToolContracts.ts index 45905b1ab68..f5e0c38da6b 100644 --- a/src/contracts/browserScenarioToolContracts.ts +++ b/src/contracts/browserScenarioToolContracts.ts @@ -44,7 +44,7 @@ export const BROWSER_SCENARIO_TOOL_CONTRACTS = [ }), ), description: - 'Drive a browser scenario when passive observation cannot exercise the app. Launch the selected executable or connect to a loopback CDP target; actions can change application state and make network requests. Supply browser, start_url and actions, e.g. {browser:{mode:"launch",executable_path:"/opt/chromium/chrome"},start_url:{url:"https://app.example.test/"},actions:[{step_id:"settle",action:"wait_for_timeout",duration_ms:250}]}. Empty storage and a URL-only final capture are defaults. Request actions use page fetch on the start origin; capture.network independently opts into request_body, response_body and header_values. Credentials and declared secrets are redacted. capture.limits controls retained event/content budgets; omissions identify affected events/transactions. Role locators match the exact full accessible name. Actions wait for completion or cancellation; per-action timeout_ms bounds a step. Default complete delivery returns Evidence inline. detail summary retains it and returns step outcomes, final/first-unsuccessful accessibility, and counts; inspect_analysis_view kind browser-scenario pages steps, events, transactions and UTF-16 text. Use inspect_web_page for observation without actions.', + 'Drive a browser scenario when passive observation cannot exercise the app. Launch the selected executable or connect to a loopback CDP target; actions can change application state and make network requests. Supply browser, start_url and actions, e.g. {browser:{mode:"launch",executable_path:"/opt/chromium/chrome"},start_url:{url:"https://app.example.test/"},actions:[{step_id:"settle",action:"wait_for_timeout",duration_ms:250}]}. Empty storage and a URL-only final capture are defaults. Request actions use page fetch on the start origin; capture.network independently opts into request_body, response_body and header_values. Credentials and declared secrets are redacted. capture.limits controls retained event/content budgets; omissions identify affected events/transactions. Role locators match the exact full accessible name. Actions wait for completion or cancellation; per-action timeout_ms bounds a step. Omitted detail returns Evidence inline within the agent result budget, else the retained summary. detail summary retains it and returns step outcomes, final/first-unsuccessful accessibility, and counts; inspect_analysis_view kind browser-scenario pages steps, events, transactions and UTF-16 text. Use inspect_web_page for observation without actions.', kind: "browser-provider", inputSchema: browserScenarioInputSchema.extend({ detail: analysisDetailSchema, diff --git a/src/contracts/browserToolContracts.ts b/src/contracts/browserToolContracts.ts index 65536086724..494ae9b1a4b 100644 --- a/src/contracts/browserToolContracts.ts +++ b/src/contracts/browserToolContracts.ts @@ -12,7 +12,7 @@ import { webPagePageViewResultSchema, webPageSummaryViewResultSchema, } from "../domain/analysisView/summarySchemas/webPageSummarySchemas.js"; -import { analysisDetailSizeAwareSchema } from "./analysisDetail.js"; +import { analysisDetailSchema } from "./analysisDetail.js"; import type { ToolContract } from "./toolContractTypes.js"; import { inspectWebPageShapeSchema, @@ -56,9 +56,9 @@ import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; import { presentRootDiscriminator } from "../domain/schemaAnnotations.js"; const listOutputSchema = evidenceResultOf(browserTargetListSchema); -/** Page inspection with size-aware delivery; detail never reaches the capture. */ +/** Page inspection with agent-budgeted delivery; detail never reaches the capture. */ const inspectWebPageRequestSchema = inspectWebPageShapeSchema - .extend({ detail: analysisDetailSizeAwareSchema }) + .extend({ detail: analysisDetailSchema }) .superRefine(refineInspectWebPageInput); const inspectionOutputSchema = evidenceResultOf( z.union([ @@ -213,7 +213,7 @@ export const BROWSER_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_web_page", browserEvidenceEffects), description: - 'Passively inspect one selected page target through CDP without evaluating JavaScript, navigating, clicking, closing, or mutating the page. If no origin filter is supplied, capture is scoped to the target\'s current origin. Returns DOM structure, accessibility, scripts, resources, attach-window network and console metadata, workers, and redacted storage inventory as Evidence. Omitted detail returns the capture inline when its Evidence is at most 32 KiB, else retains it and returns counts; page dom, accessibility, console, network, scripts or resources with inspect_analysis_view view {kind: "web-page", collection}. complete or summary forces that shape; compare_web_captures needs the complete capture.', + 'Passively inspect one selected page target through CDP without evaluating JavaScript, navigating, clicking, closing, or mutating the page. If no origin filter is supplied, capture is scoped to the target\'s current origin. Returns DOM structure, accessibility, scripts, resources, attach-window network and console metadata, workers, and redacted storage inventory as Evidence. Omitted detail returns the capture inline when it fits the agent result budget, else retains it and returns counts; page dom, accessibility, console, network, scripts or resources with inspect_analysis_view view {kind: "web-page", collection}. complete or summary forces that shape; compare_web_captures needs the complete capture.', kind: "browser-provider", inputSchema: inspectWebPageRequestSchema, outputSchema: inspectionOutputSchema, diff --git a/src/contracts/enhancedToolContracts.ts b/src/contracts/enhancedToolContracts.ts index 28aa6a48b5a..b7e1932a69f 100644 --- a/src/contracts/enhancedToolContracts.ts +++ b/src/contracts/enhancedToolContracts.ts @@ -1,8 +1,5 @@ import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js"; -import { - analysisDetailSchema, - analysisDetailSizeAwareSchema, -} from "./analysisDetail.js"; +import { analysisDetailSchema } from "./analysisDetail.js"; import { z } from "zod"; import { enhancedInputSchemas } from "./enhancedInputs.js"; @@ -73,9 +70,9 @@ export const ENHANCED_TOOL_CONTRACTS = [ enhanced( "batch_decompile", providerUiNetworkEvidenceEffects, - "Decompile an explicit list of procedure symbols/addresses in input order, with one provider read active per batch. Returns per-item pseudocode, unavailable or error outcomes and aggregate counts; input selectors and observed canonical procedure identities remain separate. Null pseudocode is unavailable, without an inferred capability or retry reason; failed counts include unavailable items. Omitted detail returns every body inline when the Evidence is at most 32 KiB, else retains the batch behind its summary for inspect_analysis_view item/body pages; complete or summary forces that shape. Per-function limits do not bound the whole batch.", + "Decompile an explicit list of procedure symbols/addresses in input order, with one provider read active per batch. Returns per-item pseudocode, unavailable or error outcomes and aggregate counts; input selectors and observed canonical procedure identities remain separate. Null pseudocode is unavailable, without an inferred capability or retry reason; failed counts include unavailable items. Select detail summary to retain the batch for inspect_analysis_view item/body pages; omitted detail is complete within the agent result budget, else the retained summary. Per-function limits do not bound the whole batch.", enhancedInputSchemas.batch_decompile.extend({ - detail: analysisDetailSizeAwareSchema, + detail: analysisDetailSchema, }), ), enhanced( @@ -124,9 +121,9 @@ export const ENHANCED_TOOL_CONTRACTS = [ toolEffects({ mutatesSession: true, idempotent: false }), providerRemoteEffects, ), - "Search procedure/string inventories for the complete literal query, then query xrefs at matched start addresses. Interior-byte references are not searched; empty results or truncated: false never establish no references. Containment refusals preserve an unavailable owner, and reference kinds remain unknown. For typed incoming procedure references use procedure_references, comparing target addresses for exact-entry matches. Omitted detail returns the trace inline when its Evidence is at most 32 KiB, else retains matches/references/unknowns behind its summary for inspect_analysis_view kind native-feature-trace; complete or summary forces that shape.", + "Search procedure/string inventories for the complete literal query, then query xrefs at matched start addresses. Interior-byte references are not searched; empty results or truncated: false never establish no references. Containment refusals preserve an unavailable owner, and reference kinds remain unknown. For typed incoming procedure references use procedure_references, comparing target addresses for exact-entry matches. Select detail summary to retain matches/references/unknowns for inspect_analysis_view kind native-feature-trace; omitted detail is complete within the agent result budget, else the retained summary.", enhancedInputSchemas.trace_feature.extend({ - detail: analysisDetailSizeAwareSchema, + detail: analysisDetailSchema, }), ), enhanced( diff --git a/src/contracts/erlang/beamToolContracts.ts b/src/contracts/erlang/beamToolContracts.ts index 35a62a77ac3..b98b33f3a28 100644 --- a/src/contracts/erlang/beamToolContracts.ts +++ b/src/contracts/erlang/beamToolContracts.ts @@ -35,7 +35,7 @@ export const ERLANG_BEAM_TOOL_CONTRACTS = [ kind: "artifact-provider", requiresActiveTarget: true, description: - "Inspect an Erlang BEAM IFF file without executing bytecode or requiring Erlang. Returns chunk byte ranges/digests, atoms, exports/imports/lambdas and Code header. Default complete returns full Evidence; detail summary retains it, and an optional beam view selects collection rows in the first call. Reuse inspect_analysis_view kind beam for atoms/exports/imports/lambdas/chunks, exact names/indices/fields and paging. source_index scopes rows to parent/collection, preserving every arity; original atom/lambda indices remain distinct. Missing tables/counts stay null, not empty; runtime absence is unknown. Malformed/truncated input or exhausted budgets fail without partial success.", + "Inspect an Erlang BEAM IFF file without executing bytecode or requiring Erlang. Returns chunk byte ranges/digests, atoms, exports/imports/lambdas and Code header. Omitted detail returns full Evidence within the agent result budget, else the retained summary; detail summary retains it, and an optional beam view selects collection rows in the first call. Reuse inspect_analysis_view kind beam for atoms/exports/imports/lambdas/chunks, exact names/indices/fields and paging. source_index scopes rows to parent/collection, preserving every arity; original atom/lambda indices remain distinct. Missing tables/counts stay null, not empty; runtime absence is unknown. Malformed/truncated input or exhausted budgets fail without partial success.", inputSchema: inspectErlangBeamRequestSchema, outputSchema: analysisDetailOutputSchemaOf( erlangBeamSchema, diff --git a/src/contracts/flutter/flutterToolContracts.ts b/src/contracts/flutter/flutterToolContracts.ts index 0040124b048..f3ee92e3e2b 100644 --- a/src/contracts/flutter/flutterToolContracts.ts +++ b/src/contracts/flutter/flutterToolContracts.ts @@ -44,7 +44,7 @@ export const FLUTTER_TOOL_CONTRACTS = [ }), ), description: - "Inspect one APK ABI's Dart AOT snapshot without executing it. Supports legacy split VM/isolate FullAOT kind 3 and unified FullAOT kind 2. Returns the observed profile, snapshot exports, headers, hashes and bounded package:/dart:/identifier-like byte-pattern strings. pool_policy.contains selects strings before collection; other pool budgets do not raise APK/ELF/response limits. Default complete returns all facts; detail summary retains them for inspect_analysis_view kind dart-aot, collections package_uris/dart_uris/class_like_tokens, using parent_evidence_id and row paging. Counts are lower bounds and page exhaustion never proves complete pool coverage.", + "Inspect one APK ABI's Dart AOT snapshot without executing it. Supports legacy split VM/isolate FullAOT kind 3 and unified FullAOT kind 2. Returns the observed profile, snapshot exports, headers, hashes and bounded package:/dart:/identifier-like byte-pattern strings. pool_policy.contains selects strings before collection; other pool budgets do not raise APK/ELF/response limits. Omitted detail returns all facts within the agent result budget, else the retained summary; detail summary retains them for inspect_analysis_view kind dart-aot, collections package_uris/dart_uris/class_like_tokens, using parent_evidence_id and row paging. Counts are lower bounds and page exhaustion never proves complete pool coverage.", kind: "flutter-provider", inputSchema: dartAotInspectionInputSchema, outputSchema: evidenceResultOf( diff --git a/src/contracts/fridaToolContracts.ts b/src/contracts/fridaToolContracts.ts index e983dc0bd47..3c60bb48df4 100644 --- a/src/contracts/fridaToolContracts.ts +++ b/src/contracts/fridaToolContracts.ts @@ -285,7 +285,7 @@ export const FRIDA_TOOL_CONTRACTS = [ ...toolContractMetadata("frida_session_status", evidenceEffects), kind: "native-provider", description: - "Read observed Frida session state on each call. Default detail=complete returns queued script messages and capture truncation. detail=summary retains the complete observation in this session and returns identity, state, scripts, retained message count and truncation without payloads. Export the complete parent with export_evidence_bundle; retained summaries are historical and never refresh live state.", + "Read observed Frida session state on each call. Omitted detail returns queued script messages and capture truncation within the agent result budget, else the retained summary. detail=summary retains the complete observation in this session and returns identity, state, scripts, retained message count and truncation without payloads. Export the complete parent with export_evidence_bundle; retained summaries are historical and never refresh live state.", inputSchema: fridaSessionStatusInputSchema, outputSchema: analysisDetailOutputSchemaOf( fridaSessionStatusSchema, diff --git a/src/contracts/gdbToolContracts.ts b/src/contracts/gdbToolContracts.ts index 5e788f98147..a6fade438d8 100644 --- a/src/contracts/gdbToolContracts.ts +++ b/src/contracts/gdbToolContracts.ts @@ -63,7 +63,7 @@ export const GDB_TOOL_CONTRACTS = [ ), kind: "native-provider", description: - "Run one unrestricted command in a persistent GDB session; commands can run shell, change target state, access files and network. Returns ordered MI/console/target/log Evidence. A timeout retains collected records with completion_status unknown and stops the owned debugger; closing does not imply target termination. Default complete preserves full Evidence; summary retains it and omits duplicate stream/raw mirrors for inspect_analysis_view summary queries. In a shared server this command retires active binary analysis: close Ghidra explicitly first, then reopen the binary after command effects settle.", + "Run one unrestricted command in a persistent GDB session; commands can run shell, change target state, access files and network. Returns ordered MI/console/target/log Evidence. A timeout retains collected records with completion_status unknown and stops the owned debugger; closing does not imply target termination. Omitted detail preserves full Evidence within the agent result budget, else the retained summary; summary retains it and omits duplicate stream/raw mirrors for inspect_analysis_view summary queries. In a shared server this command retires active binary analysis: close Ghidra explicitly first, then reopen the binary after command effects settle.", inputSchema: z.strictObject({ session_id: sessionId, command: z.string().min(1), diff --git a/src/contracts/go/goToolContracts.ts b/src/contracts/go/goToolContracts.ts index e4e57c243c8..78b65a0e6b7 100644 --- a/src/contracts/go/goToolContracts.ts +++ b/src/contracts/go/goToolContracts.ts @@ -17,7 +17,7 @@ export const GO_TOOL_CONTRACTS = [ kind: "artifact-provider", requiresActiveTarget: true, description: - "Read embedded Go compiler, module, dependency/replacement and build-setting metadata from a local ELF, PE or selected Mach-O slice without running it or requiring Go. include_string_literals: true adds inferred static UTF-8 literals; runtime use and dependency completeness remain unknown. Missing build info does not prove the image is not Go. Default complete returns artifact SHA-256, source ranges and original metadata; detail summary retains it for inspect_analysis_view kind go, collections dependencies/settings/string_literals, or kind cyclonedx for one CycloneDX 1.6 document, with parent_evidence_id. Slice ranges remain offsets in the original universal file. No function/type/source recovery. Increase only the reported per-call budget and retry the same artifact; it does not raise parser or MCP delivery limits. Malformed/unsupported inputs fail explicitly.", + "Read embedded Go compiler, module, dependency/replacement and build-setting metadata from a local ELF, PE or selected Mach-O slice without running it or requiring Go. include_string_literals: true adds inferred static UTF-8 literals; runtime use and dependency completeness remain unknown. Missing build info does not prove the image is not Go. Omitted detail returns artifact SHA-256, source ranges and original metadata within the agent result budget, else the retained summary; detail summary retains it for inspect_analysis_view kind go, collections dependencies/settings/string_literals, or kind cyclonedx for one CycloneDX 1.6 document, with parent_evidence_id. Slice ranges remain offsets in the original universal file. No function/type/source recovery. Increase only the reported per-call budget and retry the same artifact; it does not raise parser or MCP delivery limits. Malformed/unsupported inputs fail explicitly.", inputSchema: inspectGoBinaryInputSchema, outputSchema: analysisDetailOutputSchemaOf( goBinarySchema, diff --git a/src/contracts/managed/managedToolContracts.ts b/src/contracts/managed/managedToolContracts.ts index fa058fd825d..b9f74e37f87 100644 --- a/src/contracts/managed/managedToolContracts.ts +++ b/src/contracts/managed/managedToolContracts.ts @@ -66,7 +66,7 @@ export const MANAGED_TOOL_CONTRACTS = [ retainedSummary: { evidenceParameters: "omit-detail" }, ...toolContractMetadata("inspect_managed_artifact", evidenceEffects), description: - "Inspect PE/CLI identity, classification and metadata inventories from an explicit path or selected managed target without loading or executing code. Default complete returns all producer facts; detail summary retains them and returns identity, assembly/MVID, frameworks, coverage and counts. Page references/resources/attributes with inspect_analysis_view kind managed and normalized_result.parent_evidence_id. Counts cover returned rows; partial, malformed and unavailable metadata stay explicit. Tokens are build-local. Use inspect_managed_members for methods, signatures and CIL anchors.", + "Inspect PE/CLI identity, classification and metadata inventories from an explicit path or selected managed target without loading or executing code. Omitted detail returns all producer facts within the agent result budget, else the retained summary; detail summary retains them and returns identity, assembly/MVID, frameworks, coverage and counts. Page references/resources/attributes with inspect_analysis_view kind managed and normalized_result.parent_evidence_id. Counts cover returned rows; partial, malformed and unavailable metadata stay explicit. Tokens are build-local. Use inspect_managed_members for methods, signatures and CIL anchors.", kind: "managed-provider", inputSchema: managedArtifactInputSchema, outputSchema, @@ -88,7 +88,7 @@ export const MANAGED_TOOL_CONTRACTS = [ retainedSummary: { evidenceParameters: "omit-detail" }, ...toolContractMetadata("inspect_managed_members", evidenceEffects), description: - "Inspect PE/CLI types, members, signatures, CIL hashes/instruction tuples, exception regions, static calls, field accesses and loaded #US strings without executing code. type_names selects exact declaring types and their body literals; assembly-wide member_refs/exported_types are still included. Tokens remain local to artifact SHA-256/MVID; tuple hashes do not resolve them or fully commit control flow. Default complete returns collections; detail summary retains them for inspect_analysis_view kind managed-members using parent_evidence_id. Page types/exported_types/fields/methods/member_refs/call_edges/field_accesses/user_strings or unresolved_definitions for checked rows with failed name columns. Exact names/declaring_types and fields narrow supported rows. Omit body to avoid IL anchors. Unmatched names and incomplete coverage stay explicit.", + "Inspect PE/CLI types, members, signatures, CIL hashes/instruction tuples, exception regions, static calls, field accesses and loaded #US strings without executing code. type_names selects exact declaring types and narrows every collection to them: member_refs to rows their bodies use, exported_types to selected names. Tokens remain local to artifact SHA-256/MVID; tuple hashes do not resolve them or fully commit control flow. Omitted detail returns collections when they fit the agent result budget and the retained summary otherwise; detail complete returns them inline; detail summary retains them for inspect_analysis_view kind managed-members using parent_evidence_id. Page types/exported_types/fields/methods/member_refs/call_edges/field_accesses/user_strings or unresolved_definitions for checked rows with failed name columns. Exact names/declaring_types and fields narrow supported rows. Omit body to avoid IL anchors. Unmatched names and incomplete coverage stay explicit.", kind: "managed-provider", inputSchema: managedMembersInputSchema, outputSchema: memberOutputSchema, diff --git a/src/contracts/native/binaryDiagnosticsToolContracts.ts b/src/contracts/native/binaryDiagnosticsToolContracts.ts index fc085270159..0c5b94742b7 100644 --- a/src/contracts/native/binaryDiagnosticsToolContracts.ts +++ b/src/contracts/native/binaryDiagnosticsToolContracts.ts @@ -372,7 +372,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ ...toolContractMetadata("inspect_byte_entropy", evidenceEffects), kind: "native-provider", description: - "Inspect Shannon byte entropy for one explicit local file offline, without execution, extraction or external tools. Returns file-wide SHA-256 and entropy, fixed-block entropy for an optional offset/length window, and adjacent high (>=7.2) and low (<=1.0) runs with exact file offsets. Block size is a power of two from 256 to 65536 (default 4096). Complete output can become very large because it includes one row per selected block, and summary detail still retains that full list. Use a shorter length or a larger block_size; the selected window is limited to 32,768 output blocks. Entropy cannot distinguish compression from encryption. Summary detail returns file entropy plus the ten longest runs; retrieve parent Evidence for the full series. The entire file is read even for a window.", + "Inspect Shannon byte entropy for one explicit local file offline, without execution, extraction or external tools. Returns file-wide SHA-256 and entropy, fixed-block entropy for an optional offset/length window, and adjacent high (>=7.2) and low (<=1.0) runs with exact file offsets. Block size is a power of two from 256 to 65536 (default 4096). Complete Evidence has one row per selected block; omitted detail returns it only within the agent result budget and otherwise the retained summary, and inspect_analysis_view kind evidence-json pages the complete record. The selected window is limited to 32,768 output blocks. Entropy cannot distinguish compression from encryption. Summary detail returns file entropy plus the ten longest runs; retrieve parent Evidence for the full series. The entire file is read even for a window.", inputSchema: inspectByteEntropyRequestSchema, outputSchema: byteEntropyOutputSchema, examples: [ diff --git a/src/contracts/officialToolContracts.ts b/src/contracts/officialToolContracts.ts index 2a14b2cecc1..a14582b11b5 100644 --- a/src/contracts/officialToolContracts.ts +++ b/src/contracts/officialToolContracts.ts @@ -1,8 +1,5 @@ import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js"; -import { - analysisDetailSchema, - analysisDetailSizeAwareSchema, -} from "./analysisDetail.js"; +import { analysisDetailSchema } from "./analysisDetail.js"; import { z } from "zod"; import { jsonRecordSchema } from "../domain/jsonRecord.js"; import { nativeFunctionAnnotationsInputSchema } from "../domain/native/nativeFunctionAnnotations.js"; @@ -173,19 +170,19 @@ export const OFFICIAL_TOOL_CONTRACTS = [ official( "list_names", evidenceEffects, - "List every analyzed memory and external symbol as address/value pairs. Provider metadata distinguishes Ghidra primary, dynamic, external, type, and source facts when available. Omitted detail returns the complete inventory when its Evidence is at most 32 KiB, else its retained summary with counts and native-inventory pages; complete or summary forces that shape.", + "List every analyzed memory and external symbol as address/value pairs. Provider metadata distinguishes Ghidra primary, dynamic, external, type, and source facts when available. Select detail summary for counts and retained native-inventory pages; omitted detail is complete within the agent result budget, else the retained summary.", z.object({ document, address: optionalAddress, - detail: analysisDetailSizeAwareSchema, + detail: analysisDetailSchema, }), { evidenceParameters: "omit-detail" }, ), official( "list_procedures", providerNetworkEvidenceEffects, - "List every analyzed procedure as address/value pairs after provider analysis. Ghidra metadata distinguishes thunks and external functions; use returned addresses in later function operations. Omitted detail returns the complete inventory when its Evidence is at most 32 KiB, else its retained summary with counts and native-inventory pages; complete or summary forces that shape.", - z.object({ document, detail: analysisDetailSizeAwareSchema }), + "List every analyzed procedure as address/value pairs after provider analysis. Ghidra metadata distinguishes thunks and external functions; use returned addresses in later function operations. Select detail summary for counts and retained native-inventory pages; omitted detail is complete within the agent result budget, else the retained summary.", + z.object({ document, detail: analysisDetailSchema }), { evidenceParameters: "omit-detail" }, ), official( @@ -197,11 +194,11 @@ export const OFFICIAL_TOOL_CONTRACTS = [ official( "list_strings", providerNetworkEvidenceEffects, - "List every provider-reported string object or candidate, or filter to one address, as address/value pairs with encoding, terminator status, and byte length when available. Hopper reads complete typed objects and retains its original display text as provider_value; long literals may span adjacent unterminated objects. Kuna scans mapped printable sequences of at least five characters, including unterminated fragments; references are not computed. Omitted detail returns the complete inventory when its Evidence is at most 32 KiB, else its retained summary with counts and native-inventory pages; complete or summary forces that shape.", + "List every provider-reported string object or candidate, or filter to one address, as address/value pairs with encoding, terminator status, and byte length when available. Hopper reads complete typed objects and retains its original display text as provider_value; long literals may span adjacent unterminated objects. Kuna scans mapped printable sequences of at least five characters, including unterminated fragments; references are not computed. Select detail summary for counts and retained native-inventory pages; omitted detail is complete within the agent result budget, else the retained summary.", z.object({ document, address: optionalAddress, - detail: analysisDetailSizeAwareSchema, + detail: analysisDetailSchema, }), { evidenceParameters: "omit-detail" }, ), @@ -275,7 +272,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [ official( "procedure_pseudo_code", providerUiNetworkEvidenceEffects, - "Decompile one analyzed procedure by symbol or provider-normalized address. Returns provider-specific pseudocode or null, never original source; raw_result.pseudocode_absence distinguishes reported provider-failure from not-in-export, otherwise the cause is unknown. Use procedure_assembly for instruction precision. detail summary retains text for inspect_analysis_view native/pseudocode pages without another decompile; complete is default. analysis: independent_fresh requests a separate attempt only when binary_session advertises independent_decompile; it may use different analysis context. analysis: call_destination attempts standalone decompilation at an exact incoming direct call to an arm64 Mach-O address outside the procedure inventory when the capability declares call_destination_decompile. The result retains the call site and does not establish a discovered procedure. Ghidra accepts file-offset:0x... or unique file offsets when a 0x selector resolves to no procedure; existing analysis addresses take precedence, and space-qualified addresses avoid that fallback. Its terminal-call assumptions may truncate the analyzed body, as limitations report.", + "Decompile one analyzed procedure by symbol or provider-normalized address. Returns provider-specific pseudocode or null, never original source; raw_result.pseudocode_absence distinguishes reported provider-failure from not-in-export, otherwise the cause is unknown. Use procedure_assembly for instruction precision. detail summary retains text for inspect_analysis_view native/pseudocode pages without another decompile; omitted detail is complete within the agent result budget, else the retained summary. analysis: independent_fresh requests a separate attempt only when binary_session advertises independent_decompile; it may use different analysis context. analysis: call_destination attempts standalone decompilation at an exact incoming direct call to an arm64 Mach-O address outside the procedure inventory when the capability declares call_destination_decompile. The result retains the call site and does not establish a discovered procedure. Ghidra accepts file-offset:0x... or unique file offsets when a 0x selector resolves to no procedure; existing analysis addresses take precedence, and space-qualified addresses avoid that fallback. Its terminal-call assumptions may truncate the analyzed body, as limitations report.", z.object({ procedure, document, @@ -294,15 +291,15 @@ export const OFFICIAL_TOOL_CONTRACTS = [ official( "search_procedures", providerNetworkEvidenceEffects, - "Find analyzed procedures by literal name (default) or regex, including accepted secondary names. Returns deterministic provider-inventory matches under primary names with matched_aliases and available thunk/external metadata. For Ghidra case-insensitive literal searches, raw_result holds Ghidra's candidates only when Unicode filtering removed any; normalized_result holds matches. Omitted detail returns complete Evidence up to 32 KiB, else its retained summary with native-inventory pages; complete or summary forces that shape. Regex uses Java Pattern in Ghidra and ECMAScript Unicode in Kuna, IDA and Hopper; binary_session and errors report effective limits and recovery.", - z.object({ ...nativeSearchInput, detail: analysisDetailSizeAwareSchema }), + "Find analyzed procedures by literal name (default) or regex, including accepted secondary names. Returns deterministic provider-inventory matches under primary names with matched_aliases and available thunk/external metadata. For Ghidra case-insensitive literal searches, raw_result holds Ghidra's candidates only when Unicode filtering removed any; normalized_result holds matches. Select detail summary for counts and retained native-inventory pages; omitted detail is complete within the agent result budget, else the retained summary. Regex uses Java Pattern in Ghidra and ECMAScript Unicode in Kuna, IDA and Hopper; binary_session and errors report effective limits and recovery.", + z.object({ ...nativeSearchInput, detail: analysisDetailSchema }), { evidenceParameters: "omit-detail" }, ), official( "search_strings", providerNetworkEvidenceEffects, - "Find provider-reported strings by literal text (default) or regex. Complete results cover that inventory, not all artifact text; packed/undefined strings or independently matched fragments may be missing. Ghidra search_bytes finds known encoded bytes without establishing string identity/use; xrefs inspects references at a known address. Kuna scans mapped sequences of at least five characters without references or read_bytes. Hopper preserves decoded typed objects, display text and decoding unknowns. For Ghidra case-insensitive literal searches, raw_result holds candidates only when Unicode filtering removed any; normalized_result holds matches. Omitted detail returns complete Evidence up to 32 KiB, else its retained summary with native-inventory pages; complete or summary forces that shape. Regex uses Java Pattern in Ghidra and ECMAScript Unicode elsewhere; binary_session/errors report limits.", - z.object({ ...nativeSearchInput, detail: analysisDetailSizeAwareSchema }), + "Find provider-reported strings by literal text (default) or regex. Complete results cover that inventory, not all artifact text; packed/undefined strings or independently matched fragments may be missing. Ghidra search_bytes finds known encoded bytes without establishing string identity/use; xrefs inspects references at a known address. Kuna scans mapped sequences of at least five characters without references or read_bytes. Hopper preserves decoded typed objects, display text and decoding unknowns. For Ghidra case-insensitive literal searches, raw_result holds candidates only when Unicode filtering removed any; normalized_result holds matches. Select detail summary for counts and retained native-inventory pages; omitted detail is complete within the agent result budget, else the retained summary. Regex uses Java Pattern in Ghidra and ECMAScript Unicode elsewhere; binary_session/errors report limits.", + z.object({ ...nativeSearchInput, detail: analysisDetailSchema }), { evidenceParameters: "omit-detail" }, ), official( diff --git a/src/contracts/pcap/pcapToolContracts.ts b/src/contracts/pcap/pcapToolContracts.ts index c67746eaf9f..e05dc221ad6 100644 --- a/src/contracts/pcap/pcapToolContracts.ts +++ b/src/contracts/pcap/pcapToolContracts.ts @@ -44,7 +44,7 @@ export const PCAP_TOOL_CONTRACTS = [ }), ), description: - "Summarize a saved pcap/pcapng snapshot: exact packet count, SHA-256, IP endpoints, DNS questions/addresses, TLS SNI, protocols and HTTP URIs. Use inspect_packet_capture for caller-selected TShark fields or display filters. Default complete returns full Evidence; detail summary retains it for inspect_analysis_view kind pcap. Unknown DNS attribution and excluded credentials stay explicit. Requires caller-supplied capinfos/tshark and Linux prlimit or Windows Job Objects; never captures live traffic.", + "Summarize a saved pcap/pcapng snapshot: exact packet count, SHA-256, IP endpoints, DNS questions/addresses, TLS SNI, protocols and HTTP URIs. Use inspect_packet_capture for caller-selected TShark fields or display filters. Omitted detail returns full Evidence within the agent result budget, else the retained summary; detail summary retains it for inspect_analysis_view kind pcap. Unknown DNS attribution and excluded credentials stay explicit. Requires caller-supplied capinfos/tshark and Linux prlimit or Windows Job Objects; never captures live traffic.", kind: "pcap-provider", inputSchema: pcapInputSchemas.inspect_pcap_capture.extend({ detail: analysisDetailSchema, diff --git a/src/contracts/python/pythonPycToolContracts.ts b/src/contracts/python/pythonPycToolContracts.ts index 5dc3e46f0ea..0acb04e5761 100644 --- a/src/contracts/python/pythonPycToolContracts.ts +++ b/src/contracts/python/pythonPycToolContracts.ts @@ -35,7 +35,7 @@ export const PYTHON_PYC_TOOL_CONTRACTS = [ kind: "artifact-provider", requiresActiveTarget: true, description: - "Inspect local CPython 3.7–3.15 .pyc headers and nested code objects without executing bytecode, invoking Python or recovering source. Returns pinned version/header fields, names, constant summaries and bytecode lengths/digests; nested_code links code constants, not runtime calls. Default complete returns full Evidence; detail summary retains it for inspect_analysis_view kind python-pyc, collection code_objects, with exact names/indices/fields and paging. source_index preserves same-name alternatives. Unsupported magics/layouts, truncation and exhausted budgets fail without partial success. A header does not prove matching .py source exists.", + "Inspect local CPython 3.7–3.15 .pyc headers and nested code objects without executing bytecode, invoking Python or recovering source. Returns pinned version/header fields, names, constant summaries and bytecode lengths/digests; nested_code links code constants, not runtime calls. Omitted detail returns full Evidence within the agent result budget, else the retained summary; detail summary retains it for inspect_analysis_view kind python-pyc, collection code_objects, with exact names/indices/fields and paging. source_index preserves same-name alternatives. Unsupported magics/layouts, truncation and exhausted budgets fail without partial success. A header does not prove matching .py source exists.", inputSchema: inspectPythonPycRequestSchema, outputSchema: analysisDetailOutputSchemaOf( pythonPycSchema, diff --git a/src/contracts/reverseEngineeringToolContracts.ts b/src/contracts/reverseEngineeringToolContracts.ts index cc1e136cdb4..78b029f121d 100644 --- a/src/contracts/reverseEngineeringToolContracts.ts +++ b/src/contracts/reverseEngineeringToolContracts.ts @@ -24,7 +24,7 @@ export const REVERSE_ENGINEERING_TOOL_CONTRACTS = [ ), kind: "native-provider", description: - "Inspect a local artifact with caller-selected objdump and GNU-style arguments; the executable implementation/version is unverified. operation disassemble optionally scopes to symbol; omission selects all code sections. operation architectures needs no path and captures -i output without establishing artifact support. Returns authoritative stdout/stderr and artifact SHA-256, with lossy UTF-8 and truncation explicit; there is no stable normalized disassembly format. DWARF debug links are off unless follow_debug_links true; external file identities remain unbound. DEBUGINFOD_URLS is cleared to prevent debuginfod requests. Default complete returns Evidence; summary retains it and returns one command observation for later inspect_analysis_view/export via parent_evidence_id. command_timeout_ms bounds each phase; max_output_bytes independently bounds combined output (16 MiB default). Both apply next call without restart; truncation termination leaves completion unknown, and raising output does not raise client receive limits.", + "Inspect a local artifact with caller-selected objdump and GNU-style arguments; the executable implementation/version is unverified. operation disassemble optionally scopes to symbol; omission selects all code sections. operation architectures needs no path and captures -i output without establishing artifact support. Returns authoritative stdout/stderr and artifact SHA-256, with lossy UTF-8 and truncation explicit; there is no stable normalized disassembly format. DWARF debug links are off unless follow_debug_links true; external file identities remain unbound. DEBUGINFOD_URLS is cleared to prevent debuginfod requests. Omitted detail returns Evidence within the agent result budget, else the retained summary; summary retains it and returns one command observation for later inspect_analysis_view/export via parent_evidence_id. command_timeout_ms bounds each phase; max_output_bytes independently bounds combined output (16 MiB default). Both apply next call without restart; truncation termination leaves completion unknown, and raising output does not raise client receive limits.", inputSchema: objdumpInputSchema, outputSchema: analysisDetailOutputSchemaOf( commandObservationSchema, diff --git a/src/contracts/rust/rustToolContracts.ts b/src/contracts/rust/rustToolContracts.ts index 5b7c39503be..09dc59a4c64 100644 --- a/src/contracts/rust/rustToolContracts.ts +++ b/src/contracts/rust/rustToolContracts.ts @@ -19,7 +19,7 @@ export const RUST_TOOL_CONTRACTS = [ kind: "artifact-provider", requiresActiveTarget: true, description: - "Read the embedded cargo-auditable crate dependencies of a local ELF, PE, selected Mach-O slice or WebAssembly core module without running it or requiring Rust. Returns artifact identity, source ranges, ordered packages and dependency edges. Missing metadata does not prove no dependencies; a rustc commit from an observed source path is inferred. Default complete returns the report; detail summary retains it for inspect_analysis_view kind rust, collections packages/edges, or kind cyclonedx for one CycloneDX 1.6 document, via parent_evidence_id. Optional view selects a page in this call and cannot accompany explicit complete detail. Original row indices and every matching version survive selection; select dependencies explicitly for package dependency vectors. Runtime dependencies remain unknown; malformed or oversized inputs fail rather than return partial success.", + "Read the embedded cargo-auditable crate dependencies of a local ELF, PE, selected Mach-O slice or WebAssembly core module without running it or requiring Rust. Returns artifact identity, source ranges, ordered packages and dependency edges. Missing metadata does not prove no dependencies; a rustc commit from an observed source path is inferred. Omitted detail returns the report within the agent result budget, else the retained summary; detail summary retains it for inspect_analysis_view kind rust, collections packages/edges, or kind cyclonedx for one CycloneDX 1.6 document, via parent_evidence_id. Optional view selects a page in this call and cannot accompany explicit complete detail. Original row indices and every matching version survive selection; select dependencies explicitly for package dependency vectors. Runtime dependencies remain unknown; malformed or oversized inputs fail rather than return partial success.", inputSchema: inspectRustBinaryRequestSchema, outputSchema: evidenceResultOf( z.union([ diff --git a/src/contracts/wasm/wasmToolContracts.ts b/src/contracts/wasm/wasmToolContracts.ts index d96f4f3807e..38f9f951dd8 100644 --- a/src/contracts/wasm/wasmToolContracts.ts +++ b/src/contracts/wasm/wasmToolContracts.ts @@ -31,7 +31,7 @@ export const INSPECT_WASM_ARTIFACT_CONTRACT = { ), kind: "artifact-provider", requiresActiveTarget: true, - description: `Validate and inspect local WASM with caller-supplied ${WABT_RELEASE_LINE}, without executing it or fetching dependencies. Returns artifact SHA-256, sections, import/export WAT forms and decoded WAT; custom-section interpretation warnings do not invalidate the core module. Default complete returns full Evidence; detail summary retains it for inspect_analysis_view kind wasm using normalized_result.parent_evidence_id, with import/export rows or UTF-16 WAT pages. Delivery does not change analysis. Optional JavaScript glue associations preserve ambiguous candidates. Configure absolute REA_WABT_BIN_DIRECTORY. Per-call command_timeout_ms, input/tool/output, interface-precision and auxiliary-path budgets are independent; reported limit errors identify the control to adjust. No installation or original-source claim.`, + description: `Validate and inspect local WASM with caller-supplied ${WABT_RELEASE_LINE}, without executing it or fetching dependencies. Returns artifact SHA-256, sections, import/export WAT forms and decoded WAT; custom-section interpretation warnings do not invalidate the core module. Omitted detail returns full Evidence within the agent result budget, else the retained summary; detail summary retains it for inspect_analysis_view kind wasm using normalized_result.parent_evidence_id, with import/export rows or UTF-16 WAT pages. Delivery does not change analysis. Optional JavaScript glue associations preserve ambiguous candidates. Configure absolute REA_WABT_BIN_DIRECTORY. Per-call command_timeout_ms, input/tool/output, interface-precision and auxiliary-path budgets are independent; reported limit errors identify the control to adjust. No installation or original-source claim.`, inputSchema: wasmArtifactInspectionInputSchema, outputSchema: analysisDetailOutputSchemaOf( wasmArtifactSchema, diff --git a/src/contracts/webNetworkCaptureToolContracts.ts b/src/contracts/webNetworkCaptureToolContracts.ts index f9b3edd2d8e..32397adea91 100644 --- a/src/contracts/webNetworkCaptureToolContracts.ts +++ b/src/contracts/webNetworkCaptureToolContracts.ts @@ -24,7 +24,7 @@ export const WEB_NETWORK_CAPTURE_TOOL_CONTRACTS = [ }), ), description: - "Inspect a saved local HAR 1.2, mitmproxy, Fiddler SAZ or supported aioquic qlog capture without contacting recorded URLs. Returns source-linked records, preserved producer fields, precise numbers, exposed bytes and explicit coverage/limitations; transport credentials and explicitly marked sensitive values are excluded; HAR header, query and body member names that look like credentials and hold a retained value are counted in a limitation by pointer, never by value. Use inspect_web_page for a live CDP page. Preserve capture_path exactly as supplied; it names a path on the REA host, not a path to rebase onto the client workspace. Select format; record_ordinals selects records after full decoding and also decodes recognized protobuf/gRPC bodies. Optional protobuf selects body_pointers, framing and a local FileDescriptorSet/message_type; native gRPC and gRPC-web remain distinct, ambiguous readings stay candidates and compressed payloads stay unknown. Default complete delivery is inline. detail summary retains Evidence for inspect_analysis_view kind capture (preview/complete), protobuf (bodies/frames/fields), or qlog; large text/schema values require explicit fields. Qlog supports aioquic 1.5.0 JSON qlog 0.3 and reports STREAM interval unions/endpoint loss declarations, not recovered bodies or proved network loss. SAZ preserves encoded bytes without replay/HAR conversion; encrypted archives are unsupported. Mitmproxy requires caller-supplied mitmdump 12.3.1 on Linux. Malformed or oversized captures return no partial success; browser transaction attribution and HAR text’s original bytes remain unknown.", + "Inspect a saved local HAR 1.2, mitmproxy, Fiddler SAZ or supported aioquic qlog capture without contacting recorded URLs. Returns source-linked records, preserved producer fields, precise numbers, exposed bytes and explicit coverage/limitations; transport credentials and explicitly marked sensitive values are excluded; HAR header, query and body member names that look like credentials and hold a retained value are counted in a limitation by pointer, never by value. Use inspect_web_page for a live CDP page. Preserve capture_path exactly as supplied; it names a path on the REA host, not a path to rebase onto the client workspace. Select format; record_ordinals selects records after full decoding and also decodes recognized protobuf/gRPC bodies. Optional protobuf selects body_pointers, framing and a local FileDescriptorSet/message_type; native gRPC and gRPC-web remain distinct, ambiguous readings stay candidates and compressed payloads stay unknown. Omitted detail is complete inline within the agent result budget, else the retained summary. detail summary retains Evidence for inspect_analysis_view kind capture (preview/complete), protobuf (bodies/frames/fields), or qlog; large text/schema values require explicit fields. Qlog supports aioquic 1.5.0 JSON qlog 0.3 and reports STREAM interval unions/endpoint loss declarations, not recovered bodies or proved network loss. SAZ preserves encoded bytes without replay/HAR conversion; encrypted archives are unsupported. Mitmproxy requires caller-supplied mitmdump 12.3.1 on Linux. Malformed or oversized captures return no partial success; browser transaction attribution and HAR text’s original bytes remain unknown.", kind: "application", inputSchema: inspectWebNetworkCaptureInputSchema.extend({ detail: analysisDetailSchema, diff --git a/src/domain/agentBudgetOperations.ts b/src/domain/agentBudgetOperations.ts new file mode 100644 index 00000000000..faf9de8a268 --- /dev/null +++ b/src/domain/agentBudgetOperations.ts @@ -0,0 +1,52 @@ +/** + * Operations whose omitted `detail` delivers complete Evidence when it fits + * the agent budget and a retained summary when it does not. A contract test + * keeps this list equal to the contracts that declare that delivery. + */ +export const AGENT_BUDGET_OPERATIONS = [ + "analyze_javascript_application", + "analyze_web_bundle", + "batch_decompile", + "capture_browser_scenario", + "decode_interface_builder", + "frida_session_status", + "gdb_console", + "get_call_graph", + "inspect_android_class", + "inspect_android_method", + "inspect_android_package", + "inspect_artifact", + "inspect_binary_layout", + "inspect_byte_entropy", + "inspect_dart_aot", + "inspect_devicetree", + "inspect_elf_dependencies", + "inspect_erlang_beam", + "inspect_evm_interface", + "inspect_go_binary", + "inspect_macho", + "inspect_managed_artifact", + "inspect_managed_members", + "inspect_native_exports", + "inspect_native_load_image", + "inspect_pcap_capture", + "inspect_python_pyc", + "inspect_rust_binary", + "inspect_wasm_artifact", + "inspect_web_network_capture", + "inspect_web_page", + "inspect_with_objdump", + "list_names", + "list_procedures", + "list_strings", + "procedure_address", + "procedure_callees", + "procedure_callers", + "procedure_pseudo_code", + "procedure_references", + "resolve_containing_procedure", + "search_procedures", + "search_strings", + "trace_feature", + "trace_web_source_location", +] as const; diff --git a/src/domain/agentResultBudget.test.ts b/src/domain/agentResultBudget.test.ts new file mode 100644 index 00000000000..4cae9c9ec98 --- /dev/null +++ b/src/domain/agentResultBudget.test.ts @@ -0,0 +1,119 @@ +import { expect, it } from "vitest"; + +import { + DEFAULT_AGENT_RESULT_BUDGET_BYTES, + MAXIMUM_AGENT_RESULT_BUDGET_BYTES, + MINIMUM_AGENT_RESULT_BUDGET_BYTES, +} from "./analysisResourceLimits.js"; +import { + budgetedSummaryBytes, + currentAgentResultBudget, + type AgentResultBudget, +} from "./agentResultBudget.js"; +import type { JsonValue } from "./jsonValue.js"; +import { runWithAnalysisOperationSnapshot } from "./analysisOperationSnapshot.js"; + +it("resolves the runtime override, then the launch seed, then the default", () => { + expect(currentAgentResultBudget(undefined)).toEqual({ + bytes: DEFAULT_AGENT_RESULT_BUDGET_BYTES, + source: "default", + }); + const seeded = "8192"; + expect(currentAgentResultBudget(seeded)).toEqual({ + bytes: 8192, + source: "setting", + }); + expect( + runWithAnalysisOperationSnapshot( + { + revision: 1, + overrides: { "delivery.agent_result_budget_bytes": 65_536 }, + }, + () => currentAgentResultBudget(seeded), + ), + ).toEqual({ bytes: 65_536, source: "runtime" }); +}); + +it.each([ + "0", + "abc", + "1.5", + String(MINIMUM_AGENT_RESULT_BUDGET_BYTES - 1), + String(MAXIMUM_AGENT_RESULT_BUDGET_BYTES + 1), +])( + "leaves delivery unbudgeted for the invalid seed %s rather than defaulting", + (seed) => { + expect(currentAgentResultBudget(seed)).toBeUndefined(); + }, +); + +/** + * A record whose UTF-8 JSON is exactly `bytes` long. `text` is measured as + * JSON encodes it: escapes take their escaped width, multibyte characters + * their UTF-8 width. + */ +const recordOfBytes = (bytes: number, text: string): JsonValue => { + const base = { normalized_result: { text, padding: "" } }; + const used = Buffer.byteLength(JSON.stringify(base)); + const record = { + normalized_result: { text, padding: "x".repeat(bytes - used) }, + }; + expect(Buffer.byteLength(JSON.stringify(record))).toBe(bytes); + return record; +}; + +const TEXT_VARIANTS = [ + ["ASCII", "plain"], + ["escaped", '"quoted"\\\n\t\u0001'], + ["multibyte", "é漢\u{1F600}"], +] as const; + +const budgets: readonly AgentResultBudget[] = [ + { bytes: DEFAULT_AGENT_RESULT_BUDGET_BYTES, source: "default" }, + { bytes: 8192, source: "runtime" }, +]; + +const decide = (evidence: JsonValue, budget: AgentResultBudget) => + budgetedSummaryBytes({ + detail: undefined, + evidence, + budget, + retained: true, + pageable: true, + }); + +it.each( + budgets.flatMap((budget) => + TEXT_VARIANTS.map( + ([label, text]) => [budget.bytes, label, text, budget] as const, + ), + ), +)( + "delivers %i bytes of %s Evidence complete and summarizes one byte more", + (bytes, _label, text, budget) => { + expect(decide(recordOfBytes(bytes, text), budget)).toBeUndefined(); + expect(decide(recordOfBytes(bytes + 1, text), budget)).toBe(bytes + 1); + }, +); + +it("summarizes only an omitted detail of retained, pageable, budgeted Evidence", () => { + const budget = { + bytes: MINIMUM_AGENT_RESULT_BUDGET_BYTES, + source: "setting", + } as const; + const input = { + detail: undefined, + evidence: recordOfBytes(budget.bytes + 1, "plain"), + budget, + retained: true, + pageable: true, + }; + expect(budgetedSummaryBytes(input)).toBe(budget.bytes + 1); + for (const missing of ["retained", "pageable"] as const) + expect( + budgetedSummaryBytes({ ...input, [missing]: false }), + ).toBeUndefined(); + expect(budgetedSummaryBytes({ ...input, budget: undefined })).toBeUndefined(); + for (const detail of ["complete", "summary"]) + expect(budgetedSummaryBytes({ ...input, detail })).toBeUndefined(); +}); diff --git a/src/domain/agentResultBudget.ts b/src/domain/agentResultBudget.ts new file mode 100644 index 00000000000..8219de843b7 --- /dev/null +++ b/src/domain/agentResultBudget.ts @@ -0,0 +1,210 @@ +import { z } from "zod"; +import { + DEFAULT_AGENT_RESULT_BUDGET_BYTES, + MAXIMUM_AGENT_RESULT_BUDGET_BYTES, + MINIMUM_AGENT_RESULT_BUDGET_BYTES, +} from "./analysisResourceLimits.js"; +import { currentAnalysisSettingOverride } from "./analysisOperationSnapshot.js"; +import type { JsonValue } from "./jsonValue.js"; +import { jsonValueByteLength } from "./jsonValueByteLength.js"; + +/** Registered runtime setting that owns the agent delivery budget. */ +export const AGENT_RESULT_BUDGET_SETTING = + "delivery.agent_result_budget_bytes" as const; + +/** + * Documented estimate for JSON tool results, used only to label budgets and + * sizes in tokens. Real tokenizers vary with content; digests, addresses and + * identifiers tokenize denser than prose. Three bytes per token follows the + * Claude Code observation behind the default budget. + */ +export const ESTIMATED_JSON_BYTES_PER_TOKEN = 3; + +/** Launch seed for the agent result budget, for one-shot CLI callers too. */ +export const AGENT_RESULT_BUDGET_ENVIRONMENT = "REA_AGENT_RESULT_BUDGET_BYTES"; + +const decimalInteger = /^[1-9]\d*$/u; +const seedConstraint = `${AGENT_RESULT_BUDGET_ENVIRONMENT} must be a decimal integer from ${String(MINIMUM_AGENT_RESULT_BUDGET_BYTES)} to ${String(MAXIMUM_AGENT_RESULT_BUDGET_BYTES)} bytes; the default is ${String(DEFAULT_AGENT_RESULT_BUDGET_BYTES)}.`; + +/** Launch seed admission, shared with settings inspection and doctor. */ +export const agentResultBudgetBytesSchema = z + .string() + .regex(decimalInteger, { error: seedConstraint }) + .transform(Number) + .pipe( + z + .int() + .min(MINIMUM_AGENT_RESULT_BUDGET_BYTES, { error: seedConstraint }) + .max(MAXIMUM_AGENT_RESULT_BUDGET_BYTES, { error: seedConstraint }), + ); + +/** The budget in force for this operation and where it came from. */ +export interface AgentResultBudget { + readonly bytes: number; + readonly source: "default" | "setting" | "runtime"; +} + +/** + * The accepted operation's override, then the launch seed, then the built-in + * default. An invalid seed is not replaced by the default: delivery is not + * budgeted (complete, as before the budget existed), and settings inspection + * and doctor report the seed. A delivery budget never refuses work. + */ +export const currentAgentResultBudget = ( + /** The launch seed from the environment the CLI or server captured. */ + seed: string | undefined, +): AgentResultBudget | undefined => { + const override = currentAnalysisSettingOverride(AGENT_RESULT_BUDGET_SETTING); + if (override !== undefined) return { bytes: override, source: "runtime" }; + if (seed === undefined) + return { bytes: DEFAULT_AGENT_RESULT_BUDGET_BYTES, source: "default" }; + const parsed = agentResultBudgetBytesSchema.safeParse(seed); + return parsed.success ? { bytes: parsed.data, source: "setting" } : undefined; +}; + +/** Estimated tokens for a JSON byte count; a label, never a measurement. */ +export const estimatedJsonTokens = (bytes: number): number => + Math.ceil(bytes / ESTIMATED_JSON_BYTES_PER_TOKEN); + +/** + * The one decision for an omitted `detail`: the exact UTF-8 JSON bytes of + * complete Evidence when it is to be delivered as its retained summary, or + * undefined to deliver it complete. An explicit `detail` decides for itself. + * Evidence is summarized only when it exceeds the budget, the caller can + * reach the retained record, and the caller can page the summary; an + * invalid launch seed (no budget) leaves delivery unbudgeted. A fitting + * result stops measuring at the budget. + */ +export const budgetedSummaryBytes = (input: { + readonly detail: unknown; + readonly evidence: JsonValue; + readonly budget: AgentResultBudget | undefined; + readonly retained: boolean; + readonly pageable: boolean; +}): number | undefined => { + const { budget, evidence } = input; + if ( + input.detail !== undefined || + budget === undefined || + !input.retained || + !input.pageable + ) + return undefined; + return jsonValueByteLength(evidence, budget.bytes) <= budget.bytes + ? undefined + : jsonValueByteLength(evidence); +}; + +/** Where the complete Evidence that a summary replaced can be read. */ +export type AgentBudgetRecovery = + | { readonly kind: "session" } + | { readonly kind: "evidence-file"; readonly path: string | undefined } + | { readonly kind: "not-retained" }; + +/** + * Delivery facts for a result replaced by its summary. They describe the + * delivery, not the analysis, so they travel beside the summary record and + * never change its identity. + */ +export interface AgentBudgetDelivery { + readonly kind: "agent-budget-summary"; + readonly setting: typeof AGENT_RESULT_BUDGET_SETTING; + readonly budget_bytes: number; + readonly budget_source: AgentResultBudget["source"]; + readonly budget_minimum: number; + readonly budget_maximum: number; + readonly complete_bytes: number; + /** Estimated at ESTIMATED_JSON_BYTES_PER_TOKEN; not a tokenizer count. */ + readonly estimated_complete_tokens: number; + readonly evidence_id: string; + readonly retained: AgentBudgetRecovery["kind"]; + /** The view call that pages the complete record, when it was retained. */ + readonly next?: { + readonly operation: "inspect_analysis_view"; + readonly arguments: { + readonly source: Readonly>; + readonly view: { readonly kind: "evidence-json"; readonly offset: 0 }; + }; + }; + /** + * For an invocation that retained nothing: the exact arguments to add to + * the same command, for complete Evidence inline or saved to a new bundle. + * Caller inputs are never echoed, since they can carry access credentials. + */ + readonly rerun?: { + readonly complete: readonly string[]; + readonly retained: readonly string[]; + }; + readonly note: string; +} + +/** Placeholder for the caller's choice of a new bundle path. */ +export const EVIDENCE_OUTPUT_PLACEHOLDER = ""; + +const RERUN_ARGUMENTS: NonNullable = { + complete: ["--detail", "complete"], + retained: ["--evidence_output", EVIDENCE_OUTPUT_PLACEHOLDER], +}; + +const pageSource = ( + evidenceId: string, + recovery: AgentBudgetRecovery, +): Readonly> | undefined => { + if (recovery.kind === "session") + return { kind: "retained-evidence", evidence_id: evidenceId }; + if (recovery.kind === "evidence-file" && recovery.path !== undefined) + return { + kind: "evidence-file", + path: recovery.path, + evidence_id: evidenceId, + }; + return undefined; +}; + +const recoveryNote = (recovery: AgentBudgetRecovery): string => { + if (recovery.kind === "session") + return `It is retained in this session: next pages its exact JSON through inspect_analysis_view (follow coverage.next_offset); the producer's own views select facts more cheaply. Pass detail complete for all of it inline, or raise ${AGENT_RESULT_BUDGET_SETTING} with update_analysis_settings.`; + if (recovery.kind === "evidence-file") + return "It is in the --evidence_output bundle: rea inspect-analysis-view with next.arguments pages its exact JSON. Pass --detail complete for all of it inline."; + return `This invocation selected no --evidence_output, so it was not retained and nothing was written: rerun the same command with rerun.complete (--detail complete) for all of it inline, or with rerun.retained (--evidence_output ${EVIDENCE_OUTPUT_PLACEHOLDER}) to save it for inspect-analysis-view.`; +}; + +/** + * The delivery facts for one over-budget result: the effective budget, the + * complete size, where the complete Evidence is and the call that reads it. + */ +export const agentBudgetDelivery = (input: { + readonly operation: string; + readonly evidenceId: string; + readonly completeBytes: number; + readonly budget: AgentResultBudget; + readonly recovery: AgentBudgetRecovery; +}): AgentBudgetDelivery => { + const { budget, completeBytes, evidenceId, recovery } = input; + const source = pageSource(evidenceId, recovery); + return { + kind: "agent-budget-summary", + setting: AGENT_RESULT_BUDGET_SETTING, + budget_bytes: budget.bytes, + budget_source: budget.source, + budget_minimum: MINIMUM_AGENT_RESULT_BUDGET_BYTES, + budget_maximum: MAXIMUM_AGENT_RESULT_BUDGET_BYTES, + complete_bytes: completeBytes, + estimated_complete_tokens: estimatedJsonTokens(completeBytes), + evidence_id: evidenceId, + retained: recovery.kind, + ...(source === undefined + ? {} + : { + next: { + operation: "inspect_analysis_view" as const, + arguments: { + source, + view: { kind: "evidence-json" as const, offset: 0 as const }, + }, + }, + }), + ...(recovery.kind === "not-retained" ? { rerun: RERUN_ARGUMENTS } : {}), + note: `Complete ${input.operation} Evidence ${evidenceId} is ${String(completeBytes)} bytes (about ${String(estimatedJsonTokens(completeBytes))} tokens, estimated at ${String(ESTIMATED_JSON_BYTES_PER_TOKEN)} bytes per token), over the agent result budget of ${String(budget.bytes)} bytes (${AGENT_RESULT_BUDGET_SETTING}, source ${budget.source}), so its summary was delivered. Nothing was truncated. ${recoveryNote(recovery)}`, + }; +}; diff --git a/src/domain/analysisResourceLimits.ts b/src/domain/analysisResourceLimits.ts index e1ee233141f..a25f2dacb18 100644 --- a/src/domain/analysisResourceLimits.ts +++ b/src/domain/analysisResourceLimits.ts @@ -293,3 +293,19 @@ export const MAXIMUM_WINDOWS_CHANGE_TIME_SETTLE_MAX_POLLS = 1_000; export const DEFAULT_ZSTD_MAX_FRAMES = 4_096; export const MINIMUM_ZSTD_MAX_FRAMES = 1; export const MAXIMUM_ZSTD_MAX_FRAMES = 65_536; + +/** + * Agent delivery budget for one tool result's inline JSON text. This is not + * an admission limit: an over-budget result is retained and delivered as its + * summary with a cursor, never refused. Claude Code moves MCP results above + * 25,000 tokens out of context and warns above 10,000. A 120-row inventory + * page of 73K characters already crossed the 25,000-token cap there (about + * 2.9 bytes per token for dense JSON), so 32 KiB is about 11,000 tokens: more + * than twice under the cap, with room for the delivery facts. 48 KiB would be + * about 17,000 tokens, too close to the cap for denser rows. + */ +export const DEFAULT_AGENT_RESULT_BUDGET_BYTES = 32_768; +/** Below one small summary, every result would overflow. */ +export const MINIMUM_AGENT_RESULT_BUDGET_BYTES = 4_096; +/** The stdio frame floor (10 MiB); the transport limit applies above it. */ +export const MAXIMUM_AGENT_RESULT_BUDGET_BYTES = 10 * 1024 * 1024; diff --git a/src/domain/analysisSettingDefinitions.ts b/src/domain/analysisSettingDefinitions.ts index d4ee650c590..308b525a547 100644 --- a/src/domain/analysisSettingDefinitions.ts +++ b/src/domain/analysisSettingDefinitions.ts @@ -63,6 +63,9 @@ import { DEFAULT_ZSTD_MAX_FRAMES, MINIMUM_ZSTD_MAX_FRAMES, MAXIMUM_ZSTD_MAX_FRAMES, + DEFAULT_AGENT_RESULT_BUDGET_BYTES, + MINIMUM_AGENT_RESULT_BUDGET_BYTES, + MAXIMUM_AGENT_RESULT_BUDGET_BYTES, } from "./analysisResourceLimits.js"; import { JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS, @@ -70,6 +73,7 @@ import { JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM, } from "./javascript/javascriptAnalysisResourceControls.js"; import { DEFAULT_WASM_COMMAND_TIMEOUT_MS } from "./wasm/wasmArtifact.js"; +import { AGENT_BUDGET_OPERATIONS } from "./agentBudgetOperations.js"; interface SettingDefinition { readonly environment?: string; readonly defaultValue: number | null; @@ -649,6 +653,17 @@ export const ANALYSIS_SETTINGS = { "inspect_android_jni_bindings", ], }, + "delivery.agent_result_budget_bytes": { + updateMode: "runtime", + environment: "REA_AGENT_RESULT_BUDGET_BYTES", + defaultValue: DEFAULT_AGENT_RESULT_BUDGET_BYTES, + minimum: MINIMUM_AGENT_RESULT_BUDGET_BYTES, + maximum: MAXIMUM_AGENT_RESULT_BUDGET_BYTES, + unit: "bytes", + appliesAt: "next_operation", + provider: "rea-delivery", + operations: AGENT_BUDGET_OPERATIONS, + }, } as const satisfies Record; export const analysisSettingIds = Object.keys( ANALYSIS_SETTINGS, diff --git a/src/domain/analysisSettings.ts b/src/domain/analysisSettings.ts index dc47bbf6b00..84c339413b5 100644 --- a/src/domain/analysisSettings.ts +++ b/src/domain/analysisSettings.ts @@ -32,6 +32,7 @@ export interface AnalysisSettingValues { readonly "windows.change_time_settle_poll_ms": number; readonly "windows.change_time_settle_max_polls": number; readonly "zstd.max_frames": number; + readonly "delivery.agent_result_budget_bytes": number; } export type AnalysisSettingId = keyof AnalysisSettingValues; export interface AnalysisSettingsSnapshot { diff --git a/src/domain/analysisView/analysisView.ts b/src/domain/analysisView/analysisView.ts index 64dd25f8716..a4cd8378e51 100644 --- a/src/domain/analysisView/analysisView.ts +++ b/src/domain/analysisView/analysisView.ts @@ -9,6 +9,7 @@ import { } from "../native/nativeObservation.js"; import { projectNativeObservationView } from "./nativeObservationView.js"; import { projectRecordedArrayView } from "./recordedArrayView.js"; +import { projectEvidenceJsonView } from "./evidenceJsonView.js"; import { projectNativeInstructionReferencesView } from "./nativeInstructionReferencesView.js"; import { projectNativeValueTraceView } from "./nativeValueTraceView.js"; import { projectDevicetreeView } from "./devicetreeView.js"; @@ -370,6 +371,8 @@ export const projectAnalysisView = ( if (view.kind === "recorded-array") { return sealProjected(projectRecordedArrayView(parent, view)); } + if (view.kind === "evidence-json") + return sealProjected(projectEvidenceJsonView(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 d4bbdd628e0..2205040dc3e 100644 --- a/src/domain/analysisView/analysisViewParent.ts +++ b/src/domain/analysisView/analysisViewParent.ts @@ -41,6 +41,8 @@ export interface AnalysisViewParent { readonly artifact?: { readonly path: string; readonly sha256: string } | null; /** Parent Evidence parameters, when the parent operation records them. */ readonly parameters?: unknown; + /** The complete authenticated parent record, for views that page its exact JSON. */ + readonly evidence?: Evidence; } import { canBorrowParsedJsonSnapshot, diff --git a/src/domain/analysisView/analysisViewRequest.ts b/src/domain/analysisView/analysisViewRequest.ts index 7115b6542de..bcf991508a6 100644 --- a/src/domain/analysisView/analysisViewRequest.ts +++ b/src/domain/analysisView/analysisViewRequest.ts @@ -32,6 +32,7 @@ import { cycloneDxViewRequestSchema } from "./cyclonedxView.js"; import { nativeFunctionMatchingViewRequestSchema } from "./nativeFunctionMatchingView.js"; import { protobufViewRequestSchema } from "./protobufCaptureView.js"; import { nativeInventoryViewRequestSchema } from "./nativeInventoryView.js"; +import { evidenceJsonViewRequestSchema } from "./evidenceJsonView.js"; import { evidenceFileReferenceSchema, @@ -90,6 +91,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [ nativeObservationViewRequestSchema, nativeContextViewRequestSchema, recordedArrayViewSchema, + evidenceJsonViewRequestSchema, devicetreeViewRequestSchema, uefiFirmwareViewRequestSchema, uefiExtractionViewRequestSchema, diff --git a/src/domain/analysisView/analysisViewResult.ts b/src/domain/analysisView/analysisViewResult.ts index 1ffab28ba86..3dd157990cf 100644 --- a/src/domain/analysisView/analysisViewResult.ts +++ b/src/domain/analysisView/analysisViewResult.ts @@ -31,6 +31,7 @@ import { viewResultBaseFields, } from "./analysisViewBase.js"; import { recordedArrayViewSchema } from "./analysisViewRequest.js"; +import { evidenceJsonViewRequestSchema } from "./evidenceJsonView.js"; import { facetViewSchema, itemViewSchema, @@ -660,6 +661,18 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [ view: recordedArrayViewSchema, rows: z.array(jsonValueSchema), }), + z.strictObject({ + ...viewResultBaseFields, + parent_operation: z.string(), + artifact: artifactSchema.nullable(), + kind: z.literal("evidence-json"), + view: evidenceJsonViewRequestSchema, + text: z + .string() + .describe( + "This page of the parent Evidence JSON text; join pages in offset order.", + ), + }), playwrightTracePageViewResultSchema, z.strictObject({ ...viewResultBase, diff --git a/src/domain/analysisView/evidenceJsonView.ts b/src/domain/analysisView/evidenceJsonView.ts new file mode 100644 index 00000000000..1f5c83b3769 --- /dev/null +++ b/src/domain/analysisView/evidenceJsonView.ts @@ -0,0 +1,242 @@ +import { z } from "zod"; +import type { Evidence } from "../evidence.js"; +import { isImmutableJsonSnapshot } from "../immutableJson.js"; +import { DEFAULT_AGENT_RESULT_BUDGET_BYTES } from "../analysisResourceLimits.js"; +import { jsonParts } from "../jsonSerialization.js"; +import { err, ok } from "../result.js"; +import { pageViewCoverage } from "./analysisViewCoverage.js"; +import { analysisViewInputError } from "./analysisViewErrors.js"; +import type { AnalysisViewParent } from "./analysisViewParent.js"; + +/** Room for the view Evidence around a page: identity, source and coverage. */ +const EVIDENCE_JSON_PAGE_ENVELOPE_BYTES = 8_192; + +/** + * Default page size when `limit` is omitted, in UTF-8 bytes of the page as an + * escaped JSON string. With the view Evidence around it the page stays inside + * the default agent result budget whatever characters it holds. + */ +export const DEFAULT_EVIDENCE_JSON_PAGE_BYTES = + DEFAULT_AGENT_RESULT_BUDGET_BYTES - EVIDENCE_JSON_PAGE_ENVELOPE_BYTES; + +/** + * Largest page. Escaping one code unit as `\uXXXX` takes six bytes, so a full + * page of escaped text stays within the 10 MiB stdio frame floor. + */ +export const MAXIMUM_EVIDENCE_JSON_PAGE_CODE_UNITS = 1_048_576; + +export const evidenceJsonViewRequestSchema = z.strictObject({ + kind: z + .literal("evidence-json") + .describe( + "Page the exact JSON serialization of the complete parent Evidence. Concatenating every page's text in offset order reproduces it; JSON.parse restores the retained record.", + ), + offset: z + .int() + .nonnegative() + .default(0) + .describe("UTF-16 code unit offset; follow coverage.next_offset."), + limit: z + .int() + .positive() + .max(MAXIMUM_EVIDENCE_JSON_PAGE_CODE_UNITS) + .optional() + .describe( + `UTF-16 code units in this page. Omit for a page of at most ${String(DEFAULT_EVIDENCE_JSON_PAGE_BYTES)} escaped UTF-8 bytes. A surrogate pair is never split: a page that would end inside one ends before it, or after it when the pair alone exceeds the limit.`, + ), +}); + +type EvidenceJsonViewRequest = z.output; + +interface SerializedEvidenceJson { + readonly chunks: readonly string[]; + /** Cumulative UTF-16 code unit start of each chunk, ending with `totalLength`. */ + readonly starts: readonly number[]; + readonly totalLength: number; +} + +/** + * One chunked serialization per immutable retained record, built with + * `jsonParts` so records exceeding Node's single-string limit remain pageable. + * Paging is then O(log(chunks) + limit) per call after the first; a mutable + * inline parent is serialized per call because nothing proves it is unchanged. + */ +const serialized = new WeakMap(); + +const buildSerializedChunks = (evidence: Evidence): SerializedEvidenceJson => { + const chunks: string[] = []; + const starts: number[] = []; + let totalLength = 0; + for (const part of jsonParts(evidence)) { + if (part.length === 0) continue; + starts.push(totalLength); + chunks.push(part); + totalLength += part.length; + } + starts.push(totalLength); + return { chunks, starts, totalLength }; +}; + +const serializeEvidence = (evidence: Evidence): SerializedEvidenceJson => { + if (!isImmutableJsonSnapshot(evidence)) + return buildSerializedChunks(evidence); + const known = serialized.get(evidence); + if (known !== undefined) return known; + const doc = buildSerializedChunks(evidence); + serialized.set(evidence, doc); + return doc; +}; + +/** Chunk index containing UTF-16 offset `index` (`0 <= index < doc.totalLength`). */ +const locateChunk = (doc: SerializedEvidenceJson, index: number): number => { + let low = 0; + let high = doc.chunks.length - 1; + while (low < high) { + const mid = (low + high + 1) >> 1; + if (doc.starts[mid]! <= index) low = mid; + else high = mid - 1; + } + return low; +}; + +const codeUnitAt = (doc: SerializedEvidenceJson, index: number): number => { + const chunkIndex = locateChunk(doc, index); + return doc.chunks[chunkIndex]!.charCodeAt(index - doc.starts[chunkIndex]!); +}; + +const sliceChunks = ( + doc: SerializedEvidenceJson, + start: number, + end: number, +): string => { + if (end <= start) return ""; + const first = locateChunk(doc, start); + const last = locateChunk(doc, end - 1); + if (first === last) { + const base = doc.starts[first]!; + return doc.chunks[first]!.slice(start - base, end - base); + } + const parts: string[] = []; + for (let index = first; index <= last; index += 1) { + const chunk = doc.chunks[index]!; + const base = doc.starts[index]!; + const from = index === first ? start - base : 0; + const to = index === last ? end - base : chunk.length; + parts.push(chunk.slice(from, to)); + } + return parts.join(""); +}; + +const isHigh = (unit: number): boolean => unit >= 0xd800 && unit <= 0xdbff; +const isLow = (unit: number): boolean => unit >= 0xdc00 && unit <= 0xdfff; + +/** Whether `boundary` sits between the two halves of a surrogate pair. */ +const splitsPair = (doc: SerializedEvidenceJson, boundary: number): boolean => + boundary > 0 && + boundary < doc.totalLength && + isHigh(codeUnitAt(doc, boundary - 1)) && + isLow(codeUnitAt(doc, boundary)); + +/** UTF-8 bytes one code unit takes inside an escaped JSON string. */ +const escapedUnitBytes = ( + unit: number, + doc: SerializedEvidenceJson, + index: number, +): number => { + if (unit === 0x22 || unit === 0x5c) return 2; + if (unit < 0x20) + return unit === 0x08 || + unit === 0x09 || + unit === 0x0a || + unit === 0x0c || + unit === 0x0d + ? 2 + : 6; + if (unit < 0x80) return 1; + if (unit < 0x800) return 2; + // A paired surrogate is half of one four-byte character; a lone one is escaped. + if (isHigh(unit)) + return index + 1 < doc.totalLength && isLow(codeUnitAt(doc, index + 1)) + ? 2 + : 6; + if (isLow(unit)) + return index > 0 && isHigh(codeUnitAt(doc, index - 1)) ? 2 : 6; + return 3; +}; + +/** The end of the page that `limit`, or the default byte size, selects. */ +const pageEnd = ( + doc: SerializedEvidenceJson, + offset: number, + limit: number | undefined, +): number => { + let end = offset; + if (limit === undefined) { + if (offset < doc.totalLength) { + let chunkIndex = locateChunk(doc, offset); + let inChunk = offset - doc.starts[chunkIndex]!; + let bytes = 0; + while (end < doc.totalLength) { + const chunk = doc.chunks[chunkIndex]!; + const cost = escapedUnitBytes(chunk.charCodeAt(inChunk), doc, end); + if (bytes + cost > DEFAULT_EVIDENCE_JSON_PAGE_BYTES && end > offset) + break; + bytes += cost; + end += 1; + inChunk += 1; + if (inChunk === chunk.length) { + chunkIndex += 1; + inChunk = 0; + } + } + } + } else end = Math.min(doc.totalLength, offset + limit); + if (!splitsPair(doc, end)) return end; + // Keep the pair whole: end before it, or after it when it fills the page. + return end - 1 > offset ? end - 1 : end + 1; +}; + +/** Page the parent record's own JSON text without interpreting it. */ +export const projectEvidenceJsonView = ( + parent: AnalysisViewParent, + view: EvidenceJsonViewRequest, +) => { + if (parent.evidence === undefined) + return err( + analysisViewInputError([ + { + path: ["view", "kind"], + reason: "invalid_value", + message: + "evidence-json pages a complete Evidence record; select a retained, inline or file Evidence source.", + }, + ]), + ); + const doc = serializeEvidence(parent.evidence); + const start = Math.min(view.offset, doc.totalLength); + if (splitsPair(doc, start)) + return err( + analysisViewInputError([ + { + path: ["view", "offset"], + reason: "invalid_value", + message: "Evidence JSON offset splits a UTF-16 surrogate pair.", + }, + ]), + ); + const end = pageEnd(doc, start, view.limit); + return ok({ + kind: "evidence-json" as const, + view, + parent_evidence_id: parent.evidenceId, + parent_operation: parent.operation, + parent_digest: parent.evidenceId.slice(3), + artifact: parent.artifact ?? null, + text: sliceChunks(doc, start, end), + coverage: pageViewCoverage(view.offset, end - start, doc.totalLength), + limitations: [ + "Pages are UTF-16 code unit ranges of the parent Evidence JSON text, not parsed records; join every page in offset order before parsing. Prefer the producer's own views to select facts.", + ], + unknowns: [] as string[], + }); +}; diff --git a/src/domain/analysisView/managedMemberView.ts b/src/domain/analysisView/managedMemberView.ts index 876b13e96b1..6d7098fcbf9 100644 --- a/src/domain/analysisView/managedMemberView.ts +++ b/src/domain/analysisView/managedMemberView.ts @@ -38,7 +38,7 @@ import type { export const MANAGED_MEMBER_SCOPE_GUIDANCE = { selectedNominalRows: - "Exported types and member references cover the whole assembly. Named type rows, fields, methods, call edges, field accesses and user strings follow the declaring-type selection.", + "Named type rows, exported types, fields, methods, call edges, field accesses and user strings follow the declaring-type selection; member references cover only rows referenced by selected method bodies.", unresolvedTypeRows: "Unresolved TypeDef coordinates cover the assembly-wide name scan.", unresolvedMethodRows: diff --git a/src/domain/commandObservation.ts b/src/domain/commandObservation.ts index 2332535550c..12a13d3bf0a 100644 --- a/src/domain/commandObservation.ts +++ b/src/domain/commandObservation.ts @@ -101,7 +101,7 @@ export type GdbCommandResult = Readonly< export const commandEvidenceDetailSchema = z .enum(["complete", "summary"]) - .default("complete") + .optional() .describe( - "complete returns the original Evidence; summary retains that complete parent and returns command output once with completion and source context.", + "Omitted: the original Evidence when it fits the agent result budget, otherwise the retained summary. complete returns the original Evidence; summary retains that complete parent and returns command output once with completion and source context.", ); diff --git a/src/domain/go/goBinary.ts b/src/domain/go/goBinary.ts index 2623c72c4b4..a47fe53cfad 100644 --- a/src/domain/go/goBinary.ts +++ b/src/domain/go/goBinary.ts @@ -193,9 +193,9 @@ export const inspectGoBinaryInputSchema = z ...goResourceBudgetFields, detail: z .enum(["complete", "summary"]) - .default("complete") + .optional() .describe( - "complete returns all metadata inline; summary retains complete Evidence and returns build identity and counts for subsequent retained Go views.", + "Omitted: complete when it fits the agent result budget, otherwise the retained summary. complete returns all metadata inline; summary retains complete Evidence and returns build identity and counts for subsequent retained Go views.", ), }) .superRefine((input, context) => { diff --git a/src/dotnet/ManagedMemberInspector.test.ts b/src/dotnet/ManagedMemberInspector.test.ts index 06728b4b717..8c38b6f3b72 100644 --- a/src/dotnet/ManagedMemberInspector.test.ts +++ b/src/dotnet/ManagedMemberInspector.test.ts @@ -2990,7 +2990,7 @@ describe("managed member type selection", () => { expect(result.coverage).toEqual(everything.coverage); expect(result.limitations).toContainEqual( expect.stringMatching( - /types.*fields.*methods.*call edges.*field accesses.*user strings.*only the selected declaring types.*targets outside.*names.*not described/iu, + /types.*fields.*methods.*member references.*call edges.*field accesses.*user strings.*only the selected declaring types.*targets outside.*names.*not described/iu, ), ); }); @@ -3027,7 +3027,7 @@ describe("managed member type selection", () => { }, ); - it("omits members of unselected types without dropping member references", () => { + it("narrows member references to the rows selected bodies use", () => { const result = inspectManagedMembersBytes(bytes, target, { typeNames: ["Missing.Type"], }); @@ -3041,7 +3041,23 @@ describe("managed member type selection", () => { expect(result.methods).toEqual([]); expect(result.call_edges).toEqual([]); expect(result.field_accesses).toEqual([]); - expect(result.member_refs).toEqual(everything.member_refs); + expect(everything.member_refs.length).toBeGreaterThan(0); + expect(result.member_refs).toEqual([]); + }); + + it("keeps the member references a selected body calls", () => { + const result = inspectManagedMembersBytes(bytes, target, { + typeNames: ["Fixture.Program"], + }); + const called = new Set( + result.call_edges.map(({ target_token }) => target_token), + ); + expect(result.member_refs.length).toBeGreaterThan(0); + for (const ref of result.member_refs) + expect(called.has(ref.token)).toBe(true); + expect(result.member_refs).toEqual( + everything.member_refs.filter(({ token }) => called.has(token)), + ); }); }); diff --git a/src/dotnet/ManagedMemberInspector.ts b/src/dotnet/ManagedMemberInspector.ts index 82b01d91000..ed98ed707f5 100644 --- a/src/dotnet/ManagedMemberInspector.ts +++ b/src/dotnet/ManagedMemberInspector.ts @@ -136,6 +136,16 @@ const readMemberLayout = ( return { layout, memberLists }; }; +/** ECMA-335 MemberRef table number. */ +const MEMBER_REF_TABLE = 0x0a; + +/** The spelling a type_names selector matches against an ExportedType row. */ +const exportedTypeName = (type: { + readonly namespace: string; + readonly name: string; +}): string => + type.namespace.length === 0 ? type.name : `${type.namespace}.${type.name}`; + const selectTypes = ( types: readonly DecodedTypeDefinition[], typeNames: readonly string[] | undefined, @@ -263,7 +273,7 @@ export const inspectManagedMembersBytes = ( ...(selection === null ? [] : [ - "Types, fields, methods, call edges, field accesses, and user strings cover only the selected declaring types; coverage describes that selection. Edge targets outside it keep their names but are not described.", + "Types, fields, methods, member references, call edges, field accesses, and user strings cover only the selected declaring types; coverage describes that selection. Member references are the MemberRef rows the selected method bodies use, and exported types are the ExportedType rows whose full name was selected. Edge targets outside the selection keep their names but are not described.", ]), ...(unreadableNames === 0 ? [] @@ -364,12 +374,17 @@ export const inspectManagedMembersBytes = ( reference.table === 4 ? !fields.core.has(reference.token) : reference.table === 6 && !methods.core.has(reference.token); + // A selection narrows MemberRef rows to those its method bodies use, + // directly or as the generic method a MethodSpec instantiates. + const usedMemberRefs = selected === null ? null : new Set(); // Unscoped inspection already read every core. Selected members also // retain their cores; only missing edge targets need the recovery pass. if (selected !== null) for (const { tokenInstructions } of methods.methods) for (const { opcode, reference } of tokenInstructions) { if (isManagedUserStringLoad(opcode)) continue; + if (reference.table === MEMBER_REF_TABLE) + usedMemberRefs?.add(reference.token); if (needsCore(reference)) referenced.set(reference.token, reference); else if ( reference.table === 0x2b && @@ -381,6 +396,12 @@ export const inspectManagedMembersBytes = ( issues, ); const generic = spec?.method; + if ( + generic !== undefined && + generic.kind === "valid" && + generic.table === MEMBER_REF_TABLE + ) + usedMemberRefs?.add(generic.token); if ( generic !== undefined && generic.kind === "valid" && @@ -389,6 +410,16 @@ export const inspectManagedMembersBytes = ( referenced.set(generic.token, generic); } } + const selectedMemberRefs = + usedMemberRefs === null + ? memberRefs.refs + : memberRefs.refs.filter((ref) => usedMemberRefs.has(ref.token)); + const selectedExportedTypes = + selection === null || exportedTypes.exportedTypes === null + ? exportedTypes.exportedTypes + : exportedTypes.exportedTypes.filter((type) => + selection.type_names.includes(exportedTypeName(type)), + ); const referencedCores = readReferencedMemberCores( bytes, layout, @@ -440,7 +471,7 @@ export const inspectManagedMembersBytes = ( fields.fields.some( (member) => member.signature.parse_status !== "decoded", ) || - memberRefs.refs.some( + selectedMemberRefs.some( (member) => member.signature.parse_status !== "decoded", ) || resolvedMethods.some( @@ -465,10 +496,10 @@ export const inspectManagedMembersBytes = ( types, signature_resolution: "type-names-v2", nesting_read: parsedTypes.nesting.complete, - exported_types: exportedTypes.exportedTypes, + exported_types: selectedExportedTypes, fields: fields.fields, methods: resolvedMethods, - member_refs: memberRefs.refs, + member_refs: selectedMemberRefs, call_edges: related.callEdges, field_accesses: related.fieldAccesses, user_strings: null, diff --git a/src/dotnet/ManagedMemberTypeInventory.test.ts b/src/dotnet/ManagedMemberTypeInventory.test.ts index c494bb59602..dedd7c58948 100644 --- a/src/dotnet/ManagedMemberTypeInventory.test.ts +++ b/src/dotnet/ManagedMemberTypeInventory.test.ts @@ -144,12 +144,11 @@ it("decodes a single selected type to completion on a game-scale assembly", () = operand: "0x0a000001", }), ); - // Member references stay assembly-wide: the selection narrows declaring - // types, not the reference inventory behind call edges. - expect(result.member_refs).toHaveLength(11442); - expect( - result.member_refs.find((ref) => ref.token === "0x0a000001"), - ).toMatchObject({ name: "Member0" }); + // The selection narrows member references to the rows its bodies use: the + // one call target, out of 11442 in the assembly. + expect(result.member_refs).toEqual([ + expect.objectContaining({ token: "0x0a000001", name: "Member0" }), + ]); }); it("preserves explicit type selection when its selected body exhausts capacity", () => { diff --git a/src/main/eagerRuntime.ts b/src/main/eagerRuntime.ts index ec57ba6876e..dc94b626397 100644 --- a/src/main/eagerRuntime.ts +++ b/src/main/eagerRuntime.ts @@ -136,7 +136,10 @@ export const runEager = async ( analysisSettings, environment, signal: startup.signal, - delivery: createToolResultDelivery(config.value.mcpMaxResponseBytes), + delivery: createToolResultDelivery( + config.value.mcpMaxResponseBytes, + environment, + ), loadOptionalProviders: dependencies.loadOptionalProviders ?? (() => diff --git a/src/server/BundleResourcesMcp.test.ts b/src/server/BundleResourcesMcp.test.ts index 2e4471c1bde..c22686d8eb6 100644 --- a/src/server/BundleResourcesMcp.test.ts +++ b/src/server/BundleResourcesMcp.test.ts @@ -272,7 +272,7 @@ it("exposes the production resource session through the MCP SDK for a keyless bu const decoded = await client.callTool({ name: "decode_interface_builder", - arguments: {}, + arguments: { detail: "complete" }, }); expect(decoded.isError).not.toBe(true); const decodedEvidence = toolContract( diff --git a/src/server/EvidenceMcpServerCore.ts b/src/server/EvidenceMcpServerCore.ts index 5abf067da85..b3e6c4d1d30 100644 --- a/src/server/EvidenceMcpServerCore.ts +++ b/src/server/EvidenceMcpServerCore.ts @@ -47,14 +47,18 @@ import { } from "../contracts/mcpSchemaPresentation.js"; import { ErrorEvidenceTransport } from "./ErrorEvidenceTransport.js"; import { isRecord } from "../kernel/isRecord.js"; +import { RETAINED_SUMMARY_VIEW_TOOL } from "./retainedSummaryDelivery.js"; /** Capture caller selections and issues at the canonical SDK validation boundary. */ const captureInputValidation = ( tool: string, schema: Schema, + pageable: boolean, ): Schema => { const standard = schema["~standard"]; - if (standard.vendor !== "zod") return schema; + // Zod issues feed field-level diagnostics; the delivery selection is + // captured for every vendor, since every admitted call has its own. + const zod = standard.vendor === "zod"; return { ...schema, "~standard": { @@ -64,13 +68,18 @@ const captureInputValidation = ( const capture = ( result: Awaited>, ) => { - if (context?.tool === tool && result.issues !== undefined) + if (zod && context?.tool === tool && result.issues !== undefined) context.validation = { issues: result.issues as readonly z.core.$ZodIssue[], input: value, }; - if (result.issues === undefined) + if (zod && result.issues === undefined) context?.captureCallerParameters(tool, value, result.value); + if (result.issues === undefined && context?.tool === tool) + context.deliverySelection = { + detail: isRecord(value) ? value.detail : undefined, + pageable, + }; return result; }; const result = standard.validate(value); @@ -371,6 +380,7 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer { inputSchema: captureInputValidation( name, presented.inputSchema as StandardSchemaWithJSON, + this.advertisesTool(RETAINED_SUMMARY_VIEW_TOOL), ), }), ...(outputSchema === undefined ? {} : { outputSchema }), diff --git a/src/server/McpToolRequest.ts b/src/server/McpToolRequest.ts index 62e5069bd05..43dcfad006c 100644 --- a/src/server/McpToolRequest.ts +++ b/src/server/McpToolRequest.ts @@ -33,6 +33,17 @@ export class McpToolRequest { readonly issues: readonly z.core.$ZodIssue[]; readonly input: unknown; }; + /** + * The `detail` this request's tool call spelled before schema defaults, + * captured at canonical validation. An omitted `detail` leaves delivery to + * the agent result budget; without a capture nothing is known about it. + * `pageable` records whether the session advertises the view tool that + * pages a summary, without which the budget never replaces Evidence. + */ + deliverySelection?: { + readonly detail: unknown; + readonly pageable: boolean; + }; #handlerStarted = false; #finishHandler: () => void = () => undefined; readonly #handlerDone = new Promise((resolve) => { diff --git a/src/server/ToolResultDelivery.agentBudget.test.ts b/src/server/ToolResultDelivery.agentBudget.test.ts new file mode 100644 index 00000000000..0b6980f1c43 --- /dev/null +++ b/src/server/ToolResultDelivery.agentBudget.test.ts @@ -0,0 +1,157 @@ +import { randomBytes } from "node:crypto"; +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect, it } from "vitest"; + +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; +import { EvidenceLedger } from "../application/investigation/EvidenceLedger.js"; +import { createByteEntropyService } from "../composition/binaryDiagnostics/byteEntropy.js"; +import { toolContract } from "../contracts/toolContracts.js"; +import { AGENT_RESULT_BUDGET_ENVIRONMENT } from "../domain/agentResultBudget.js"; +import { + DEFAULT_AGENT_RESULT_BUDGET_BYTES, + MAXIMUM_AGENT_RESULT_BUDGET_BYTES, +} from "../domain/analysisResourceLimits.js"; + +/** In range, and far below the complete entropy Evidence. */ +const VALID_SEED_BYTES = 8192; +import type { Evidence } from "../domain/evidence.js"; +import { McpToolRequest, runMcpToolRequest } from "./McpToolRequest.js"; +import { + AGENT_BUDGET_DELIVERY_META, + ToolResultDelivery, +} from "./ToolResultDelivery.js"; +import { measureMcpResultWithinBudget } from "./toolResultEncoding.js"; + +const contract = toolContract("inspect_byte_entropy"); + +/** Complete entropy Evidence far over the default agent budget. */ +const largeEntropyEvidence = async (): Promise => { + const root = await createTestTempDirectory("rea-delivery-budget-"); + const path = join(root, "bytes"); + await writeFile(path, randomBytes(1024 * 1024)); + const inspected = await createByteEntropyService().inspect({ + path, + block_size: 256, + }); + if (!inspected.ok) throw inspected.error; + return inspected.value; +}; + +/** Deliver as a request whose caller omitted `detail`. */ +const deliver = ( + delivery: ToolResultDelivery, + evidence: Evidence, + ledger: EvidenceLedger, +) => { + const request = new McpToolRequest(1, contract.name); + request.deliverySelection = { detail: undefined, pageable: true }; + return runMcpToolRequest(request, () => + delivery.toEvidenceToolResult( + evidence, + contract, + ledger.record(evidence), + undefined, + (summary) => ledger.record(summary), + ), + ); +}; + +const frameBytes = (result: unknown): number => { + const measured = measureMcpResultWithinBudget( + result, + Number.MAX_SAFE_INTEGER, + ); + if (!measured.ok) throw new Error("unbounded measurement failed"); + return measured.bytes; +}; + +it("counts the delivery facts in the frame check, at the exact boundary", async () => { + const evidence = await largeEntropyEvidence(); + const unlimited = deliver( + new ToolResultDelivery(1024 * 1024 * 1024), + evidence, + new EvidenceLedger(), + ); + expect(unlimited.isError).not.toBe(true); + expect(unlimited._meta?.[AGENT_BUDGET_DELIVERY_META]).toBeDefined(); + const total = frameBytes(unlimited); + + // A frame budget one byte short of the complete response refuses it with + // recovery instead of sending an oversized frame. + const short = deliver( + new ToolResultDelivery(total - 1 + 1024), + evidence, + new EvidenceLedger(), + ); + expect(short.isError).toBe(true); + expect(short.structuredContent).toMatchObject({ + error: { + details: { + reported_limits: { + evidence_reference: { evidence_id: evidence.evidence_id }, + agent_budget: { evidence_id: evidence.evidence_id }, + }, + }, + }, + }); + + // The reservation is an upper bound: with room for it the response is sent + // and the whole frame, delivery facts included, fits the frame budget. + const roomy = new ToolResultDelivery(total + 64 + 1024); + const sent = deliver(roomy, evidence, new EvidenceLedger()); + expect(sent.isError).not.toBe(true); + expect(frameBytes(sent)).toBeLessThanOrEqual(roomy.resultBudgetBytes); +}); + +it("reads the budget seed from the environment the server captured, not the process", async () => { + const evidence = await largeEntropyEvidence(); + const previous = process.env[AGENT_RESULT_BUDGET_ENVIRONMENT]; + // The ambient seed would raise the budget; the captured one keeps the default. + process.env[AGENT_RESULT_BUDGET_ENVIRONMENT] = String(10 * 1024 * 1024); + try { + const defaulted = deliver( + new ToolResultDelivery(64 * 1024 * 1024), + evidence, + new EvidenceLedger(), + ); + expect(defaulted._meta?.[AGENT_BUDGET_DELIVERY_META]).toMatchObject({ + budget_bytes: DEFAULT_AGENT_RESULT_BUDGET_BYTES, + budget_source: "default", + }); + const seeded = deliver( + new ToolResultDelivery( + 64 * 1024 * 1024, + undefined, + undefined, + // A valid seed below the result size, so the seed itself decides. + String(VALID_SEED_BYTES), + ), + evidence, + new EvidenceLedger(), + ); + expect(seeded._meta?.[AGENT_BUDGET_DELIVERY_META]).toMatchObject({ + budget_bytes: VALID_SEED_BYTES, + budget_source: "setting", + }); + // An out-of-range seed is rejected rather than defaulted: unbudgeted. + const invalid = deliver( + new ToolResultDelivery( + 64 * 1024 * 1024, + undefined, + undefined, + String(MAXIMUM_AGENT_RESULT_BUDGET_BYTES + 1), + ), + evidence, + new EvidenceLedger(), + ); + expect(invalid._meta?.[AGENT_BUDGET_DELIVERY_META]).toBeUndefined(); + expect((invalid.structuredContent as Evidence).operation).toBe( + "inspect_byte_entropy", + ); + } finally { + if (previous === undefined) + delete process.env[AGENT_RESULT_BUDGET_ENVIRONMENT]; + else process.env[AGENT_RESULT_BUDGET_ENVIRONMENT] = previous; + } +}); diff --git a/src/server/ToolResultDelivery.ts b/src/server/ToolResultDelivery.ts index 2b1fb76bfd4..d6a061c3603 100644 --- a/src/server/ToolResultDelivery.ts +++ b/src/server/ToolResultDelivery.ts @@ -37,6 +37,23 @@ import { type ToolResultEncoding, } from "./toolResultEncoding.js"; import { isRecord } from "../kernel/isRecord.js"; +import { summarizeOverBudgetEvidence } from "../application/analysisView/AnalysisViewService.js"; +import { INSPECT_ANALYSIS_VIEW_OPERATION } from "../domain/analysisView/analysisViewErrors.js"; +import { + agentBudgetDelivery, + budgetedSummaryBytes, + currentAgentResultBudget, + type AgentBudgetDelivery, +} from "../domain/agentResultBudget.js"; +import { currentMcpToolRequest } from "./McpToolRequest.js"; +import { AGENT_BUDGET_OPERATIONS } from "../domain/agentBudgetOperations.js"; + +const AGENT_BUDGET_OPERATION_NAMES: ReadonlySet = new Set( + AGENT_BUDGET_OPERATIONS, +); + +/** `_meta` key for the delivery facts of a budget-replaced result. */ +export const AGENT_BUDGET_DELIVERY_META = "rea/agent-budget-delivery"; /** Project a response-budget refusal without labeling REA's reserved string limit as Node's ceiling. */ export const mcpResponseOverflowProjection = (input: { @@ -193,6 +210,8 @@ export class ToolResultDelivery { viewSource?: JsonValue, ) => Readonly> = () => ({}), private readonly noTargetRecovery?: string, + /** REA_AGENT_RESULT_BUDGET_BYTES from the environment this server captured. */ + private readonly agentBudgetSeed?: string, ) { this.maximumResponseBytes = maximumResponseBytes; this.resultBudgetBytes = maximumResponseBytes - 1024; @@ -205,6 +224,7 @@ export class ToolResultDelivery { this.maximumResponseBytes, this.nativeContinuation, recovery, + this.agentBudgetSeed, ); } @@ -291,32 +311,63 @@ export class ToolResultDelivery { contract: ToolContract, recorded: Result | undefined, viewSource?: JsonValue | (() => JsonValue | undefined), + /** Retains a budgeted summary as `detail: "summary"` would; none, no budget. */ + recordSummary?: EvidenceWriter["recordEvidence"], ): CallToolResult { - return recorded !== undefined && !recorded.ok - ? this.toErrorToolResult(recorded.error, contract.returnsTargetContent) - : this.successResult(evidence, contract, () => { - const resolvedViewSource = - typeof viewSource === "function" ? viewSource() : viewSource; - return { + if (recorded !== undefined && !recorded.ok) + return this.toErrorToolResult( + recorded.error, + contract.returnsTargetContent, + ); + // Only a retained record can be replaced by its summary. + const budgeted = + recorded === undefined + ? undefined + : overBudgetSummary( + evidence, + contract, + recordSummary, + this.agentBudgetSeed, + ); + if (budgeted !== undefined) { + // The frame check covers the delivery facts added after encoding. + const delivered = this.successResult( + budgeted.summary, + contract, + { + evidence_id: budgeted.summary.evidence_id, + evidence_reference: { + kind: "retained-evidence", evidence_id: evidence.evidence_id, - ...(recorded === undefined - ? {} - : { - evidence_reference: { - kind: "retained-evidence", - evidence_id: evidence.evidence_id, - }, - }), - // A view names its caller's source, which needs no session to read again. - ...(recorded === undefined && resolvedViewSource === undefined - ? {} - : this.nativeContinuation( - evidence, - undefined, - resolvedViewSource, - )), - }; - }); + }, + agent_budget: budgeted.delivery as unknown as JsonValue, + }, + undefined, + agentBudgetDeliveryBytes(budgeted.delivery), + ); + return delivered.isError === true + ? delivered + : withAgentBudgetDelivery(delivered, budgeted.delivery); + } + return this.successResult(evidence, contract, () => { + const resolvedViewSource = + typeof viewSource === "function" ? viewSource() : viewSource; + return { + evidence_id: evidence.evidence_id, + ...(recorded === undefined + ? {} + : { + evidence_reference: { + kind: "retained-evidence", + evidence_id: evidence.evidence_id, + }, + }), + // A view names its caller's source, which needs no session to read again. + ...(recorded === undefined && resolvedViewSource === undefined + ? {} + : this.nativeContinuation(evidence, undefined, resolvedViewSource)), + }; + }); } /** @@ -532,18 +583,21 @@ export class ToolResultDelivery { failure: Extract, budgetBytes: number, ) => Iterable, + /** Bytes the caller adds to a successful result after this encoding. */ + reservedBytes = 0, ): CallToolResult { + const budgetBytes = this.resultBudgetBytes - reservedBytes; let encoded = encodeToolResult( value, - this.resultBudgetBytes, + budgetBytes, "structured-and-text", contract.returnsTargetContent, ); if (!encoded.ok && alternatives !== undefined) - for (const candidate of alternatives(encoded, this.resultBudgetBytes)) { + for (const candidate of alternatives(encoded, budgetBytes)) { const candidateEncoding = encodeToolResult( candidate, - this.resultBudgetBytes, + budgetBytes, "structured-and-text", contract.returnsTargetContent, ); @@ -595,6 +649,87 @@ export class ToolResultDelivery { } } +/** + * The retained summary that replaces complete Evidence over the agent result + * budget, for a request whose caller left `detail` to that budget. A + * selected view, an explicit `detail`, an operation without a summary view, + * or a summary its contract does not advertise keeps complete delivery. + */ +const overBudgetSummary = ( + evidence: Evidence, + contract: ToolContract, + recordSummary: EvidenceWriter["recordEvidence"] | undefined, + agentBudgetSeed: string | undefined, +): + | { readonly summary: Evidence; readonly delivery: AgentBudgetDelivery } + | undefined => { + if (evidence.operation === INSPECT_ANALYSIS_VIEW_OPERATION) return undefined; + // Only a tool with a detail selector is budgeted: its caller can always + // request complete delivery with detail complete. + if (!AGENT_BUDGET_OPERATION_NAMES.has(contract.name)) return undefined; + const selection = currentMcpToolRequest()?.deliverySelection; + if (selection === undefined) return undefined; + const budget = currentAgentResultBudget(agentBudgetSeed); + const completeBytes = budgetedSummaryBytes({ + detail: selection.detail, + evidence, + budget, + retained: recordSummary !== undefined, + pageable: selection.pageable, + }); + if (completeBytes === undefined || budget === undefined) return undefined; + const summary = summarizeOverBudgetEvidence(evidence); + if (!summary.ok || !contract.outputSchema.safeParse(summary.value).success) + return undefined; + // The summary is retained like an explicit one, so its own ID resolves; + // a summary that cannot be retained leaves complete delivery in place. + if (recordSummary === undefined || !recordSummary(summary.value).ok) + return undefined; + return { + summary: summary.value, + delivery: agentBudgetDelivery({ + operation: evidence.operation, + evidenceId: evidence.evidence_id, + completeBytes, + budget, + recovery: { kind: "session" }, + }), + }; +}; + +const agentBudgetDeliveryBlock = (delivery: AgentBudgetDelivery) => ({ + type: "text" as const, + text: JSON.stringify({ delivery }), +}); + +/** + * Upper bound on the wire bytes the delivery facts add: their text block + * with its separator, and their `_meta` member with its separator. + */ +export const agentBudgetDeliveryBytes = ( + delivery: AgentBudgetDelivery, +): number => + Buffer.byteLength(JSON.stringify(agentBudgetDeliveryBlock(delivery))) + + 1 + + Buffer.byteLength( + JSON.stringify({ [AGENT_BUDGET_DELIVERY_META]: delivery }), + ) + + 1; + +/** + * Carry the delivery facts beside the summary record: a second text block + * the model reads, and `_meta` for clients that read structured metadata. + * The structured content stays the summary, unchanged. + */ +const withAgentBudgetDelivery = ( + result: CallToolResult, + delivery: AgentBudgetDelivery, +): CallToolResult => ({ + ...result, + content: [...result.content, agentBudgetDeliveryBlock(delivery)], + _meta: { ...result._meta, [AGENT_BUDGET_DELIVERY_META]: delivery }, +}); + /** The ledger's own retained/unretained fact for this exact record, if it gave one. */ const ledgerRetentionFact = ( fact: unknown, diff --git a/src/server/browserToolBindings.ts b/src/server/browserToolBindings.ts index 3a46011aad0..ad8fae2d428 100644 --- a/src/server/browserToolBindings.ts +++ b/src/server/browserToolBindings.ts @@ -9,7 +9,10 @@ import { captureElectronScenario } from "../application/javascript/ElectronActiv import { analyzeJavaScriptApplicationValidated } from "../application/javascript/JavaScriptApplicationService.js"; import { reconcileJavaScriptRuntimeEvidence } from "../application/javascript/JavaScriptRuntimeReconciliationService.js"; import { javascriptSourceAnalysis } from "../composition/javascriptSourceAnalysis.js"; -import { projectRetainedAnalysis } from "../application/analysisView/AnalysisViewService.js"; +import { + projectRetainedAnalysis, + summarizeRetainedAnalysis, +} from "../application/analysisView/AnalysisViewService.js"; import { requireAnalysisViewRetention, type AnalysisViewRetention, @@ -95,7 +98,21 @@ export const bindBrowserObservationTools = ( inspect_web_page: { admission: "sdk", ...optional, - run: (input, options) => inspectWebPage(browser, input, options), + // Delivery detail never reaches the capture, so its Evidence identity + // is the same for every detail. + run: async ({ detail, ...request }, options) => { + if (detail === "summary") { + const ready = requireAnalysisViewRetention( + "inspect_web_page", + retention, + ); + if (!ready.ok) return ready; + } + const inspected = await inspectWebPage(browser, request, options); + return inspected.ok && detail === "summary" + ? summarizeRetainedAnalysis(inspected.value, retention) + : inspected; + }, }, analyze_web_bundle: { admission: "sdk", diff --git a/src/server/contractToolBindings.ts b/src/server/contractToolBindings.ts index 0cee39d4364..64871e03bc8 100644 --- a/src/server/contractToolBindings.ts +++ b/src/server/contractToolBindings.ts @@ -274,6 +274,15 @@ type ApplicationBinding = readonly admission: "application"; }); +/** Whether a contract input declares the delivery `detail` selector. */ +type HasDeliveryDetail = string extends keyof Input + ? false + : "detail" extends keyof Input + ? Input extends { readonly detail?: "complete" | "summary" | undefined } + ? true + : false + : false; + /** * Run a provider-backed workflow on the analysis that admission grants for * the call. When `detail` selects delivery (`detail: "delivery"`), it never @@ -283,22 +292,15 @@ type AnalysisBinding = { readonly admission: "sdk"; readonly completionProgress?: AnalysisWorkflowOptions["completionProgress"]; } & ExclusiveBinding<"analyze"> & - // A declared detail, required or size-aware optional, selects delivery; an - // index signature declares no field. - (string extends keyof Input + (HasDeliveryDetail extends true ? { + readonly detail: "delivery"; + readonly analyze: AnalysisOperation>; + } + : { readonly detail?: never; readonly analyze: AnalysisOperation; - } - : "detail" extends keyof Input - ? { - readonly detail: "delivery"; - readonly analyze: AnalysisOperation>; - } - : { - readonly detail?: never; - readonly analyze: AnalysisOperation; - }); + }); type AnalysisOperation = ( input: Input, @@ -329,7 +331,7 @@ export type ContractToolBinding = | QueryBinding> // Only a provider operation binds a provider, and only to its own name. | (Name extends ProviderOperation ? ProviderBinding : never) - | (ContractInput extends { readonly detail: "complete" | "summary" } + | (HasDeliveryDetail> extends true ? RetainedSummaryBinding> : never); @@ -421,7 +423,7 @@ type SummaryContract = ToolContract< string, z.ZodType< Readonly> & { - readonly detail: "complete" | "summary"; + readonly detail?: "complete" | "summary" | undefined; } > >; @@ -535,7 +537,6 @@ const createContractBindingHandler = ( recordEvidence, withAdmittedAnalysis, binding.viewSource, - retention, )(contract); return createRetainedSummaryToolHandler( server, diff --git a/src/server/contractToolHandler.ts b/src/server/contractToolHandler.ts index 806ff125561..fa5c85218fc 100644 --- a/src/server/contractToolHandler.ts +++ b/src/server/contractToolHandler.ts @@ -7,11 +7,6 @@ import type { z } from "zod"; import type { ProgressReporter } from "../ports/ProgressReporter.js"; import { mcpProgressReporter } from "./mcpProgress.js"; -import { - deliversRetainedSummary, - RETAINED_SUMMARY_VIEW_TOOL, -} from "./retainedSummaryDelivery.js"; -import { declaresSizeAwareDetail } from "../contracts/analysisDetail.js"; import type { AnalysisOperationPort, ExecutionOptions, @@ -78,6 +73,7 @@ export const deliverEvidenceResult = ( contract, recorded, viewSource, + recordEvidence, ); }; @@ -103,7 +99,7 @@ export const createRetainedSummaryToolHandler = < Name extends string, InputSchema extends z.ZodType< Readonly> & { - readonly detail: "complete" | "summary"; + readonly detail?: "complete" | "summary" | undefined; readonly view?: AnalysisViewRequest; } >, @@ -188,55 +184,30 @@ export const createEvidenceToolHandler = recordEvidence?: EvidenceWriter["recordEvidence"], withAdmittedAnalysis?: WithAdmittedAnalysis, viewSource?: (input: unknown) => JsonValue | undefined, - retention?: AnalysisViewRetention, ) => - (contract: ToolContract) => { - // A size-aware contract's detail selects delivery and never reaches the - // operation, so its Evidence identity is the same for every detail. - const sizeAware = declaresSizeAwareDetail(contract.inputSchema); - return (input: unknown, context: ServerContext) => - runAdmittedToolOperation( - server, - withAdmittedAnalysis, - contract.name, - context.mcpReq.signal, - async () => { - const { detail, input: operationInput } = sizeAware - ? deliveryDetail(input) - : { detail: undefined, input }; - const ready = requireAnalysisViewRetention( - contract.name, - retention ?? { recordEvidence: undefined, evidenceById: undefined }, - ); - if (detail === "summary" && !ready.ok) - return server.delivery.toCallToolResult(err(ready.error), contract); - const result = await logToolExecution(logger, contract.name, () => - operation(operationInput, { - signal: context.mcpReq.signal, - progress: mcpProgressReporter(context), - }), - ); - const delivered = - result.ok && - retention !== undefined && - sizeAware && - deliversRetainedSummary(detail, result.value, { - sizeAware, - retained: ready.ok, - pageable: server.advertisesTool(RETAINED_SUMMARY_VIEW_TOOL), - }) - ? summarizeRetainedAnalysis(result.value, retention) - : result; - return deliverEvidenceResult( - server, - delivered, - contract, - recordEvidence, - viewSource === undefined ? undefined : () => viewSource(input), - ); - }, - ); - }; + (contract: ToolContract) => + (input: unknown, context: ServerContext) => + runAdmittedToolOperation( + server, + withAdmittedAnalysis, + contract.name, + context.mcpReq.signal, + async () => { + const result = await logToolExecution(logger, contract.name, () => + operation(input, { + signal: context.mcpReq.signal, + progress: mcpProgressReporter(context), + }), + ); + return deliverEvidenceResult( + server, + result, + contract, + recordEvidence, + viewSource === undefined ? undefined : () => viewSource(input), + ); + }, + ); /** The MCP request a value-returning workflow runs for. */ export interface ValueToolRequest { @@ -592,12 +563,7 @@ export const createAnalysisToolHandler = analyze(input, analysis, { signal, progress }), ); const response = - !analyzed.ok || - deliversRetainedSummary(detail, analyzed.value.evidence, { - sizeAware: declaresSizeAwareDetail(contract.inputSchema), - retained: requireAnalysisViewRetention(contract.name, retention).ok, - pageable: server.advertisesTool(RETAINED_SUMMARY_VIEW_TOOL), - }) + !analyzed.ok || detail === "summary" ? deliverEvidenceResult( server, analyzed.ok @@ -620,6 +586,8 @@ export const createAnalysisToolHandler = analyzed.value.evidence, contract, analyzed.value.recorded, + undefined, + retention.recordEvidence, ); return progress.complete(response); }, diff --git a/src/server/createServer.ts b/src/server/createServer.ts index d0094774156..262bee9fb1e 100644 --- a/src/server/createServer.ts +++ b/src/server/createServer.ts @@ -581,7 +581,7 @@ const selectToolResultDelivery = ( environment.REA_MCP_MAX_RESPONSE_BYTES, ); if (!configured.ok) throw configured.error; - return createToolResultDelivery(configured.value); + return createToolResultDelivery(configured.value, environment); }; const outputSchemaProfile = ( diff --git a/src/server/deliverApplicationExecution.ts b/src/server/deliverApplicationExecution.ts index 7de29b99e01..dda3e2b04b8 100644 --- a/src/server/deliverApplicationExecution.ts +++ b/src/server/deliverApplicationExecution.ts @@ -72,7 +72,13 @@ export const deliverApplicationExecution = async ( ? records.recordEvidence?.(parent) : records.recordEvidenceWithUnknown?.(parent, execution.unknown); if (view === undefined) - return delivery.toEvidenceToolResult(parent, contract, saved); + return delivery.toEvidenceToolResult( + parent, + contract, + saved, + undefined, + records.recordEvidence, + ); if (saved !== undefined && !saved.ok) return delivery.toCallToolResult(saved, contract); return delivery.toSelectedViewToolResult( diff --git a/src/server/deliverInvestigationWorkflow.ts b/src/server/deliverInvestigationWorkflow.ts index 75814eb5bf0..9d2a2ed7052 100644 --- a/src/server/deliverInvestigationWorkflow.ts +++ b/src/server/deliverInvestigationWorkflow.ts @@ -42,5 +42,7 @@ export const deliverInvestigationWorkflow = ( evidence, contract, recorded.ok ? ok(evidence) : recorded, + undefined, + (summary) => session.recordEvidence(summary), ); }; diff --git a/src/server/providerOperationToolHandler.ts b/src/server/providerOperationToolHandler.ts index 459b4c687c5..e729de65737 100644 --- a/src/server/providerOperationToolHandler.ts +++ b/src/server/providerOperationToolHandler.ts @@ -9,7 +9,6 @@ import { executeWithNativeSymbolSelection } from "../application/NativeSymbolSel import type { EvidenceLookup } from "../application/EvidenceInputResolver.js"; import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js"; import { - RETAINED_SUMMARY_VIEW_TOOL, retainedSummaryDelivery, withoutDeliveryDetail, } from "./retainedSummaryDelivery.js"; @@ -18,7 +17,6 @@ import type { AnalysisOperationPort, } from "../ports/AnalysisProvider.js"; import type { ToolContract } from "../contracts/toolContractTypes.js"; -import { declaresSizeAwareDetail } from "../contracts/analysisDetail.js"; import { ok } from "../domain/result.js"; import type { RecoveryAdmission } from "../application/investigation/InvestigationRetention.js"; import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; @@ -82,11 +80,7 @@ export const createProviderOperationToolHandler = const delivery = contract.retainedSummary === undefined ? undefined - : retainedSummaryDelivery( - contract.name, - dependencies, - declaresSizeAwareDetail(contract.inputSchema), - ); + : retainedSummaryDelivery(contract.name, dependencies); return async ( input: unknown, context: ServerContext, @@ -170,11 +164,8 @@ export const createProviderOperationToolHandler = server.delivery.toCallToolResult(evidence, contract), ); const projected = - delivery?.projectEvidence( - resolved, - evidence.value, - server.advertisesTool(RETAINED_SUMMARY_VIEW_TOOL), - ) ?? ok(evidence.value); + delivery?.projectEvidence(resolved, evidence.value) ?? + ok(evidence.value); if (!projected.ok) return progress.complete( server.delivery.toCallToolResult(projected, contract), @@ -185,6 +176,8 @@ export const createProviderOperationToolHandler = projected.value, contract, recorded, + undefined, + dependencies.recordEvidence, ), ); }, diff --git a/src/server/retainedSummaryDelivery.test.ts b/src/server/retainedSummaryDelivery.test.ts deleted file mode 100644 index e896793f3ac..00000000000 --- a/src/server/retainedSummaryDelivery.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { expect, it } from "vitest"; - -import { SIZE_AWARE_INLINE_EVIDENCE_BYTES } from "../contracts/analysisDetail.js"; -import type { Evidence } from "../domain/evidence.js"; -import { deliversRetainedSummary } from "./retainedSummaryDelivery.js"; - -/** A record whose UTF-8 JSON is exactly `bytes` long, with escaped and multibyte text. */ -const recordOfBytes = (bytes: number): Evidence => { - const text = 'é"\n\u{1F600}'; - const base = { normalized_result: { text, padding: "" } }; - const used = Buffer.byteLength(JSON.stringify(base)); - const record = { - normalized_result: { text, padding: "x".repeat(bytes - used) }, - }; - expect(Buffer.byteLength(JSON.stringify(record))).toBe(bytes); - return record as unknown as Evidence; -}; - -const sized = { sizeAware: true, retained: true, pageable: true } as const; - -it("inlines omitted size-aware detail through exactly 32 KiB and summarizes one byte more", () => { - expect( - deliversRetainedSummary( - undefined, - recordOfBytes(SIZE_AWARE_INLINE_EVIDENCE_BYTES), - sized, - ), - ).toBe(false); - expect( - deliversRetainedSummary( - undefined, - recordOfBytes(SIZE_AWARE_INLINE_EVIDENCE_BYTES + 1), - sized, - ), - ).toBe(true); -}); - -it("summarizes large Evidence only when it is retained, pageable and size-aware", () => { - const large = recordOfBytes(SIZE_AWARE_INLINE_EVIDENCE_BYTES + 1); - for (const missing of ["sizeAware", "retained", "pageable"] as const) - expect( - deliversRetainedSummary(undefined, large, { ...sized, [missing]: false }), - ).toBe(false); - expect(deliversRetainedSummary("complete", large, sized)).toBe(false); - const small = recordOfBytes(64); - expect( - deliversRetainedSummary("summary", small, { - sizeAware: false, - retained: false, - pageable: false, - }), - ).toBe(true); -}); diff --git a/src/server/retainedSummaryDelivery.ts b/src/server/retainedSummaryDelivery.ts index 4119b4d32f0..eb2a2a3c0fc 100644 --- a/src/server/retainedSummaryDelivery.ts +++ b/src/server/retainedSummaryDelivery.ts @@ -4,9 +4,7 @@ import { summarizeRetainedAnalysis } from "../application/analysisView/AnalysisV import { requireAnalysisViewRetention } from "../application/analysisView/AnalysisViewRetention.js"; import type { Evidence } from "../domain/evidence.js"; import type { JsonValue } from "../domain/jsonValue.js"; -import { jsonValueByteLength } from "../domain/jsonValueByteLength.js"; import { ok } from "../domain/result.js"; -import { SIZE_AWARE_INLINE_EVIDENCE_BYTES } from "../contracts/analysisDetail.js"; type Parameters = Readonly>; @@ -14,36 +12,10 @@ type Parameters = Readonly>; export const RETAINED_SUMMARY_VIEW_TOOL = "inspect_analysis_view"; /** - * Whether completed Evidence is delivered as its retained summary. An - * explicit detail decides. Omitted under a size-aware contract, Evidence - * above the inline bound is retained behind its summary only when this - * server can retain it and the session advertises the view tool that pages - * it; otherwise it is delivered complete. - */ -export const deliversRetainedSummary = ( - detail: unknown, - evidence: Evidence, - options: { - readonly sizeAware: boolean; - readonly retained: boolean; - readonly pageable: boolean; - }, -): boolean => - detail === "summary" || - (detail === undefined && - options.sizeAware && - options.retained && - options.pageable && - jsonValueByteLength( - evidence as unknown as JsonValue, - SIZE_AWARE_INLINE_EVIDENCE_BYTES, - ) > SIZE_AWARE_INLINE_EVIDENCE_BYTES); - -/** - * Summary delivery for one named operation: refuse a requested summary before + * Requested summary delivery for one named operation: refuse it before * analysis when this server retains no Evidence, then return the retained - * summary view. A size-aware contract also summarizes large Evidence when the - * caller omits detail. + * summary view. An omitted detail is left to the agent result budget, which + * tool-result delivery applies to every budgeted operation. */ export const retainedSummaryDelivery = ( operation: string, @@ -51,29 +23,18 @@ export const retainedSummaryDelivery = ( readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined; readonly evidenceById?: EvidenceLookup | undefined; }, - sizeAware = false, ) => { const retention = { recordEvidence: options.recordEvidence, evidenceById: options.evidenceById, }; - const retained = requireAnalysisViewRetention(operation, retention).ok; return { preflight: (parameters: Parameters) => parameters.detail === "summary" ? requireAnalysisViewRetention(operation, retention) : ok(null), - projectEvidence: ( - parameters: Parameters, - evidence: Evidence, - // Only an omitted size-aware detail reads it. - pageable = false, - ) => - deliversRetainedSummary(parameters.detail, evidence, { - sizeAware, - retained, - pageable, - }) + projectEvidence: (parameters: Parameters, evidence: Evidence) => + parameters.detail === "summary" ? summarizeRetainedAnalysis(evidence, retention) : ok(evidence), }; diff --git a/src/server/serviceToolBindings.ts b/src/server/serviceToolBindings.ts index dbc587b3255..23db9f53b6c 100644 --- a/src/server/serviceToolBindings.ts +++ b/src/server/serviceToolBindings.ts @@ -407,7 +407,7 @@ const SERVICE_TOOL_BINDINGS = { ), ); const { detail, ...input } = parsed.data; - const parameters = { detail }; + const parameters = detail === undefined ? {} : { detail }; const ready = delivery.preflight(parameters); if (!ready.ok) return ready; const inspected = await service.inspect(input, options); @@ -753,7 +753,7 @@ const SERVICE_TOOL_BINDINGS = { ), ); const { detail, ...input } = parsed.data; - const parameters = { detail }; + const parameters = detail === undefined ? {} : { detail }; const ready = delivery.preflight(parameters); if (!ready.ok) return ready; const inspected = await service.inspect(input, options); diff --git a/src/server/toolResult.ts b/src/server/toolResult.ts index 01fe3693044..7d29272a832 100644 --- a/src/server/toolResult.ts +++ b/src/server/toolResult.ts @@ -2,6 +2,7 @@ import { isNativeObservationOperation } from "../domain/native/nativeObservation import { isNativeInventoryOperation } from "../domain/native/nativeInventory.js"; import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server"; import { ToolResultDelivery } from "./ToolResultDelivery.js"; +import { AGENT_RESULT_BUDGET_ENVIRONMENT } from "../domain/agentResultBudget.js"; import { INSPECT_ANALYSIS_VIEW_OPERATION } from "../domain/analysisView/analysisViewErrors.js"; import { inspectAnalysisViewInputSchema } from "../domain/analysisView/analysisViewRequest.js"; import { smallerBatchDecompileSelection } from "../domain/analysisView/batchDecompileView.js"; @@ -11,10 +12,14 @@ import { ownedJsonValueSchema, type JsonValue } from "../domain/jsonValue.js"; /** Compose native Evidence continuation with the selected, parsed response budget. */ export const createToolResultDelivery = ( maximumResponseBytes: number | undefined, + /** The server's captured launch environment, read only for its budget seed. */ + environment: Readonly> = {}, ): ToolResultDelivery => new ToolResultDelivery( maximumResponseBytes ?? STDIO_DEFAULT_MAX_BUFFER_SIZE, retainedEvidenceContinuation, + undefined, + environment[AGENT_RESULT_BUDGET_ENVIRONMENT], ); /** diff --git a/tests/acceptance/applications/applicationVersionMatchingCli.test.ts b/tests/acceptance/applications/applicationVersionMatchingCli.test.ts index 895e81c2646..15bc1dcb89d 100644 --- a/tests/acceptance/applications/applicationVersionMatchingCli.test.ts +++ b/tests/acceptance/applications/applicationVersionMatchingCli.test.ts @@ -8,6 +8,14 @@ import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/j import { applicationVersionComparisonResultSchema } from "../../../src/domain/javascript/javascriptApplicationVersionComparisonSchemas.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; +import { + COMPLETE_DETAIL, + completeApplicationAnalysis, +} from "../../support/completeDetail.js"; + +/** Analyze an application with its complete Evidence inline. */ +const analyzeComplete = (application: string): string[] => + completeApplicationAnalysis(application); cliTest( "keeps unavailable source-selection scopes unknown in version comparisons", @@ -27,6 +35,7 @@ cliTest( const response = await cli.run({ arguments: [ "analyze-javascript-application", + ...COMPLETE_DETAIL, application, ...(selected ? ["--source-path", "main.js"] : []), "--json", @@ -151,7 +160,7 @@ cliTest( `globalThis.webpackChunkApp.push([[1], {17(module, exports) {${side === 1 ? left : right}}}]);`, ); const response = await cli.run({ - arguments: ["analyze-javascript-application", application, "--json"], + arguments: analyzeComplete(application), environment: { REA_LOG_LEVEL: "silent" }, }); expect(response.exitCode, response.stderr).toBe(0); @@ -278,7 +287,7 @@ cliTest( ); await writeFile(join(application, "chunk.js"), bundle); const response = await cli.run({ - arguments: ["analyze-javascript-application", application, "--json"], + arguments: analyzeComplete(application), environment: { REA_LOG_LEVEL: "silent" }, }); expect(response.exitCode, response.stderr).toBe(0); @@ -371,7 +380,7 @@ cliTest( `module.exports = ${JSON.stringify(name)};\n`, ); const response = await cli.run({ - arguments: ["analyze-javascript-application", application, "--json"], + arguments: analyzeComplete(application), environment: { REA_LOG_LEVEL: "silent" }, }); expect(response.exitCode, response.stderr).toBe(0); @@ -481,7 +490,7 @@ cliTest( ); await writeFile(join(application, "src/util.js"), utilSource); const response = await cli.run({ - arguments: ["analyze-javascript-application", application, "--json"], + arguments: analyzeComplete(application), environment: { REA_LOG_LEVEL: "silent" }, }); expect(response.exitCode, response.stderr).toBe(0); diff --git a/tests/acceptance/applications/applicationWorkflowCli.test.ts b/tests/acceptance/applications/applicationWorkflowCli.test.ts index e2f21a353e2..92627a13b91 100644 --- a/tests/acceptance/applications/applicationWorkflowCli.test.ts +++ b/tests/acceptance/applications/applicationWorkflowCli.test.ts @@ -39,6 +39,10 @@ import { ELECTRON_IDENTITY_LIMITATION } from "../../../src/domain/javascript/jav import { javaScriptSemanticTraceResultSchema } from "../../../src/domain/javascript/javascriptSemanticTraceSchemas.js"; import type { JavaScriptSemanticQueryInput } from "../../../src/domain/javascript/javascriptSemanticQuerySchemas.js"; import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; +import { + COMPLETE_DETAIL, + completeApplicationAnalysis, +} from "../../support/completeDetail.js"; const execute = promisify(execFile); let cliSession: CliCommandSession | undefined; @@ -214,6 +218,7 @@ const analyzeEvidenceThroughStdioMcp = async ( const response = await client.callTool({ name: "analyze_javascript_application", arguments: { + detail: "complete", input_path: inputPath, ...(sourcePaths === undefined ? {} : { source_paths: [...sourcePaths] }), }, @@ -231,9 +236,7 @@ const expectCliAnalysisParity = async ( ): Promise => { const cli = z .object({ normalized_result: javascriptApplicationAnalysisResultSchema }) - .parse( - await runCli(["analyze-javascript-application", root, "--json"]), - ).normalized_result; + .parse(await runCli(completeApplicationAnalysis(root))).normalized_result; expect(cli).toEqual(mcp); }; @@ -514,9 +517,7 @@ it("preserves source-map declarations while decoding each path once through CLI ); const { graph } = z .object({ normalized_result: javascriptApplicationAnalysisResultSchema }) - .parse( - await runCli(["analyze-javascript-application", root, "--json"]), - ).normalized_result; + .parse(await runCli(completeApplicationAnalysis(root))).normalized_result; const maps = graph.nodes.filter(({ kind }) => kind === "source-map"); expect( maps.flatMap(({ observations }) => @@ -615,11 +616,7 @@ describe("JavaScript application path CLI", () => { const absoluteAnalysis = javascriptApplicationAnalysisResultSchema.parse( absolute.value.normalized_result, ); - const fromCli = await runCli([ - "analyze-javascript-application", - relativePath, - "--json", - ]); + const fromCli = await runCli(completeApplicationAnalysis(relativePath)); expect(fromCli).toMatchObject({ evidence_id: absolute.value.evidence_id, @@ -637,11 +634,7 @@ describe("JavaScript application path CLI", () => { ); await writeSelfImportFixture(root); - const analyzed = await runCli([ - "analyze-javascript-application", - root, - "--json", - ]); + const analyzed = await runCli(completeApplicationAnalysis(root)); const result = z .object({ normalized_result: javascriptApplicationAnalysisResultSchema }) .parse(analyzed); @@ -660,9 +653,7 @@ describe("JavaScript application path CLI", () => { const cliResult = z .object({ normalized_result: javascriptApplicationAnalysisResultSchema }) - .parse( - await runCli(["analyze-javascript-application", root, "--json"]), - ).normalized_result; + .parse(await runCli(completeApplicationAnalysis(root))).normalized_result; expect(cliResult.summary).toMatchObject({ browser_windows: 1, explicit_web_preferences: 1, @@ -856,7 +847,7 @@ it("traces all endpoint carriers and their response consumers through CLI and MC const sourcePath = join(root, "app.js"); await writeFile(sourcePath, source); const application = parseEvidence( - await runCli(["analyze-javascript-application", root, "--json"]), + await runCli(completeApplicationAnalysis(root)), ); const graph = javascriptApplicationAnalysisResultSchema.parse( application.normalized_result, @@ -973,11 +964,7 @@ describe("rest parameter semantic trace CLI", () => { join(root, "app.js"), "function collect(first, ...rest) { return rest; } collect('first', 'second', 'third');", ); - const application = await runCli([ - "analyze-javascript-application", - root, - "--json", - ]); + const application = await runCli(completeApplicationAnalysis(root)); const graph = z .object({ normalized_result: javascriptApplicationAnalysisResultSchema }) .parse(application).normalized_result.semantic_graph; @@ -1027,11 +1014,7 @@ it("links empty-key reads and destructuring to the same property slot through CL "const {'': pattern} = routes;", ].join("\n"), ); - const evidence = await runCli([ - "analyze-javascript-application", - root, - "--json", - ]); + const evidence = await runCli(completeApplicationAnalysis(root)); const { semantic_graph: graph } = z .object({ normalized_result: javascriptApplicationAnalysisResultSchema }) .parse(evidence).normalized_result; @@ -1101,6 +1084,7 @@ describe("Webpack factory CommonJS export keys", () => { const cliEvidence = applicationEvidenceSchema.parse( await runCli([ "analyze-javascript-application", + ...COMPLETE_DETAIL, root, "--artifact-format", "directory", @@ -1110,7 +1094,7 @@ describe("Webpack factory CommonJS export keys", () => { const client = await connectedMcpClient(); const response = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: root, format: "directory" }, + arguments: { detail: "complete", input_path: root, format: "directory" }, }); expect(response.isError).not.toBe(true); const mcpEvidence = applicationEvidenceSchema.parse( @@ -1362,7 +1346,7 @@ describe("application workflow CLI and MCP capture lifetimes", () => { // Retain a complete CLI analysis-to-comparison journey alongside MCP parity. const [left, right] = await Promise.all( (await writeComparisonSources(root, sources)).map((applicationRoot) => - runCli(["analyze-javascript-application", applicationRoot, "--json"]), + runCli(completeApplicationAnalysis(applicationRoot)), ), ); // Execute the authored fixtures independently of static analysis. @@ -1723,7 +1707,7 @@ const analyzeComparisonSources = async ( async (applicationRoot) => { const response = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: applicationRoot }, + arguments: { detail: "complete", input_path: applicationRoot }, }); expect(response.isError).not.toBe(true); return response.structuredContent; @@ -1759,7 +1743,7 @@ it("retains bundled isolated-world contextBridge APIs through dedicated and gene if (loader === "commonjs") await writeFile(join(root, "package.json"), '{"type":"commonjs"}'); for (const arguments_ of [ - ["analyze-javascript-application", root, "--json"], + completeApplicationAnalysis(root), ["analyze", root, "--format", "json"], ]) { const result = javascriptApplicationAnalysisResultSchema.parse( diff --git a/tests/acceptance/applications/artifactComparisonCoverage.test.ts b/tests/acceptance/applications/artifactComparisonCoverage.test.ts index 7b744f9f2cd..07dd68fb3d6 100644 --- a/tests/acceptance/applications/artifactComparisonCoverage.test.ts +++ b/tests/acceptance/applications/artifactComparisonCoverage.test.ts @@ -28,6 +28,7 @@ import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest, type TestCli } from "../../support/cli/cliFixture.js"; +import { completeArguments } from "../../support/completeDetail.js"; const plist = (message: string) => `\nmessage${message}\n`; @@ -38,7 +39,7 @@ const inspectPair = async ( rightPath: string, ) => { const result = await cli.run({ - arguments: ["inspect-artifact", leftPath, "--json"], + arguments: completeArguments("inspect-artifact", leftPath), }); expect(result.exitCode, `${result.stderr}\n${result.stdout}`).toBe(0); const left = inventoryEvidence(result.json); @@ -241,7 +242,7 @@ cliTest( await writer.add("b.txt", new TextReader("def")); await writeFile(path, await writer.close()); const inspected = await cli.run({ - arguments: ["inspect-artifact", path, "--json"], + arguments: completeArguments("inspect-artifact", path), }); expect(inspected.exitCode, inspected.stderr).toBe(0); const source = inventoryEvidence(inspected.json); @@ -348,7 +349,7 @@ cliTest( writeFile(rightPath, plist("hello")), ]); const leftResult = await cli.run({ - arguments: ["inspect-artifact", leftPath, "--json"], + arguments: completeArguments("inspect-artifact", leftPath), }); expect(leftResult.exitCode, leftResult.stderr).toBe(0); const left = inventoryEvidence(leftResult.json); @@ -450,7 +451,7 @@ cliTest.skipIf(process.platform === "win32")( ]); await Promise.all([chmod(leftPath, 0o644), chmod(rightPath, 0o755)]); const result = await cli.run({ - arguments: ["inspect-artifact", leftPath, "--json"], + arguments: completeArguments("inspect-artifact", leftPath), }); expect(result.exitCode, result.stderr).toBe(0); const left = inventoryEvidence(result.json); diff --git a/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts b/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts index c1385923d95..74248dcb879 100644 --- a/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts +++ b/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts @@ -28,6 +28,7 @@ import { createTestWorkspace, removeTestWorkspace, } from "../../support/workspace/workspaceFixture.js"; +import { completeApplicationAnalysis } from "../../support/completeDetail.js"; const requireFixture = createRequire(import.meta.url); const comparisonEnvelope = z.object({ @@ -998,7 +999,7 @@ it("retains runtime namespace re-exports and erases type-only re-exports through const documents = [ await analyzeThroughMcp(root), - await runCli(["analyze-javascript-application", root, "--json"]), + await runCli(completeApplicationAnalysis(root)), ]; const digest = createHash("sha256").update(source).digest("hex"); for (const document of documents) { @@ -1367,6 +1368,7 @@ const expectRuntimeReceiver = ( const analyzeThroughMcp = async (inputPath: string) => { const call = await mcp.session.call(); const response = await call("analyze_javascript_application", { + detail: "complete", input_path: inputPath, format: "auto", }); @@ -1382,7 +1384,7 @@ const expectCliAnalysisParity = async ( [join(fixture.root, "right"), fixture.input.right], ] as const) { const cli = applicationEnvelope.parse( - await runCli(["analyze-javascript-application", root, "--json"]), + await runCli(completeApplicationAnalysis(root)), ); const mcp = applicationEnvelope.parse(evidence); expect(cli.normalized_result).toEqual(mcp.normalized_result); diff --git a/tests/acceptance/applications/javascriptBuiltinDefaultsCli.test.ts b/tests/acceptance/applications/javascriptBuiltinDefaultsCli.test.ts index ab8352944a3..7af0b3a0873 100644 --- a/tests/acceptance/applications/javascriptBuiltinDefaultsCli.test.ts +++ b/tests/acceptance/applications/javascriptBuiltinDefaultsCli.test.ts @@ -118,6 +118,7 @@ it("preserves earlier and sibling effects without inventing replaced cached-modu ).toHaveLength(1); const { client, call } = await connectLocalToolsMcp(); const response = await call("analyze_javascript_application", { + detail: "complete", input_path: root, format: "auto", }); @@ -169,6 +170,7 @@ it("excludes monkey-patched CommonJS effects from CLI and MCP evidence", async ( ).toEqual([]); const { client, call } = await connectLocalToolsMcp(); const response = await call("analyze_javascript_application", { + detail: "complete", input_path: root, format: "auto", }); @@ -246,6 +248,7 @@ it("retains CommonJS builtin effects and handle links through CLI and MCP", asyn ); const { client, call } = await connectLocalToolsMcp(); const response = await call("analyze_javascript_application", { + detail: "complete", input_path: root, format: "auto", }); diff --git a/tests/acceptance/applications/javascriptCallbackTargets.test.ts b/tests/acceptance/applications/javascriptCallbackTargets.test.ts index 3a0229ffbd1..eb58cf2589f 100644 --- a/tests/acceptance/applications/javascriptCallbackTargets.test.ts +++ b/tests/acceptance/applications/javascriptCallbackTargets.test.ts @@ -11,6 +11,7 @@ import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; import { verifyJavaScriptReturnShapes } from "../../fixtures/javascriptReturnShapes.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; +import { COMPLETE_DETAIL } from "../../support/completeDetail.js"; const createCallbackFixture = async () => { const root = await createTestTempDirectory("rea-callback-targets-"); @@ -165,6 +166,7 @@ cliTest( const analyzed = await cli.run({ arguments: [ "analyze-javascript-application", + ...COMPLETE_DETAIL, root, "--artifact-format", "directory", diff --git a/tests/acceptance/applications/javascriptCapturedParameters.test.ts b/tests/acceptance/applications/javascriptCapturedParameters.test.ts index 5aaf88ad19e..a341e086607 100644 --- a/tests/acceptance/applications/javascriptCapturedParameters.test.ts +++ b/tests/acceptance/applications/javascriptCapturedParameters.test.ts @@ -9,6 +9,7 @@ import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarnes import { verifyJavaScriptReturnShapes } from "../../fixtures/javascriptReturnShapes.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; +import { completeApplicationAnalysis } from "../../support/completeDetail.js"; const source = ` export function captured(x) { const saved=x; x=2; return {type:"ok",value:saved}; } @@ -443,7 +444,7 @@ cliTest( `export function read(x) { ${body} }`, ); const response = await cli.run({ - arguments: ["analyze-javascript-application", directory, "--json"], + arguments: completeApplicationAnalysis(directory), }); expect(response.exitCode, response.stderr).toBe(0); evidence.push(parseEvidence(response.json)); diff --git a/tests/acceptance/applications/javascriptChildHandleOwnership.test.ts b/tests/acceptance/applications/javascriptChildHandleOwnership.test.ts index 5b55e7dc730..eed404e13d9 100644 --- a/tests/acceptance/applications/javascriptChildHandleOwnership.test.ts +++ b/tests/acceptance/applications/javascriptChildHandleOwnership.test.ts @@ -35,6 +35,7 @@ const analyzeThroughCliAndMcp = async (source: string) => { const evidence = parseEvidence(JSON.parse(stdout)); const { client, call } = await connectLocalToolsMcp({ HOME: home }); const response = await call("analyze_javascript_application", { + detail: "complete", input_path: app, format: "auto", }); diff --git a/tests/acceptance/applications/playwrightTrace.test.ts b/tests/acceptance/applications/playwrightTrace.test.ts index 0b57cc225bc..2a30701b630 100644 --- a/tests/acceptance/applications/playwrightTrace.test.ts +++ b/tests/acceptance/applications/playwrightTrace.test.ts @@ -633,7 +633,12 @@ cliTest( kind: "playwright-trace", collection: "streams", }); - for (const delivery of [[], ["--detail", "complete"]]) { + // An omitted --detail with a view selects summary delivery, which still + // needs a bundle; --detail complete cannot page a view at all. + for (const [delivery, path] of [ + [[], "evidence_output"], + [["--detail", "complete"], "view"], + ] as const) { const result = await cli.run({ arguments: [ "inspect-playwright-trace", @@ -647,7 +652,7 @@ cliTest( expect(result.exitCode).not.toBe(0); expect(result.json).toMatchObject({ code: "invalid_request", - details: { issues: [{ path: ["view"], reason: "invalid_value" }] }, + details: { issues: [{ path: [path], reason: "invalid_value" }] }, }); } }, diff --git a/tests/acceptance/applications/unboundRequires.test.ts b/tests/acceptance/applications/unboundRequires.test.ts index 41eba1189dd..085f42ec13f 100644 --- a/tests/acceptance/applications/unboundRequires.test.ts +++ b/tests/acceptance/applications/unboundRequires.test.ts @@ -16,6 +16,7 @@ import { resolveJavaScriptApplicationMcpCall, } from "../../support/cli/javascriptApplication.js"; import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js"; +import { COMPLETE_DETAIL } from "../../support/completeDetail.js"; const execute = promisify(execFile); @@ -899,7 +900,13 @@ cliTest( } const response = await cli.run({ - arguments: ["analyze-javascript-application", root, "--format", "json"], + arguments: [ + "analyze-javascript-application", + ...COMPLETE_DETAIL, + root, + "--format", + "json", + ], environment: { REA_LOG_LEVEL: "silent" }, }); @@ -1161,7 +1168,13 @@ cliTest( await expectNativeModuleControls(root); const response = await cli.run({ - arguments: ["analyze-javascript-application", root, "--format", "json"], + arguments: [ + "analyze-javascript-application", + ...COMPLETE_DETAIL, + root, + "--format", + "json", + ], environment: { REA_LOG_LEVEL: "silent" }, }); expect(response.exitCode, response.stderr).toBe(0); @@ -1177,6 +1190,7 @@ cliTest( const call = await resolveJavaScriptApplicationMcpCall(cli, undefined); const mcp = await call("analyze_javascript_application", { + detail: "complete", input_path: root, format: "directory", }); diff --git a/tests/acceptance/browserScenarioReferenceDiagnostics.test.ts b/tests/acceptance/browserScenarioReferenceDiagnostics.test.ts index b8a24833bae..4d9defa2b5a 100644 --- a/tests/acceptance/browserScenarioReferenceDiagnostics.test.ts +++ b/tests/acceptance/browserScenarioReferenceDiagnostics.test.ts @@ -8,6 +8,7 @@ import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { parseMcpToolError } from "../fixtures/mcpToolError.js"; import { cliTest } from "../support/cli/cliFixture.js"; import { createMcpSchemaValidation } from "../fixtures/mcpSchemaValidation.js"; +import { completeArguments } from "../support/completeDetail.js"; cliTest.for([ ["CLI", "query"], @@ -39,7 +40,7 @@ cliTest.for([ await writeFile(path, JSON.stringify(input)); // A real file argument avoids the host argv limit for this valid JSON. const result = await cli.run({ - arguments: ["capture-browser-scenario", path, "--json"], + arguments: completeArguments("capture-browser-scenario", path), environment: { HOME: home, REA_LOG_LEVEL: "silent" }, }); expect(result.exitCode).toBe(1); @@ -71,7 +72,7 @@ cliTest.for([ await client.connect(transport); const result = await client.callTool({ name: "capture_browser_scenario", - arguments: input, + arguments: { ...input, detail: "complete" }, }); expect(result.isError).toBe(true); expect(parseMcpToolError(result).error).toMatchObject(expected); diff --git a/tests/acceptance/byteEntropyWindowsIdentity.test.ts b/tests/acceptance/byteEntropyWindowsIdentity.test.ts index 26d7024515a..1f77ee15604 100644 --- a/tests/acceptance/byteEntropyWindowsIdentity.test.ts +++ b/tests/acceptance/byteEntropyWindowsIdentity.test.ts @@ -9,6 +9,7 @@ import { cliTest } from "../support/cli/cliFixture.js"; import { ByteEntropyService } from "../../src/application/binaryDiagnostics/ByteEntropyService.js"; import { parseEvidence } from "../../src/domain/evidence.js"; import { createMcpSchemaValidation } from "../fixtures/mcpSchemaValidation.js"; +import { completeArguments } from "../support/completeDetail.js"; describe.skipIf(process.platform !== "win32")( "Windows selected-file spelling", @@ -46,13 +47,13 @@ describe.skipIf(process.platform !== "win32")( const direct = await service.inspect({ path: spelling }); if (!direct.ok) throw direct.error; const fromCli = await cli.run({ - arguments: ["inspect-byte-entropy", spelling, "--json"], + arguments: completeArguments("inspect-byte-entropy", spelling), }); expect(fromCli.exitCode, fromCli.stderr).toBe(0); const evidence = parseEvidence(fromCli.json); const response = await client.callTool({ name: "inspect_byte_entropy", - arguments: { path: spelling }, + arguments: { detail: "complete", path: spelling }, }); expect(response.isError).not.toBe(true); const mcpEvidence = parseEvidence(response.structuredContent); diff --git a/tests/acceptance/dotnetBundleJourney.test.ts b/tests/acceptance/dotnetBundleJourney.test.ts index b0b4703a162..a6ac4520f31 100644 --- a/tests/acceptance/dotnetBundleJourney.test.ts +++ b/tests/acceptance/dotnetBundleJourney.test.ts @@ -18,6 +18,7 @@ import { import { workspaceCliTest as test } from "../support/cli/workspaceCliFixture.js"; import { createMcpSchemaValidation } from "../fixtures/mcpSchemaValidation.js"; import { expectCarrierProbes } from "../fixtures/nativeCarrierProbes.js"; +import { completeArguments } from "../support/completeDetail.js"; // Compile SDK output validators for the tools a test calls, not the whole catalog. const schemaValidation = createMcpSchemaValidation(); @@ -158,7 +159,7 @@ for (const format of ["dotnet-bundle", "pyinstaller"] as const) { }; try { const inspected = await cli.run({ - arguments: ["inspect-artifact", path, "--json"], + arguments: completeArguments("inspect-artifact", path), environment, }); expect(inspected.exitCode, inspected.stderr).toBe(0); @@ -192,7 +193,7 @@ for (const format of ["dotnet-bundle", "pyinstaller"] as const) { expect(opened.isError, JSON.stringify(opened)).not.toBe(true); const observed = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(observed.isError, JSON.stringify(observed)).not.toBe(true); expect( @@ -241,7 +242,7 @@ test("reports excessive bundle path depth as a public CLI limit", async ({ ); const result = await cli.run({ - arguments: ["inspect-artifact", path, "--json"], + arguments: completeArguments("inspect-artifact", path), environment: { REA_LOG_LEVEL: "silent" }, }); expect(result.exitCode, result.stderr).toBe(1); diff --git a/tests/acceptance/harmonyArtifactJourney.test.ts b/tests/acceptance/harmonyArtifactJourney.test.ts index 9f4563e4c45..85d716a6fac 100644 --- a/tests/acceptance/harmonyArtifactJourney.test.ts +++ b/tests/acceptance/harmonyArtifactJourney.test.ts @@ -17,6 +17,7 @@ import { } from "../../src/domain/harmony/harmonyApplication.js"; import { workspaceCliTest as test } from "../support/cli/workspaceCliFixture.js"; import { createMcpSchemaValidation } from "../fixtures/mcpSchemaValidation.js"; +import { COMPLETE_DETAIL } from "../support/completeDetail.js"; const expectProjectionParity = ( graph: HarmonyApplicationProjectionResult, @@ -144,7 +145,13 @@ test("preserves Harmony archive formats through the public CLI/MCP lifecycle", a await writeFile(path, bytes); const sha256 = createHash("sha256").update(bytes).digest("hex"); const cliReply = await cli.run({ - arguments: ["inspect-artifact", path, "--format", "json"], + arguments: [ + "inspect-artifact", + ...COMPLETE_DETAIL, + path, + "--format", + "json", + ], environment, }); expect(cliReply.exitCode, cliReply.stderr).toBe(0); @@ -182,7 +189,7 @@ test("preserves Harmony archive formats through the public CLI/MCP lifecycle", a }); const inspected = await artifactMcpCall(client, { name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(inspected.isError, JSON.stringify(inspected)).not.toBe(true); const inventoryEvidence = parseEvidence(inspected.structuredContent); diff --git a/tests/acceptance/machoSelectedSliceCli.test.ts b/tests/acceptance/machoSelectedSliceCli.test.ts index 32147c5a3cc..ac9c7b84f4e 100644 --- a/tests/acceptance/machoSelectedSliceCli.test.ts +++ b/tests/acceptance/machoSelectedSliceCli.test.ts @@ -4,6 +4,7 @@ import { join } from "node:path"; import { expect } from "vitest"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { cliTest } from "../support/cli/cliFixture.js"; +import { completeArguments } from "../support/completeDetail.js"; const thin = (subtype: number): Buffer => { const bytes = Buffer.alloc(4096); @@ -61,7 +62,7 @@ cliTest.skipIf(process.platform !== "darwin" || process.arch !== "arm64")( const path = join(root, name); await writeFile(path, bytes); const result = await cli.run({ - arguments: ["inspect-macho", path, "--json"], + arguments: completeArguments("inspect-macho", path), }); expect(result.exitCode, result.stderr).toBe(0); expect(result.json).toMatchObject({ @@ -102,7 +103,7 @@ cliTest.skipIf(process.platform !== "darwin" || process.arch !== "arm64")( ]); const before = await readFile(path); const result = await cli.run({ - arguments: ["inspect-macho", path, "--json"], + arguments: completeArguments("inspect-macho", path), }); expect(result.exitCode, result.stderr + result.stdout).toBe(0); expect(result.json).toMatchObject({ @@ -131,7 +132,7 @@ cliTest.skipIf(process.platform !== "darwin" || process.arch !== "arm64")( patched[sectionName] = 0xff; await writeFile(path, patched); const undecodable = await cli.run({ - arguments: ["inspect-macho", path, "--json"], + arguments: completeArguments("inspect-macho", path), }); expect(undecodable.exitCode, undecodable.stderr + undecodable.stdout).toBe( 0, diff --git a/tests/acceptance/managedMemberRecovery.test.ts b/tests/acceptance/managedMemberRecovery.test.ts index 5efef5ad814..b126300ec72 100644 --- a/tests/acceptance/managedMemberRecovery.test.ts +++ b/tests/acceptance/managedMemberRecovery.test.ts @@ -20,6 +20,10 @@ import { buildManagedMemberCapacityFixture } from "../fixtures/managedMemberCapa import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { cliTest } from "../support/cli/cliFixture.js"; import { createMcpSchemaValidation } from "../fixtures/mcpSchemaValidation.js"; +import { + COMPLETE_DETAIL, + completeArguments, +} from "../support/completeDetail.js"; const createTransport = () => new StdioClientTransport({ @@ -88,13 +92,13 @@ cliTest( expect(ajv.validateSchema(definition.inputSchema)).toBe(true); expect(ajv.validateSchema(outputSchema)).toBe(true); const output = await cli.run({ - arguments: ["inspect-managed-members", path, "--json"], + arguments: completeArguments("inspect-managed-members", path), }); expect(output.exitCode, output.stderr).toBe(0); const cliEvidence = parseEvidence(output.json); const response = await artifactMcpCall(client, { name: "inspect_managed_members", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(response.isError, JSON.stringify(response)).not.toBe(true); expect( @@ -113,6 +117,7 @@ cliTest( const selectedCli = await cli.run({ arguments: [ "inspect-managed-members", + ...COMPLETE_DETAIL, path, "--type", empty.full_name, @@ -122,7 +127,7 @@ cliTest( expect(selectedCli.exitCode, selectedCli.stderr).toBe(0); const selected = await artifactMcpCall(client, { name: "inspect_managed_members", - arguments: { path, type_names: [empty.full_name] }, + arguments: { detail: "complete", path, type_names: [empty.full_name] }, }); expect(selected.isError).not.toBe(true); const selectedEvidence = parseEvidence(selected.structuredContent); diff --git a/tests/acceptance/nonBinaryComposition.test.ts b/tests/acceptance/nonBinaryComposition.test.ts index a50bc58338a..f04e1974981 100644 --- a/tests/acceptance/nonBinaryComposition.test.ts +++ b/tests/acceptance/nonBinaryComposition.test.ts @@ -13,6 +13,7 @@ import { writeOrderedZip } from "../fixtures/artifactEntryOrder.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { cliTest } from "../support/cli/cliFixture.js"; import { createMcpSchemaValidation } from "../fixtures/mcpSchemaValidation.js"; +import { completeArguments } from "../support/completeDetail.js"; const connect = async (environment: NodeJS.ProcessEnv) => { const session = createTestBinarySession(() => { @@ -68,7 +69,7 @@ for (const { jarConfigured, setting } of [ ...(jarConfigured ? { REA_JADX_MCP_JAR: jar } : {}), }; const cliResult = await cli.run({ - arguments: ["inspect-android-package", apk, "--json"], + arguments: completeArguments("inspect-android-package", apk), environment, }); expect(cliResult.exitCode).toBe(1); @@ -76,7 +77,7 @@ for (const { jarConfigured, setting } of [ const client = await connect(environment); const response = await client.callTool({ name: "inspect_android_package", - arguments: { path: apk }, + arguments: { detail: "complete", path: apk }, }); expect(response.isError).toBe(true); expect(parseMcpToolError(response)).toEqual({ error: cliResult.json }); @@ -92,14 +93,14 @@ cliTest.skipIf(process.platform === "win32")( await writeOrderedZip(apk, ["AndroidManifest.xml"]); const run = async (environment: Record) => { const cliResult = await cli.run({ - arguments: ["inspect-android-package", apk, "--json"], + arguments: completeArguments("inspect-android-package", apk), environment: { REA_LOG_LEVEL: "silent", ...environment }, }); expect(cliResult.exitCode).toBe(1); const client = await connect({ REA_LOG_LEVEL: "silent", ...environment }); const response = await client.callTool({ name: "inspect_android_package", - arguments: { path: apk }, + arguments: { detail: "complete", path: apk }, }); expect(response.isError).toBe(true); expect(parseMcpToolError(response)).toEqual({ error: cliResult.json }); @@ -289,7 +290,7 @@ cliTest.skipIf(process.platform === "win32")( }); const request = { name: "inspect_android_package", - arguments: { path: apk }, + arguments: { detail: "complete", path: apk }, }; const inspect = async () => parseMcpToolError(await client.callTool(request)).error; diff --git a/tests/acceptance/providers/idaEndpointFailure.test.ts b/tests/acceptance/providers/idaEndpointFailure.test.ts index e878af50d0a..9e2a0dc59f8 100644 --- a/tests/acceptance/providers/idaEndpointFailure.test.ts +++ b/tests/acceptance/providers/idaEndpointFailure.test.ts @@ -62,7 +62,9 @@ for (const encodedCredential of [false, true]) provider_id: "ida", }); if (opened.isError) throw new Error(JSON.stringify(opened)); - const failure = parseMcpToolError(await call("list_procedures", {})); + const failure = parseMcpToolError( + await call("list_procedures", { detail: "complete" }), + ); expect(failure.error).toMatchObject({ code: "execution_failure", details: { diagnostics: { endpoint: expectedEndpoint } }, diff --git a/tests/acceptance/tools/historicalCaptureResources.test.ts b/tests/acceptance/tools/historicalCaptureResources.test.ts index 2b4adf28146..2bbf3c89a94 100644 --- a/tests/acceptance/tools/historicalCaptureResources.test.ts +++ b/tests/acceptance/tools/historicalCaptureResources.test.ts @@ -17,6 +17,7 @@ import { CAPTURE_RUNTIME_SUPPORTED } from "../../fixtures/captureDecoderLimits.j import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { COMPLETE_DETAIL } from "../../support/completeDetail.js"; const execute = promisify(execFile); const cli = fileURLToPath(new URL("../../../scripts/rea.mjs", import.meta.url)); @@ -74,6 +75,7 @@ it.skipIf( ), }); const response = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "har", sensitive_values: ["caller-marked"], @@ -123,6 +125,7 @@ it.skipIf( [ cli, "inspect-web-network-capture", + ...COMPLETE_DETAIL, path, "har", "--json", @@ -165,6 +168,7 @@ it.skipIf( await writeFile(small, capture(2)); await client.ping(); const control = await call("inspect_web_network_capture", { + detail: "complete", capture_path: small, format: "har", }); @@ -177,7 +181,7 @@ it.skipIf( const defaultServer = await connectLocalToolsMcp(); const defaultControl = await defaultServer.call( "inspect_web_network_capture", - { capture_path: small, format: "har" }, + { detail: "complete", capture_path: small, format: "har" }, ); expect(defaultControl.isError, JSON.stringify(defaultControl)).not.toBe( true, @@ -187,6 +191,7 @@ it.skipIf( ); await truncate(path, WEB_NETWORK_CAPTURE_LIMITS.inputBytes + 1); const oversized = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "har", }); diff --git a/tests/acceptance/tools/qlogCapture.test.ts b/tests/acceptance/tools/qlogCapture.test.ts index 2444b95f9f7..a484c9d1e8a 100644 --- a/tests/acceptance/tools/qlogCapture.test.ts +++ b/tests/acceptance/tools/qlogCapture.test.ts @@ -29,6 +29,7 @@ import { definedCliEnvironment, } from "../../support/cli/cliFixture.js"; import { issuesByContractField } from "../../support/cli/cliIssueFields.js"; +import { COMPLETE_DETAIL } from "../../support/completeDetail.js"; const execute = promisify(execFile); const it = runtimeTest.skipIf(!hasMemoryBound || !runtimeSupported); @@ -55,6 +56,7 @@ it("preserves aioquic recovery packet-number spaces and their source records", a const ordinals = [1, 5, 9, 13, 17, 21, 25]; const { call } = await sharedMcp(); const response = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "qlog", record_ordinals: ordinals, @@ -152,6 +154,7 @@ const expectRecoveredCapture = async ( path: string, ): Promise => { const response = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "qlog", }); @@ -363,6 +366,7 @@ runtimeTest.runIf(!hasMemoryBound && runtimeSupported)( expect( parseMcpToolError( await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "qlog", }), @@ -393,6 +397,7 @@ it("runs built CLI and real stdio SDK with exact evidence parity, selection, ret const mcp = parseEvidence(response.structuredContent); const result = await runSharedCli([ "inspect-web-network-capture", + ...COMPLETE_DETAIL, path, "qlog", "--record", @@ -444,12 +449,14 @@ it("runs built CLI and real stdio SDK with exact evidence parity, selection, ret } const sensitive = ["trace-local", "/traces/0", "input.qlog", "data"]; const hidden = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "qlog", sensitive_values: sensitive, }); const hiddenCli = await runSharedCli([ "inspect-web-network-capture", + ...COMPLETE_DETAIL, path, "qlog", ...sensitive.flatMap((value) => ["--sensitive-value", value]), @@ -550,6 +557,7 @@ it("fails whole-capture validation before selection and survives malformed, unsu await writeFile(path, outsideSelection); const failed = await runSharedCli([ "inspect-web-network-capture", + ...COMPLETE_DETAIL, path, "qlog", "--record", @@ -567,6 +575,7 @@ it("fails whole-capture validation before selection and survives malformed, unsu expect( parseMcpToolError( await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "qlog", record_ordinals: [0], @@ -578,6 +587,7 @@ it("fails whole-capture validation before selection and survives malformed, unsu expect( parseMcpToolError( await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "qlog", }), @@ -617,6 +627,7 @@ runtimeTest.skipIf( await writeFile(path, dense); const { call, client } = await connectLocalToolsMcp(); const response = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "qlog", record_ordinals: [0], @@ -632,7 +643,14 @@ runtimeTest.skipIf( }); const failed: unknown = await execute( process.execPath, - [cli, "inspect-web-network-capture", path, "qlog", "--json"], + [ + cli, + "inspect-web-network-capture", + ...COMPLETE_DETAIL, + path, + "qlog", + "--json", + ], { timeout: 40_000, maxBuffer: 1024 * 1024 }, ).catch((cause: unknown) => cause); expect(failed).toMatchObject({ diff --git a/tests/acceptance/uefiFirmware.test.ts b/tests/acceptance/uefiFirmware.test.ts index 84d3a8ccd8a..45f692f75e0 100644 --- a/tests/acceptance/uefiFirmware.test.ts +++ b/tests/acceptance/uefiFirmware.test.ts @@ -24,6 +24,7 @@ import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js"; import { parseMcpToolError } from "../fixtures/mcpToolError.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { cliTest } from "../support/cli/cliFixture.js"; +import { COMPLETE_DETAIL } from "../support/completeDetail.js"; const execute = promisify(execFile); const cli = fileURLToPath(new URL("../../scripts/rea.mjs", import.meta.url)); @@ -121,7 +122,9 @@ it("maps a flash image end to end through CLI inspection and MCP session invento const opened = await call("open_binary", { path: imagePath }); expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true); - const inspectedSession = await call("inspect_artifact", {}); + const inspectedSession = await call("inspect_artifact", { + detail: "complete", + }); expect(inspectedSession.isError, JSON.stringify(inspectedSession)).not.toBe( true, ); @@ -262,6 +265,7 @@ it("never admits prose carrying a `_FVH` string as the flash image format", asyn const cliResult = await execute(process.execPath, [ cli, "inspect-artifact", + ...COMPLETE_DETAIL, path, "--json", ]); @@ -294,6 +298,7 @@ it.each([ const command = await execute(process.execPath, [ cli, "inspect-artifact", + ...COMPLETE_DETAIL, path, "--json", ]); @@ -381,7 +386,7 @@ it("retains an opaque volume and reports only the unparsed ranges in the selecte const opened = await call("open_binary", { path }); expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true); const inventoryEvidence = parseEvidence( - (await call("inspect_artifact", {})).structuredContent, + (await call("inspect_artifact", { detail: "complete" })).structuredContent, ); const inventory = artifactInventoryResultSchema.parse( artifactInspectionResultSchema.parse(inventoryEvidence.normalized_result) diff --git a/tests/acceptance/webRuntimeCli.test.ts b/tests/acceptance/webRuntimeCli.test.ts index 244b0b7b990..80b5d78425c 100644 --- a/tests/acceptance/webRuntimeCli.test.ts +++ b/tests/acceptance/webRuntimeCli.test.ts @@ -10,6 +10,7 @@ import { z } from "zod"; import { parseEvidence } from "../../src/domain/evidence.js"; import { webEventListenersSchema } from "../../src/domain/webEventListeners.js"; import { startRuntimeBrowser } from "../fixtures/webRuntime.js"; +import { COMPLETE_DETAIL } from "../support/completeDetail.js"; const entrypoint = fileURLToPath( new URL("../../scripts/rea.mjs", import.meta.url), @@ -234,6 +235,7 @@ const cancellationCommands: readonly CliCancellationCommand[] = [ operation: "analyze_web_bundle", buildArgs: (endpoint) => [ "analyze-web-bundle", + ...COMPLETE_DETAIL, endpoint, "page-fixture", "--json", diff --git a/tests/boundary/browser/historicalWebCapture.test.ts b/tests/boundary/browser/historicalWebCapture.test.ts index 7f8097f82dc..9a87ef587c3 100644 --- a/tests/boundary/browser/historicalWebCapture.test.ts +++ b/tests/boundary/browser/historicalWebCapture.test.ts @@ -25,6 +25,7 @@ const cli = async ( [ entrypoint, "inspect-web-network-capture", + ...COMPLETE_DETAIL, path, format, "--json", @@ -47,6 +48,7 @@ import { historicalHar, harWithContainerLookalikes, } from "../../fixtures/historicalHar.js"; +import { COMPLETE_DETAIL } from "../../support/completeDetail.js"; it("preserves opaque HAR container fields through CLI and MCP", async () => { const root = await createTestTempDirectory("rea-har-container-fields-"); @@ -65,6 +67,7 @@ it("preserves opaque HAR container fields through CLI and MCP", async () => { expect(fromCli.ok, fromCli.stdout).toBe(true); const cliEvidence = parseEvidence(JSON.parse(fromCli.stdout)); const response = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "har", sensitive_values: sensitive, @@ -180,6 +183,7 @@ it("retains Playwright IPv6 spelling through public CLI and MCP workflows", asyn expect(fromCli.ok, fromCli.stdout).toBe(true); const cliEvidence = parseEvidence(JSON.parse(fromCli.stdout)); const response = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "har", }); @@ -444,6 +448,7 @@ it("counts credential-named HAR members by pointer, excluding values the decoder expect(fromCli.ok, fromCli.stdout).toBe(true); const cliEvidence = parseEvidence(JSON.parse(fromCli.stdout)); const response = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "har", sensitive_values: sensitive, diff --git a/tests/boundary/browser/sazWebCapture.test.ts b/tests/boundary/browser/sazWebCapture.test.ts index 3ccf90ee0e8..b2f0d235611 100644 --- a/tests/boundary/browser/sazWebCapture.test.ts +++ b/tests/boundary/browser/sazWebCapture.test.ts @@ -41,6 +41,7 @@ import { CAPTURE_RUNTIME_SUPPORTED as runtimeSupported, } from "../../fixtures/captureDecoderLimits.js"; import { issuesByContractField } from "../../support/cli/cliIssueFields.js"; +import { COMPLETE_DETAIL } from "../../support/completeDetail.js"; const it = runtimeTest.skipIf(!hasMemoryBound || !runtimeSupported); @@ -111,6 +112,7 @@ const cliResponse = async (path: string, extra: string[] = []) => { [ entrypoint, "inspect-web-network-capture", + ...COMPLETE_DETAIL, path, "saz", "--json", @@ -187,6 +189,7 @@ it("uses HTTP optional whitespace for SAZ identity codings without changing raw } const { call } = await connectSazMcp(); const response = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "saz", record_ordinals: [0, 1, 2, 3], @@ -198,6 +201,7 @@ it("uses HTTP optional whitespace for SAZ identity codings without changing raw ); for (const sensitive of ["gzip", "Content-Encoding"]) { const excluded = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "saz", record_ordinals: [0, 1, 2, 3], @@ -320,6 +324,7 @@ it("checks trailer credentials before hidden metadata blocks analysis and withho for (const excluded of [path, sha256, "content_base64", "fixture-only"]) expect(JSON.stringify(excludedResponse)).not.toContain(excluded); const opaqueReply = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "saz", record_ordinals: [2], @@ -1118,6 +1123,7 @@ it.each([ ]); const { call } = await connectSazMcp(); const response = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "saz", record_ordinals: [0], @@ -1186,6 +1192,7 @@ it("names the ZIP decoder window instead of the expanded-input budget for a larg expect(JSON.stringify(error)).not.toContain("max_input_bytes"); const { call } = await connectSazMcp(); const response = await call("inspect_web_network_capture", { + detail: "complete", capture_path: path, format: "saz", }); diff --git a/tests/boundary/cli/browserScenarioSummaryCli.test.ts b/tests/boundary/cli/browserScenarioSummaryCli.test.ts index 58cbe01f15c..67918ab0dec 100644 --- a/tests/boundary/cli/browserScenarioSummaryCli.test.ts +++ b/tests/boundary/cli/browserScenarioSummaryCli.test.ts @@ -15,6 +15,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import type { BrowserScenarioCapturePort } from "../../../src/ports/BrowserScenarioCapturePort.js"; import { controlledCleanup } from "../../support/lifecycleHarness.js"; +import { COMPLETE_DETAIL } from "../../support/completeDetail.js"; const identity = { id: "fixture", name: "Fixture", version: "1" }; const capture = scenarioCaptureFixture(); @@ -35,6 +36,7 @@ const runCli = async ( await cli.serve( [ "capture-browser-scenario", + ...COMPLETE_DETAIL, JSON.stringify({ browser: { mode: "launch", executable_path: process.execPath }, start_url: { url: "http://127.0.0.1:3101/" }, diff --git a/tests/boundary/cli/cliOutput.test.ts b/tests/boundary/cli/cliOutput.test.ts index ccb7d7cece3..b02ddd6b5aa 100644 --- a/tests/boundary/cli/cliOutput.test.ts +++ b/tests/boundary/cli/cliOutput.test.ts @@ -14,6 +14,7 @@ import { renderVersionReport, parseCliOutputArguments, } from "../../../src/cli/cliOutput.js"; +import { COMPLETE_DETAIL } from "../../support/completeDetail.js"; describe("CLI output argument boundary", () => { it("requires an exact row selector and explicit columns for delimited formats", () => { @@ -405,6 +406,31 @@ describe("CLI output filter slice validation", () => { }, ); + workspaceCliTest( + "preserves --filter-output selections on over-budget CLI Evidence instead of returning {}", + async ({ cli, workspace }) => { + const target = workspace.path("entropy-over-budget.bin"); + await writeFile(target, Buffer.alloc(64 * 1024, 0x41)); + const result = await cli.run({ + delivery: "budgeted", + environment: { REA_AGENT_RESULT_BUDGET_BYTES: "4096" }, + arguments: [ + "inspect-byte-entropy", + target, + "--block-size", + "256", + "--json", + "--filter-output", + "normalized_result.file_entropy", + ], + }); + expect(result.exitCode).toBe(0); + expect(result.json).toEqual({ + normalized_result: { file_entropy: 0 }, + }); + }, + ); + workspaceCliTest( "retains closed slices and multiple filter paths", async ({ cli }) => { @@ -554,6 +580,7 @@ describe("compiled CLI filter results", () => { const result = await cli.run({ arguments: [ "analyze-javascript-application", + ...COMPLETE_DETAIL, "tests/conformance/readiness/javascript-cli", "--format", "json", @@ -570,6 +597,7 @@ describe("compiled CLI filter results", () => { const nested = await cli.run({ arguments: [ "analyze-javascript-application", + ...COMPLETE_DETAIL, "tests/conformance/readiness/javascript-cli", "--format", "json", @@ -585,6 +613,7 @@ describe("compiled CLI filter results", () => { const selected = await cli.run({ arguments: [ "analyze-javascript-application", + ...COMPLETE_DETAIL, "tests/conformance/readiness/javascript-cli", "--format", "json", diff --git a/tests/boundary/cli/contractCommandViewDelivery.test.ts b/tests/boundary/cli/contractCommandViewDelivery.test.ts index 135a1382857..4f0ae62360b 100644 --- a/tests/boundary/cli/contractCommandViewDelivery.test.ts +++ b/tests/boundary/cli/contractCommandViewDelivery.test.ts @@ -146,8 +146,26 @@ const viewRefusal = { const view = JSON.stringify({ page: 1 }); +// An omitted --detail with a view selects the summary that view pages, so +// the refusal names the bundle that summary delivery still needs. +it.each([ + ["argv", { path: "/missing" }], + ["document", { inputJson: '{"capture":"c"}' }], +])( + "%s treats a view without --detail as summary delivery and refuses it without a bundle before opening its target (%j)", + async (command, args) => { + const { invoke, opened } = harness(); + await expect(invoke(command, args, { view })).resolves.toMatchObject({ + code: "invalid_request", + details: { + issues: [{ path: ["evidence_output"], reason: "invalid_value" }], + }, + }); + expect(opened).toEqual([]); + }, +); + it.each([ - ["argv", { path: "/missing" }, { view }], ["argv", { path: "/missing" }, { view, detail: "complete" }], [ "argv", @@ -155,7 +173,6 @@ it.each([ { view, detail: "complete", evidence_output: "/missing.bundle.json" }, ], ["selects-summary", { path: "/missing" }, { view, detail: "complete" }], - ["document", { inputJson: '{"capture":"c"}' }, { view }], ["document", { inputJson: '{"capture":"c"}' }, { view, detail: "complete" }], ])( "%s refuses a view without summary delivery before opening its target (%j %j)", @@ -186,7 +203,12 @@ it.each([ // refusal of options the invocation can never use. it.each([ [{ view: "{" }, { path: ["view"], reason: "invalid_format" }], - [{ view }, { path: ["view"], reason: "invalid_value" }], + // A view selects summary delivery, which still needs a bundle. + [{ view }, { path: ["evidence_output"], reason: "invalid_value" }], + [ + { view, detail: "complete" }, + { path: ["view"], reason: "invalid_value" }, + ], [ { detail: "summary" }, { path: ["evidence_output"], reason: "invalid_value" }, diff --git a/tests/boundary/cli/electronCli.test.ts b/tests/boundary/cli/electronCli.test.ts index 1c1269291b0..f428d8c89f7 100644 --- a/tests/boundary/cli/electronCli.test.ts +++ b/tests/boundary/cli/electronCli.test.ts @@ -24,6 +24,10 @@ import { } from "../../fixtures/javascriptRuntimeReconciliation.js"; import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../../src/contracts/javascript/javascriptRuntimeReconciliationExample.js"; import { waitFor } from "../../support/testWait.js"; +import { + COMPLETE_DETAIL, + completeApplicationAnalysis, +} from "../../support/completeDetail.js"; const cliProcesses = createTestProcessRegistry(); const cli = createTestCli(cliProcesses); @@ -238,10 +242,7 @@ it("returns the static JavaScript application Evidence contract", async () => { ...process.env, }; - const analyzed = await runCli( - ["analyze-javascript-application", root, "--json"], - environment, - ); + const analyzed = await runCli(completeApplicationAnalysis(root), environment); expect(analyzed).toMatchObject({ operation: "analyze_javascript_application", @@ -274,6 +275,7 @@ describe("Electron CLI artifact behavior", () => { "--format", "json", "analyze-javascript-application", + ...COMPLETE_DETAIL, root, "--artifact-format", "directory", diff --git a/tests/boundary/cli/javascriptIntegrityPolicyCli.test.ts b/tests/boundary/cli/javascriptIntegrityPolicyCli.test.ts index 0cff7cb6750..791ee56d3ea 100644 --- a/tests/boundary/cli/javascriptIntegrityPolicyCli.test.ts +++ b/tests/boundary/cli/javascriptIntegrityPolicyCli.test.ts @@ -4,12 +4,17 @@ import { promisify } from "node:util"; import { expect, it } from "vitest"; import { createStrippedAsarAddon } from "../../fixtures/strippedAsarAddon.js"; +import { completeEvidenceCliArguments } from "../../support/completeEvidenceByDefault.js"; const execute = promisify(execFile); const run = async (arguments_: readonly string[]): Promise => { const { stdout } = await execute( process.execPath, - ["scripts/rea.mjs", ...arguments_, "--json"], + [ + "scripts/rea.mjs", + ...(await completeEvidenceCliArguments(arguments_)), + "--json", + ], { cwd: process.cwd(), maxBuffer: 16 * 1024 * 1024 }, ); return JSON.parse(stdout); diff --git a/tests/boundary/cli/jsonOutput.test.ts b/tests/boundary/cli/jsonOutput.test.ts index 9937b72fe6d..1768cd51bbd 100644 --- a/tests/boundary/cli/jsonOutput.test.ts +++ b/tests/boundary/cli/jsonOutput.test.ts @@ -20,6 +20,7 @@ import { logCliCommand } from "../../../src/cliLogging.js"; import { registerManagedCommands } from "../../../src/cli/managedCommands.js"; import { analysisErrorProjectionSchema } from "../../../src/domain/analysisErrorProjectionSchema.js"; import { silentLogger } from "../../../src/logger.js"; +import { COMPLETE_DETAIL } from "../../support/completeDetail.js"; /** These managed commands inspect one target; none composes Evidence. */ const unusedManagedEvidence = (): never => { @@ -531,6 +532,7 @@ describe("full-output token counts", () => { }; const argv = [ "inspect-managed-artifact", + ...COMPLETE_DETAIL, "missing.dll", "--json", "--full-output", @@ -685,7 +687,12 @@ describe("CLI result output surface", () => { }); // A terminal destination exercises the indented encoding past the limit. Object.defineProperty(destination, "isTTY", { value: true }); - const argv = ["inspect-managed-members", "fixture.dll", "--json"]; + const argv = [ + "inspect-managed-members", + ...COMPLETE_DETAIL, + "fixture.dll", + "--json", + ]; const output = createCliResultOutput( parseCliOutputArguments(argv), destination, diff --git a/tests/boundary/cli/managedMemberSummaryCli.test.ts b/tests/boundary/cli/managedMemberSummaryCli.test.ts index e22d2dab852..1ef2ab9d0fd 100644 --- a/tests/boundary/cli/managedMemberSummaryCli.test.ts +++ b/tests/boundary/cli/managedMemberSummaryCli.test.ts @@ -128,6 +128,7 @@ const verifyCliSelection = async ({ const verifyCliFullPages = async ( { cli, cwd, bundlePath, parent, report }: CliMemberViewContext, reportedCounts: Readonly>, + expectedEmpty: ReadonlySet = new Set(), ) => { for (const collection of [ "types", @@ -144,7 +145,8 @@ const verifyCliFullPages = async ( ? report.user_strings?.literals : report[collection]; if (rows == null) throw new Error(`${collection} was not examined`); - expect(rows.length, collection).toBeGreaterThan(0); + if (expectedEmpty.has(collection)) expect(rows.length, collection).toBe(0); + else expect(rows.length, collection).toBeGreaterThan(0); expect(reportedCounts[collection]).toBe(rows.length); const paged: unknown[] = []; for (let offset: number | null = 0; offset !== null;) { @@ -328,14 +330,14 @@ cliTest( const report = managedMemberInspectionSchema.parse( parent.normalized_result, ); - // The fixture declares three MemberRef rows. Paging against the produced - // report alone would also pass if the inspector silently dropped rows. + // Selected Fixture.Program bodies reference only 0x0a000001 and no + // ExportedType matches the selected type names. expect(report.member_refs.map(({ token }) => token)).toEqual([ "0x0a000001", - "0x0a000002", - "0x0a000003", ]); - expect(summary.summary.reported_counts.member_refs).toBe(3); + expect(summary.summary.reported_counts.member_refs).toBe(1); + expect(report.exported_types).toEqual([]); + expect(summary.summary.reported_counts.exported_types).toBe(0); expect(summary.summary.selection).toEqual({ type_names: typeNames, unmatched_type_names: ["Missing.Type"], @@ -346,6 +348,41 @@ cliTest( expect(summary.summary).not.toHaveProperty("member_refs"); expect(summary.summary).not.toHaveProperty("methods"); + // Whole-assembly (unselected) inspection retains all three MemberRef rows + // and the System.Object ExportedType row. + const wholeBundlePath = join(root, "whole-members.json"); + const wholeReply = await cli.run({ + cwd: root, + arguments: [ + "inspect-managed-members", + path, + "--detail", + "summary", + "--evidence_output", + "whole-members.json", + "--json", + ], + }); + expect(wholeReply.exitCode).toBe(0); + const wholeDelivered = wholeReply.json as { summary: unknown }; + const wholeSummary = managedMemberSummaryViewResultSchema.parse( + parseEvidence(wholeDelivered.summary).normalized_result, + ); + const wholeParent = parseEvidenceBundle( + JSON.parse(await readFile(wholeBundlePath, "utf8")), + ).records[0]!; + const wholeReport = managedMemberInspectionSchema.parse( + wholeParent.normalized_result, + ); + expect(wholeReport.member_refs.map(({ token }) => token)).toEqual([ + "0x0a000001", + "0x0a000002", + "0x0a000003", + ]); + expect(wholeSummary.summary.reported_counts.member_refs).toBe(3); + expect(wholeReport.exported_types).toHaveLength(1); + expect(wholeSummary.summary.reported_counts.exported_types).toBe(1); + await unlink(path); const otherDirectory = join(root, "later-process"); await mkdir(otherDirectory); @@ -358,8 +395,22 @@ cliTest( }; // The producer has exited and its target is gone. Reuse only the reader // process across page selections; every command still loads the bundle. - await verifyCliFullPages(pageContext, summary.summary.reported_counts); + await verifyCliFullPages( + pageContext, + summary.summary.reported_counts, + new Set(["exported_types"]), + ); await verifyCliSelection(pageContext); + await verifyCliFullPages( + { + cli, + cwd: otherDirectory, + bundlePath: wholeBundlePath, + parent: wholeParent, + report: wholeReport, + }, + wholeSummary.summary.reported_counts, + ); expect(await readFile(bundlePath, "utf8")).toBe(originalBytes); }, ); diff --git a/tests/boundary/cli/markdownNestedFacts.test.ts b/tests/boundary/cli/markdownNestedFacts.test.ts index 31f55d45bb2..047f01c607e 100644 --- a/tests/boundary/cli/markdownNestedFacts.test.ts +++ b/tests/boundary/cli/markdownNestedFacts.test.ts @@ -15,6 +15,7 @@ import { createCliResultOutput } from "../../../src/cli/cliResultOutput.js"; import { writeOrderedZip } from "../../fixtures/artifactEntryOrder.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js"; +import { completeArguments } from "../../support/completeDetail.js"; it("keeps source keys literal in Markdown headings through CLI result output", async () => { const value = Object.freeze({ @@ -114,7 +115,7 @@ workspaceCliTest( arguments: ["inspect-artifact", archive, "--format", "md"], }); const json = await cli.run({ - arguments: ["inspect-artifact", archive, "--json"], + arguments: completeArguments("inspect-artifact", archive), }); expect(markdown.exitCode).toBe(0); expect(json.exitCode).toBe(0); diff --git a/tests/boundary/cli/rawDiskImageCli.test.ts b/tests/boundary/cli/rawDiskImageCli.test.ts index bcbff8f3b50..5a65f8ec4ba 100644 --- a/tests/boundary/cli/rawDiskImageCli.test.ts +++ b/tests/boundary/cli/rawDiskImageCli.test.ts @@ -9,6 +9,10 @@ import { parseEvidence } from "../../../src/domain/evidence.js"; import { execFileOutput } from "../../../src/process/ExecFileOutput.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; +import { + COMPLETE_DETAIL, + completeArguments, +} from "../../support/completeDetail.js"; const envelope = z.object({ ok: z.literal(true), data: z.unknown() }); @@ -54,7 +58,13 @@ describe.skipIf(process.platform !== "darwin")( const inspect = async (path: string) => { const result = await cli.run({ - arguments: ["inspect-artifact", path, "--json", "--full-output"], + arguments: [ + "inspect-artifact", + ...COMPLETE_DETAIL, + path, + "--json", + "--full-output", + ], environment: { REA_LOG_LEVEL: "silent" }, }); expect(result.exitCode, result.stdout + result.stderr).toBe(0); @@ -118,7 +128,7 @@ describe.skipIf(process.platform !== "darwin")( // hdiutil itself treats any file as a raw image with no checksum. await writeFile(blob, Buffer.alloc(1024 * 1024)); const result = await cli.run({ - arguments: ["inspect-artifact", blob, "--json"], + arguments: completeArguments("inspect-artifact", blob), environment: { REA_LOG_LEVEL: "silent" }, }); expect(result.exitCode).not.toBe(0); diff --git a/tests/boundary/cli/reconstructionObligationLedgerCli.test.ts b/tests/boundary/cli/reconstructionObligationLedgerCli.test.ts index b55ef0d3672..c326f7fa160 100644 --- a/tests/boundary/cli/reconstructionObligationLedgerCli.test.ts +++ b/tests/boundary/cli/reconstructionObligationLedgerCli.test.ts @@ -18,6 +18,7 @@ import { readyProcessLedgerRequest, readyReviewedLedgerRequest, } from "../../../src/application/ReconstructionObligationLedger.fixture.js"; +import { completeApplicationAnalysis } from "../../support/completeDetail.js"; const execute = promisify(execFile); @@ -233,7 +234,7 @@ cliTest( ].join("\n"), ); const analyzed = await cli.run({ - arguments: ["analyze-javascript-application", root, "--json"], + arguments: completeApplicationAnalysis(root), }); expect(analyzed.exitCode).toBe(0); const application = parseEvidence(analyzed.json); diff --git a/tests/boundary/cli/sharedJavaScriptCliSession.test.ts b/tests/boundary/cli/sharedJavaScriptCliSession.test.ts index 530301a6469..272378a7a46 100644 --- a/tests/boundary/cli/sharedJavaScriptCliSession.test.ts +++ b/tests/boundary/cli/sharedJavaScriptCliSession.test.ts @@ -20,6 +20,10 @@ import { } from "../../support/cli/cliCommandSessionFrames.mjs"; import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js"; import { writeFixtureFiles } from "../../support/workspace/writeFixtureFiles.js"; +import { + COMPLETE_DETAIL, + completeApplicationAnalysis, +} from "../../support/completeDetail.js"; // Inert process models exercise escalation without waiting for real I/O. const MOCK_SHUTDOWN_GRACE_MS = 1; @@ -886,7 +890,7 @@ test("keeps a malformed JSON command's failure status and serves the next comman "app.mjs": "export function current() { return 1; }\n", }); const recovered = await session.run( - command(["analyze-javascript-application", root, "--json"], environment), + command(completeApplicationAnalysis(root), environment), ); expect(recovered.exitCode, recovered.stderr).toBe(0); expect(recovered.json).toMatchObject({ @@ -928,7 +932,7 @@ test("closes the real JavaScript CLI worker through its resource cleanup", async "app.mjs": "export function current() { return 1; }\n", }); const analyzed = await session.run( - command(["analyze-javascript-application", root, "--json"], { + command(completeApplicationAnalysis(root), { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent", }), @@ -955,6 +959,7 @@ const normalized = (result: CliResult) => const analyzeArguments = (root: string): readonly string[] => [ "analyze-javascript-application", + ...COMPLETE_DETAIL, root, "--format", "json", diff --git a/tests/boundary/cli/workflowInputIdentities.test.ts b/tests/boundary/cli/workflowInputIdentities.test.ts index 449aad95de9..8ba6bd7719a 100644 --- a/tests/boundary/cli/workflowInputIdentities.test.ts +++ b/tests/boundary/cli/workflowInputIdentities.test.ts @@ -353,10 +353,12 @@ cliTest( ); const { client, tools, call } = await connectMcp(root); const first = await call("analyze_javascript_application", { + detail: "complete", input_path: left, format: "directory", }); const second = await call("analyze_javascript_application", { + detail: "complete", input_path: right, format: "directory", }); diff --git a/tests/boundary/javascript/javascriptSelectedPathEvidence.test.ts b/tests/boundary/javascript/javascriptSelectedPathEvidence.test.ts index 72d8b2258a3..0bf5ded38e3 100644 --- a/tests/boundary/javascript/javascriptSelectedPathEvidence.test.ts +++ b/tests/boundary/javascript/javascriptSelectedPathEvidence.test.ts @@ -19,6 +19,7 @@ import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "../../../src/contracts/ import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; +import { COMPLETE_DETAIL } from "../../support/completeDetail.js"; cliTest( "retains selected JavaScript path separately from resolved identity", @@ -39,6 +40,7 @@ cliTest( const cliResponse = await cli.run({ arguments: [ "analyze-javascript-application", + ...COMPLETE_DETAIL, selectedPath, "--artifact-format", "directory", @@ -101,21 +103,21 @@ cliTest( } const { call } = await connectLocalToolsMcp({ REA_LOG_LEVEL: "silent" }); - const aliasResponse = await call("analyze_javascript_application", { - input_path: selectedPath, - format: "directory", - integrity_policy: "fail", - }); + // Each path is analyzed with its complete Evidence inline. + const analyzeComplete = (input_path: string) => + call("analyze_javascript_application", { + detail: "complete", + input_path, + format: "directory", + integrity_policy: "fail", + }); + const aliasResponse = await analyzeComplete(selectedPath); expect( aliasResponse.isError, JSON.stringify(aliasResponse.content), ).not.toBe(true); const aliasEvidence = parseEvidence(aliasResponse.structuredContent); - const physicalResponse = await call("analyze_javascript_application", { - input_path: physicalPath, - format: "directory", - integrity_policy: "fail", - }); + const physicalResponse = await analyzeComplete(physicalPath); expect( physicalResponse.isError, JSON.stringify(physicalResponse.content), diff --git a/tests/boundary/javascriptSemanticTraceEvidence.test.ts b/tests/boundary/javascriptSemanticTraceEvidence.test.ts index a2e7c28a5fa..6fd9e2e199d 100644 --- a/tests/boundary/javascriptSemanticTraceEvidence.test.ts +++ b/tests/boundary/javascriptSemanticTraceEvidence.test.ts @@ -19,6 +19,10 @@ import { analysisCliErrorEnvelopeSchema } from "../../src/contracts/errorSchemas import { toolContract } from "../../src/contracts/toolContracts.js"; import { javascriptApplicationAnalysisResultSchema } from "../../src/domain/javascript/javascriptApplicationAnalysis.js"; import { javaScriptSemanticTraceResultSchema } from "../../src/domain/javascript/javascriptSemanticTraceSchemas.js"; +import { + COMPLETE_DETAIL, + completeApplicationAnalysis, +} from "../support/completeDetail.js"; const SEMANTIC_GRAPH_ID = `jsrg_${"0".repeat(64)}`; @@ -35,11 +39,7 @@ it("reports invalid nested semantic graph Evidence as caller input through CLI a ); const cli = createCli({}); - const analyzed = await serveCli(cli, [ - "analyze-javascript-application", - root, - "--json", - ]); + const analyzed = await serveCli(cli, completeApplicationAnalysis(root)); expect(analyzed.exitCode).toBe(0); const sourceEvidence = parseEvidence(JSON.parse(analyzed.stdout)); const normalizedResult = structuredClone(sourceEvidence.normalized_result); @@ -140,11 +140,7 @@ it("excludes local exports from writes-only traces through CLI and MCP", async ( ); const cli = createCli({}); - const analyzed = await serveCli(cli, [ - "analyze-javascript-application", - root, - "--json", - ]); + const analyzed = await serveCli(cli, completeApplicationAnalysis(root)); expect(analyzed.exitCode).toBe(0); const application = parseEvidence(JSON.parse(analyzed.stdout)); const analysisResult = javascriptApplicationAnalysisResultSchema.parse( @@ -204,11 +200,7 @@ it("traces exact empty property names through CLI and MCP", async () => { "const routes = {'': 'HOME', x: 'NAMED'}; const root = routes['']; const named = routes.x;\n", ); const cli = createCli({}); - const analyzed = await serveCli(cli, [ - "analyze-javascript-application", - root, - "--json", - ]); + const analyzed = await serveCli(cli, completeApplicationAnalysis(root)); expect(analyzed.exitCode).toBe(0); const application = parseEvidence(JSON.parse(analyzed.stdout)); const { semantic_graph: graph } = @@ -276,11 +268,7 @@ it("traces transformed operands through CLI and advertised MCP output", async () 'const base = "https://example.test"; const url = base + "/x"; fetch(url); consume("only-direct"); const nested = "nested-token"; const box = { url: wrap(nested + "/x") };', ); const cli = createCli({}); - const analyzed = await serveCli(cli, [ - "analyze-javascript-application", - root, - "--json", - ]); + const analyzed = await serveCli(cli, completeApplicationAnalysis(root)); expect(analyzed.exitCode, analyzed.stdout).toBe(0); const application = parseEvidence(JSON.parse(analyzed.stdout)); const harness = await createApplicationMcpHarness(); @@ -343,6 +331,7 @@ it("reports offered semantic capacity when a large template exceeds it", async ( ); const analyzed = await serveCli(createCli({}), [ "analyze-javascript-application", + ...COMPLETE_DETAIL, root, "--max-semantic-nodes-per-file", "4", diff --git a/tests/boundary/mcp/absoluteLocalPathSchema.test.ts b/tests/boundary/mcp/absoluteLocalPathSchema.test.ts index 2550fe466cf..b71bb259fb8 100644 --- a/tests/boundary/mcp/absoluteLocalPathSchema.test.ts +++ b/tests/boundary/mcp/absoluteLocalPathSchema.test.ts @@ -429,6 +429,7 @@ it("rejects unpaired surrogates through in-memory MCP handlers", async () => { const symbol = await client.callTool({ name: "inspect_with_objdump", arguments: { + detail: "complete", path: absolute, operation: "disassemble", symbol: "main\ud800", diff --git a/tests/boundary/mcp/agentResultBudgetMcp.test.ts b/tests/boundary/mcp/agentResultBudgetMcp.test.ts new file mode 100644 index 00000000000..4bff8293f9f --- /dev/null +++ b/tests/boundary/mcp/agentResultBudgetMcp.test.ts @@ -0,0 +1,501 @@ +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import { randomBytes } from "node:crypto"; +import { readdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect, it, onTestFinished } from "vitest"; +import { createCli } from "../../../src/cli.js"; + +import { + DEFAULT_AGENT_RESULT_BUDGET_BYTES, + MINIMUM_AGENT_RESULT_BUDGET_BYTES, +} from "../../../src/domain/analysisResourceLimits.js"; +import { BinaryLayoutService } from "../../../src/application/binaryDiagnostics/BinaryLayoutService.js"; +import { ok } from "../../../src/domain/result.js"; +import { analysisViewLayoutFixture } from "../../fixtures/analysisView.js"; +import { BINARY_LAYOUT_TEST_PROVIDER } from "../../fixtures/binaryDiagnostics/layout.js"; +import { + AGENT_RESULT_BUDGET_SETTING, + EVIDENCE_OUTPUT_PLACEHOLDER, +} from "../../../src/domain/agentResultBudget.js"; +import { AGENT_BUDGET_DELIVERY_META } from "../../../src/server/ToolResultDelivery.js"; +import { parseEvidence, type Evidence } from "../../../src/domain/evidence.js"; +import { createServer } from "../../../src/server/createServer.js"; +import { publishCliAnalysisEvidence } from "../../../src/cli/analysisEvidenceDelivery.js"; +import { withCliEvidencePublication } from "../../../src/cli/cliEvidencePublication.js"; +import { createByteEntropyService } from "../../../src/composition/binaryDiagnostics/byteEntropy.js"; +import { inspectAnalysisView } from "../../../src/application/analysisView/AnalysisViewService.js"; +import { createTestBinarySession } from "../../fixtures/binarySession.js"; +import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +const connect = async () => { + const session = createTestBinarySession(() => { + throw new Error("Entropy inspection must not start a deep provider"); + }); + // Exercise the default budget, not the complete-delivery seed the test + // environment gives spawned processes. + const { REA_AGENT_RESULT_BUDGET_BYTES: _seed, ...environment } = process.env; + const server = createServer({ kind: "session", session }, { environment }); + const client = new Client( + { name: "agent-result-budget", version: "1" }, + { jsonSchemaValidator: createMcpSchemaValidation() }, + ); + onTestFinished(async () => { + await client.close(); + await server.close(); + await session.close(); + }); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + return client; +}; + +/** Random bytes in 256-byte blocks give one entropy row per block. */ +const entropyTarget = async (bytes: number) => { + const root = await createTestTempDirectory("rea-agent-budget-"); + const path = join(root, "bytes"); + await writeFile(path, randomBytes(bytes)); + return { path, block_size: 256 }; +}; + +const textBytes = (content: unknown): number => { + const [first] = Array.isArray(content) ? content : []; + if (first?.type !== "text") throw new Error("Missing MCP text result"); + return Buffer.byteLength(String(first.text)); +}; + +type Delivery = { + readonly kind: string; + readonly budget_bytes: number; + readonly complete_bytes: number; + readonly evidence_id: string; + readonly retained: string; + readonly note: string; + readonly next?: { + readonly operation: string; + readonly arguments: { + readonly source: Record; + readonly view: Record; + }; + }; +}; + +/** The delivery facts block that follows the summary's own text block. */ +const deliveryOf = (result: { + readonly content?: unknown; + readonly _meta?: Record | undefined; +}): Delivery => { + const blocks = result.content as { type: string; text: string }[]; + expect(blocks).toHaveLength(2); + const { delivery } = JSON.parse(blocks[1]!.text) as { + readonly delivery: Delivery; + }; + expect(result._meta?.[AGENT_BUDGET_DELIVERY_META]).toEqual(delivery); + return delivery; +}; + +type EvidenceJsonPage = { + readonly text: string; + readonly coverage: { readonly next_offset: number | null }; +}; + +/** Page the retained record through inspect_analysis_view until exhausted. */ +const pageEvidenceJson = async ( + client: Client, + next: NonNullable, +): Promise => { + const pages: string[] = []; + let offset: number | null = 0; + while (offset !== null) { + const page = await client.callTool({ + name: next.operation, + arguments: { + ...next.arguments, + view: { ...next.arguments.view, offset }, + }, + }); + expect(page.isError).not.toBe(true); + // Each default page itself fits the agent result budget. + expect(textBytes(page.content)).toBeLessThanOrEqual( + DEFAULT_AGENT_RESULT_BUDGET_BYTES, + ); + const result = parseEvidence(page.structuredContent) + .normalized_result as unknown as EvidenceJsonPage; + pages.push(result.text); + offset = result.coverage.next_offset; + } + return pages.join(""); +}; + +it("delivers a retained summary with a cursor when complete Evidence exceeds the agent budget", async () => { + const client = await connect(); + const input = await entropyTarget(1024 * 1024); + + const delivered = await client.callTool({ + name: "inspect_byte_entropy", + arguments: input, + }); + expect(delivered.isError).not.toBe(true); + expect(textBytes(delivered.content)).toBeLessThanOrEqual( + DEFAULT_AGENT_RESULT_BUDGET_BYTES, + ); + const summary = parseEvidence(delivered.structuredContent); + expect(summary.operation).toBe("inspect_analysis_view"); + const view = summary.normalized_result as { + readonly kind: string; + readonly parent_operation: string; + readonly parent_evidence_id: string; + readonly summary: { readonly block_count: number }; + }; + expect(view).toMatchObject({ + kind: "summary", + parent_operation: "inspect_byte_entropy", + summary: { block_count: 4096 }, + }); + const delivery = deliveryOf(delivered); + expect(delivery).toMatchObject({ + kind: "agent-budget-summary", + budget_bytes: DEFAULT_AGENT_RESULT_BUDGET_BYTES, + evidence_id: view.parent_evidence_id, + retained: "session", + next: { + operation: "inspect_analysis_view", + arguments: { + source: { + kind: "retained-evidence", + evidence_id: view.parent_evidence_id, + }, + view: { kind: "evidence-json", offset: 0 }, + }, + }, + }); + + // The budgeted summary is the same record detail summary delivers, so its + // identity holds wherever a summary is accepted. + const explicit = await client.callTool({ + name: "inspect_byte_entropy", + arguments: { ...input, detail: "summary" }, + }); + expect(parseEvidence(explicit.structuredContent).evidence_id).toBe( + summary.evidence_id, + ); + // The delivered summary is itself retained, as an explicit one is. + const summaryRecord = await client.callTool({ + name: "inspect_analysis_view", + arguments: { + source: { kind: "retained-evidence", evidence_id: summary.evidence_id }, + view: { kind: "evidence-json", offset: 0 }, + }, + }); + expect(summaryRecord.isError).not.toBe(true); + + // An explicit per-call detail keeps complete inline delivery. + const complete = await client.callTool({ + name: "inspect_byte_entropy", + arguments: { ...input, detail: "complete" }, + }); + expect(complete.isError).not.toBe(true); + const completeEvidence: Evidence = parseEvidence(complete.structuredContent); + expect(completeEvidence.operation).toBe("inspect_byte_entropy"); + expect(completeEvidence.evidence_id).toBe(view.parent_evidence_id); + expect(complete.content).toHaveLength(1); + expect(textBytes(complete.content)).toBe(delivery.complete_bytes); + + // Paging the cursor reproduces the complete retained Evidence exactly. + const joined = await pageEvidenceJson(client, delivery.next!); + expect(joined).toBe(JSON.stringify(complete.structuredContent)); + expect(JSON.parse(joined)).toEqual(complete.structuredContent); +}); + +it("delivers complete Evidence that fits, and follows a runtime budget override", async () => { + const client = await connect(); + const small = await entropyTarget(4096); + const fitting = await client.callTool({ + name: "inspect_byte_entropy", + arguments: small, + }); + expect(parseEvidence(fitting.structuredContent).operation).toBe( + "inspect_byte_entropy", + ); + + const large = await entropyTarget(1024 * 1024); + const updated = await client.callTool({ + name: "update_analysis_settings", + arguments: { + changes: [ + { + setting: AGENT_RESULT_BUDGET_SETTING, + action: "set", + value: 10 * 1024 * 1024, + }, + ], + }, + }); + expect(updated.isError).not.toBe(true); + const raised = await client.callTool({ + name: "inspect_byte_entropy", + arguments: large, + }); + expect(parseEvidence(raised.structuredContent).operation).toBe( + "inspect_byte_entropy", + ); +}); + +it("budgets tools whose SDK schema defers validation to the application", async () => { + const fixture = analysisViewLayoutFixture(); + // Enough symbol rows to exceed the smallest budget. + const layout = { + ...fixture, + symbols: [ + ...fixture.symbols, + ...Array.from({ length: 16 }, (_, index) => ({ + ...fixture.symbols[0]!, + entry_index: fixture.symbols.length + index, + })), + ], + }; + const session = createTestBinarySession(() => { + throw new Error("Layout inspection must not start a deep provider"); + }); + const server = createServer( + { kind: "session", session }, + { + binaryLayout: new BinaryLayoutService({ + inspectAndClose(input, options) { + return this.inspect(input, options); + }, + identity: BINARY_LAYOUT_TEST_PROVIDER, + inspect: () => Promise.resolve(ok(layout)), + }), + }, + ); + const client = new Client( + { name: "agent-result-budget-layout", version: "1" }, + { jsonSchemaValidator: createMcpSchemaValidation() }, + ); + onTestFinished(async () => { + await client.close(); + await server.close(); + await session.close(); + }); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + const lowered = await client.callTool({ + name: "update_analysis_settings", + arguments: { + changes: [ + { + setting: AGENT_RESULT_BUDGET_SETTING, + action: "set", + value: MINIMUM_AGENT_RESULT_BUDGET_BYTES, + }, + ], + }, + }); + expect(lowered.isError).not.toBe(true); + const target = { path: layout.artifact.path }; + const complete = await client.callTool({ + name: "inspect_binary_layout", + arguments: { ...target, detail: "complete" }, + }); + expect(textBytes(complete.content)).toBeGreaterThan( + MINIMUM_AGENT_RESULT_BUDGET_BYTES, + ); + const budgeted = await client.callTool({ + name: "inspect_binary_layout", + arguments: target, + }); + expect(budgeted.isError).not.toBe(true); + expect(parseEvidence(budgeted.structuredContent).operation).toBe( + "inspect_analysis_view", + ); + expect(deliveryOf(budgeted)).toMatchObject({ + budget_bytes: MINIMUM_AGENT_RESULT_BUDGET_BYTES, + evidence_id: parseEvidence(complete.structuredContent).evidence_id, + }); +}); + +it("writes nothing for CLI overflow without --evidence_output and names both rerun commands", async () => { + const input = await entropyTarget(1024 * 1024); + // Every location a spill could use is a fresh, empty directory. + const home = await createTestTempDirectory("rea-agent-budget-home-"); + const temporary = await createTestTempDirectory("rea-agent-budget-tmp-"); + const cache = await createTestTempDirectory("rea-agent-budget-cache-"); + const environment = { + HOME: home, + TMPDIR: temporary, + XDG_CACHE_HOME: cache, + XDG_STATE_HOME: cache, + PATH: process.env.PATH ?? "/usr/bin:/bin", + }; + const argv = [ + "inspect-byte-entropy", + input.path, + "--block-size", + "256", + "--json", + ]; + let stdout = ""; + let exitCode = 0; + await createCli(environment).serve([...argv], { + env: environment, + exit: (code) => { + exitCode = code; + }, + stdout: (text) => { + stdout += text; + }, + }); + expect(exitCode, stdout).toBe(0); + const output = JSON.parse(stdout) as { + readonly summary: unknown; + readonly delivery: Delivery & { + readonly rerun: { + readonly complete: readonly string[]; + readonly retained: readonly string[]; + }; + }; + readonly evidence_bundle?: unknown; + }; + expect(parseEvidence(output.summary).operation).toBe("inspect_analysis_view"); + expect(output.evidence_bundle).toBeUndefined(); + expect(output.delivery).toMatchObject({ retained: "not-retained" }); + // Only the arguments to add: caller inputs, which can carry access + // credentials such as a browser socket ID, are never echoed. + expect(output.delivery.rerun).toEqual({ + complete: ["--detail", "complete"], + retained: ["--evidence_output", EVIDENCE_OUTPUT_PLACEHOLDER], + }); + expect(JSON.stringify(output.delivery)).not.toContain(input.path); + expect(output.delivery.note).toContain("--detail complete"); + expect(output.delivery.note).toContain("--evidence_output"); + for (const directory of [home, temporary, cache]) + expect(await readdir(directory)).toEqual([]); + expect(await readdir(join(input.path, ".."))).toEqual(["bytes"]); +}); + +it("keeps admission refusals unchanged by the delivery budget", async () => { + const client = await connect(); + // 32,769 blocks of 256 bytes exceed the 32,768-block admission limit. + const input = await entropyTarget(256 * 32_769); + for (const detail of [undefined, "complete"] as const) { + const refused = await client.callTool({ + name: "inspect_byte_entropy", + arguments: detail === undefined ? input : { ...input, detail }, + }); + expect(refused.isError).toBe(true); + const [first] = refused.content as { type: string; text: string }[]; + expect(JSON.parse(first!.text)).toMatchObject({ + error: { code: "resource_constraint" }, + }); + } +}); + +it("delivers a target failure unchanged by the delivery budget", async () => { + const client = await connect(); + const updated = await client.callTool({ + name: "update_analysis_settings", + arguments: { + changes: [ + { + setting: AGENT_RESULT_BUDGET_SETTING, + action: "set", + value: MINIMUM_AGENT_RESULT_BUDGET_BYTES, + }, + ], + }, + }); + expect(updated.isError).not.toBe(true); + const root = await createTestTempDirectory("rea-agent-budget-failure-"); + const path = join(root, "not-rust"); + await writeFile(path, randomBytes(4096)); + const omitted = await client.callTool({ + name: "inspect_rust_binary", + arguments: { path }, + }); + const complete = await client.callTool({ + name: "inspect_rust_binary", + arguments: { path, detail: "complete" }, + }); + expect(omitted.isError).toBe(true); + const [first] = omitted.content as { type: string; text: string }[]; + expect(JSON.parse(first!.text)).toMatchObject({ + error: { code: "unsupported_target" }, + }); + // The failure keeps its own projection: no summary, no delivery facts. + expect(omitted._meta?.[AGENT_BUDGET_DELIVERY_META]).toBeUndefined(); + expect(omitted).toEqual(complete); +}); + +it("delivers the same over-budget summary through CLI publication, with complete Evidence in the bundle", async () => { + const input = await entropyTarget(1024 * 1024); + const inspected = await createByteEntropyService().inspect(input); + if (!inspected.ok) throw inspected.error; + const complete = inspected.value; + const publish = ( + detail: "complete" | "summary" | undefined, + evidenceOutput?: string, + ) => + publishCliAnalysisEvidence(inspected, { + operation: "inspect_byte_entropy", + signal: new AbortController().signal, + detail, + evidenceOutput, + }); + + const unretained = (await publish(undefined)) as { + readonly summary: unknown; + readonly delivery: Delivery; + }; + const unretainedSummary = parseEvidence(unretained.summary); + expect(unretainedSummary.operation).toBe("inspect_analysis_view"); + expect( + (unretainedSummary.normalized_result as { parent_evidence_id: string }) + .parent_evidence_id, + ).toBe(complete.evidence_id); + expect(unretained.delivery).toMatchObject({ + retained: "not-retained", + evidence_id: complete.evidence_id, + }); + expect(unretained.delivery.next).toBeUndefined(); + expect(parseEvidence(await publish("complete")).evidence_id).toBe( + complete.evidence_id, + ); + // The invocation's captured seed, a valid value below the result size, + // decides the budget. + const seeded = (await withCliEvidencePublication(() => publish(undefined), { + agentBudgetSeed: "8192", + })) as { readonly delivery: Delivery & { readonly budget_source: string } }; + expect(seeded.delivery).toMatchObject({ + budget_bytes: 8192, + budget_source: "setting", + }); + + const bundle = join( + await createTestTempDirectory("rea-agent-budget-bundle-"), + "evidence.json", + ); + const published = (await publish(undefined, bundle)) as { + readonly summary: Evidence; + readonly evidence_bundle: { readonly path: string }; + readonly delivery: Delivery; + }; + expect(published.summary.operation).toBe("inspect_analysis_view"); + expect(published.evidence_bundle.path).toBe(bundle); + expect(published.delivery.next?.arguments.source).toEqual({ + kind: "evidence-file", + path: bundle, + evidence_id: complete.evidence_id, + }); + const page = await inspectAnalysisView({ + ...published.delivery.next!.arguments, + view: { kind: "evidence-json", offset: 0, limit: 1_048_576 }, + }); + if (!page.ok) throw page.error; + const { text } = page.value.normalized_result as unknown as EvidenceJsonPage; + expect(JSON.parse(text)).toEqual(JSON.parse(JSON.stringify(complete))); +}); diff --git a/tests/boundary/mcp/analysisSnapshotProvenanceMcp.test.ts b/tests/boundary/mcp/analysisSnapshotProvenanceMcp.test.ts index 421a38f2ad1..63e5e88569a 100644 --- a/tests/boundary/mcp/analysisSnapshotProvenanceMcp.test.ts +++ b/tests/boundary/mcp/analysisSnapshotProvenanceMcp.test.ts @@ -161,7 +161,7 @@ for (const missingSource of [false, true]) const client = await mcp.connect(server); const response = await client.callTool({ name: "inspect_managed_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); if (missingSource) { expect(parseMcpToolError(response)).toMatchObject({ @@ -255,7 +255,7 @@ for (const missingSource of [false, true]) ); const refreshedResponse = await client.callTool({ name: "inspect_managed_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect( refreshedResponse.isError, diff --git a/tests/boundary/mcp/analysisSummaryDetailMcp.test.ts b/tests/boundary/mcp/analysisSummaryDetailMcp.test.ts index c1596ff365a..c19606ea598 100644 --- a/tests/boundary/mcp/analysisSummaryDetailMcp.test.ts +++ b/tests/boundary/mcp/analysisSummaryDetailMcp.test.ts @@ -80,7 +80,7 @@ it("returns the summary of complete Evidence retained for later views", async () const input = await application(); const complete = await client.callTool({ name: contract.name, - arguments: input, + arguments: { ...input, detail: "complete" }, }); expect(complete.isError).not.toBe(true); const completeEvidence = contract.outputSchema.parse( diff --git a/tests/boundary/mcp/analysisViewMcp.test.ts b/tests/boundary/mcp/analysisViewMcp.test.ts index e05d25c2180..526192ecd44 100644 --- a/tests/boundary/mcp/analysisViewMcp.test.ts +++ b/tests/boundary/mcp/analysisViewMcp.test.ts @@ -631,7 +631,7 @@ it("advertises exact schemas and projects one layout section from retained Evide ).toBe(false); const inspected = await client.callTool({ name: "inspect_binary_layout", - arguments: { path: layout.artifact.path }, + arguments: { detail: "complete", path: layout.artifact.path }, }); expect(inspected.isError).not.toBe(true); const parent = toolContract("inspect_binary_layout").outputSchema.parse( @@ -1374,7 +1374,7 @@ it("projects an actual HAR capture retained by the public MCP workflow", async ( const { client } = await connect(undefined, service); const captureResponse = await client.callTool({ name: "inspect_web_network_capture", - arguments: { capture_path: path, format: "har" }, + arguments: { detail: "complete", capture_path: path, format: "har" }, }); expect(captureResponse.isError).not.toBe(true); const parent = parseEvidence(captureResponse.structuredContent); @@ -1455,7 +1455,7 @@ it.each(PUBLISHED_EXAMPLES)( const { client } = await connect(undefined, service); const capture = await client.callTool({ name: "inspect_web_network_capture", - arguments: { capture_path: path, format: "har" }, + arguments: { detail: "complete", capture_path: path, format: "har" }, }); expect(parseEvidence(capture.structuredContent).evidence_id).toBe( example.input.source.evidence_id, diff --git a/tests/boundary/mcp/androidLateCompletionMcp.test.ts b/tests/boundary/mcp/androidLateCompletionMcp.test.ts index c8135c2a615..5f7be389a53 100644 --- a/tests/boundary/mcp/androidLateCompletionMcp.test.ts +++ b/tests/boundary/mcp/androidLateCompletionMcp.test.ts @@ -71,7 +71,7 @@ it("retains completed Android Evidence through the MCP cancellation delivery pat await client.connect(clientTransport); const request = { name: "inspect_android_package", - arguments: { path: fixture.apk }, + arguments: { detail: "complete", path: fixture.apk }, }; const controlReply = await client.callTool(request); expect(controlReply.isError).not.toBe(true); diff --git a/tests/boundary/mcp/artifactArmSlicesMcp.test.ts b/tests/boundary/mcp/artifactArmSlicesMcp.test.ts index a8546d5afa4..688507b72f4 100644 --- a/tests/boundary/mcp/artifactArmSlicesMcp.test.ts +++ b/tests/boundary/mcp/artifactArmSlicesMcp.test.ts @@ -35,7 +35,7 @@ describe.skipIf(process.platform !== "darwin")( expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true); const inspected = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(inspected.isError, JSON.stringify(inspected.content)).not.toBe( true, diff --git a/tests/boundary/mcp/artifactInspectionCoverageMcp.test.ts b/tests/boundary/mcp/artifactInspectionCoverageMcp.test.ts index 22e4b44ab61..6e9f29245e7 100644 --- a/tests/boundary/mcp/artifactInspectionCoverageMcp.test.ts +++ b/tests/boundary/mcp/artifactInspectionCoverageMcp.test.ts @@ -84,7 +84,7 @@ describe.skipIf(process.platform === "win32")( expect(opened.isError, JSON.stringify(opened)).not.toBe(true); const inspected = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(inspected.isError, JSON.stringify(inspected)).not.toBe(true); const parent = parseEvidence(inspected.structuredContent); diff --git a/tests/boundary/mcp/artifactMcp.inlineInventory.test.ts b/tests/boundary/mcp/artifactMcp.inlineInventory.test.ts index 0237f338ffe..5781dcad1af 100644 --- a/tests/boundary/mcp/artifactMcp.inlineInventory.test.ts +++ b/tests/boundary/mcp/artifactMcp.inlineInventory.test.ts @@ -306,7 +306,8 @@ const assertSummaryDelivery = async ( session: ReturnType, complete: Evidence, ) => { - expect(complete.parameters).not.toHaveProperty("detail"); + // Explicit complete delivery is recorded with the caller's choice. + expect(complete.parameters).toMatchObject({ detail: "complete" }); const reply = await client.callTool({ name: "inspect_artifact", arguments: { detail: "summary" }, @@ -417,7 +418,7 @@ mcpTest( expect(opened.isError).not.toBe(true); const result = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(result.isError, JSON.stringify(result.structuredContent)).not.toBe( true, diff --git a/tests/boundary/mcp/artifactMcp.test.ts b/tests/boundary/mcp/artifactMcp.test.ts index ea22ef1d865..261b42ed7da 100644 --- a/tests/boundary/mcp/artifactMcp.test.ts +++ b/tests/boundary/mcp/artifactMcp.test.ts @@ -163,7 +163,7 @@ it.for([ const result = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(result.isError).toBe(true); const projected = parseMcpToolError(result); @@ -281,7 +281,7 @@ it("preserves raw legacy ZIP name bytes and CP437 path interpretation through MC expect(opened.isError).not.toBe(true); const inspected = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(inspected.isError).not.toBe(true); const result = toolEvidence(inspected.structuredContent); @@ -399,6 +399,7 @@ it("records an explicitly continued mismatch, preserves verified siblings, and n const result = await client.callTool({ name: "inspect_artifact", arguments: { + detail: "complete", integrity_policy: "record-and-continue", }, }); @@ -609,7 +610,7 @@ it("returns full artifact graphs inline and compares changed inventories", async expect(opened.isError).not.toBe(true); const inspected = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(inspected.isError).not.toBe(true); const inspectionResult = toolEvidence(inspected.structuredContent); @@ -641,7 +642,7 @@ it("returns full artifact graphs inline and compares changed inventories", async ]); const inventory = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(inventory.isError).not.toBe(true); const inventoryResult = toolEvidence(inventory.structuredContent); @@ -678,7 +679,7 @@ it("returns full artifact graphs inline and compares changed inventories", async expect(openedChanged.isError).not.toBe(true); const changedInventory = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); const changedResult = toolEvidence(changedInventory.structuredContent); const changedInspection = z @@ -840,7 +841,7 @@ const inspectArtifactInventoryThroughMcp = async ( expect(opened.isError).not.toBe(true); const reply = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(reply.isError).not.toBe(true); const inspection = artifactInspectionResultSchema.parse( @@ -1390,7 +1391,10 @@ it("attributes ASAR integrity contradictions to their actual inputs and withhold ).not.toBe(true); const inspected = await client.callTool({ name: "inspect_artifact", - arguments: { integrity_policy: "record-and-continue" }, + arguments: { + detail: "complete", + integrity_policy: "record-and-continue", + }, }); expect(inspected.isError).not.toBe(true); observations.push(toolEvidence(inspected.structuredContent)); diff --git a/tests/boundary/mcp/batchSourcePublicationCleanup.test.ts b/tests/boundary/mcp/batchSourcePublicationCleanup.test.ts index 6a6e3916c30..7268c1f009d 100644 --- a/tests/boundary/mcp/batchSourcePublicationCleanup.test.ts +++ b/tests/boundary/mcp/batchSourcePublicationCleanup.test.ts @@ -131,6 +131,7 @@ it("keeps a batch cleanup owner and its completed prefix after source retention (await call("open_binary", { path: target, format: "dos-com" })).isError, ).not.toBe(true); const response = await call("batch_decompile", { + detail: "complete", addresses: ["first", "second"], }); expectRecoveredBatch(response, owned); diff --git a/tests/boundary/mcp/batchSourcePublicationRecovery.test.ts b/tests/boundary/mcp/batchSourcePublicationRecovery.test.ts index ed7e6d42455..076ebfe6105 100644 --- a/tests/boundary/mcp/batchSourcePublicationRecovery.test.ts +++ b/tests/boundary/mcp/batchSourcePublicationRecovery.test.ts @@ -98,7 +98,7 @@ it.each([ await client.connect(ct); const response = await client.callTool({ name: "batch_decompile", - arguments: { addresses: ["example"] }, + arguments: { detail: "complete", addresses: ["example"] }, }); expect(response.isError).toBe(true); const error = parseMcpToolError(response).error; diff --git a/tests/boundary/mcp/binaryDiagnosticsMcp.test.ts b/tests/boundary/mcp/binaryDiagnosticsMcp.test.ts index 4be7ddd2ef0..dbae1f470bd 100644 --- a/tests/boundary/mcp/binaryDiagnosticsMcp.test.ts +++ b/tests/boundary/mcp/binaryDiagnosticsMcp.test.ts @@ -79,7 +79,7 @@ it("reports the exhausted native export allowance through MCP", async () => { await writeFile(path, fixture.bytes); const response = await client.callTool({ name: "inspect_native_exports", - arguments: { path }, + arguments: { detail: "complete", path }, }); const { error } = parseMcpToolError(response); expect(error).toMatchObject({ @@ -231,7 +231,7 @@ it.each([false, true])( await client.connect(clientTransport); const response = await client.callTool({ name: "inspect_byte_entropy", - arguments: { path, block_size: 256 }, + arguments: { detail: "complete", path, block_size: 256 }, }); const failure = parseMcpToolError(response).error; expect(failure).toMatchObject({ @@ -333,7 +333,10 @@ it("records inline layout with compact schemas and canonical path checks", async }), ).toBe(false); const response = await client.callTool( - { name: "inspect_binary_layout", arguments: { path: value.artifact.path } }, + { + name: "inspect_binary_layout", + arguments: { detail: "complete", path: value.artifact.path }, + }, { toolDefinition: schemas.toolDefinition }, ); const evidence = assertRecordedMcpEvidence( @@ -365,7 +368,7 @@ it("records inline layout with compact schemas and canonical path checks", async }); const relative = await client.callTool({ name: "inspect_binary_layout", - arguments: { path: "relative.elf" }, + arguments: { detail: "complete", path: "relative.elf" }, }); expect(parseMcpToolError(relative).error.code).toBe("invalid_request"); expect(providerCalls).toBe(1); @@ -418,7 +421,7 @@ it("profiles real bytes with exact offsets, valid advertised schemas and read-on ); expect(ajv.validate(inputSchema, { path, surprise: true })).toBe(false); const response = await client.callTool( - { name: "inspect_byte_entropy", arguments: { path } }, + { name: "inspect_byte_entropy", arguments: { detail: "complete", path } }, { toolDefinition }, ); expect(response.isError).not.toBe(true); @@ -447,7 +450,7 @@ it("profiles real bytes with exact offsets, valid advertised schemas and read-on ( await client.callTool({ name: "inspect_byte_entropy", - arguments: { path, offset: 999999 }, + arguments: { detail: "complete", path, offset: 999999 }, }) ).isError, ).toBe(true); @@ -488,7 +491,7 @@ it("records a portable export inventory through MCP without a binary target", as ); expect(schemas.ajv.validate(schemas.inputSchema, { path })).toBe(true); const response = await client.callTool( - { name: "inspect_native_exports", arguments: { path } }, + { name: "inspect_native_exports", arguments: { detail: "complete", path } }, { toolDefinition: schemas.toolDefinition }, ); expect( @@ -520,7 +523,7 @@ it("records a portable export inventory through MCP without a binary target", as ); const relative = await client.callTool({ name: "inspect_native_exports", - arguments: { path: "relative.so" }, + arguments: { detail: "complete", path: "relative.so" }, }); expect(parseMcpToolError(relative).error).toMatchObject({ code: "invalid_request", diff --git a/tests/boundary/mcp/browserMcp.test.ts b/tests/boundary/mcp/browserMcp.test.ts index cefa90686bb..f6ea8d03ffd 100644 --- a/tests/boundary/mcp/browserMcp.test.ts +++ b/tests/boundary/mcp/browserMcp.test.ts @@ -32,6 +32,7 @@ import { type FakeCdpBrowser, type FakeOptions, } from "../../fixtures/fakeCdpBrowser.js"; +import { COMPLETE_DETAIL } from "../../support/completeDetail.js"; const schemaValidation = createMcpSchemaValidation(); const resources = new ArtifactResourceScope(); @@ -259,6 +260,7 @@ cliTest( const cliResult = await cli.run({ arguments: [ "analyze-web-bundle", + ...COMPLETE_DETAIL, browser.endpoint, "allowed-page", "--allowed-origins", @@ -446,6 +448,7 @@ it("exposes CLI-equivalent Evidence results and session tools", async () => { const analyzed = await connected.client.callTool({ name: "analyze_web_bundle", arguments: { + detail: "complete", cdp_endpoint: browser.endpoint, target_id: "allowed-page", observation_ms: 0, @@ -774,6 +777,7 @@ cliTest( const result = await connected.client.callTool({ name: "analyze_web_bundle", arguments: { + detail: "complete", cdp_endpoint: browser.endpoint, target_id: "allowed-page", allowed_origins: [browser.allowedOrigin], @@ -812,6 +816,7 @@ cliTest( const cliResult = await cli.run({ arguments: [ "analyze-web-bundle", + ...COMPLETE_DETAIL, browser.endpoint, "allowed-page", "--allowed-origins", diff --git a/tests/boundary/mcp/browserScenarioInputDiagnosticsMcp.test.ts b/tests/boundary/mcp/browserScenarioInputDiagnosticsMcp.test.ts index 4e089203d12..bf4244ae1b8 100644 --- a/tests/boundary/mcp/browserScenarioInputDiagnosticsMcp.test.ts +++ b/tests/boundary/mcp/browserScenarioInputDiagnosticsMcp.test.ts @@ -12,6 +12,7 @@ import { } from "../../fixtures/mcpToolError.js"; import { cliTest } from "../../support/cli/cliFixture.js"; import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; +import { COMPLETE_DETAIL } from "../../support/completeDetail.js"; // Compile SDK output validators for the tools a test calls, not the whole catalog. const schemaValidation = createMcpSchemaValidation(); @@ -140,6 +141,7 @@ cliTest( const cliResult = await cli.run({ arguments: [ "capture-browser-scenario", + ...COMPLETE_DETAIL, JSON.stringify(input), "--json", ], diff --git a/tests/boundary/mcp/bunStandaloneMcp.test.ts b/tests/boundary/mcp/bunStandaloneMcp.test.ts index 3f032f43d78..c6dcb8aadbe 100644 --- a/tests/boundary/mcp/bunStandaloneMcp.test.ts +++ b/tests/boundary/mcp/bunStandaloneMcp.test.ts @@ -87,7 +87,10 @@ it("keeps a budget-limited Bun layout unresolved through MCP", async () => { for (const moduleCount of [9, 13]) { const reply = await client.callTool({ name: "inspect_artifact", - arguments: { artifact_limits: { bun: { module_count: moduleCount } } }, + arguments: { + detail: "complete", + artifact_limits: { bun: { module_count: moduleCount } }, + }, }); expect(reply.isError).toBe(true); expect(parseMcpToolError(reply).error).toMatchObject({ diff --git a/tests/boundary/mcp/capabilityRemediationMcp.test.ts b/tests/boundary/mcp/capabilityRemediationMcp.test.ts index 0c86383f608..76e57d88300 100644 --- a/tests/boundary/mcp/capabilityRemediationMcp.test.ts +++ b/tests/boundary/mcp/capabilityRemediationMcp.test.ts @@ -231,7 +231,7 @@ it.skipIf(process.platform === "win32")( const failed = (await client.callTool({ name: "inspect_with_objdump", - arguments: { operation: "architectures" }, + arguments: { detail: "complete", operation: "architectures" }, })) as CallToolResult; expect(failed.isError).toBe(true); const parsedFailure = parseMcpToolError(failed); @@ -266,7 +266,7 @@ it.skipIf(process.platform === "win32")( const retried = await client.callTool({ name: "inspect_with_objdump", - arguments: { operation: "architectures" }, + arguments: { detail: "complete", operation: "architectures" }, }); expect(retried.isError).not.toBe(true); diff --git a/tests/boundary/mcp/commandObservationViews.test.ts b/tests/boundary/mcp/commandObservationViews.test.ts index 35a61277b29..0057c21f16b 100644 --- a/tests/boundary/mcp/commandObservationViews.test.ts +++ b/tests/boundary/mcp/commandObservationViews.test.ts @@ -120,7 +120,7 @@ it("delivers ordered GDB records once and queries their retained parent after cl ); const input = { session_id: sessionId, command: capture.command }; const full = await client.callTool( - { name: "gdb_console", arguments: input }, + { name: "gdb_console", arguments: { ...input, detail: "complete" } }, { toolDefinition: schemas.toolDefinition }, ); const summary = await client.callTool( @@ -191,7 +191,10 @@ it("keeps pathless objdump observations subjectless and preserves the default co }), ).toBe(true); const full = await client.callTool( - { name: "inspect_with_objdump", arguments: { operation: "architectures" } }, + { + name: "inspect_with_objdump", + arguments: { detail: "complete", operation: "architectures" }, + }, { toolDefinition: schemas.toolDefinition }, ); const selected = await client.callTool( diff --git a/tests/boundary/mcp/completeEvidenceByDefault.test.ts b/tests/boundary/mcp/completeEvidenceByDefault.test.ts new file mode 100644 index 00000000000..dbdbda5a169 --- /dev/null +++ b/tests/boundary/mcp/completeEvidenceByDefault.test.ts @@ -0,0 +1,54 @@ +import { expect, it } from "vitest"; + +import { + completeEvidenceArguments, + completeEvidenceCliArguments, +} from "../../support/completeEvidenceByDefault.js"; + +it("requests complete Evidence only for budgeted tools that select neither detail nor view", () => { + expect( + completeEvidenceArguments("inspect_managed_members", { path: "/a" }), + ).toEqual({ + path: "/a", + detail: "complete", + }); + expect(completeEvidenceArguments("inspect_artifact", undefined)).toEqual({ + detail: "complete", + }); + for (const selected of [ + { path: "/a", detail: "summary" }, + { path: "/a", detail: "complete" }, + { path: "/a", view: { kind: "summary" } }, + ]) + expect(completeEvidenceArguments("inspect_managed_members", selected)).toBe( + selected, + ); + // A tool whose omitted detail is not budgeted, and a forwarded upstream + // tool, are sent as written. + const desktop = { path: "/apps/game" }; + expect( + completeEvidenceArguments("inspect_desktop_application", desktop), + ).toBe(desktop); + const forwarded = { x: 1 }; + expect(completeEvidenceArguments("computer_click", forwarded)).toBe( + forwarded, + ); +}); + +it("adds --detail complete to budgeted CLI commands under the same rule", async () => { + expect( + await completeEvidenceCliArguments([ + "inspect-byte-entropy", + "/f", + "--json", + ]), + ).toEqual(["inspect-byte-entropy", "--detail", "complete", "/f", "--json"]); + for (const argv of [ + ["inspect-byte-entropy", "/f", "--detail", "summary", "--json"], + ["inspect-byte-entropy", "/f", "--detail=summary"], + ["inspect-rust-binary", "/f", "--view", "{}"], + ["inspect-binary-layout", "/f", "--json"], + ["doctor"], + ]) + expect(await completeEvidenceCliArguments(argv)).toBe(argv); +}); diff --git a/tests/boundary/mcp/completionInventoryAliasMcp.test.ts b/tests/boundary/mcp/completionInventoryAliasMcp.test.ts index 324a2cad7cc..5adbb241016 100644 --- a/tests/boundary/mcp/completionInventoryAliasMcp.test.ts +++ b/tests/boundary/mcp/completionInventoryAliasMcp.test.ts @@ -56,7 +56,7 @@ it.each([false, true])( await client.connect(clientTransport); const listed = await client.callTool({ name: "list_procedures", - arguments: {}, + arguments: { detail: "complete" }, }); expect(listed.isError).not.toBe(true); expect(listed.structuredContent).toMatchObject({ diff --git a/tests/boundary/mcp/debuggerExternalMutationLifecycleMcp.test.ts b/tests/boundary/mcp/debuggerExternalMutationLifecycleMcp.test.ts index 700ca3b70f9..474f5d9a63e 100644 --- a/tests/boundary/mcp/debuggerExternalMutationLifecycleMcp.test.ts +++ b/tests/boundary/mcp/debuggerExternalMutationLifecycleMcp.test.ts @@ -185,9 +185,15 @@ const GDB: Debugger = { session, { recordEvidence }, ), - command: { name: "gdb_console", arguments: GDB_CONSOLE }, + command: { + name: "gdb_console", + arguments: { ...GDB_CONSOLE, detail: "complete" }, + }, next: { - call: { name: "gdb_console", arguments: GDB_CONSOLE }, + call: { + name: "gdb_console", + arguments: { ...GDB_CONSOLE, detail: "complete" }, + }, runs: "execute", }, close: { name: "close_gdb_session", arguments: { session_id: SESSION_ID } }, diff --git a/tests/boundary/mcp/desktopApplicationMcp.test.ts b/tests/boundary/mcp/desktopApplicationMcp.test.ts index 9d99d5b6dff..625962a6b7a 100644 --- a/tests/boundary/mcp/desktopApplicationMcp.test.ts +++ b/tests/boundary/mcp/desktopApplicationMcp.test.ts @@ -74,7 +74,7 @@ it.each([false, true])( expect(selected.isError).not.toBe(true); const inspected = await harness.client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(inspected.isError).not.toBe(true); const inspection = artifactInspectionResultSchema.parse( diff --git a/tests/boundary/mcp/devicetreeMcp.test.ts b/tests/boundary/mcp/devicetreeMcp.test.ts index c8ef0dcf06c..8ccb28e9498 100644 --- a/tests/boundary/mcp/devicetreeMcp.test.ts +++ b/tests/boundary/mcp/devicetreeMcp.test.ts @@ -244,7 +244,7 @@ mcpTest("rejects relative paths and unsupported versions", async ({ mcp }) => { try { const response = await client.callTool({ name: "inspect_devicetree", - arguments: { path: "board.dtb" }, + arguments: { detail: "complete", path: "board.dtb" }, }); expect(parseMcpToolError(response).error).toMatchObject({ code: "invalid_request", @@ -254,7 +254,7 @@ mcpTest("rejects relative paths and unsupported versions", async ({ mcp }) => { await writeFile(path, devicetreeFixture(undefined, 18)); const unsupported = await client.callTool({ name: "inspect_devicetree", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(parseMcpToolError(unsupported).error).toMatchObject({ code: "unsupported_target", diff --git a/tests/boundary/mcp/electronMcp.test.ts b/tests/boundary/mcp/electronMcp.test.ts index 1971bf34b28..8f18adeec02 100644 --- a/tests/boundary/mcp/electronMcp.test.ts +++ b/tests/boundary/mcp/electronMcp.test.ts @@ -74,6 +74,7 @@ it("retains failed JavaScript inventory cleanup through server shutdown retries" const response = await client.callTool({ name: "analyze_javascript_application", arguments: { + detail: "complete", input_path: archive, integrity_policy: "record-and-continue", }, @@ -212,7 +213,7 @@ it("lets MCP JavaScript analysis continue only with recorded untrusted ASAR byte const rejected = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: archive }, + arguments: { detail: "complete", input_path: archive }, }); expect(parseMcpToolError(rejected)).toMatchObject({ error: { @@ -226,6 +227,7 @@ it("lets MCP JavaScript analysis continue only with recorded untrusted ASAR byte const continued = await client.callTool({ name: "analyze_javascript_application", arguments: { + detail: "complete", input_path: archive, integrity_policy: "record-and-continue", }, @@ -376,7 +378,7 @@ it("exposes endpoint-scoped Electron discovery and inspection as Evidence", asyn ); const analyzed = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: root }, + arguments: { detail: "complete", input_path: root }, }); expect(analyzed.isError).not.toBe(true); expect(analyzed.structuredContent).toMatchObject({ @@ -661,7 +663,7 @@ it("exposes the target-free static JavaScript application workflow", async () => const analyzed = await client.callTool( { name: "analyze_javascript_application", - arguments: { input_path: root }, + arguments: { detail: "complete", input_path: root }, }, { onprogress: (update) => progress.push(update.progress) }, ); @@ -763,13 +765,13 @@ it.skipIf(process.platform === "win32")( await client.connect(clientTransport); const initial = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: join(root, "app") }, + arguments: { detail: "complete", input_path: join(root, "app") }, }); expect(initial.isError, JSON.stringify(initial)).not.toBe(true); const initialEvidence = parseEvidence(initial.structuredContent); const refused = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: `${root}/file/../app` }, + arguments: { detail: "complete", input_path: `${root}/file/../app` }, }); expect(refused.isError).toBe(true); expect(parseMcpToolError(refused)).toMatchObject({ @@ -781,7 +783,7 @@ it.skipIf(process.platform === "win32")( const selected = `${root}/link/../app`; const admitted = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: selected }, + arguments: { detail: "complete", input_path: selected }, }); expect(admitted.isError, JSON.stringify(admitted)).not.toBe(true); const evidence = parseEvidence(admitted.structuredContent); diff --git a/tests/boundary/mcp/erlangBeamMcp.test.ts b/tests/boundary/mcp/erlangBeamMcp.test.ts index 32595ff727c..05808f93801 100644 --- a/tests/boundary/mcp/erlangBeamMcp.test.ts +++ b/tests/boundary/mcp/erlangBeamMcp.test.ts @@ -54,7 +54,7 @@ mcpTest( await writeFile(path, erlangBeamFixture("mcp_mod")); const response = await client.callTool({ name: "inspect_erlang_beam", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(response.isError, JSON.stringify(response.content)).not.toBe(true); const evidence = completeBeamEvidenceSchema.parse( @@ -159,7 +159,7 @@ mcpTest( ); const response = await client.callTool({ name: "inspect_erlang_beam", - arguments: { path: malformed, max_atoms: 1 }, + arguments: { detail: "complete", path: malformed, max_atoms: 1 }, }); expect(parseMcpToolError(response).error).toMatchObject({ code: "unsupported_target", @@ -207,7 +207,7 @@ mcpTest( await writeFile(path, erlangBeamFixture("without_retention")); const complete = await client.callTool({ name: "inspect_erlang_beam", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(complete.isError).not.toBe(true); expect( @@ -235,7 +235,7 @@ mcpTest( ); const response = await client.callTool({ name: "inspect_erlang_beam", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(parseMcpToolError(response).error).toMatchObject({ code: "unsupported_target", diff --git a/tests/boundary/mcp/errorEvidenceLifecycleMcp.test.ts b/tests/boundary/mcp/errorEvidenceLifecycleMcp.test.ts index c6e4da02e64..257ce3ddc21 100644 --- a/tests/boundary/mcp/errorEvidenceLifecycleMcp.test.ts +++ b/tests/boundary/mcp/errorEvidenceLifecycleMcp.test.ts @@ -42,7 +42,7 @@ const fixture = () => const invalidKey = `unexpected_${"x".repeat(6_000)}`; const invalidRequest = { name: "procedure_pseudo_code", - arguments: { [invalidKey]: true }, + arguments: { detail: "complete", [invalidKey]: true }, }; const retainedReference = (reply: CallToolResult): string => { const projected = parseMcpToolError(reply).error; diff --git a/tests/boundary/mcp/evmInterfaceMcp.test.ts b/tests/boundary/mcp/evmInterfaceMcp.test.ts index bb026d12545..13d9bb75daf 100644 --- a/tests/boundary/mcp/evmInterfaceMcp.test.ts +++ b/tests/boundary/mcp/evmInterfaceMcp.test.ts @@ -81,7 +81,6 @@ mcpTest( expect(inputSchema).toHaveProperty(["properties", "detail"], { type: "string", enum: ["complete", "summary"], - default: "complete", description: expect.stringContaining( "summary retains that complete Evidence", ), diff --git a/tests/boundary/mcp/flutterMcp.test.ts b/tests/boundary/mcp/flutterMcp.test.ts index 13dc221fe78..ef92371563a 100644 --- a/tests/boundary/mcp/flutterMcp.test.ts +++ b/tests/boundary/mcp/flutterMcp.test.ts @@ -243,7 +243,7 @@ it("advertises and enforces the same Unicode selector grammar through MCP", asyn ( await harness.client.callTool({ name: "inspect_dart_aot", - arguments: arguments_, + arguments: { ...arguments_, detail: "complete" }, }) ).isError, ).not.toBe(true); @@ -262,7 +262,7 @@ it("advertises and enforces the same Unicode selector grammar through MCP", asyn ); const refused = await harness.client.callTool({ name: "inspect_dart_aot", - arguments: arguments_, + arguments: { ...arguments_, detail: "complete" }, }); expect(parseMcpToolError(refused).error).toMatchObject({ code: "invalid_request", @@ -320,7 +320,11 @@ it("advertises an exact valid Flutter schema and records inline evidence through const inspected = await client.callTool({ name: "inspect_dart_aot", - arguments: { path: "/targets/gallery.apk", abi: "arm64-v8a" }, + arguments: { + detail: "complete", + path: "/targets/gallery.apk", + abi: "arm64-v8a", + }, }); expect(inspected.isError).not.toBe(true); const inspectedText = (inspected.content as { readonly text?: string }[]) diff --git a/tests/boundary/mcp/fridaLifecycleMcp.test.ts b/tests/boundary/mcp/fridaLifecycleMcp.test.ts index 07c97fdbde8..d0792ec176b 100644 --- a/tests/boundary/mcp/fridaLifecycleMcp.test.ts +++ b/tests/boundary/mcp/fridaLifecycleMcp.test.ts @@ -310,7 +310,7 @@ it.each(["attached", "during-resume", "after-resume"] as const)( const state = async () => { const result = await fixture.client.callTool({ name: "frida_session_status", - arguments: { session_id: id }, + arguments: { detail: "complete", session_id: id }, }); return fridaSessionStatusSchema.parse( toolContract("frida_session_status").outputSchema.parse( @@ -383,7 +383,7 @@ it("retains detached state and resume evidence when remote cleanup needs retry", expect((await close()).isError).toBe(true); const result = await fixture.client.callTool({ name: "frida_session_status", - arguments: { session_id: id }, + arguments: { detail: "complete", session_id: id }, }); expect( fridaSessionStatusSchema.parse( @@ -549,7 +549,7 @@ it.each([ ).toBeLessThanOrEqual(32_768); const status = await client.callTool({ name: "frida_session_status", - arguments: { session_id: sessionId }, + arguments: { detail: "complete", session_id: sessionId }, }); expect(status.isError).not.toBe(true); expect( @@ -638,7 +638,7 @@ it("declares non-destructive session mutation when status retains Evidence", asy expect((await bundle()).records).toHaveLength(0); const response = await client.callTool({ name: "frida_session_status", - arguments: { session_id: id }, + arguments: { detail: "complete", session_id: id }, }); expect(response.isError).not.toBe(true); const evidence = toolContract("frida_session_status").outputSchema.parse( @@ -688,7 +688,10 @@ it("declares non-destructive session mutation when status retains Evidence", asy const missing = await client.callTool({ name: "frida_session_status", - arguments: { session_id: "00000000-0000-4000-8000-000000000000" }, + arguments: { + detail: "complete", + session_id: "00000000-0000-4000-8000-000000000000", + }, }); expect(parseMcpToolError(missing)).toMatchObject({ error: { code: "invalid_request" }, @@ -1280,7 +1283,7 @@ it.each([ ( await fixture.client.callTool({ name: "frida_session_status", - arguments: { session_id: id }, + arguments: { detail: "complete", session_id: id }, }) ).isError, ).not.toBe(true); diff --git a/tests/boundary/mcp/gdbCancellationMcp.test.ts b/tests/boundary/mcp/gdbCancellationMcp.test.ts index 4475932a71d..9b3015f032f 100644 --- a/tests/boundary/mcp/gdbCancellationMcp.test.ts +++ b/tests/boundary/mcp/gdbCancellationMcp.test.ts @@ -122,7 +122,11 @@ process.stdin.on("data", (chunk) => { const command = await client.callTool({ name: "gdb_console", - arguments: { session_id: sessionId, command: "show version" }, + arguments: { + detail: "complete", + session_id: sessionId, + command: "show version", + }, }); expect(parseMcpToolError(command)).toMatchObject({ error: { code: "invalid_request" }, @@ -213,7 +217,11 @@ process.stdin.on("data", async (chunk) => { const command = client.callTool( { name: "gdb_console", - arguments: { session_id: sessionId, command: "shell sleep 600" }, + arguments: { + detail: "complete", + session_id: sessionId, + command: "shell sleep 600", + }, }, { signal: controller.signal }, ); @@ -237,7 +245,11 @@ process.stdin.on("data", async (chunk) => { parseMcpToolError( (await client.callTool({ name: "gdb_console", - arguments: { session_id: sessionId, command: "info registers" }, + arguments: { + detail: "complete", + session_id: sessionId, + command: "info registers", + }, })) as CallToolResult, ).error, ).toMatchObject({ @@ -510,6 +522,7 @@ it("records partial GDB Evidence from an MCP command error", async () => { const response = await client.callTool({ name: "gdb_console", arguments: { + detail: "complete", session_id: "00000000-0000-4000-8000-000000000001", command: "info registers", }, @@ -565,7 +578,11 @@ it("recovers only the owning debugger cleanup and reopens admitted analysis", as await client.connect(clientTransport); const command = await client.callTool({ name: "gdb_console", - arguments: { session_id: ownerId, command: "shell writer" }, + arguments: { + detail: "complete", + session_id: ownerId, + command: "shell writer", + }, }); expect(command.isError).toBe(true); diff --git a/tests/boundary/mcp/gdbCloseDisposition.test.ts b/tests/boundary/mcp/gdbCloseDisposition.test.ts index 2cd4da7e7fd..66209bcf438 100644 --- a/tests/boundary/mcp/gdbCloseDisposition.test.ts +++ b/tests/boundary/mcp/gdbCloseDisposition.test.ts @@ -76,7 +76,7 @@ createInterface({ input: process.stdin }).on('line', line => { ).session_id; const running = await client.callTool({ name: "gdb_console", - arguments: { session_id: sessionId, command: "run" }, + arguments: { detail: "complete", session_id: sessionId, command: "run" }, }); expect(running.isError).not.toBe(true); for (let attempt = 0; attempt < 2; attempt += 1) { @@ -103,7 +103,11 @@ createInterface({ input: process.stdin }).on('line', line => { } const disposed = await client.callTool({ name: "gdb_console", - arguments: { session_id: sessionId, command: disposition }, + arguments: { + detail: "complete", + session_id: sessionId, + command: disposition, + }, }); expect(disposed.isError).not.toBe(true); const closed = await client.callTool({ diff --git a/tests/boundary/mcp/gdbExecutableSelection.test.ts b/tests/boundary/mcp/gdbExecutableSelection.test.ts index c215ce73a27..0eef757f45a 100644 --- a/tests/boundary/mcp/gdbExecutableSelection.test.ts +++ b/tests/boundary/mcp/gdbExecutableSelection.test.ts @@ -30,6 +30,7 @@ import { fakeGdbStartupPreamble, } from "../providers/gdbTestHelpers.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { COMPLETE_DETAIL } from "../../support/completeDetail.js"; const selectedBytes = Buffer.from("caller-selected executable bytes\n"); const selectedDigest = createHash("sha256").update(selectedBytes).digest("hex"); @@ -57,6 +58,7 @@ it.skipIf(process.platform === "win32")( }); const reply = await serveInProcessCli(cli, [ "debug-with-gdb", + ...COMPLETE_DETAIL, "info files", "--executable", f.executable, @@ -286,7 +288,7 @@ it.skipIf(process.platform === "win32")( for (const command of ["info files", "file /other/file", "info files"]) { const reply = await f.client.callTool({ name: "gdb_console", - arguments: { session_id, command }, + arguments: { detail: "complete", session_id, command }, }); expect(reply.isError).not.toBe(true); const evidence = evidenceSchema.parse(reply.structuredContent); @@ -323,7 +325,7 @@ it.skipIf(process.platform === "win32")( const { session_id } = startSchema.parse(started.structuredContent); const reply = await f.client.callTool({ name: "gdb_console", - arguments: { session_id, command: "info files" }, + arguments: { detail: "complete", session_id, command: "info files" }, }); const evidence = evidenceSchema.parse(reply.structuredContent); expect(evidence.subject.identity).toMatchObject({ diff --git a/tests/boundary/mcp/ghidraMcpHarness.ts b/tests/boundary/mcp/ghidraMcpHarness.ts index dfc5f923439..269788a000e 100644 --- a/tests/boundary/mcp/ghidraMcpHarness.ts +++ b/tests/boundary/mcp/ghidraMcpHarness.ts @@ -8,6 +8,7 @@ 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 type { TestDelivery } from "../../support/completeEvidenceByDefault.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"; @@ -40,6 +41,8 @@ export const connectGhidraMcp = async ( readonly attestDosTargetSnapshot?: ReturnType["attestDosTargetSnapshot"]; readonly close?: ReturnType["close"]; readonly delivery?: ToolResultDelivery; + /** "budgeted" leaves an omitted detail to the agent result budget. */ + readonly testDelivery?: TestDelivery; readonly environment?: Readonly; readonly schemaValidator?: ReturnType; } = {}, @@ -84,6 +87,9 @@ export const connectGhidraMcp = async ( ...(fixture.schemaValidator === undefined ? {} : { schemaValidator: fixture.schemaValidator }), + ...(fixture.testDelivery === undefined + ? {} + : { testDelivery: fixture.testDelivery }), serverOptions: { logger: silentLogger, environment: { diff --git a/tests/boundary/mcp/ghidraReopen.test.ts b/tests/boundary/mcp/ghidraReopen.test.ts index a9bcd8e20a5..2dec821fedf 100644 --- a/tests/boundary/mcp/ghidraReopen.test.ts +++ b/tests/boundary/mcp/ghidraReopen.test.ts @@ -210,7 +210,7 @@ const connectGhidra = async () => { query: (addressSuffix: number) => mcp.callTool({ name: "list_strings", - arguments: { address: `0x200${addressSuffix}` }, + arguments: { detail: "complete", address: `0x200${addressSuffix}` }, }), }; }; diff --git a/tests/boundary/mcp/ghidraStartupCancellationMcp.test.ts b/tests/boundary/mcp/ghidraStartupCancellationMcp.test.ts index 4e284248796..5808b499010 100644 --- a/tests/boundary/mcp/ghidraStartupCancellationMcp.test.ts +++ b/tests/boundary/mcp/ghidraStartupCancellationMcp.test.ts @@ -104,7 +104,7 @@ it.each([0, 1])( calls.push( mcp .callTool( - { name: "list_strings", arguments: {} }, + { name: "list_strings", arguments: { detail: "complete" } }, { signal: controller.signal }, ) .then( @@ -133,7 +133,10 @@ it.each([0, 1])( expect(staying.value.isError).not.toBe(true); expect(startResults[1 - cancelledIndex]).toMatchObject({ ok: true }); expect(controllers[1 - cancelledIndex]?.signal.aborted).toBe(false); - const warm = await mcp.callTool({ name: "list_strings", arguments: {} }); + const warm = await mcp.callTool({ + name: "list_strings", + arguments: { detail: "complete" }, + }); expect(warm.isError).not.toBe(true); expect(startCount).toBe(3); expect(queryCount).toBe(2); diff --git a/tests/boundary/mcp/goBinaryMcp.test.ts b/tests/boundary/mcp/goBinaryMcp.test.ts index 17101522e99..ed606856dc2 100644 --- a/tests/boundary/mcp/goBinaryMcp.test.ts +++ b/tests/boundary/mcp/goBinaryMcp.test.ts @@ -98,7 +98,7 @@ mcpTest( }); inspection = client.callTool({ name: "inspect_go_binary", - arguments: { path }, + arguments: { detail: "complete", path }, }); await goInspection.reached(inspection, "Go inspection"); closing = client.callTool({ @@ -160,7 +160,7 @@ for (const expectedErrno of ["ELOOP", "ENAMETOOLONG"] as const) { ); const response = await client.callTool({ name: "inspect_go_binary", - arguments: { path }, + arguments: { detail: "complete", path }, }); const diagnostic = parseMcpToolError(response); expect(diagnostic.error).toMatchObject({ @@ -194,7 +194,7 @@ goMcpTest.skipIf(process.platform === "win32")( const rejected = await client.callTool({ name: "inspect_go_binary", - arguments: { path: selected }, + arguments: { detail: "complete", path: selected }, }); const diagnostic = parseMcpToolError(rejected).error; expect(diagnostic).toMatchObject({ @@ -208,7 +208,7 @@ goMcpTest.skipIf(process.platform === "win32")( const retried = await client.callTool({ name: "inspect_go_binary", - arguments: { path: original }, + arguments: { detail: "complete", path: original }, }); expect(retried.isError).not.toBe(true); }, @@ -226,7 +226,7 @@ for (const targetKind of ["dangling", "directory"] as const) { const rejected = await client.callTool({ name: "inspect_go_binary", - arguments: { path: selected }, + arguments: { detail: "complete", path: selected }, }); const diagnostic = parseMcpToolError(rejected).error; expect(diagnostic).toMatchObject({ @@ -255,7 +255,7 @@ goMcpTest( await writeFile(path, fixture.bytes); const response = await client.callTool({ name: "inspect_go_binary", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(response.isError).not.toBe(true); const evidence = evidenceResultOf(goBinarySchema).parse( @@ -277,7 +277,7 @@ goMcpTest( await writeFile(path, fixture.bytes); const response = await client.callTool({ name: "inspect_go_binary", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect( response.isError, @@ -352,7 +352,7 @@ goMcpTest( }); const nulPath = await client.callTool({ name: "inspect_go_binary", - arguments: { path: "/artifacts/\0program" }, + arguments: { detail: "complete", path: "/artifacts/\0program" }, }); expect(parseMcpToolError(nulPath)).toMatchObject({ error: { @@ -367,7 +367,7 @@ goMcpTest( }); await writeFile(path, fixture.bytes); const response = await client.callTool( - { name: "inspect_go_binary", arguments: { path } }, + { name: "inspect_go_binary", arguments: { detail: "complete", path } }, { toolDefinition: withCanonicalOutputSchema(advertised) }, ); expect(response.isError).not.toBe(true); @@ -387,7 +387,7 @@ goMcpTest( expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence); const invalid = await client.callTool({ name: "inspect_go_binary", - arguments: { path: "relative.bin" }, + arguments: { detail: "complete", path: "relative.bin" }, }); expect(parseMcpToolError(invalid)).toMatchObject({ error: { diff --git a/tests/boundary/mcp/goBinaryViews.test.ts b/tests/boundary/mcp/goBinaryViews.test.ts index 454656ea739..63beea950ed 100644 --- a/tests/boundary/mcp/goBinaryViews.test.ts +++ b/tests/boundary/mcp/goBinaryViews.test.ts @@ -119,7 +119,10 @@ goViewTest( "rejects authenticated inline and file parents with conflicting architecture", async ({ goViews: { client, root, call } }) => { const { path } = await writeGoModuleFixture(root); - const complete = await call("inspect_go_binary", { path }); + const complete = await call("inspect_go_binary", { + detail: "complete", + path, + }); const report = goBinarySchema.parse(complete.normalized_result); const conflicting = createEvidence( { @@ -175,7 +178,10 @@ goViewTest( ] = 0xff; const path = join(root, encoding); await writeFile(path, fixture.bytes); - const admitted = await call("inspect_go_binary", { path }); + const admitted = await call("inspect_go_binary", { + detail: "complete", + path, + }); const report = goBinarySchema.parse(admitted.normalized_result); const info = report.build_info; if (info === null) throw new Error("Expected observed build info"); @@ -258,7 +264,10 @@ goViewTest( "retains exact Go rows and complete Evidence after source removal", async ({ goViews: { client, root, call } }) => { const { path, bytes } = await writeGoModuleFixture(root); - const complete = await call("inspect_go_binary", { path }); + const complete = await call("inspect_go_binary", { + detail: "complete", + path, + }); const summary = await call("inspect_go_binary", { path, detail: "summary", diff --git a/tests/boundary/mcp/javascriptAnalysisResources.test.ts b/tests/boundary/mcp/javascriptAnalysisResources.test.ts index 9cc774348a3..9aa19c4a61d 100644 --- a/tests/boundary/mcp/javascriptAnalysisResources.test.ts +++ b/tests/boundary/mcp/javascriptAnalysisResources.test.ts @@ -212,6 +212,7 @@ it("returns a directly usable partial analysis reference for an oversized timeou { name: "analyze_javascript_application", arguments: { + detail: "complete", input_path: root, format: "directory", max_heap_mb: 128, diff --git a/tests/boundary/mcp/javascriptSourceSelection.test.ts b/tests/boundary/mcp/javascriptSourceSelection.test.ts index 10fa275d345..d5ee4a7e111 100644 --- a/tests/boundary/mcp/javascriptSourceSelection.test.ts +++ b/tests/boundary/mcp/javascriptSourceSelection.test.ts @@ -65,7 +65,7 @@ it("resolves ESM whitespace specifiers through the public application tool", asy await client.connect(transport); const output = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: root }, + arguments: { detail: "complete", input_path: root }, }); expect(output.isError, JSON.stringify(output.content)).not.toBe(true); const result = javascriptApplicationAnalysisResultSchema.parse( @@ -103,7 +103,7 @@ it("retains missing ASAR native-addon inventory through the public application t await client.connect(transport); const output = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: archive }, + arguments: { detail: "complete", input_path: archive }, }); expect(output.isError, JSON.stringify(output.content)).not.toBe(true); const result = javascriptApplicationAnalysisResultSchema.parse( @@ -220,7 +220,7 @@ it("advertises exact source selection and retains its scope through summary, Evi ]) { const invalid = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: root, source_paths }, + arguments: { detail: "complete", input_path: root, source_paths }, }); expect(invalid.isError).toBe(true); const text = invalid.content.find((item) => item.type === "text"); @@ -238,7 +238,11 @@ it("advertises exact source selection and retains its scope through summary, Evi } const next = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: root, source_paths: ["main.mjs"] }, + arguments: { + detail: "complete", + input_path: root, + source_paths: ["main.mjs"], + }, }); expect(next.isError).not.toBe(true); expect( @@ -270,6 +274,7 @@ it("selects nested ASAR paths and distinguishes missing inventoried bytes from i const nested = await client.callTool({ name: "analyze_javascript_application", arguments: { + detail: "complete", input_path: nestedRoot, source_paths: ["nested.asar/main.mjs"], }, @@ -303,7 +308,11 @@ it("selects nested ASAR paths and distinguishes missing inventoried bytes from i await rm(join(unpacked + ".unpacked", "main.mjs")); const unavailable = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: unpacked, source_paths: ["main.mjs"] }, + arguments: { + detail: "complete", + input_path: unpacked, + source_paths: ["main.mjs"], + }, }); expect(unavailable.isError).toBe(true); const unavailableText = unavailable.content.find( @@ -340,7 +349,11 @@ it("accepts ASAR headers with long legal JSON whitespace through the public appl await client.connect(transport); const output = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: archive, source_paths: ["main.mjs"] }, + arguments: { + detail: "complete", + input_path: archive, + source_paths: ["main.mjs"], + }, }); expect(output.isError, JSON.stringify(output.content)).not.toBe(true); const result = javascriptApplicationAnalysisResultSchema.parse( @@ -385,7 +398,7 @@ it("does not parse ASAR-looking JSON beyond the declared JSON extent through MCP await client.connect(transport); const output = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: archive }, + arguments: { detail: "complete", input_path: archive }, }); expect(output.isError).toBe(true); const message = output.content.find((item) => item.type === "text"); diff --git a/tests/boundary/mcp/keyedArchiveXmlExtensionMcp.test.ts b/tests/boundary/mcp/keyedArchiveXmlExtensionMcp.test.ts index 3b5e8bb5ec2..8646e39c83b 100644 --- a/tests/boundary/mcp/keyedArchiveXmlExtensionMcp.test.ts +++ b/tests/boundary/mcp/keyedArchiveXmlExtensionMcp.test.ts @@ -50,7 +50,7 @@ mcpTest( expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true); const inventoryReply = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect( inventoryReply.isError, diff --git a/tests/boundary/mcp/kunaCloseRetryMcp.test.ts b/tests/boundary/mcp/kunaCloseRetryMcp.test.ts index 6f5bcf53d6b..9502fd14dd1 100644 --- a/tests/boundary/mcp/kunaCloseRetryMcp.test.ts +++ b/tests/boundary/mcp/kunaCloseRetryMcp.test.ts @@ -72,7 +72,10 @@ it("names the same-connection close_binary retry for an unproven Kuna export sto const opened = await call("open_binary", { path: program }); expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true); // The single-function answer returns while the project export stays live. - const text = await call("procedure_pseudo_code", { procedure: "main" }); + const text = await call("procedure_pseudo_code", { + detail: "complete", + procedure: "main", + }); expect(text.isError, JSON.stringify(text.content)).not.toBe(true); await expect.poll(() => exportsOf(fixture.kuna)).toHaveLength(1); diff --git a/tests/boundary/mcp/largeToolResult.test.ts b/tests/boundary/mcp/largeToolResult.test.ts index 27e7bfc03d6..08c0d4fc0d1 100644 --- a/tests/boundary/mcp/largeToolResult.test.ts +++ b/tests/boundary/mcp/largeToolResult.test.ts @@ -112,7 +112,7 @@ const callPseudoCode = async ( throw new Error("Missing named procedure_pseudo_code output schema"); const result = await client.callTool({ name: "procedure_pseudo_code", - arguments: { procedure: "main" }, + arguments: { detail: "complete", procedure: "main" }, }); return { result, diff --git a/tests/boundary/mcp/lateAbortApplicationEvidenceMcp.test.ts b/tests/boundary/mcp/lateAbortApplicationEvidenceMcp.test.ts index 5baab6b9de4..fa4251a9f9e 100644 --- a/tests/boundary/mcp/lateAbortApplicationEvidenceMcp.test.ts +++ b/tests/boundary/mcp/lateAbortApplicationEvidenceMcp.test.ts @@ -58,7 +58,10 @@ it("retains late-cancelled Go artifact Evidence through MCP and keeps the server await server.connect(serverTransport); await client.connect(clientTransport); const call = client.callTool( - { name: "inspect_go_binary", arguments: { path: report.artifact.path } }, + { + name: "inspect_go_binary", + arguments: { detail: "complete", path: report.artifact.path }, + }, { signal: controller.signal }, ); await goInspection.reached(call, "MCP observation"); diff --git a/tests/boundary/mcp/managedArtifactSummaryMcp.test.ts b/tests/boundary/mcp/managedArtifactSummaryMcp.test.ts index 1ccbc374ed9..ea0e1cbf0d2 100644 --- a/tests/boundary/mcp/managedArtifactSummaryMcp.test.ts +++ b/tests/boundary/mcp/managedArtifactSummaryMcp.test.ts @@ -159,7 +159,7 @@ it("keeps malformed metadata, empty returned rows and historical null subjects e const { client } = await createHarness(); const completeReply = await client.callTool({ name: "inspect_managed_artifact", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(completeReply.isError).not.toBe(true); const parent = parseEvidence(completeReply.structuredContent); @@ -260,7 +260,7 @@ it("refuses selected delivery before file access when the server cannot retain E } const complete = await client.callTool({ name: "inspect_managed_artifact", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(complete.isError).not.toBe(true); expect( diff --git a/tests/boundary/mcp/managedMemberSummaryMcp.test.ts b/tests/boundary/mcp/managedMemberSummaryMcp.test.ts index 64b7aa83a00..cdd5951e80b 100644 --- a/tests/boundary/mcp/managedMemberSummaryMcp.test.ts +++ b/tests/boundary/mcp/managedMemberSummaryMcp.test.ts @@ -76,7 +76,10 @@ const verifyProjection = async ({ const viewOutputSchema: Record = canonicalOutputSchema( viewDefinition.name, ); - for (const collection of COLLECTIONS) { + // The type selection leaves no exported type rows to project. + for (const collection of COLLECTIONS.filter( + (name) => name !== "exported_types", + )) { const projectedReply = await client.callTool( { name: "inspect_analysis_view", @@ -271,7 +274,9 @@ it("summarizes selected members and pages every original collection after the fi : report[collection]; if (rows == null) throw new Error(`${collection} was not examined`); // Empty collections would compare equal even if a row schema dropped facts. - expect(rows.length, collection).toBeGreaterThan(0); + // The selection narrows exported types to selected names; none is exported. + if (collection !== "exported_types") + expect(rows.length, collection).toBeGreaterThan(0); expect(view.summary.reported_counts[collection]).toBe(rows.length); const paged: unknown[] = []; for (let offset: number | null = 0; offset !== null;) { diff --git a/tests/boundary/mcp/nativeInventoryViewsMcp.test.ts b/tests/boundary/mcp/nativeInventoryViewsMcp.test.ts index 3414495afc3..7833acecc26 100644 --- a/tests/boundary/mcp/nativeInventoryViewsMcp.test.ts +++ b/tests/boundary/mcp/nativeInventoryViewsMcp.test.ts @@ -216,8 +216,10 @@ it("summarizes an inventory above the inline bound when detail is omitted, and r byte_length: 7001, }, })); - const harness = await connectGhidraMcp("native-inventory-capacity", () => - Promise.resolve(ok(items)), + const harness = await connectGhidraMcp( + "native-inventory-capacity", + () => Promise.resolve(ok(items)), + { testDelivery: "budgeted" }, ); onTestFinished(() => harness.close()); const omitted = await harness.mcp.callTool({ @@ -279,8 +281,10 @@ it("inlines a small inventory, summarizes a large one, and keeps it complete whe procedure: { external: false, thunk: false, thunk_target: null }, })); let result = rows(2); - const harness = await connectGhidraMcp("native-inventory-size-aware", () => - Promise.resolve(ok(result)), + const harness = await connectGhidraMcp( + "native-inventory-size-aware", + () => Promise.resolve(ok(result)), + { testDelivery: "budgeted" }, ); onTestFinished(() => harness.close()); const small = await harness.mcp.callTool({ @@ -317,7 +321,10 @@ it("inlines a small inventory, summarizes a large one, and keeps it complete whe const unpaged = await connectGhidraMcp( "native-inventory-size-aware-unpaged", () => Promise.resolve(ok(rows(600))), - { environment: { REA_MCP_TOOL_FAMILIES: "session,direct,enhanced" } }, + { + environment: { REA_MCP_TOOL_FAMILIES: "session,direct,enhanced" }, + testDelivery: "budgeted", + }, ); onTestFinished(() => unpaged.close()); const unpagedReply = await unpaged.mcp.callTool({ diff --git a/tests/boundary/mcp/nativeMachoSummaryMcp.test.ts b/tests/boundary/mcp/nativeMachoSummaryMcp.test.ts index 9cbe5425a85..04ea6751c12 100644 --- a/tests/boundary/mcp/nativeMachoSummaryMcp.test.ts +++ b/tests/boundary/mcp/nativeMachoSummaryMcp.test.ts @@ -384,7 +384,7 @@ describe.skipIf(process.platform !== "darwin")( const complete = await client.callTool({ name: "inspect_macho", - arguments: {}, + arguments: { detail: "complete" }, }); expect(complete.isError, JSON.stringify(complete.content)).not.toBe( true, diff --git a/tests/boundary/mcp/nativeObservationViewsMcp.test.ts b/tests/boundary/mcp/nativeObservationViewsMcp.test.ts index dd26f9b4d45..f3fb0919196 100644 --- a/tests/boundary/mcp/nativeObservationViewsMcp.test.ts +++ b/tests/boundary/mcp/nativeObservationViewsMcp.test.ts @@ -15,6 +15,7 @@ import { NATIVE_PRIMITIVE_OBSERVATION_OPERATIONS } from "../../../src/domain/nat import { connectGhidraMcp } from "./ghidraMcpHarness.js"; import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; import { advertisedMcpToolSchemas } from "../../fixtures/advertisedMcpTool.js"; +import { applyCompleteEvidenceByDefault } from "../../support/completeEvidenceByDefault.js"; const validation = createMcpSchemaValidation(); afterAll(() => validation.clear()); @@ -195,12 +196,16 @@ it("follows native overflow continuations through MCP without repeating provider { kind: "session", session }, { delivery: createToolResultDelivery(32 * 1024) }, ); - const client = new Client( - { - name: "native-observation-capacity", - version: "1", - }, - { jsonSchemaValidator: createMcpSchemaValidation() }, + // Each observation asks for complete Evidence, which overflows the 32 KiB + // transport and returns a paging continuation. + const client = applyCompleteEvidenceByDefault( + new Client( + { + name: "native-observation-capacity", + version: "1", + }, + { jsonSchemaValidator: createMcpSchemaValidation() }, + ), ); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/ntfsMftAdmission.test.ts b/tests/boundary/mcp/ntfsMftAdmission.test.ts index fa3bff573be..7f2d7e024a6 100644 --- a/tests/boundary/mcp/ntfsMftAdmission.test.ts +++ b/tests/boundary/mcp/ntfsMftAdmission.test.ts @@ -12,6 +12,7 @@ import { createServer } from "../../../src/server/createServer.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { mcpTest } from "../../support/mcp/mcpFixture.js"; import { serveCli } from "../cli/cliServeHarness.js"; +import { completeArguments } from "../../support/completeDetail.js"; const expectMftInventory = (value: unknown): void => { const evidence = parseEvidence(value); @@ -98,7 +99,7 @@ mcpTest( record.writeUInt16LE(5, 1022); await writeFile(path, record); - const cli = await serveCli(["inspect-artifact", path, "--json"]); + const cli = await serveCli(completeArguments("inspect-artifact", path)); expect(cli.exitCode, cli.stdout).toBe(0); expectMftInventory(JSON.parse(cli.stdout)); @@ -118,7 +119,7 @@ mcpTest( expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true); const inspected = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(inspected.isError, JSON.stringify(inspected.content)).not.toBe(true); expectMftInventory(inspected.structuredContent); diff --git a/tests/boundary/mcp/officialArguments.test.ts b/tests/boundary/mcp/officialArguments.test.ts index c45646fc368..4b9ec5b20cf 100644 --- a/tests/boundary/mcp/officialArguments.test.ts +++ b/tests/boundary/mcp/officialArguments.test.ts @@ -182,7 +182,7 @@ describe("official operation arguments", () => { expect(calls).toEqual([]); const valid = await client.callTool({ name: "list_procedures", - arguments: {}, + arguments: { detail: "complete" }, }); expect(valid.isError).not.toBe(true); expect(calls).toEqual(["list_procedures"]); diff --git a/tests/boundary/mcp/officialTools.test.ts b/tests/boundary/mcp/officialTools.test.ts index c8c91f6f480..1c1549530b8 100644 --- a/tests/boundary/mcp/officialTools.test.ts +++ b/tests/boundary/mcp/officialTools.test.ts @@ -278,7 +278,7 @@ describe("official Hopper proxy tools", () => { const result = await client.callTool({ name: "list_procedures", - arguments: {}, + arguments: { detail: "complete" }, }); expect(result.structuredContent).toMatchObject({ @@ -313,7 +313,7 @@ describe("official Hopper proxy tools", () => { const result = await client.callTool({ name: "search_strings", - arguments: { pattern: "coffee" }, + arguments: { detail: "complete", pattern: "coffee" }, }); expect(result.structuredContent).toMatchObject({ diff --git a/tests/boundary/mcp/optionalProviderIsolation.test.ts b/tests/boundary/mcp/optionalProviderIsolation.test.ts index 967719a3daa..ac0c4744061 100644 --- a/tests/boundary/mcp/optionalProviderIsolation.test.ts +++ b/tests/boundary/mcp/optionalProviderIsolation.test.ts @@ -217,7 +217,11 @@ mcpTest.for(failedAdapters)( await writeFile(join(directory, "index.js"), "exports.answer = 42;\n"); const analyzed = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: directory, format: "directory" }, + arguments: { + detail: "complete", + input_path: directory, + format: "directory", + }, }); expect(analyzed.isError).not.toBe(true); expect(analyzed.structuredContent).toMatchObject({ diff --git a/tests/boundary/mcp/oversizedErrorDeliveryMcp.test.ts b/tests/boundary/mcp/oversizedErrorDeliveryMcp.test.ts index 2a3effb66f6..1e571925f39 100644 --- a/tests/boundary/mcp/oversizedErrorDeliveryMcp.test.ts +++ b/tests/boundary/mcp/oversizedErrorDeliveryMcp.test.ts @@ -392,7 +392,7 @@ it("keeps the untrusted target-content marker on an oversized error's replacemen await client.connect(clientTransport); const failure = await client.callTool({ name: "procedure_pseudo_code", - arguments: {}, + arguments: { detail: "complete" }, }); expect(failure.isError).toBe(true); expect(parseMcpToolError(failure)).toMatchObject({ @@ -406,7 +406,7 @@ it("keeps the untrusted target-content marker on an oversized error's replacemen // transport still marks them for target-content tools only. const invalidTarget = await client.callTool({ name: "list_strings", - arguments: {}, + arguments: { detail: "complete" }, }); expect(invalidTarget.isError).toBe(true); expect(invalidTarget._meta).toEqual(UNTRUSTED_TARGET_CONTENT); diff --git a/tests/boundary/mcp/pcapMcp.test.ts b/tests/boundary/mcp/pcapMcp.test.ts index 798e8a2fd47..6a04f3ab26c 100644 --- a/tests/boundary/mcp/pcapMcp.test.ts +++ b/tests/boundary/mcp/pcapMcp.test.ts @@ -116,7 +116,7 @@ it("advertises exact valid pcap schemas and records inline evidence through MCP" const inspected = await client.callTool({ name: "inspect_pcap_capture", - arguments: { path: "/captures/session.pcap" }, + arguments: { detail: "complete", path: "/captures/session.pcap" }, }); expect(inspected.isError).not.toBe(true); const text = (inspected.content as { readonly text?: string }[]) diff --git a/tests/boundary/mcp/pcapWorkspaceAllocation.test.ts b/tests/boundary/mcp/pcapWorkspaceAllocation.test.ts index 064dba343c8..66747680b88 100644 --- a/tests/boundary/mcp/pcapWorkspaceAllocation.test.ts +++ b/tests/boundary/mcp/pcapWorkspaceAllocation.test.ts @@ -77,7 +77,7 @@ const inspectWith = async (allocate: Allocate, path: string) => { return parseMcpToolError( await client.callTool({ name: "inspect_pcap_capture", - arguments: { path }, + arguments: { detail: "complete", path }, }), ).error; }; diff --git a/tests/boundary/mcp/pseudocodeDeliveryMcp.test.ts b/tests/boundary/mcp/pseudocodeDeliveryMcp.test.ts index d7d02171704..0f1f5e37939 100644 --- a/tests/boundary/mcp/pseudocodeDeliveryMcp.test.ts +++ b/tests/boundary/mcp/pseudocodeDeliveryMcp.test.ts @@ -112,13 +112,11 @@ it("retains a complete pseudocode observation once and pages its exact text thro } expect(restored).toBe(text); expect(calls).toEqual(executions); - for (const detail of [undefined, "complete"] as const) { + // Omitted detail is budgeted; complete delivery is requested explicitly. + for (const detail of ["complete"] as const) { const complete = await mcp.callTool({ name: "procedure_pseudo_code", - arguments: { - procedure: "fixture_main", - ...(detail === undefined ? {} : { detail }), - }, + arguments: { procedure: "fixture_main", detail }, }); expect(complete.isError).not.toBe(true); expect( @@ -295,7 +293,7 @@ it("keeps transport-overflow recovery usable for the original pseudocode observa const { mcp, session, calls } = await connectPseudocode(text); const response = await mcp.callTool({ name: "procedure_pseudo_code", - arguments: { procedure: "fixture_main" }, + arguments: { procedure: "fixture_main", detail: "complete" }, }); const failure = parseMcpToolError(response).error; expect(failure.code).toBe("resource_constraint"); diff --git a/tests/boundary/mcp/pyinstallerArtifactMcp.test.ts b/tests/boundary/mcp/pyinstallerArtifactMcp.test.ts index 21438621209..8624807b97d 100644 --- a/tests/boundary/mcp/pyinstallerArtifactMcp.test.ts +++ b/tests/boundary/mcp/pyinstallerArtifactMcp.test.ts @@ -218,7 +218,7 @@ mcpTest.for([false, true])( expect(opened.isError).not.toBe(true); const inspected = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(inspected.isError).not.toBe(true); const inspection = artifactInspectionResultSchema.parse( @@ -343,7 +343,7 @@ mcpTest( expect(opened.isError).not.toBe(true); const inspected = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(inspected.isError).not.toBe(true); const inventory = artifactInspectionResultSchema.parse( @@ -396,7 +396,7 @@ mcpTest( expect(opened.isError).not.toBe(true); const inspected = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(inspected.isError).not.toBe(true); const inspection = artifactInspectionResultSchema.parse( @@ -514,7 +514,7 @@ mcpTest.for([ ).not.toBe(true); const reply = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(reply.isError).not.toBe(true); const inspection = artifactInspectionResultSchema.parse( @@ -636,7 +636,7 @@ mcpTest.for([false, true])( ).not.toBe(true); const reply = await client.callTool({ name: "inspect_artifact", - arguments: {}, + arguments: { detail: "complete" }, }); expect(reply.isError).not.toBe(true); const inventory = artifactInspectionResultSchema.parse( diff --git a/tests/boundary/mcp/pythonPycMcp.test.ts b/tests/boundary/mcp/pythonPycMcp.test.ts index 009843bac18..1f5e50558bd 100644 --- a/tests/boundary/mcp/pythonPycMcp.test.ts +++ b/tests/boundary/mcp/pythonPycMcp.test.ts @@ -71,7 +71,7 @@ it("reads signed TYPE_INT64 constants and rejects a truncated payload", async () ); const response = await client.callTool({ name: "inspect_python_pyc", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(response.isError, JSON.stringify(response.content)).not.toBe(true); const { normalized_result } = completePycEvidenceSchema.parse( @@ -96,7 +96,7 @@ it("reads signed TYPE_INT64 constants and rejects a truncated payload", async () ); const truncated = await client.callTool({ name: "inspect_python_pyc", - arguments: { path: truncatedPath }, + arguments: { detail: "complete", path: truncatedPath }, }); expect(truncated.isError).toBe(true); expect(parseMcpToolError(truncated).error).toMatchObject({ @@ -141,7 +141,7 @@ it("advertises inspect_python_pyc and reads nested code objects", async () => { ]); await writeFile(path, bytes); const response = await client.callTool( - { name: "inspect_python_pyc", arguments: { path } }, + { name: "inspect_python_pyc", arguments: { detail: "complete", path } }, { toolDefinition: withCanonicalOutputSchema(advertised) }, ); expect(response.isError, JSON.stringify(response.content)).not.toBe(true); @@ -193,7 +193,7 @@ it("advertised pyc output schema preserves historical signed fields", async () = ]), ); const response = await client.callTool( - { name: "inspect_python_pyc", arguments: { path } }, + { name: "inspect_python_pyc", arguments: { detail: "complete", path } }, { toolDefinition: withCanonicalOutputSchema(advertised) }, ); expect(response.isError, JSON.stringify(response.content)).not.toBe(true); @@ -226,7 +226,7 @@ it("rejects negative code fields for magics after constructor validation was add ); const response = await client.callTool({ name: "inspect_python_pyc", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(response.isError).toBe(true); expect(parseMcpToolError(response).error).toMatchObject({ @@ -252,7 +252,7 @@ it("reports an unknown pyc magic as unsupported", async () => { await writeFile(path, bytes); const response = await client.callTool({ name: "inspect_python_pyc", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(response.isError).toBe(true); expect(parseMcpToolError(response).error).toMatchObject({ diff --git a/tests/boundary/mcp/reverseEngineeringPartialMcp.test.ts b/tests/boundary/mcp/reverseEngineeringPartialMcp.test.ts index 0e5cfa2a324..13d9474350c 100644 --- a/tests/boundary/mcp/reverseEngineeringPartialMcp.test.ts +++ b/tests/boundary/mcp/reverseEngineeringPartialMcp.test.ts @@ -72,7 +72,11 @@ mcpTest( const client = await mcp.connect(server); const result = await client.callTool({ name: "inspect_with_objdump", - arguments: { path: "package.json", operation: "file_headers" }, + arguments: { + detail: "complete", + path: "package.json", + operation: "file_headers", + }, }); const projected = parseMcpToolError(result); expect(projected.error).toMatchObject({ diff --git a/tests/boundary/mcp/serverIdentity.test.ts b/tests/boundary/mcp/serverIdentity.test.ts index c28a0761533..6f78200ee09 100644 --- a/tests/boundary/mcp/serverIdentity.test.ts +++ b/tests/boundary/mcp/serverIdentity.test.ts @@ -262,7 +262,7 @@ describe("active-target availability over MCP", () => { }); const call = await client.callTool({ name: "inspect_macho", - arguments: {}, + arguments: { detail: "complete" }, }); expect(parseMcpToolError(call)).toMatchObject({ error: { code: "target_unavailable" }, diff --git a/tests/boundary/mcp/serverLifecycleMcp.test.ts b/tests/boundary/mcp/serverLifecycleMcp.test.ts index b5999434906..c65e8f9f83f 100644 --- a/tests/boundary/mcp/serverLifecycleMcp.test.ts +++ b/tests/boundary/mcp/serverLifecycleMcp.test.ts @@ -423,7 +423,7 @@ it("closes the bound Go, IL2CPP and web-capture services and retries failed shut await client.connect(clientTransport); const result = await client.callTool({ name: "inspect_go_binary", - arguments: { path: "/tmp/go-fixture" }, + arguments: { detail: "complete", path: "/tmp/go-fixture" }, }); expect(result.isError).toBe(true); expect(goCalls).toBe(1); diff --git a/tests/boundary/mcp/serverUnknownsMcp.test.ts b/tests/boundary/mcp/serverUnknownsMcp.test.ts index d1d1327abd0..856067f18dc 100644 --- a/tests/boundary/mcp/serverUnknownsMcp.test.ts +++ b/tests/boundary/mcp/serverUnknownsMcp.test.ts @@ -220,9 +220,7 @@ it("does not record capability unavailability without supporting Evidence", asyn const unavailable = await client.callTool({ name: "procedure_pseudo_code", - arguments: { - procedure: "main", - }, + arguments: { detail: "complete", procedure: "main" }, }); expect(unavailable.isError).toBe(true); expect(structured(unavailable)).toMatchObject({ diff --git a/tests/boundary/mcp/serverWorkflowMcp.test.ts b/tests/boundary/mcp/serverWorkflowMcp.test.ts index 696488dd908..661cfced00e 100644 --- a/tests/boundary/mcp/serverWorkflowMcp.test.ts +++ b/tests/boundary/mcp/serverWorkflowMcp.test.ts @@ -79,7 +79,7 @@ it("executes a realistic workflow: list methods, decompile selected, get xrefs", const listResult = await client.callTool({ name: "list_procedures", - arguments: {}, + arguments: { detail: "complete" }, }); expect(listResult.isError).not.toBe(true); expect(structured(listResult)).toMatchObject({ @@ -91,7 +91,7 @@ it("executes a realistic workflow: list methods, decompile selected, get xrefs", const decompileResult = await client.callTool({ name: "procedure_pseudo_code", - arguments: { procedure: "0x1000" }, + arguments: { detail: "complete", procedure: "0x1000" }, }); expect(structured(decompileResult)).toMatchObject({ normalized_result: "pseudo for 0x1000", diff --git a/tests/boundary/mcp/sessionAvailabilityRecovery.test.ts b/tests/boundary/mcp/sessionAvailabilityRecovery.test.ts index 7a4507e6157..34bbba75cda 100644 --- a/tests/boundary/mcp/sessionAvailabilityRecovery.test.ts +++ b/tests/boundary/mcp/sessionAvailabilityRecovery.test.ts @@ -901,7 +901,7 @@ it("keeps each provider's failures and ignores cancelled requests", async () => fixtureBroken = true; expect(await call("address_name", ADDRESS)).toBe("error"); // A cancelled request is not evidence that the provider recovered. - expect(await call("list_procedures", {})).toBe("error"); + expect(await call("list_procedures", { detail: "complete" })).toBe("error"); const fixtureFailure = { address_name: observedFailure("address_name"), current_address: inferredFailure("address_name"), @@ -1078,7 +1078,7 @@ it("restores composed tools in a scoped catalog after one composed success", asy const batchItemStatus = async () => { const reply = await client.callTool({ name: "batch_decompile", - arguments: { addresses: ["0x1"] }, + arguments: { detail: "complete", addresses: ["0x1"] }, }); expect(reply.isError).not.toBe(true); return reply.structuredContent; diff --git a/tests/boundary/mcp/sessionEvidenceRecovery.test.ts b/tests/boundary/mcp/sessionEvidenceRecovery.test.ts index 4d3b58cdc97..89638121d00 100644 --- a/tests/boundary/mcp/sessionEvidenceRecovery.test.ts +++ b/tests/boundary/mcp/sessionEvidenceRecovery.test.ts @@ -129,6 +129,7 @@ it.each(["switch", "restart"] as const)( // independently of the investigation's Evidence and Unknown history. await call("address_name", query); const analyzed = await call("analyze_javascript_application", { + detail: "complete", input_path: application, format: "directory", max_heap_mb: 128, diff --git a/tests/boundary/mcp/sessionEvidenceReuseMcp.test.ts b/tests/boundary/mcp/sessionEvidenceReuseMcp.test.ts index b878619eae2..efcbf06d56c 100644 --- a/tests/boundary/mcp/sessionEvidenceReuseMcp.test.ts +++ b/tests/boundary/mcp/sessionEvidenceReuseMcp.test.ts @@ -199,9 +199,15 @@ it("preserves the selected path when reusing an identical observation for a diff return r.structuredContent; }; await call("open_binary", { path: first, format: "dos-com" }); - const before = await call("procedure_callees", { procedure: "0x100" }); + const before = await call("procedure_callees", { + detail: "complete", + procedure: "0x100", + }); await call("open_binary", { path: second, format: "dos-com" }); - const after = await call("procedure_callees", { procedure: "0x100" }); + const after = await call("procedure_callees", { + detail: "complete", + procedure: "0x100", + }); expect(before).toMatchObject({ subject: { name: "first.com", local_path: first }, }); @@ -218,7 +224,10 @@ it("preserves the selected path when reusing an identical observation for a diff ]), ).ok, ).toBe(true); - const sameTarget = await call("procedure_callees", { procedure: "0x100" }); + const sameTarget = await call("procedure_callees", { + detail: "complete", + procedure: "0x100", + }); expect(sameTarget).not.toHaveProperty("caller_input_path"); } finally { await client.close(); diff --git a/tests/boundary/mcp/stableArtifactSymlinkRecoveryMcp.test.ts b/tests/boundary/mcp/stableArtifactSymlinkRecoveryMcp.test.ts index edb1892e001..ef18dbbe62d 100644 --- a/tests/boundary/mcp/stableArtifactSymlinkRecoveryMcp.test.ts +++ b/tests/boundary/mcp/stableArtifactSymlinkRecoveryMcp.test.ts @@ -44,6 +44,7 @@ mcpTest.skipIf(process.platform === "win32")( const captureResponse = await client.callTool({ name: "inspect_web_network_capture", arguments: { + detail: "complete", capture_path: selected, format: "har", sensitive_values: ["unrelated marked value"], diff --git a/tests/boundary/mcp/universalSliceMcp.test.ts b/tests/boundary/mcp/universalSliceMcp.test.ts index 7156b2dd29e..e7ef5a91452 100644 --- a/tests/boundary/mcp/universalSliceMcp.test.ts +++ b/tests/boundary/mcp/universalSliceMcp.test.ts @@ -110,7 +110,7 @@ sliceTest( const response = await client.callTool({ name: "inspect_go_binary", - arguments: { path, architecture: "arm64" }, + arguments: { detail: "complete", path, architecture: "arm64" }, }); expect(response.isError, JSON.stringify(response.content)).not.toBe(true); expect( @@ -225,7 +225,7 @@ sliceTest( issues( await client.callTool({ name: "inspect_go_binary", - arguments: { path: thin, architecture: "arm64" }, + arguments: { detail: "complete", path: thin, architecture: "arm64" }, }), ), ).toMatchObject({ @@ -310,7 +310,11 @@ sliceTest( containerRefusal( await client.callTool({ name: "inspect_go_binary", - arguments: { path: disagreeing, architecture: "arm64" }, + arguments: { + detail: "complete", + path: disagreeing, + architecture: "arm64", + }, }), ), ).toMatchObject({ @@ -356,7 +360,7 @@ sliceTest( const read = async (architecture: string) => { const response = await client.callTool({ name: "inspect_go_binary", - arguments: { path, architecture }, + arguments: { detail: "complete", path, architecture }, }); expect(response.isError, JSON.stringify(response.content)).not.toBe(true); return goBinarySchema.parse( @@ -401,6 +405,7 @@ sliceTest( await client.callTool({ name: "inspect_go_binary", arguments: { + detail: "complete", path: await write(name, universalMacho(subtypes.map(slice)).bytes), architecture, }, @@ -441,7 +446,7 @@ sliceTest( containerRefusal( await client.callTool({ name: "inspect_go_binary", - arguments: { path, architecture }, + arguments: { detail: "complete", path, architecture }, }), ), ).toMatchObject({ @@ -468,11 +473,11 @@ sliceTest( const path = await write("universal-rust", universal.bytes); const thinResponse = await client.callTool({ name: "inspect_rust_binary", - arguments: { path: thinPath }, + arguments: { detail: "complete", path: thinPath }, }); const response = await client.callTool({ name: "inspect_rust_binary", - arguments: { path, architecture: "arm64" }, + arguments: { detail: "complete", path, architecture: "arm64" }, }); expect(response.isError, JSON.stringify(response.content)).not.toBe(true); const contract = toolContract("inspect_rust_binary"); @@ -503,7 +508,7 @@ sliceTest( issues( await client.callTool({ name: "inspect_rust_binary", - arguments: { path }, + arguments: { detail: "complete", path }, }), ).details.issues[0]?.path, ).toEqual(["architecture"]); diff --git a/tests/boundary/mcp/wasmArtifactMcp.test.ts b/tests/boundary/mcp/wasmArtifactMcp.test.ts index add5c6cfb16..4035548bd81 100644 --- a/tests/boundary/mcp/wasmArtifactMcp.test.ts +++ b/tests/boundary/mcp/wasmArtifactMcp.test.ts @@ -523,7 +523,7 @@ it("reads an oversized completed WASM result through its reported retained refer ); const reply = await harness.client.callTool({ name: "inspect_wasm_artifact", - arguments: { path: value.artifact.path }, + arguments: { path: value.artifact.path, detail: "complete" }, }); const reference = z .object({ diff --git a/tests/boundary/mcp/webBundleContainmentMcp.test.ts b/tests/boundary/mcp/webBundleContainmentMcp.test.ts index a5db7937f91..69e58344b87 100644 --- a/tests/boundary/mcp/webBundleContainmentMcp.test.ts +++ b/tests/boundary/mcp/webBundleContainmentMcp.test.ts @@ -71,6 +71,7 @@ it("retains timeout Evidence and recovers on the same MCP server", async () => { const interrupted = await client.callTool({ name: "analyze_web_bundle", arguments: { + detail: "complete", cdp_endpoint: browser.endpoint, allowed_origins: [browser.allowedOrigin], target_id: "allowed-page", @@ -139,6 +140,7 @@ it("retains timeout Evidence and recovers on the same MCP server", async () => { const recovered = await client.callTool({ name: "analyze_web_bundle", arguments: { + detail: "complete", cdp_endpoint: browser.endpoint, allowed_origins: [browser.allowedOrigin], target_id: "allowed-page", diff --git a/tests/boundary/mcp/webNetworkCaptureMcp.test.ts b/tests/boundary/mcp/webNetworkCaptureMcp.test.ts index 8bc8d095c7e..ab7abb99361 100644 --- a/tests/boundary/mcp/webNetworkCaptureMcp.test.ts +++ b/tests/boundary/mcp/webNetworkCaptureMcp.test.ts @@ -80,7 +80,10 @@ it("publishes valid SDK schemas and retains historical inline Evidence with the const args = { capture_path: "/capture.har", format: "har" }; expect(ajv.validate(inputSchema, args)).toBe(true); const response = await client.callTool( - { name: "inspect_web_network_capture", arguments: args }, + { + name: "inspect_web_network_capture", + arguments: { ...args, detail: "complete" }, + }, { toolDefinition: withCanonicalOutputSchema(advertised) }, ); expect(response.isError).not.toBe(true); @@ -171,7 +174,11 @@ it.each([false, true])( const response = await client.callTool({ name: "inspect_web_network_capture", - arguments: { capture_path: "/capture.har", format: "har" }, + arguments: { + detail: "complete", + capture_path: "/capture.har", + format: "har", + }, }); expect(response.isError).not.toBe(true); const capture = webNetworkCaptureSchema.parse( diff --git a/tests/boundary/mcp/webPageViewMcp.test.ts b/tests/boundary/mcp/webPageViewMcp.test.ts index 5ad0eff441f..bc6174354ba 100644 --- a/tests/boundary/mcp/webPageViewMcp.test.ts +++ b/tests/boundary/mcp/webPageViewMcp.test.ts @@ -34,6 +34,8 @@ const connect = async (count: number) => { onTestFinished(() => browser.close()); const { client } = await createApplicationMcpHarness({ serverOptions: { browserObservation: new CdpBrowserProvider() }, + // These cases cover the budget's choice for an omitted detail. + testDelivery: "budgeted", }); const definitions = (await client.listTools()).tools; const call = async (name: string, args: Record) => { @@ -114,7 +116,7 @@ it("returns a small page capture inline when detail is omitted", async () => { }); it("pages a captured script's metadata without its text, and the text separately", async () => { - const body = "x".repeat(40_000); + const body = "x".repeat(60_000); const browser = await startFakeCdpBrowser({ commandEvents: ({ method }, origin) => method === "Debugger.enable" @@ -140,6 +142,7 @@ it("pages a captured script's metadata without its text, and the text separately onTestFinished(() => browser.close()); const { client } = await createApplicationMcpHarness({ serverOptions: { browserObservation: new CdpBrowserProvider() }, + testDelivery: "budgeted", }); const call = async (name: string, args: Record) => { const reply = await client.callTool({ name, arguments: args }); diff --git a/tests/boundary/mcp/webSourceLocationMcp.test.ts b/tests/boundary/mcp/webSourceLocationMcp.test.ts index ec127f594f7..333105e41b9 100644 --- a/tests/boundary/mcp/webSourceLocationMcp.test.ts +++ b/tests/boundary/mcp/webSourceLocationMcp.test.ts @@ -56,7 +56,10 @@ it("validates source-location delivery and retains Evidence without a binary tar const inputSchema: Record = advertised.inputSchema; expect(ajv.validate(inputSchema, args)).toBe(true); const response = await client.callTool( - { name: "trace_web_source_location", arguments: args }, + { + name: "trace_web_source_location", + arguments: { ...args, detail: "complete" }, + }, { toolDefinition: withCanonicalOutputSchema(advertised) }, ); expect(response.isError).not.toBe(true); @@ -148,7 +151,7 @@ it("preserves missing Linux ps capability and recovery through source-map tracin for (let attempt = 0; attempt < 2; attempt += 1) { const response = await harness.client.callTool({ name: "trace_web_source_location", - arguments: args, + arguments: { ...args, detail: "complete" }, }); const { error } = parseMcpToolError(response); expect(error).toMatchObject({ diff --git a/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts b/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts index 62b90b59637..f3a81c998d2 100644 --- a/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts +++ b/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts @@ -281,7 +281,7 @@ describe("MCP composed workflow snapshot replay", () => { .parse(output); const primitiveResult = await mcp.callTool({ name: "list_strings", - arguments: { document: "fixture" }, + arguments: { detail: "complete", document: "fixture" }, }); expect( primitiveResult.isError, @@ -329,7 +329,7 @@ describe("MCP composed workflow snapshot replay", () => { expect(reopened.isError, JSON.stringify(reopened.content)).not.toBe(true); const cachedPrimitive = await mcp.callTool({ name: "list_strings", - arguments: { document: "fixture" }, + arguments: { detail: "complete", document: "fixture" }, }); expect( cachedPrimitive.isError, @@ -464,7 +464,7 @@ describe("MCP investigation history snapshot replay", () => { if (disposition === "verified") { const inspected = await mcp.callTool({ name: "list_strings", - arguments: {}, + arguments: { detail: "complete" }, }); expect(inspected.isError, JSON.stringify(inspected.content)).not.toBe( true, @@ -482,7 +482,7 @@ describe("MCP investigation history snapshot replay", () => { await openWorkflowTarget(mcp, secondPath); const unrelated = await mcp.callTool({ name: "list_strings", - arguments: {}, + arguments: { detail: "complete" }, }); expect(unrelated.isError).not.toBe(true); const foreignEvidence = toolContract("list_strings").outputSchema.parse( @@ -628,7 +628,7 @@ it("replays a source-bearing observation through an exported MCP snapshot", asyn ( await client.callTool({ name: "list_strings", - arguments: { document: "fixture" }, + arguments: { detail: "complete", document: "fixture" }, }) ).structuredContent, ); @@ -783,7 +783,7 @@ const expectRestoredSourceReplay = async ( ( await mcp.callTool({ name: "list_strings", - arguments: { document: "fixture" }, + arguments: { detail: "complete", document: "fixture" }, }) ).structuredContent, ); diff --git a/tests/boundary/process/androidAnalysisMcp.test.ts b/tests/boundary/process/androidAnalysisMcp.test.ts index a0d98b4805e..eee83902970 100644 --- a/tests/boundary/process/androidAnalysisMcp.test.ts +++ b/tests/boundary/process/androidAnalysisMcp.test.ts @@ -245,7 +245,7 @@ test.each([ const response = await client.callTool({ name: "inspect_android_package", - arguments: { path: apk }, + arguments: { detail: "complete", path: apk }, }); const projected = parseMcpToolError(response).error; expect(projected.code).toBe(errorCode); @@ -319,7 +319,10 @@ it("cleans an active engine when the MCP client disconnects", async () => { serverOptions: { androidAnalysis: provider }, }); const pending = client - .callTool({ name: "inspect_android_package", arguments: { path: apk } }) + .callTool({ + name: "inspect_android_package", + arguments: { detail: "complete", path: apk }, + }) .catch(() => undefined); await expect.poll(() => launches.length).toBe(1); await client.close(); diff --git a/tests/boundary/process/androidMappingMcp.test.ts b/tests/boundary/process/androidMappingMcp.test.ts index 44298eae972..bc623cb1838 100644 --- a/tests/boundary/process/androidMappingMcp.test.ts +++ b/tests/boundary/process/androidMappingMcp.test.ts @@ -51,6 +51,7 @@ const connect = async () => { client.callTool({ name: "inspect_android_class", arguments: { + detail: "complete", path: fixture.apk, class_name: "fixture.Target", mapping_path, @@ -240,7 +241,7 @@ it("annotates class inspection with a caller-selected mapping and reuses one eng }); const unannotated = await client.callTool({ name: "inspect_android_class", - arguments: { path: apk, class_name: "fixture.Target" }, + arguments: { detail: "complete", path: apk, class_name: "fixture.Target" }, }); expect(unannotated.isError).not.toBe(true); expect( diff --git a/tests/boundary/process/jadxStartup.test.ts b/tests/boundary/process/jadxStartup.test.ts index 44b9c972d01..b6fee38108e 100644 --- a/tests/boundary/process/jadxStartup.test.ts +++ b/tests/boundary/process/jadxStartup.test.ts @@ -300,7 +300,7 @@ it("returns terminal startup diagnostics and partial identity through the MCP co await client.connect(local); const pending = client.callTool({ name: "inspect_android_package", - arguments: { path: f.apk }, + arguments: { detail: "complete", path: f.apk }, }); await f.request; f.process.exit(); diff --git a/tests/boundary/providers/kuna/kunaAliasSearchMcp.test.ts b/tests/boundary/providers/kuna/kunaAliasSearchMcp.test.ts index bb143f3930d..1f970ee9acb 100644 --- a/tests/boundary/providers/kuna/kunaAliasSearchMcp.test.ts +++ b/tests/boundary/providers/kuna/kunaAliasSearchMcp.test.ts @@ -144,7 +144,7 @@ test("searches the aliases exact lookup accepts without listing them as procedur ).toBe("0x1334"); const ambiguous = await client.callTool({ name: "procedure_address", - arguments: { procedure: "audit_transform" }, + arguments: { detail: "complete", procedure: "audit_transform" }, }); expect(parseMcpToolError(ambiguous).error.message).toContain( "0x1334, 0x133a", @@ -247,7 +247,7 @@ test("omits a data entry an alias names while keeping the code entry that shares const { error } = parseMcpToolError( await client.callTool({ name: "procedure_address", - arguments: { procedure: "global_count" }, + arguments: { detail: "complete", procedure: "global_count" }, }), ); expect(error.recovery).toBeUndefined(); @@ -267,7 +267,7 @@ test("reports lookup failures with recovery for the selected target, not the inp ]) { const response = await client.callTool({ name: "procedure_address", - arguments: { procedure }, + arguments: { detail: "complete", procedure }, }); const { error } = parseMcpToolError(response); expect(error.code).toBe("invalid_request"); diff --git a/tests/boundary/providers/kuna/kunaBatchDecompileMcp.test.ts b/tests/boundary/providers/kuna/kunaBatchDecompileMcp.test.ts index fd7faf171d0..0c93633d5c1 100644 --- a/tests/boundary/providers/kuna/kunaBatchDecompileMcp.test.ts +++ b/tests/boundary/providers/kuna/kunaBatchDecompileMcp.test.ts @@ -108,6 +108,7 @@ test("keeps each Kuna no-pseudocode observation's limitations on its batch item" const direct = async (procedure: string) => parseEvidence( + // One small observation fits the agent result budget unchanged. (await call("procedure_pseudo_code", { procedure })).structuredContent, ); const mainDirect = await direct("main"); @@ -128,6 +129,7 @@ test("keeps each Kuna no-pseudocode observation's limitations on its batch item" const batch = parseEvidence( ( await call("batch_decompile", { + detail: "complete", addresses: ["main", "broken", "puts", "0xdead"], }) ).structuredContent, diff --git a/tests/boundary/providers/kuna/kunaMachoInventoryMcp.test.ts b/tests/boundary/providers/kuna/kunaMachoInventoryMcp.test.ts index 8cedf5084cc..42051062329 100644 --- a/tests/boundary/providers/kuna/kunaMachoInventoryMcp.test.ts +++ b/tests/boundary/providers/kuna/kunaMachoInventoryMcp.test.ts @@ -98,7 +98,7 @@ test("keeps Mach-O data symbols out of listings, overviews and decompile_all", a const refused = await client.callTool({ name: "procedure_pseudo_code", - arguments: { procedure: "global_count" }, + arguments: { detail: "complete", procedure: "global_count" }, }); expect(refused.isError).toBe(true); expect(parseMcpToolError(refused).error).toMatchObject({ @@ -292,7 +292,11 @@ test("recovers only an explicitly selected, evidenced Mach-O call destination", ( await client.callTool({ name: "procedure_pseudo_code", - arguments: { procedure, analysis: "call_destination" }, + arguments: { + detail: "complete", + procedure, + analysis: "call_destination", + }, }) ).isError, procedure, @@ -302,7 +306,7 @@ test("recovers only an explicitly selected, evidenced Mach-O call destination", ( await client.callTool({ name: "procedure_pseudo_code", - arguments: { procedure: destination }, + arguments: { detail: "complete", procedure: destination }, }) ).isError, ).toBe(true); @@ -369,7 +373,11 @@ test.for([ } const failed = await client.callTool({ name: "procedure_pseudo_code", - arguments: { procedure: destination, analysis: "call_destination" }, + arguments: { + detail: "complete", + procedure: destination, + analysis: "call_destination", + }, }); expect(failed.isError).toBe(true); const error = parseMcpToolError(failed).error; diff --git a/tests/boundary/providers/native/nativeMachoUuidlessInspection.test.ts b/tests/boundary/providers/native/nativeMachoUuidlessInspection.test.ts index cc7f88681dd..d0ae085d0bc 100644 --- a/tests/boundary/providers/native/nativeMachoUuidlessInspection.test.ts +++ b/tests/boundary/providers/native/nativeMachoUuidlessInspection.test.ts @@ -313,7 +313,7 @@ it("delivers partial UUID-less inspection Evidence through production MCP", asyn const inspected = await client.callTool({ name: "inspect_macho", - arguments: {}, + arguments: { detail: "complete" }, }); expect(inspected.isError, JSON.stringify(inspected.content)).not.toBe(true); expect(inspected.structuredContent).toMatchObject({ diff --git a/tests/fixtures/applicationMcpHarness.ts b/tests/fixtures/applicationMcpHarness.ts index 1a2c2ff494d..7ee8d6a0449 100644 --- a/tests/fixtures/applicationMcpHarness.ts +++ b/tests/fixtures/applicationMcpHarness.ts @@ -13,6 +13,8 @@ import { type McpClientIdentity, type TestMcp, } from "../support/mcp/mcpFixture.js"; +import type { TestDelivery } from "../support/completeEvidenceByDefault.js"; +import { testDeliveryEnvironment } from "../support/completeEvidenceByDefault.js"; /** Owned MCP SDK session shared by application workflow scenarios. */ export interface ApplicationMcpHarness { @@ -29,6 +31,8 @@ export async function createApplicationMcpHarness( readonly clientIdentity?: McpClientIdentity; readonly schemaValidator?: Parameters[2]; readonly registerCleanup?: (close: ApplicationMcpHarness["close"]) => void; + /** "budgeted" leaves an omitted detail to the agent result budget. */ + readonly testDelivery?: TestDelivery; } = {}, ): Promise { const session = @@ -65,10 +69,13 @@ export async function createApplicationMcpHarness( { kind: "session", session }, { ...options.serverOptions, - environment: { - ...INLINE_EVIDENCE_MCP_ENVIRONMENT, - ...(options.serverOptions?.environment ?? process.env), - }, + environment: testDeliveryEnvironment( + { + ...INLINE_EVIDENCE_MCP_ENVIRONMENT, + ...(options.serverOptions?.environment ?? process.env), + }, + options.testDelivery, + ), }, ); const client = await mcp.connect( @@ -78,6 +85,7 @@ export async function createApplicationMcpHarness( version: "1", }, options.schemaValidator, + options.testDelivery, ); return { client, session, close }; } catch (cause) { diff --git a/tests/fixtures/artifactComparisonMcp.ts b/tests/fixtures/artifactComparisonMcp.ts index f61f5450123..152a96ca53e 100644 --- a/tests/fixtures/artifactComparisonMcp.ts +++ b/tests/fixtures/artifactComparisonMcp.ts @@ -22,7 +22,7 @@ export async function connectArtifactComparisonMcp() { const inspect = async (path: string): Promise => { const opened = await call("open_binary", { path }); expect(opened.isError, JSON.stringify(opened)).not.toBe(true); - const response = await call("inspect_artifact", {}); + const response = await call("inspect_artifact", { detail: "complete" }); expect(response.isError, JSON.stringify(response)).not.toBe(true); return inventoryEvidence(response.structuredContent); }; diff --git a/tests/fixtures/cli-parity/discovery-help-over-schema.txt b/tests/fixtures/cli-parity/discovery-help-over-schema.txt index 721e192794b..52260970263 100644 --- a/tests/fixtures/cli-parity/discovery-help-over-schema.txt +++ b/tests/fixtures/cli-parity/discovery-help-over-schema.txt @@ -9,9 +9,11 @@ Arguments: path Local file Options: - --block-size Power-of-two block size from 256 to 65536 bytes (default: 4096) - --offset Window start as a decimal file byte offset (default: 0) - --length Window length in bytes; omit to extend through EOF + --block-size Power-of-two block size from 256 to 65536 bytes (default: 4096) + --offset Window start as a decimal file byte offset (default: 0) + --length Window length in bytes; omit to extend through EOF + --detail Omit for complete Evidence when it fits the agent result budget (32768 compact JSON bytes by default, about 11k tokens) and its summary otherwise; complete always delivers everything; summary needs --evidence_output + --evidence_output Save complete Evidence as a bundle; required for summary delivery. Never overwrites. Custom Global Options: --timings Write measured command timing to stderr. diff --git a/tests/fixtures/cli-parity/discovery-llms-full-over-llms.txt b/tests/fixtures/cli-parity/discovery-llms-full-over-llms.txt index 8d592e36fe8..f4c5edb533e 100644 --- a/tests/fixtures/cli-parity/discovery-llms-full-over-llms.txt +++ b/tests/fixtures/cli-parity/discovery-llms-full-over-llms.txt @@ -18,6 +18,8 @@ Inspect file-wide and block byte entropy without executing the file | `--block-size` | `unknown` | `4096` | Power-of-two block size from 256 to 65536 bytes | | `--offset` | `unknown` | `0` | Window start as a decimal file byte offset | | `--length` | `unknown` | | Window length in bytes; omit to extend through EOF | +| `--detail` | `string` | | Omit for complete Evidence when it fits the agent result budget (32768 compact JSON bytes by default, about 11k tokens) and its summary otherwise; complete always delivers everything; summary needs --evidence_output | +| `--evidence_output` | `string` | | Save complete Evidence as a bundle; required for summary delivery. Never overwrites. | --- stderr diff --git a/tests/fixtures/cli-parity/help-contract-command.txt b/tests/fixtures/cli-parity/help-contract-command.txt index 1b42e38d667..d2fc1cfe173 100644 --- a/tests/fixtures/cli-parity/help-contract-command.txt +++ b/tests/fixtures/cli-parity/help-contract-command.txt @@ -9,9 +9,11 @@ Arguments: path Local file Options: - --block-size Power-of-two block size from 256 to 65536 bytes (default: 4096) - --offset Window start as a decimal file byte offset (default: 0) - --length Window length in bytes; omit to extend through EOF + --block-size Power-of-two block size from 256 to 65536 bytes (default: 4096) + --offset Window start as a decimal file byte offset (default: 0) + --length Window length in bytes; omit to extend through EOF + --detail Omit for complete Evidence when it fits the agent result budget (32768 compact JSON bytes by default, about 11k tokens) and its summary otherwise; complete always delivers everything; summary needs --evidence_output + --evidence_output Save complete Evidence as a bundle; required for summary delivery. Never overwrites. Custom Global Options: --timings Write measured command timing to stderr. diff --git a/tests/fixtures/cli-parity/help-contract-long-description.txt b/tests/fixtures/cli-parity/help-contract-long-description.txt index 8b735066265..cf21d18ca47 100644 --- a/tests/fixtures/cli-parity/help-contract-long-description.txt +++ b/tests/fixtures/cli-parity/help-contract-long-description.txt @@ -11,7 +11,7 @@ Arguments: Options: --analysis Select standalone analysis. independent_fresh requires independent_decompile. call_destination requires call_destination_decompile and an exact address. - --detail Deliver complete Evidence, or a summary with --evidence_output (default: complete) + --detail Omit for complete Evidence when it fits the agent result budget (32768 compact JSON bytes by default, about 11k tokens) and its summary otherwise; complete always delivers everything; summary needs --evidence_output --snapshot Load and update a local analysis snapshot --target-format Explicit interpretation: dos-com or raw-binary (headerless), or gamecube-dol (GameCube/Wii DOL, never auto-detected); omission preserves header-based detection --architecture <6502|x86|x86_64|arm|arm64|m68k> Caller-supplied CPU family; required with --target-format raw-binary, must be omitted with gamecube-dol diff --git a/tests/fixtures/cli-parity/llms-full-command-yaml.txt b/tests/fixtures/cli-parity/llms-full-command-yaml.txt index c2dfa373f75..45d380d975e 100644 --- a/tests/fixtures/cli-parity/llms-full-command-yaml.txt +++ b/tests/fixtures/cli-parity/llms-full-command-yaml.txt @@ -46,6 +46,21 @@ commands: - type: string pattern: ^0*(?:[0-9]|[1-9][0-9]|[1-9][0-9]{2}|[1-9][0-9]{3}|[1-9][0-9]{4}|[1-9][0-9]{5}|[1-9][0-9]{6}|[1-9][0-9]{7}|[1-9][0-9]{8}|[1-9][0-9]{9}|[1-9][0-9]{10}|[1-9][0-9]{11}|[1-9][0-9]{12}|[1-9][0-9]{13}|[1-9][0-9]{14}|(?:1[0-9]{15}|[2-8][0-9]{15}|900(?:0[0-9]{12}|[1-6][0-9]{12}|7(?:0[0-9]{11}|1(?:0[0-9]{10}|[1-8][0-9]{10}|9(?:0[0-9]{9}|[1-8][0-9]{9}|9(?:0[0-9]{8}|1[0-9]{8}|2(?:0[0-9]{7}|[1-4][0-9]{7}|5(?:0[0-9]{6}|[1-3][0-9]{6}|4(?:0[0-9]{5}|[1-6][0-9]{5}|7(?:0[0-9]{4}|[1-3][0-9]{4}|40(?:0[0-9]{2}|[1-8][0-9]{2}|9(?:0[0-9]|[1-8][0-9]|9[0-1])))))))))))))$ description: Window length in bytes; omit to extend through EOF + detail: + description: Omit for complete Evidence when it fits the agent result budget + (32768 compact JSON bytes by default, about 11k tokens) and its + summary otherwise; complete always delivers everything; summary + needs --evidence_output + type: string + enum: + - complete + - summary + evidence_output: + description: Save complete Evidence as a bundle; required for summary delivery. + Never overwrites. + type: string + minLength: 1 + pattern: ^[^\x00]*$ additionalProperties: false globals: type: object diff --git a/tests/fixtures/cli-parity/llms-full-command.txt b/tests/fixtures/cli-parity/llms-full-command.txt index 2766bfa8ecd..e262da7c2f1 100644 --- a/tests/fixtures/cli-parity/llms-full-command.txt +++ b/tests/fixtures/cli-parity/llms-full-command.txt @@ -18,6 +18,8 @@ Inspect file-wide and block byte entropy without executing the file | `--block-size` | `unknown` | `4096` | Power-of-two block size from 256 to 65536 bytes | | `--offset` | `unknown` | `0` | Window start as a decimal file byte offset | | `--length` | `unknown` | | Window length in bytes; omit to extend through EOF | +| `--detail` | `string` | | Omit for complete Evidence when it fits the agent result budget (32768 compact JSON bytes by default, about 11k tokens) and its summary otherwise; complete always delivers everything; summary needs --evidence_output | +| `--evidence_output` | `string` | | Save complete Evidence as a bundle; required for summary delivery. Never overwrites. | --- stderr diff --git a/tests/fixtures/cli-parity/schema-command-json.txt b/tests/fixtures/cli-parity/schema-command-json.txt index c76b5e72ff8..7ac936c3d4f 100644 --- a/tests/fixtures/cli-parity/schema-command-json.txt +++ b/tests/fixtures/cli-parity/schema-command-json.txt @@ -1,7 +1,7 @@ $ rea inspect-byte-entropy --schema --format json exit: 0 --- stdout -{"args":{"type":"object","properties":{"path":{"type":"string","minLength":1,"pattern":"^[^\\x00]*$","description":"Local file"}},"required":["path"],"additionalProperties":false},"options":{"type":"object","properties":{"blockSize":{"default":4096,"anyOf":[{"type":"integer","minimum":256,"maximum":65536},{"type":"string","pattern":"^0*(?:(?:2(?:5[6-9]|[6-8][0-9]|9[0-9])|[3-8][0-9]{2}|9[0-9]{2})|[1-9][0-9]{3}|(?:1[0-9]{4}|[2-5][0-9]{4}|6(?:0[0-9]{3}|[1-4][0-9]{3}|5(?:0[0-9]{2}|[1-4][0-9]{2}|5(?:0[0-9]|[1-2][0-9]|3[0-6])))))$"}],"description":"Power-of-two block size from 256 to 65536 bytes"},"offset":{"default":0,"anyOf":[{"type":"integer","minimum":0,"maximum":9007199254740991},{"type":"string","pattern":"^0*(?:[0-9]|[1-9][0-9]|[1-9][0-9]{2}|[1-9][0-9]{3}|[1-9][0-9]{4}|[1-9][0-9]{5}|[1-9][0-9]{6}|[1-9][0-9]{7}|[1-9][0-9]{8}|[1-9][0-9]{9}|[1-9][0-9]{10}|[1-9][0-9]{11}|[1-9][0-9]{12}|[1-9][0-9]{13}|[1-9][0-9]{14}|(?:1[0-9]{15}|[2-8][0-9]{15}|900(?:0[0-9]{12}|[1-6][0-9]{12}|7(?:0[0-9]{11}|1(?:0[0-9]{10}|[1-8][0-9]{10}|9(?:0[0-9]{9}|[1-8][0-9]{9}|9(?:0[0-9]{8}|1[0-9]{8}|2(?:0[0-9]{7}|[1-4][0-9]{7}|5(?:0[0-9]{6}|[1-3][0-9]{6}|4(?:0[0-9]{5}|[1-6][0-9]{5}|7(?:0[0-9]{4}|[1-3][0-9]{4}|40(?:0[0-9]{2}|[1-8][0-9]{2}|9(?:0[0-9]|[1-8][0-9]|9[0-1])))))))))))))$"}],"description":"Window start as a decimal file byte offset"},"length":{"anyOf":[{"type":"integer","minimum":0,"maximum":9007199254740991},{"type":"string","pattern":"^0*(?:[0-9]|[1-9][0-9]|[1-9][0-9]{2}|[1-9][0-9]{3}|[1-9][0-9]{4}|[1-9][0-9]{5}|[1-9][0-9]{6}|[1-9][0-9]{7}|[1-9][0-9]{8}|[1-9][0-9]{9}|[1-9][0-9]{10}|[1-9][0-9]{11}|[1-9][0-9]{12}|[1-9][0-9]{13}|[1-9][0-9]{14}|(?:1[0-9]{15}|[2-8][0-9]{15}|900(?:0[0-9]{12}|[1-6][0-9]{12}|7(?:0[0-9]{11}|1(?:0[0-9]{10}|[1-8][0-9]{10}|9(?:0[0-9]{9}|[1-8][0-9]{9}|9(?:0[0-9]{8}|1[0-9]{8}|2(?:0[0-9]{7}|[1-4][0-9]{7}|5(?:0[0-9]{6}|[1-3][0-9]{6}|4(?:0[0-9]{5}|[1-6][0-9]{5}|7(?:0[0-9]{4}|[1-3][0-9]{4}|40(?:0[0-9]{2}|[1-8][0-9]{2}|9(?:0[0-9]|[1-8][0-9]|9[0-1])))))))))))))$"}],"description":"Window length in bytes; omit to extend through EOF"}},"additionalProperties":false},"globals":{"type":"object","properties":{"timings":{"default":false,"description":"Write measured command timing to stderr.","type":"boolean"}},"required":["timings"],"additionalProperties":false}} +{"args":{"type":"object","properties":{"path":{"type":"string","minLength":1,"pattern":"^[^\\x00]*$","description":"Local file"}},"required":["path"],"additionalProperties":false},"options":{"type":"object","properties":{"blockSize":{"default":4096,"anyOf":[{"type":"integer","minimum":256,"maximum":65536},{"type":"string","pattern":"^0*(?:(?:2(?:5[6-9]|[6-8][0-9]|9[0-9])|[3-8][0-9]{2}|9[0-9]{2})|[1-9][0-9]{3}|(?:1[0-9]{4}|[2-5][0-9]{4}|6(?:0[0-9]{3}|[1-4][0-9]{3}|5(?:0[0-9]{2}|[1-4][0-9]{2}|5(?:0[0-9]|[1-2][0-9]|3[0-6])))))$"}],"description":"Power-of-two block size from 256 to 65536 bytes"},"offset":{"default":0,"anyOf":[{"type":"integer","minimum":0,"maximum":9007199254740991},{"type":"string","pattern":"^0*(?:[0-9]|[1-9][0-9]|[1-9][0-9]{2}|[1-9][0-9]{3}|[1-9][0-9]{4}|[1-9][0-9]{5}|[1-9][0-9]{6}|[1-9][0-9]{7}|[1-9][0-9]{8}|[1-9][0-9]{9}|[1-9][0-9]{10}|[1-9][0-9]{11}|[1-9][0-9]{12}|[1-9][0-9]{13}|[1-9][0-9]{14}|(?:1[0-9]{15}|[2-8][0-9]{15}|900(?:0[0-9]{12}|[1-6][0-9]{12}|7(?:0[0-9]{11}|1(?:0[0-9]{10}|[1-8][0-9]{10}|9(?:0[0-9]{9}|[1-8][0-9]{9}|9(?:0[0-9]{8}|1[0-9]{8}|2(?:0[0-9]{7}|[1-4][0-9]{7}|5(?:0[0-9]{6}|[1-3][0-9]{6}|4(?:0[0-9]{5}|[1-6][0-9]{5}|7(?:0[0-9]{4}|[1-3][0-9]{4}|40(?:0[0-9]{2}|[1-8][0-9]{2}|9(?:0[0-9]|[1-8][0-9]|9[0-1])))))))))))))$"}],"description":"Window start as a decimal file byte offset"},"length":{"anyOf":[{"type":"integer","minimum":0,"maximum":9007199254740991},{"type":"string","pattern":"^0*(?:[0-9]|[1-9][0-9]|[1-9][0-9]{2}|[1-9][0-9]{3}|[1-9][0-9]{4}|[1-9][0-9]{5}|[1-9][0-9]{6}|[1-9][0-9]{7}|[1-9][0-9]{8}|[1-9][0-9]{9}|[1-9][0-9]{10}|[1-9][0-9]{11}|[1-9][0-9]{12}|[1-9][0-9]{13}|[1-9][0-9]{14}|(?:1[0-9]{15}|[2-8][0-9]{15}|900(?:0[0-9]{12}|[1-6][0-9]{12}|7(?:0[0-9]{11}|1(?:0[0-9]{10}|[1-8][0-9]{10}|9(?:0[0-9]{9}|[1-8][0-9]{9}|9(?:0[0-9]{8}|1[0-9]{8}|2(?:0[0-9]{7}|[1-4][0-9]{7}|5(?:0[0-9]{6}|[1-3][0-9]{6}|4(?:0[0-9]{5}|[1-6][0-9]{5}|7(?:0[0-9]{4}|[1-3][0-9]{4}|40(?:0[0-9]{2}|[1-8][0-9]{2}|9(?:0[0-9]|[1-8][0-9]|9[0-1])))))))))))))$"}],"description":"Window length in bytes; omit to extend through EOF"},"detail":{"description":"Omit for complete Evidence when it fits the agent result budget (32768 compact JSON bytes by default, about 11k tokens) and its summary otherwise; complete always delivers everything; summary needs --evidence_output","type":"string","enum":["complete","summary"]},"evidence_output":{"description":"Save complete Evidence as a bundle; required for summary delivery. Never overwrites.","type":"string","minLength":1,"pattern":"^[^\\x00]*$"}},"additionalProperties":false},"globals":{"type":"object","properties":{"timings":{"default":false,"description":"Write measured command timing to stderr.","type":"boolean"}},"required":["timings"],"additionalProperties":false}} --- stderr diff --git a/tests/fixtures/cli-parity/schema-command-md.txt b/tests/fixtures/cli-parity/schema-command-md.txt index 5513564adbc..a64e07a5e96 100644 --- a/tests/fixtures/cli-parity/schema-command-md.txt +++ b/tests/fixtures/cli-parity/schema-command-md.txt @@ -67,6 +67,27 @@ Window start as a decimal file byte offset Window length in bytes; omit to extend through EOF +## options.properties.detail.description + +Omit for complete Evidence when it fits the agent result budget (32768 compact JSON bytes by default, about 11k tokens) and its summary otherwise; complete always delivers everything; summary needs --evidence_output + +## options.properties.detail.type + +string + +## options.properties.detail.enum + +\["complete","summary"\] + +## options.properties.evidence_output + +| Key | Value | +|-------------|--------------------------------------------------------------------------------------| +| description | Save complete Evidence as a bundle; required for summary delivery. Never overwrites. | +| type | string | +| minLength | 1 | +| pattern | ^\[^\\x00\]\*$ | + ## options.additionalProperties false diff --git a/tests/fixtures/cli-parity/schema-command.txt b/tests/fixtures/cli-parity/schema-command.txt index 05e29034523..0efd5a67987 100644 --- a/tests/fixtures/cli-parity/schema-command.txt +++ b/tests/fixtures/cli-parity/schema-command.txt @@ -40,6 +40,15 @@ options: - type: string pattern: "^0*(?:[0-9]|[1-9][0-9]|[1-9][0-9]{2}|[1-9][0-9]{3}|[1-9][0-9]{4}|[1-9][0-9]{5}|[1-9][0-9]{6}|[1-9][0-9]{7}|[1-9][0-9]{8}|[1-9][0-9]{9}|[1-9][0-9]{10}|[1-9][0-9]{11}|[1-9][0-9]{12}|[1-9][0-9]{13}|[1-9][0-9]{14}|(?:1[0-9]{15}|[2-8][0-9]{15}|900(?:0[0-9]{12}|[1-6][0-9]{12}|7(?:0[0-9]{11}|1(?:0[0-9]{10}|[1-8][0-9]{10}|9(?:0[0-9]{9}|[1-8][0-9]{9}|9(?:0[0-9]{8}|1[0-9]{8}|2(?:0[0-9]{7}|[1-4][0-9]{7}|5(?:0[0-9]{6}|[1-3][0-9]{6}|4(?:0[0-9]{5}|[1-6][0-9]{5}|7(?:0[0-9]{4}|[1-3][0-9]{4}|40(?:0[0-9]{2}|[1-8][0-9]{2}|9(?:0[0-9]|[1-8][0-9]|9[0-1])))))))))))))$" description: Window length in bytes; omit to extend through EOF + detail: + description: "Omit for complete Evidence when it fits the agent result budget (32768 compact JSON bytes by default, about 11k tokens) and its summary otherwise; complete always delivers everything; summary needs --evidence_output" + type: string + enum[2]: complete,summary + evidence_output: + description: Save complete Evidence as a bundle; required for summary delivery. Never overwrites. + type: string + minLength: 1 + pattern: "^[^\\x00]*$" additionalProperties: false globals: type: object diff --git a/tests/fixtures/cli-parity/terminal-error-refined-number.txt b/tests/fixtures/cli-parity/terminal-error-refined-number.txt index 33abe917b83..b482a54de49 100644 --- a/tests/fixtures/cli-parity/terminal-error-refined-number.txt +++ b/tests/fixtures/cli-parity/terminal-error-refined-number.txt @@ -13,9 +13,11 @@ Arguments: path Local file Options: - --block-size Power-of-two block size from 256 to 65536 bytes (default: 4096) - --offset Window start as a decimal file byte offset (default: 0) - --length Window length in bytes; omit to extend through EOF + --block-size Power-of-two block size from 256 to 65536 bytes (default: 4096) + --offset Window start as a decimal file byte offset (default: 0) + --length Window length in bytes; omit to extend through EOF + --detail Omit for complete Evidence when it fits the agent result budget (32768 compact JSON bytes by default, about 11k tokens) and its summary otherwise; complete always delivers everything; summary needs --evidence_output + --evidence_output Save complete Evidence as a bundle; required for summary delivery. Never overwrites. Global Options: --filter-output Filter output by key paths (e.g. foo,bar.baz,a[0,3]) diff --git a/tests/fixtures/cli-parity/terminal-help-command.txt b/tests/fixtures/cli-parity/terminal-help-command.txt index d62ef7f2338..3faadd7bd3d 100644 --- a/tests/fixtures/cli-parity/terminal-help-command.txt +++ b/tests/fixtures/cli-parity/terminal-help-command.txt @@ -9,9 +9,11 @@ Arguments: path Local file Options: - --block-size Power-of-two block size from 256 to 65536 bytes (default: 4096) - --offset Window start as a decimal file byte offset (default: 0) - --length Window length in bytes; omit to extend through EOF + --block-size Power-of-two block size from 256 to 65536 bytes (default: 4096) + --offset Window start as a decimal file byte offset (default: 0) + --length Window length in bytes; omit to extend through EOF + --detail Omit for complete Evidence when it fits the agent result budget (32768 compact JSON bytes by default, about 11k tokens) and its summary otherwise; complete always delivers everything; summary needs --evidence_output + --evidence_output Save complete Evidence as a bundle; required for summary delivery. Never overwrites. Custom Global Options: --timings Write measured command timing to stderr. diff --git a/tests/fixtures/javascriptReturnShapes.ts b/tests/fixtures/javascriptReturnShapes.ts index 8e24c39ef4b..24ae8883358 100644 --- a/tests/fixtures/javascriptReturnShapes.ts +++ b/tests/fixtures/javascriptReturnShapes.ts @@ -49,6 +49,8 @@ const analyzeReturnShapesThroughCli = async ( const cliResponse = await cli.run({ arguments: [ "analyze-javascript-application", + "--detail", + "complete", root, "--artifact-format", "directory", @@ -101,7 +103,7 @@ export const verifyJavaScriptReturnShapes = async ( await client.connect(transport); const response = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: root, format: "directory" }, + arguments: { detail: "complete", input_path: root, format: "directory" }, }); expect(response.isError).not.toBe(true); const evidence = contract.outputSchema.parse(response.structuredContent); diff --git a/tests/fixtures/localToolsMcp.ts b/tests/fixtures/localToolsMcp.ts index 0b3ffab3c38..4db32597b34 100644 --- a/tests/fixtures/localToolsMcp.ts +++ b/tests/fixtures/localToolsMcp.ts @@ -16,6 +16,10 @@ import { fileURLToPath } from "node:url"; import { afterAll, beforeAll, expect, onTestFinished } from "vitest"; import { createMcpSchemaValidation } from "./mcpSchemaValidation.js"; import { createSharedMcpSession } from "../support/mcp/sharedMcpSession.js"; +import { + applyCompleteEvidenceByDefault, + type TestDelivery, +} from "../support/completeEvidenceByDefault.js"; /** Default to native tools while preserving explicit caller configuration. */ export const localToolsMcpEnvironment = ( @@ -34,6 +38,7 @@ export async function connectLocalToolsMcp( registerCleanup: (cleanup: () => Promise) => void = onTestFinished, transportOptions: Readonly> = {}, jsonSchemaValidator?: NonNullable, + delivery: TestDelivery = "completeEvidenceByDefault", ) { const transport = new StdioClientTransport({ ...transportOptions, @@ -46,9 +51,12 @@ export async function connectLocalToolsMcp( stderr: "pipe", }); const validation = createMcpSchemaValidation(); - const client = new Client( - { name: "local-tools-e2e", version: "1" }, - { jsonSchemaValidator: jsonSchemaValidator ?? validation }, + const client = applyCompleteEvidenceByDefault( + new Client( + { name: "local-tools-e2e", version: "1" }, + { jsonSchemaValidator: jsonSchemaValidator ?? validation }, + ), + delivery, ); registerCleanup(async () => { await closeVerifierResources([ diff --git a/tests/process-global/browserScenarioCleanup.test.ts b/tests/process-global/browserScenarioCleanup.test.ts index 6b7c52166ea..e1d39006bc1 100644 --- a/tests/process-global/browserScenarioCleanup.test.ts +++ b/tests/process-global/browserScenarioCleanup.test.ts @@ -34,6 +34,7 @@ import { import { ok } from "../../src/domain/result.js"; import { phaseGate } from "../support/lifecycleHarness.js"; import { primaryAnalysisError } from "../../src/domain/analysisErrorBase.js"; +import { COMPLETE_DETAIL } from "../support/completeDetail.js"; const state = vi.hoisted(() => ({ provider: undefined as BrowserScenarioCapturePort | undefined, @@ -151,7 +152,12 @@ const serveScenario = async () => { let stdout = ""; let exitCode = 0; await cli.serve( - ["capture-browser-scenario", JSON.stringify(scenario), "--json"], + [ + "capture-browser-scenario", + ...COMPLETE_DETAIL, + JSON.stringify(scenario), + "--json", + ], { env: {}, exit: (code) => { diff --git a/tests/process-global/javascriptAnalysisCancellation.test.ts b/tests/process-global/javascriptAnalysisCancellation.test.ts index 5025c83dff7..2a312a02858 100644 --- a/tests/process-global/javascriptAnalysisCancellation.test.ts +++ b/tests/process-global/javascriptAnalysisCancellation.test.ts @@ -154,6 +154,7 @@ it.each([ { name: "analyze_javascript_application", arguments: { + detail: "complete", input_path: root, format: "directory", }, @@ -218,10 +219,7 @@ it.each([ expect(view.isError, JSON.stringify(view)).not.toBe(true); const next = await client.callTool({ name: "analyze_javascript_application", - arguments: { - input_path: root, - format: "directory", - }, + arguments: { detail: "complete", input_path: root, format: "directory" }, }); expect(next.isError, JSON.stringify(next)).not.toBe(true); await client.ping(); diff --git a/tests/process-global/javascriptFilesystemErrors.test.ts b/tests/process-global/javascriptFilesystemErrors.test.ts index 9b41239159a..6aebcf2535c 100644 --- a/tests/process-global/javascriptFilesystemErrors.test.ts +++ b/tests/process-global/javascriptFilesystemErrors.test.ts @@ -67,7 +67,11 @@ it.each([ ); const response = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: root, format: "directory" }, + arguments: { + detail: "complete", + input_path: root, + format: "directory", + }, }); expect(fault.calls).toBe(1); expect(response.isError).toBe(true); @@ -102,7 +106,11 @@ it.each([ fault.method = ""; const control = await client.callTool({ name: "analyze_javascript_application", - arguments: { input_path: root, format: "directory" }, + arguments: { + detail: "complete", + input_path: root, + format: "directory", + }, }); expect(control.isError, JSON.stringify(control)).not.toBe(true); } finally { diff --git a/tests/process-global/javascriptRuntimeObservationCli.test.ts b/tests/process-global/javascriptRuntimeObservationCli.test.ts index b2e08303536..a9c10960886 100644 --- a/tests/process-global/javascriptRuntimeObservationCli.test.ts +++ b/tests/process-global/javascriptRuntimeObservationCli.test.ts @@ -16,6 +16,7 @@ import { ProviderCleanupError } from "../../src/domain/providerCleanupError.js"; import { ok } from "../../src/domain/result.js"; import { silentLogger } from "../../src/logger.js"; import { cliTest } from "../support/cli/cliFixture.js"; +import { completeApplicationAnalysis } from "../support/completeDetail.js"; const runtimeFactory = vi.hoisted(() => ({ provider: undefined as JavaScriptRuntimeObservationPort | undefined, @@ -109,7 +110,7 @@ cliTest( }, }); const analyzed = await cli.run({ - arguments: ["analyze-javascript-application", root, "--json"], + arguments: completeApplicationAnalysis(root), }); expect(analyzed.exitCode, analyzed.stderr).toBe(0); const analysis = parseEvidence(analyzed.json); diff --git a/tests/process-global/mcpDeliveryEnvironment.test.ts b/tests/process-global/mcpDeliveryEnvironment.test.ts index ac4a1554e11..ab1e71f8691 100644 --- a/tests/process-global/mcpDeliveryEnvironment.test.ts +++ b/tests/process-global/mcpDeliveryEnvironment.test.ts @@ -95,7 +95,7 @@ it("keeps independent server budgets for successful results and oversized errors [smallClient, largeClient].map((client) => client.callTool({ name: "procedure_pseudo_code", - arguments: { procedure: "main" }, + arguments: { detail: "complete", procedure: "main" }, }), ), ); diff --git a/tests/process-global/stableArtifactConsumers.test.ts b/tests/process-global/stableArtifactConsumers.test.ts index ee531c0a4f6..c012cccd9b6 100644 --- a/tests/process-global/stableArtifactConsumers.test.ts +++ b/tests/process-global/stableArtifactConsumers.test.ts @@ -873,7 +873,7 @@ mcpTest( for (let attempt = 0; attempt < 2; attempt++) { const response = await client.callTool({ name: "inspect_rust_binary", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(response.isError).toBe(true); const { error } = parseMcpToolError(response); @@ -916,7 +916,7 @@ mcpTest( fault.blocked.clear(); const recovered = await client.callTool({ name: "inspect_rust_binary", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(recovered.isError).not.toBe(true); expect(failures.map((error) => error.cleanupIncomplete)).toEqual([ @@ -1005,7 +1005,7 @@ mcpTest( try { const response = await client.callTool({ name: "inspect_rust_binary", - arguments: { path }, + arguments: { detail: "complete", path }, }); expect(parseMcpToolError(response).error.code).toBe("cleanup_incomplete"); expect(fault.handles[0]?.fd).toBeGreaterThanOrEqual(0); diff --git a/tests/process-global/windowsNativeControlCapability.test.ts b/tests/process-global/windowsNativeControlCapability.test.ts index 2f2f5f36826..7acdab6acb3 100644 --- a/tests/process-global/windowsNativeControlCapability.test.ts +++ b/tests/process-global/windowsNativeControlCapability.test.ts @@ -120,7 +120,7 @@ it("reports a missing Windows native control as an unavailable capability", asyn const response = await client.callTool({ name: "trace_web_source_location", - arguments: webSourceLocationArgs, + arguments: { ...webSourceLocationArgs, detail: "complete" }, }); const { error } = parseMcpToolError(response as CallToolResult); diff --git a/tests/support/cli/cliCommandSession.ts b/tests/support/cli/cliCommandSession.ts index 8149df589af..6c144f3764b 100644 --- a/tests/support/cli/cliCommandSession.ts +++ b/tests/support/cli/cliCommandSession.ts @@ -4,6 +4,10 @@ import { fileURLToPath } from "node:url"; import { z } from "zod"; import { waitForExit } from "../process/processFixture.js"; +import { + completeEvidenceCliArguments, + type TestDelivery, +} from "../completeEvidenceByDefault.js"; import { createCliSessionFrameReader, encodeCliSessionFrame, @@ -34,6 +38,8 @@ export interface CliCommandRequest { readonly arguments: readonly string[]; readonly cwd: string; readonly environment: Readonly>; + /** The harness requests complete Evidence unless this is `"budgeted"`. */ + readonly delivery?: TestDelivery; } /** Captured result from one shared CLI command. */ @@ -220,7 +226,19 @@ class SharedCliProcess implements CliCommandSession { } run(request: CliCommandRequest): Promise { - const result = this.#queue.then(() => this.#invoke(request)); + const result = this.#queue.then(async () => { + const selected = + request.delivery === "budgeted" + ? request + : { + ...request, + arguments: await completeEvidenceCliArguments( + request.arguments, + request.cwd, + ), + }; + return this.#invoke(selected); + }); this.#queue = result.then( () => undefined, () => undefined, diff --git a/tests/support/cli/cliFixture.ts b/tests/support/cli/cliFixture.ts index 39c29d1f993..c29564affa0 100644 --- a/tests/support/cli/cliFixture.ts +++ b/tests/support/cli/cliFixture.ts @@ -27,10 +27,16 @@ import { } from "../mcp/sharedMcpSession.js"; import { REGISTRATION_GUARD_NODE_OPTIONS_ENV } from "./registrationEnvironment.js"; import { terminalStdoutInvocation } from "./terminalStdout.js"; +import { + completeEvidenceCliArguments, + type TestDelivery, +} from "../completeEvidenceByDefault.js"; /** Caller-controlled values for one compiled REA CLI invocation. */ export interface CliInvocation { readonly arguments: readonly string[]; + /** The harness requests complete Evidence unless this is `"budgeted"`. */ + readonly delivery?: TestDelivery; readonly cwd?: string; readonly environment?: NodeJS.ProcessEnv; readonly input?: string | Uint8Array; @@ -199,7 +205,8 @@ export const createTestCli = ( compileCache?: string, ): TestCli => ({ run: async ({ - arguments: arguments_, + arguments: written, + delivery, cwd, environment, input, @@ -208,6 +215,10 @@ export const createTestCli = ( }) => { if (terminal === true && input !== undefined) throw new Error("A terminal run has an empty stdin."); + const arguments_ = + delivery === "budgeted" + ? written + : await completeEvidenceCliArguments(written, cwd); const rea = [resolve("scripts/rea.mjs"), ...arguments_]; const { command, arguments: commandArguments } = terminal === true @@ -274,6 +285,9 @@ export const cliTest = processTest.extend<{ sharedProcessCanServe(invocation) ? cliCommandSession.run({ arguments: invocation.arguments, + ...(invocation.delivery === undefined + ? {} + : { delivery: invocation.delivery }), cwd: invocation.cwd ?? process.cwd(), environment: definedCliEnvironment( cliProcessEnvironment(invocation.environment, cliCompileCache), diff --git a/tests/support/cli/javascriptApplication.ts b/tests/support/cli/javascriptApplication.ts index 0d70ae42d5c..096ec260e63 100644 --- a/tests/support/cli/javascriptApplication.ts +++ b/tests/support/cli/javascriptApplication.ts @@ -9,6 +9,7 @@ import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/j import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "../../../scripts/lib/mcp-verification-environment.mjs"; import type { SharedMcpCall, TestCli } from "./cliFixture.js"; +import { COMPLETE_DETAIL } from "../completeDetail.js"; const execute = promisify(execFile); @@ -60,6 +61,7 @@ export const analyzeJavaScriptDirectory = async ( const response = await run({ arguments: [ "analyze-javascript-application", + ...COMPLETE_DETAIL, root, ...sourcePaths.flatMap((path) => ["--source-path", path]), "--format", @@ -72,6 +74,7 @@ export const analyzeJavaScriptDirectory = async ( } else { const call = await resolveJavaScriptApplicationMcpCall(cli, mcpCall); const response = await call("analyze_javascript_application", { + detail: "complete", input_path: root, format: "directory", ...(sourcePaths.length === 0 ? {} : { source_paths: sourcePaths }), diff --git a/tests/support/completeDetail.ts b/tests/support/completeDetail.ts new file mode 100644 index 00000000000..5792bf57079 --- /dev/null +++ b/tests/support/completeDetail.ts @@ -0,0 +1,18 @@ +/** + * CLI arguments that request complete Evidence inline. Workflows that read + * complete Evidence from a tool whose omitted detail is budgeted ask for it + * with these, instead of relying on the agent result budget. + */ +export const COMPLETE_DETAIL = ["--detail", "complete"] as const; + +/** `rea ` argv with complete Evidence as JSON. */ +export const completeArguments = (command: string, path: string): string[] => [ + command, + ...COMPLETE_DETAIL, + path, + "--json", +]; + +/** `rea analyze-javascript-application ` with complete Evidence as JSON. */ +export const completeApplicationAnalysis = (path: string): string[] => + completeArguments("analyze-javascript-application", path); diff --git a/tests/support/completeEvidenceByDefault.ts b/tests/support/completeEvidenceByDefault.ts new file mode 100644 index 00000000000..41aa6ef141c --- /dev/null +++ b/tests/support/completeEvidenceByDefault.ts @@ -0,0 +1,207 @@ +import { resolve } from "node:path"; +import type { Client } from "@modelcontextprotocol/client"; + +import { TOOL_CONTRACTS } from "../../src/contracts/toolContracts.js"; +import { AGENT_BUDGET_OPERATIONS } from "../../src/domain/agentBudgetOperations.js"; +import { createCli } from "../../src/cli.js"; +import { parseCliArgv } from "../../src/cli/argvParser.js"; +import { cliCommands } from "../../src/cli/commandRegistry.js"; +import { isJavaScriptApplicationPath } from "../../src/cli/coreBinaryCommands.js"; +import { parseCliGlobalArguments } from "../../src/cliBuiltinArguments.js"; +import { COMPLETE_DETAIL } from "./completeDetail.js"; + +/** + * Test-harness delivery policy. Production omitted `detail` is budgeted: + * complete Evidence when it fits the agent result budget, a retained summary + * otherwise. Most tests read complete Evidence, so the shared transport + * helpers request it by default. Tests whose subject is delivery itself pass + * `"budgeted"` to send calls exactly as written. + */ +export type TestDelivery = "completeEvidenceByDefault" | "budgeted"; + +/** + * The server environment for a test's delivery choice. The test environment + * seeds the largest agent result budget so spawned processes deliver complete + * Evidence; a "budgeted" test removes that seed and gets the shipped default. + */ +export const testDeliveryEnvironment = ( + environment: NodeJS.ProcessEnv, + delivery: TestDelivery | undefined, +): NodeJS.ProcessEnv => { + if (delivery !== "budgeted") return environment; + const { REA_AGENT_RESULT_BUDGET_BYTES: _seed, ...shipped } = environment; + return shipped; +}; + +const contracts = new Map( + TOOL_CONTRACTS.map((contract) => [contract.name, contract] as const), +); + +/** + * Each budgeted operation must resolve to a tool contract; otherwise the + * default could not know what it changes, so the harness fails loudly at + * load instead of guessing. `src/contracts/analysisDetail.test.ts` proves the + * list equals the contracts whose omitted `detail` is budgeted. Every other + * tool, an REA contract or a forwarded upstream tool, is sent as written. + */ +const budgeted: ReadonlySet = new Set( + AGENT_BUDGET_OPERATIONS.map((name) => { + if (!contracts.has(name)) + throw new Error( + `completeEvidenceByDefault cannot resolve a tool contract for budgeted operation "${name}".`, + ); + return name; + }), +); + +interface CliDetailMetadata { + readonly detailCommands: ReadonlySet; + readonly analyzeEntry: ReturnType[number] | undefined; + readonly jsOptionKeys: ReadonlySet; +} + +/** + * CLI commands whose `--detail` accepts `"complete"`, read from the CLI's own + * registry. Commands whose `--detail` uses another enum (such as + * `import-reference-source` with `"full" | "summary"`) are excluded. + */ +let cachedCliMetadata: CliDetailMetadata | undefined; +const cliDetailMetadata = (): CliDetailMetadata => { + if (cachedCliMetadata !== undefined) return cachedCliMetadata; + const commands = new Map( + cliCommands(createCli({})).map((entry) => [entry.name, entry] as const), + ); + const detailCommands = new Set( + [...commands.values()] + .filter((entry) => { + const shape = ( + entry.definition.options as + | { + readonly shape?: Readonly< + Record< + string, + { + safeParse?: (v: unknown) => { readonly success: boolean }; + } + > + >; + } + | undefined + )?.shape; + const detail = shape?.detail; + return ( + detail !== undefined && + typeof detail.safeParse === "function" && + detail.safeParse("complete").success + ); + }) + .map(({ name }) => name), + ); + const jsShape = ( + commands.get("analyze-javascript-application")?.definition.options as + | { readonly shape?: object } + | undefined + )?.shape; + cachedCliMetadata = { + detailCommands, + analyzeEntry: commands.get("analyze"), + jsOptionKeys: new Set(jsShape === undefined ? [] : Object.keys(jsShape)), + }; + return cachedCliMetadata; +}; + +/** Whether an `analyze` invocation selects the JavaScript route (which takes `--detail`). */ +const selectsAnalyzeJavaScriptRoute = async ( + metadata: CliDetailMetadata, + commandArgs: readonly string[], + cwd: string | undefined, +): Promise => { + if (metadata.analyzeEntry === undefined) return false; + const parsed = parseCliArgv(commandArgs, metadata.analyzeEntry.definition); + if (!parsed.ok) return false; + const suppliedOptions = Object.entries(parsed.value.options) + .filter(([, value]) => value !== undefined) + .map(([key]) => key); + if (!suppliedOptions.every((key) => metadata.jsOptionKeys.has(key))) + return false; + const target = parsed.value.args.path; + if (typeof target !== "string" || target.length === 0) return false; + return isJavaScriptApplicationPath(resolve(cwd ?? process.cwd(), target)); +}; + +/** + * The arguments one MCP call sends under the complete-Evidence default: a + * budgeted tool called with neither `detail` nor `view` gets + * `detail: "complete"`. Any other tool is sent as written. + */ +export const completeEvidenceArguments = ( + name: string, + arguments_: Record | undefined, +): Record | undefined => { + if (!budgeted.has(name)) return arguments_; + const selected = arguments_ ?? {}; + return Object.hasOwn(selected, "detail") || Object.hasOwn(selected, "view") + ? arguments_ + : { ...selected, detail: "complete" }; +}; + +/** + * The argv one CLI invocation runs under the complete-Evidence default: a + * command whose `--detail` accepts `"complete"`, given neither `--detail` nor + * `--view` (and selecting a route that accepts `--detail` when routed), gets + * `--detail complete` after the command word. Other commands run as written. + */ +export const completeEvidenceCliArguments = async ( + arguments_: readonly string[], + cwd?: string, +): Promise => { + const [command, ...rest] = arguments_; + const metadata = cliDetailMetadata(); + if (command === undefined || !metadata.detailCommands.has(command)) + return arguments_; + const global = parseCliGlobalArguments(arguments_); + if ( + global.flags.has("--help") || + global.flags.has("-h") || + global.flags.has("--schema") + ) + return arguments_; + const selects = (flag: string) => + rest.some( + (argument) => argument === flag || argument.startsWith(`${flag}=`), + ); + if (selects("--detail") || selects("--view")) return arguments_; + if ( + command === "analyze" && + !(await selectsAnalyzeJavaScriptRoute( + metadata, + global.command.slice(1), + cwd, + )) + ) + return arguments_; + return [command, ...COMPLETE_DETAIL, ...rest]; +}; + +const applied = new WeakSet(); + +/** + * Apply the complete-Evidence default to every `callTool` on this client. + * The shared MCP helpers call it once per client they create. + */ +export const applyCompleteEvidenceByDefault = ( + client: Client, + delivery: TestDelivery = "completeEvidenceByDefault", +): Client => { + if (delivery === "budgeted" || applied.has(client)) return client; + applied.add(client); + const callTool = client.callTool.bind(client); + client.callTool = ((params, ...rest) => { + const arguments_ = completeEvidenceArguments(params.name, params.arguments); + return callTool( + arguments_ === undefined ? params : { ...params, arguments: arguments_ }, + ...rest, + ); + }) as Client["callTool"]; + return client; +}; diff --git a/tests/support/mcp/mcpFixture.ts b/tests/support/mcp/mcpFixture.ts index 2ebe9e18a48..426bf4bfb2d 100644 --- a/tests/support/mcp/mcpFixture.ts +++ b/tests/support/mcp/mcpFixture.ts @@ -6,6 +6,10 @@ import { import type { McpServer } from "@modelcontextprotocol/server"; import { test as base } from "vitest"; import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; +import { + applyCompleteEvidenceByDefault, + type TestDelivery, +} from "../completeEvidenceByDefault.js"; /** Client identity used during an in-memory MCP negotiation. */ export interface McpClientIdentity { @@ -37,6 +41,7 @@ export interface TestMcp { server: McpServer, identity?: McpClientIdentity, jsonSchemaValidator?: NonNullable, + delivery?: TestDelivery, ): Promise; close(): Promise; } @@ -100,6 +105,7 @@ export const createTestMcp = (): TestMcp => { server, identity = DEFAULT_CLIENT_IDENTITY, jsonSchemaValidator, + delivery = "completeEvidenceByDefault", ) => { if (closed) return Promise.reject(registryClosed()); // Compile shared schema references once per connection instead of @@ -110,7 +116,10 @@ export const createTestMcp = (): TestMcp => { validation = createMcpSchemaValidation(); jsonSchemaValidator = validation; } - const client = new Client(identity, { jsonSchemaValidator }); + const client = applyCompleteEvidenceByDefault( + new Client(identity, { jsonSchemaValidator }), + delivery, + ); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const connection: McpConnectionOwner = { diff --git a/vitest.config.ts b/vitest.config.ts index db53389f1aa..8c72b2e9739 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -177,6 +177,10 @@ export default defineConfig({ test: { env: { TMPDIR: CANONICAL_TEMPORARY_DIRECTORY, + // Tests read analysis facts, so a CLI or server they spawn delivers + // complete Evidence, as the in-process harness default does. Delivery + // tests set their own budget; this is the largest accepted seed. + REA_AGENT_RESULT_BUDGET_BYTES: String(10 * 1024 * 1024), }, maxWorkers: MAX_TEST_WORKERS, projects,