From 717333ce9b240a3a711c9deca23045bab744b028 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:50:32 +0800 Subject: [PATCH] refactor(contracts): declare each tool's effect audit on its contract (#11305) * refactor(contracts): declare each tool's effect audit on its contract Every public tool's effects lived in a 255-entry TOOL_EFFECT_AUDIT table in toolEffects.ts, keyed by name and looked up again by toolContractMetadata, the capability inventory (toolSessionEffects) and tests (TOOL_EFFECTS). toolContractMetadata(name, audit) now takes the audit from the contract declaration, and the contract carries both the provider-wide effects and the session effects. The inventory reads contract.sessionEffects. The table, TOOL_EFFECTS and toolSessionEffects are removed; toolEffects.ts keeps the effect type, the shared presets and annotation derivation. Effects, session effects, annotations and titles are byte-identical for all 255 contracts. * test(contracts): read focused effect expectations from their contract family --- src/application/CapabilityInventory.ts | 3 +- .../binary/BinarySession.openEffects.test.ts | 7 +- src/contracts/adb/adbToolContracts.ts | 244 ++++- src/contracts/analysisSettingsContracts.ts | 9 +- src/contracts/analysisViewToolContracts.ts | 4 +- src/contracts/android/androidToolContracts.ts | 56 +- src/contracts/apiContractToolContracts.ts | 4 +- .../apkSignature/apkSignatureToolContracts.ts | 4 +- src/contracts/apktool/apktoolToolContracts.ts | 19 +- src/contracts/applicationToolContracts.ts | 49 +- src/contracts/artifactToolContracts.ts | 26 +- src/contracts/browserScenarioToolContracts.ts | 17 +- src/contracts/browserToolContracts.ts | 30 +- .../captures/captureToolContracts.ts | 20 +- src/contracts/cutterToolContracts.ts | 21 +- .../desktopApplicationToolContracts.ts | 4 +- src/contracts/desktopBuildMeasureContract.ts | 15 +- src/contracts/desktopBuildSecretsContract.ts | 11 +- src/contracts/desktopBuildToolContracts.ts | 98 +- src/contracts/enhancedToolContracts.ts | 40 +- src/contracts/environmentToolContracts.ts | 10 +- src/contracts/erlang/beamToolContracts.ts | 4 +- src/contracts/evm/evmToolContracts.ts | 11 +- .../firmware/firmwareToolContracts.ts | 21 +- src/contracts/flutter/flutterToolContracts.ts | 18 +- src/contracts/fridaToolContracts.ts | 91 +- .../functionWorkflowToolContracts.ts | 17 +- src/contracts/gdbToolContracts.ts | 38 +- src/contracts/go/goToolContracts.ts | 4 +- src/contracts/gpu/gpuToolContracts.ts | 4 +- src/contracts/hopperMemoryContracts.ts | 4 + src/contracts/il2cpp/il2cppToolContracts.ts | 4 +- .../javascript/electronToolContracts.ts | 39 +- .../javascriptRecoveryToolContracts.ts | 12 +- ...vascriptRuntimeObservationToolContracts.ts | 15 +- src/contracts/jeb/jebToolContracts.ts | 35 +- src/contracts/managed/managedToolContracts.ts | 11 +- .../managed/managedWorkflowToolContracts.ts | 16 +- src/contracts/model/modelToolContracts.ts | 4 +- .../native/binaryDiagnosticsToolContracts.ts | 54 +- src/contracts/native/nativeToolContracts.ts | 41 +- src/contracts/ntfsJournalToolContracts.ts | 4 +- src/contracts/officialToolContracts.ts | 85 +- src/contracts/pcap/pcapToolContracts.ts | 20 +- src/contracts/playwrightTraceToolContracts.ts | 4 +- .../python/pythonPycToolContracts.ts | 4 +- src/contracts/releaseExposureToolContracts.ts | 11 +- .../reverseEngineeringToolContracts.ts | 24 +- src/contracts/rizinDebugToolContracts.ts | 45 +- src/contracts/rust/rustToolContracts.ts | 4 +- src/contracts/sessionToolContracts.ts | 75 +- src/contracts/signals/signalToolContracts.ts | 20 +- src/contracts/sqlite/sqliteToolContracts.ts | 11 +- src/contracts/toolContractTypes.ts | 3 + src/contracts/toolEffects.test.ts | 32 +- src/contracts/toolEffects.ts | 932 +----------------- src/contracts/v8/v8CodeCacheToolContracts.ts | 4 +- src/contracts/wasm/wasmComparisonContracts.ts | 4 +- src/contracts/wasm/wasmToolContracts.ts | 11 +- .../webNetworkCaptureToolContracts.ts | 11 +- src/contracts/webRuntimeToolContracts.ts | 22 +- src/contracts/webScriptToolContracts.ts | 30 +- .../boundary/mcp/binaryDiagnosticsMcp.test.ts | 3 +- tests/boundary/mcp/serverIdentity.test.ts | 7 +- tests/boundary/mcp/toolResult.test.ts | 25 +- .../providers/RizinInferiorTty.test.ts | 8 +- .../ida/idaCapabilityInventory.test.ts | 38 +- 67 files changed, 1393 insertions(+), 1178 deletions(-) diff --git a/src/application/CapabilityInventory.ts b/src/application/CapabilityInventory.ts index 31025c2bcb..efe2ded189 100644 --- a/src/application/CapabilityInventory.ts +++ b/src/application/CapabilityInventory.ts @@ -36,7 +36,6 @@ import { } from "../contracts/toolOutputSchemaPrimitives.js"; import { annotationsFromEffects, - toolSessionEffects, type ToolEffects, } from "../contracts/toolEffects.js"; import type { ToolKind } from "../contracts/toolContractTypes.js"; @@ -349,7 +348,7 @@ export const buildCapabilityInventory = ( }); const effects = composedEffects( contract.name, - toolSessionEffects(contract.name), + contract.sessionEffects, status.capabilities, ); const annotations = annotationsFromEffects(effects); diff --git a/src/application/binary/BinarySession.openEffects.test.ts b/src/application/binary/BinarySession.openEffects.test.ts index d0fc70e6c6..0e3994ed27 100644 --- a/src/application/binary/BinarySession.openEffects.test.ts +++ b/src/application/binary/BinarySession.openEffects.test.ts @@ -4,7 +4,7 @@ import { expect, it, onTestFinished } from "vitest"; import type { AnalysisProvider } from "../AnalysisProvider.js"; import { BinarySession } from "./BinarySession.js"; -import { toolSessionEffects } from "../../contracts/toolEffects.js"; +import { SESSION_TOOL_CONTRACTS } from "../../contracts/sessionToolContracts.js"; import { ok } from "../../domain/result.js"; import { observed } from "../../../tests/fixtures/analysisExecution.js"; import { @@ -94,7 +94,10 @@ it.each([ await expect(readFile(checkpointPath, "utf8")).rejects.toMatchObject({ code: "ENOENT", }); - expect(toolSessionEffects(operation)).toMatchObject({ + expect( + SESSION_TOOL_CONTRACTS.find(({ name }) => name === operation) + ?.sessionEffects, + ).toMatchObject({ writesFilesystem: true, mayDiscardData: true, }); diff --git a/src/contracts/adb/adbToolContracts.ts b/src/contracts/adb/adbToolContracts.ts index 7402412918..fafb2ebd29 100644 --- a/src/contracts/adb/adbToolContracts.ts +++ b/src/contracts/adb/adbToolContracts.ts @@ -4,14 +4,20 @@ import { } from "../../domain/adb/adbDeviceAnalysis.js"; import type { ToolContract } from "../toolContractTypes.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; /** ADB device inspection and acquisition over a caller-supplied binary. */ export const ADB_TOOL_CONTRACTS = [ { name: "inspect_adb_client", cli: true, - ...toolContractMetadata("inspect_adb_client"), + ...toolContractMetadata( + "inspect_adb_client", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + }), + ), description: "Inspect the caller-selected adb client: resolved binary, version, and install path. Never contacts devices and never starts the adb server. REA never installs platform tools; select a binary with REA_ADB_PATH (absolute) or adb on PATH.", kind: "adb-provider", @@ -22,7 +28,14 @@ export const ADB_TOOL_CONTRACTS = [ { name: "list_adb_devices", cli: true, - ...toolContractMetadata("list_adb_devices"), + ...toolContractMetadata( + "list_adb_devices", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "List attached devices exactly as `adb devices -l` reports them: serial, state, transport, model metadata, and an inferred emulator/physical kind with its evidence basis. Emulators and USB or network devices appear alike; REA neither starts nor manages them. transport_id_text preserves exact full-range transport identity; transport_id is its safe numeric projection or null. May start the local adb server on first use.", kind: "adb-provider", @@ -33,7 +46,14 @@ export const ADB_TOOL_CONTRACTS = [ { name: "inspect_adb_device", cli: true, - ...toolContractMetadata("inspect_adb_device"), + ...toolContractMetadata( + "inspect_adb_device", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "Inspect one device's build identity through a fixed `getprop` whitelist: Android and SDK versions, security patch, fingerprint, product identity, CPU ABIs, and debuggable flag, plus the observed emulator indicator ro.kernel.qemu. Present properties retain empty values; omitted keys were not reported. Read-only with respect to the device.", kind: "adb-provider", @@ -46,7 +66,14 @@ export const ADB_TOOL_CONTRACTS = [ { name: "list_adb_packages", cli: true, - ...toolContractMetadata("list_adb_packages"), + ...toolContractMetadata( + "list_adb_packages", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "List installed packages on one device with each base APK's device path, optionally scoped to third-party or system packages. Paths are device filesystem paths, not host-local. Read-only.", kind: "adb-provider", @@ -62,7 +89,16 @@ export const ADB_TOOL_CONTRACTS = [ { name: "pull_adb_package", cli: true, - ...toolContractMetadata("pull_adb_package"), + ...toolContractMetadata( + "pull_adb_package", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + accessesNetwork: true, + idempotent: false, + }), + ), description: "Pull one installed package's complete APK set (base plus every split, as `pm path` reports) from the device into a caller-selected output directory, creating a package-named subdirectory that must not already exist. Every pulled file is digested with SHA-256; partial pulls keep successful artifacts and per-file failure reasons. The device keeps the originals.", kind: "adb-provider", @@ -82,7 +118,14 @@ export const ADB_TOOL_CONTRACTS = [ { name: "read_adb_logcat", cli: true, - ...toolContractMetadata("read_adb_logcat"), + ...toolContractMetadata( + "read_adb_logcat", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "Read a bounded dump of the device log (`logcat -d -t`) for one buffer, optionally restricted to a process id. No streaming, no clearing; the newest lines are kept when the count cap trims. Read-only.", kind: "adb-provider", @@ -98,7 +141,14 @@ export const ADB_TOOL_CONTRACTS = [ { name: "inspect_adb_package", cli: true, - ...toolContractMetadata("inspect_adb_package"), + ...toolContractMetadata( + "inspect_adb_package", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "Inspect installed-package versions, install times, installer, user id, flags, and requested-permission count through read-only `dumpsys package`. Malformed numeric declarations are retained in bounded numeric_issues and make coverage partial; version_code stays exact text. Unknown sections are not inferred.", kind: "adb-provider", @@ -114,7 +164,16 @@ export const ADB_TOOL_CONTRACTS = [ { name: "pull_adb_file", cli: true, - ...toolContractMetadata("pull_adb_file"), + ...toolContractMetadata( + "pull_adb_file", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + accessesNetwork: true, + idempotent: false, + }), + ), description: "Pull one absolute device path (a database, shared-preferences XML, or any readable file) into a caller-selected output directory, digesting it with SHA-256. The local copy must not already exist. Read-only with respect to the device.", kind: "adb-provider", @@ -134,7 +193,18 @@ export const ADB_TOOL_CONTRACTS = [ { name: "push_adb_file", cli: true, - ...toolContractMetadata("push_adb_file"), + ...toolContractMetadata( + "push_adb_file", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + accessesNetwork: true, + mutatesDevice: true, + idempotent: false, + }), + ), description: "Push one local file to an absolute device path. If the destination is an existing directory, adb places the file inside it under the local basename and the result reports that file path. A device-mutating tool: checks for an existing destination file before transfer and refuses it unless overwrite is explicitly requested; this check is not atomic and another process can create the path before adb writes. The private staged copy remains non-writable and preserves source executable bits. When the device provides sha256sum, the transfer is verified by comparing it with the local digest.", kind: "adb-provider", @@ -154,7 +224,16 @@ export const ADB_TOOL_CONTRACTS = [ { name: "capture_adb_screen", cli: true, - ...toolContractMetadata("capture_adb_screen"), + ...toolContractMetadata( + "capture_adb_screen", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + accessesNetwork: true, + idempotent: false, + }), + ), description: "Capture one frame of the device screen as a PNG (`screencap -p` through exec-out, no device-side file) into a caller-selected output directory, digesting it and reporting its dimensions. No recording or interaction.", kind: "adb-provider", @@ -173,7 +252,14 @@ export const ADB_TOOL_CONTRACTS = [ { name: "list_adb_processes", cli: true, - ...toolContractMetadata("list_adb_processes"), + ...toolContractMetadata( + "list_adb_processes", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "List running processes exactly as `ps -A` reports them: user, pid, ppid, rss, state, and name. Useful for pairing with instrumentation lanes. Read-only.", kind: "adb-provider", @@ -184,7 +270,14 @@ export const ADB_TOOL_CONTRACTS = [ { name: "list_adb_directory", cli: true, - ...toolContractMetadata("list_adb_directory"), + ...toolContractMetadata( + "list_adb_directory", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "List the immediate children of one absolute device directory, including hidden entries: names, kinds, permissions, owner, group, sizes, dates, and symlink targets. Names and targets preserve embedded newlines. Recognizes the standard errors for absent paths and denied reads. Read-only.", kind: "adb-provider", @@ -203,7 +296,14 @@ export const ADB_TOOL_CONTRACTS = [ { name: "list_adb_features", cli: true, - ...toolContractMetadata("list_adb_features"), + ...toolContractMetadata( + "list_adb_features", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "List the device's declared hardware and software features (`pm list features`) for device fingerprinting. Read-only.", kind: "adb-provider", @@ -214,7 +314,14 @@ export const ADB_TOOL_CONTRACTS = [ { name: "list_adb_services", cli: true, - ...toolContractMetadata("list_adb_services"), + ...toolContractMetadata( + "list_adb_services", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "List the device's binder services with their interfaces (`service list`). Read-only.", kind: "adb-provider", @@ -225,7 +332,14 @@ export const ADB_TOOL_CONTRACTS = [ { name: "inspect_adb_display", cli: true, - ...toolContractMetadata("inspect_adb_display"), + ...toolContractMetadata( + "inspect_adb_display", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "Read physical and override size/density from `wm size` and `wm density`. Malformed numeric declarations are retained in numeric_issues with partial coverage; optional values remain null. Required physical-size failures retain partial display facts. Read-only.", kind: "adb-provider", @@ -238,7 +352,14 @@ export const ADB_TOOL_CONTRACTS = [ { name: "inspect_adb_window", cli: true, - ...toolContractMetadata("inspect_adb_window"), + ...toolContractMetadata( + "inspect_adb_window", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "Report the window manager's focus declarations with display context, original lines and explicit summary status. Reads `dumpsys window windows`, falling back to `displays` only when no focus field is declared. Singular fields are unknown for multiple contexts or repeated declarations; inspect focus_contexts for every observation. Read-only; no interaction occurs.", kind: "adb-provider", @@ -251,7 +372,14 @@ export const ADB_TOOL_CONTRACTS = [ { name: "read_adb_setting", cli: true, - ...toolContractMetadata("read_adb_setting"), + ...toolContractMetadata( + "read_adb_setting", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "Read one settings value (`settings get`) from the system, secure, or global namespace. Absent keys report the device's own null observation. Read-only; writing settings is not exposed.", kind: "adb-provider", @@ -271,7 +399,16 @@ export const ADB_TOOL_CONTRACTS = [ { name: "collect_adb_bugreport", cli: true, - ...toolContractMetadata("collect_adb_bugreport"), + ...toolContractMetadata( + "collect_adb_bugreport", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + accessesNetwork: true, + idempotent: false, + }), + ), description: "Collect one device-generated bugreport archive (`adb bugreport`) into a caller-selected output directory, digesting the zip. The archive contains the device's own dumpstate, dumpsys, and logcat report; collection can take minutes. Read-only with respect to configuration.", kind: "adb-provider", @@ -290,7 +427,14 @@ export const ADB_TOOL_CONTRACTS = [ { name: "resolve_adb_packages", cli: true, - ...toolContractMetadata("resolve_adb_packages"), + ...toolContractMetadata( + "resolve_adb_packages", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "Find installed packages by case-insensitive package-name substring and return each base APK device path. Pass an exact returned name to pull_adb_package to retrieve its base and split APKs. Read-only.", kind: "adb-provider", @@ -306,7 +450,17 @@ export const ADB_TOOL_CONTRACTS = [ { name: "install_adb_package", cli: true, - ...toolContractMetadata("install_adb_package"), + ...toolContractMetadata( + "install_adb_package", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + mutatesDevice: true, + idempotent: false, + }), + ), description: "Install one local APK on the device (`adb install [-r]`), recording the APK's host digest and byte size. A device-mutating tool: `replace_requested` records whether `-r` was selected; `replaced` is null because install success does not establish prior package state. The device's own Success/Failure verdict is preserved with its reason.", kind: "adb-provider", @@ -330,7 +484,17 @@ export const ADB_TOOL_CONTRACTS = [ { name: "uninstall_adb_package", cli: true, - ...toolContractMetadata("uninstall_adb_package"), + ...toolContractMetadata( + "uninstall_adb_package", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + mutatesDevice: true, + idempotent: false, + }), + ), description: "Request package removal for user 0 (`adb shell pm uninstall --user 0`) without data retention. A device-mutating tool; absent packages report the device's own refusal reason.", kind: "adb-provider", @@ -346,7 +510,17 @@ export const ADB_TOOL_CONTRACTS = [ { name: "start_adb_app", cli: true, - ...toolContractMetadata("start_adb_app"), + ...toolContractMetadata( + "start_adb_app", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + mutatesDevice: true, + idempotent: false, + }), + ), description: "Start one installed app's resolved launcher activity with `am start -W -n`. A device-mutating tool for dynamic analysis. The full wait report determines success; failures retain launch-attempt facts and raw output. Pair with `read_adb_logcat` (pid filter) and `list_adb_processes` to observe the app, and `stop_adb_app` to end the run.", kind: "adb-provider", @@ -362,7 +536,17 @@ export const ADB_TOOL_CONTRACTS = [ { name: "start_adb_activity", cli: true, - ...toolContractMetadata("start_adb_activity"), + ...toolContractMetadata( + "start_adb_activity", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + mutatesDevice: true, + idempotent: false, + }), + ), description: "Start an intent with `am start -W`: one action, optional data URI, optional explicit component, and up to 16 typed extras (string, boolean, int, long, float). A device-mutating tool; the full wait report determines success, with failed-attempt facts and raw output retained.", kind: "adb-provider", @@ -390,7 +574,17 @@ export const ADB_TOOL_CONTRACTS = [ { name: "stop_adb_app", cli: true, - ...toolContractMetadata("stop_adb_app"), + ...toolContractMetadata( + "stop_adb_app", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + mutatesDevice: true, + idempotent: false, + }), + ), description: "Force-stop every process of one package (`am force-stop`), ending a dynamic-analysis run. A device-mutating tool; it succeeds whether or not the package had running processes.", kind: "adb-provider", diff --git a/src/contracts/analysisSettingsContracts.ts b/src/contracts/analysisSettingsContracts.ts index 1b58163d74..003821aff0 100644 --- a/src/contracts/analysisSettingsContracts.ts +++ b/src/contracts/analysisSettingsContracts.ts @@ -5,7 +5,7 @@ import { analysisSettingIdSchema, analysisSettingValueSchema, } from "../domain/analysisSettingDefinitions.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, toolEffects } from "./toolEffects.js"; import type { ToolContract } from "./toolContractTypes.js"; export const inspectAnalysisSettingsInputSchema = z.strictObject({ @@ -95,7 +95,7 @@ export const updateAnalysisSettingsResultSchema = export const ANALYSIS_SETTINGS_TOOL_CONTRACTS = [ { name: "inspect_analysis_settings", - ...toolContractMetadata("inspect_analysis_settings"), + ...toolContractMetadata("inspect_analysis_settings", toolEffects()), kind: "application", description: "Inspect REA's editable runtime admission sizes, deadlines and worker heaps, their bounds, launch values and application points. No active target is required. Filters intersect. If an error already names a setting and its bounds, update_analysis_settings can be called directly. Explicit per-call arguments override runtime defaults. Active worker values are not observed by this configuration view.", @@ -110,7 +110,10 @@ export const ANALYSIS_SETTINGS_TOOL_CONTRACTS = [ }, { name: "update_analysis_settings", - ...toolContractMetadata("update_analysis_settings"), + ...toolContractMetadata( + "update_analysis_settings", + toolEffects({ mutatesSession: true }), + ), kind: "application", description: "Atomically set or reset editable runtime defaults for new work. Changes survive target close/open but disappear on REA restart; reset restores launch configuration. Follow an error's named setting/bounds directly, then retry after work and cleanup settle; no inspection is needed when they are supplied. Does not change active work, edit files, restart providers, raise client limits or override explicit per-call arguments.", diff --git a/src/contracts/analysisViewToolContracts.ts b/src/contracts/analysisViewToolContracts.ts index b230bb927c..99dcdd8a53 100644 --- a/src/contracts/analysisViewToolContracts.ts +++ b/src/contracts/analysisViewToolContracts.ts @@ -3,7 +3,7 @@ import { ENVIRONMENT_MANIFEST_EXAMPLE } from "./analysisViewEnvironmentManifestE import { inspectAnalysisViewInputSchema } from "../domain/analysisView/analysisViewRequest.js"; import { analysisViewResultSchema } from "../domain/analysisView/analysisViewResult.js"; import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "./toolEffects.js"; import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; const RETAINED_EXAMPLE_ID = `ev_${"a".repeat(64)}`; @@ -13,7 +13,7 @@ export const ANALYSIS_VIEW_TOOL_CONTRACTS = [ { name: "inspect_analysis_view", cli: true, - ...toolContractMetadata("inspect_analysis_view"), + ...toolContractMetadata("inspect_analysis_view", evidenceEffects), kind: "application", description: 'Read summaries, selected facts, or pages from completed Evidence without rerunning analysis. Use the producing tool’s retained-view handoff for compatible selectors; the examples here are not exhaustive. Copy normalized_result.parent_evidence_id from a summary into source: {kind: "retained-evidence", evidence_id: ""}. Other sources are {kind: "inline", evidence: } or {kind: "evidence-file", path: "", evidence_id?: ""}; select an ID for a multi-record bundle. For native pseudocode use {source: {kind: "retained-evidence", evidence_id: ""}, view: {kind: "native", facet: "pseudocode", offset: 0, limit: 128}}; procedure_pseudo_code parents support this text facet, while other native function facets require analyze_function. Common views: {kind: "summary"} has no facet; {kind: "inventory", collection: "occurrences", logical_paths: ["package.json"], offset: 0, limit: 64} selects artifact paths; {kind: "capture", detail: "preview", offset: 0, limit: 20} pages saved network records; {kind: "managed-members", collection: "methods", offset: 0, limit: 64} pages managed members. Use the producer’s named kind for other families; compact schemas may omit nested shapes, so do not invent selectors. Text offsets/limits use UTF-16 code units; row pages count the selected retained collection. Preserve parent identity, null/unavailable values, source coverage, limitations and unknowns; exhausting pages does not prove complete discovery, runtime use or absence. Smaller pages can resolve delivery limits without repeating analysis; complete parent Evidence remains available for export.', diff --git a/src/contracts/android/androidToolContracts.ts b/src/contracts/android/androidToolContracts.ts index a7f1eb59b5..3be65f6d94 100644 --- a/src/contracts/android/androidToolContracts.ts +++ b/src/contracts/android/androidToolContracts.ts @@ -18,14 +18,21 @@ import { } from "../../domain/analysisView/analysisViewResult.js"; import type { ToolContract } from "../toolContractTypes.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; /** Static APK operations backed by a separately supplied headless engine. */ export const ANDROID_TOOL_CONTRACTS = [ { name: "inspect_android_jni_bindings", cli: true, - ...toolContractMetadata("inspect_android_jni_bindings"), + ...toolContractMetadata( + "inspect_android_jni_bindings", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), description: "Link an APK's DEX native declarations to Java_* exports and static JNINativeMethod candidates by ABI and exact library occurrence, without executing it or loading libraries. Returns digests, relation IDs, slot/relocation provenance and explicit partial/unknown coverage; a candidate match does not prove uniqueness or runtime registration. Declaration filters and ABI/library filters narrow results; RegisterNatives attribution uses the full declaration inventory first. Default summary retains complete Evidence. Optional view kind android-jni selects bindings/declarations/candidates/libraries, fields and pages; use inspect_analysis_view with parent_evidence_id for later pages. Empty selections match none. Requires caller-supplied JADX MCP JAR and JDK.", kind: "android-provider", @@ -53,7 +60,14 @@ export const ANDROID_TOOL_CONTRACTS = [ { name: "inspect_android_package", cli: true, - ...toolContractMetadata("inspect_android_package"), + ...toolContractMetadata( + "inspect_android_package", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), 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.", kind: "android-provider", @@ -100,7 +114,14 @@ export const ANDROID_TOOL_CONTRACTS = [ { name: "search_android_classes", cli: true, - ...toolContractMetadata("search_android_classes"), + ...toolContractMetadata( + "search_android_classes", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), description: "Search complete top-level decompiler class-name rows in an explicit local APK by case-sensitive substring. Empty query inventories all rows. Repeated names remain repeated and appear in duplicate_names; the provider accepts only class names for lookup, so these rows do not identify which same-name class node a later lookup selects. Retains artifact and engine identity; no APK execution.", kind: "android-provider", @@ -116,7 +137,14 @@ export const ANDROID_TOOL_CONTRACTS = [ { name: "inspect_android_class", cli: true, - ...toolContractMetadata("inspect_android_class"), + ...toolContractMetadata( + "inspect_android_class", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), 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.", kind: "android-provider", @@ -146,7 +174,14 @@ export const ANDROID_TOOL_CONTRACTS = [ { name: "inspect_android_method", cli: true, - ...toolContractMetadata("inspect_android_method"), + ...toolContractMetadata( + "inspect_android_method", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), 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.", kind: "android-provider", @@ -171,7 +206,14 @@ export const ANDROID_TOOL_CONTRACTS = [ { name: "trace_android_references", cli: true, - ...toolContractMetadata("trace_android_references"), + ...toolContractMetadata( + "trace_android_references", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), description: "Trace incoming static using nodes to an exact Android class or selected method overload. A method target may be an external class directly named by DEX invokes: target_definition external and reference_scope direct_dex_invokes identify this narrower inventory, without inventing a class definition or body. Ambiguous external requests list observed DEX prototypes; select overload_index explicitly. For APK-defined targets use inspect_android_class. The total counts containing nodes, not individual invokes. External callers include source_selector for inspect_android_method. Source lines and the containing node dex_offset remain unknown. direct_invokes carries exact DEX code-unit offsets when available; direct_invokes_exhaustive false marks byte-bounded partial instruction evidence, and null means unknown. No reflection, JNI or runtime dispatch is inferred.", kind: "android-provider", diff --git a/src/contracts/apiContractToolContracts.ts b/src/contracts/apiContractToolContracts.ts index 3ee487edbb..7da68aa916 100644 --- a/src/contracts/apiContractToolContracts.ts +++ b/src/contracts/apiContractToolContracts.ts @@ -8,7 +8,7 @@ import { graphqlContractPageViewResultSchema, } from "../domain/analysisView/analysisViewResult.js"; import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "./toolEffects.js"; import type { ToolContract } from "./toolContractTypes.js"; /** Named, provider-free contract for declarations in one local specification. */ @@ -16,7 +16,7 @@ export const API_CONTRACT_TOOL_CONTRACTS = [ { name: "inspect_api_contract", cli: true, - ...toolContractMetadata("inspect_api_contract"), + ...toolContractMetadata("inspect_api_contract", evidenceEffects), kind: "application", description: 'Inspect declared APIs in local OpenAPI JSON or GraphQL SDL without a session, network requests or target execution. OpenAPI 3.0/3.1/3.2 returns inline method/path operations with source pointers; references remain unresolved. format:"graphql-sdl" returns types/fields and optional operations_path bindings, preserving aliases, fragment/spread owners and unknowns without expanding fragments or claiming full operation validation. Default summary retains Evidence; view overrides detail. For HTTP rows use view {kind:"api-contract",collection:"operations",methods:["GET"],limit:20}; GraphQL uses view {kind:"graphql-contract",collection:"references",limit:20}. inspect_analysis_view pages the same retained facts. Source declaration coverage stays separate from page exhaustion; paging does not increase parser allowances. Introspection, runtime behavior and contract comparison are outside scope.', diff --git a/src/contracts/apkSignature/apkSignatureToolContracts.ts b/src/contracts/apkSignature/apkSignatureToolContracts.ts index 95ba508cb6..5786075199 100644 --- a/src/contracts/apkSignature/apkSignatureToolContracts.ts +++ b/src/contracts/apkSignature/apkSignatureToolContracts.ts @@ -6,7 +6,7 @@ import { apkSignatureSummaryViewResultSchema, } from "../../domain/analysisView/analysisViewResult.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "../toolEffects.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; /** Static APK signature-scheme inspection of a selected local archive. */ @@ -14,7 +14,7 @@ export const INSPECT_APK_SIGNATURE_CONTRACT = { name: "inspect_apk_signature", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_apk_signature"), + ...toolContractMetadata("inspect_apk_signature", evidenceEffects), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/apktool/apktoolToolContracts.ts b/src/contracts/apktool/apktoolToolContracts.ts index b2cf13c4a2..a6195e1a85 100644 --- a/src/contracts/apktool/apktoolToolContracts.ts +++ b/src/contracts/apktool/apktoolToolContracts.ts @@ -4,14 +4,20 @@ import { } from "../../domain/apktool/apktoolResourceAnalysis.js"; import type { ToolContract } from "../toolContractTypes.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; /** Apktool resource decoding served by a caller-supplied launcher. */ export const APKTOOL_TOOL_CONTRACTS = [ { name: "inspect_apktool_client", cli: true, - ...toolContractMetadata("inspect_apktool_client"), + ...toolContractMetadata( + "inspect_apktool_client", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + }), + ), description: "Inspect the caller-selected apktool launcher: resolved command, selection source, and version. Decodes nothing. REA never installs Apktool or Java; select a launcher with REA_APKTOOL_COMMAND (absolute) or apktool on PATH.", kind: "apktool-provider", @@ -22,7 +28,14 @@ export const APKTOOL_TOOL_CONTRACTS = [ { name: "decode_android_resources", cli: true, - ...toolContractMetadata("decode_android_resources"), + ...toolContractMetadata( + "decode_android_resources", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), description: "Decode APK resources with apktool d --no-src: readable manifest, version/SDK facts, string resources/locales and decoded file count. Uses a temporary workspace removed after projection; smali/source recovery belongs to JADX. Strings default to 2000 valid entries per table; use string_offset/string_limit and table.page.next_offset for later pages, checking target.sha256 across calls. Per-call string budgets can be raised without restart. decode_timeout_ms controls decoding (default 600000 ms), independently of output capture and version probes.", kind: "apktool-provider", diff --git a/src/contracts/applicationToolContracts.ts b/src/contracts/applicationToolContracts.ts index b9d60e2d23..1f58b1ee95 100644 --- a/src/contracts/applicationToolContracts.ts +++ b/src/contracts/applicationToolContracts.ts @@ -36,7 +36,11 @@ import { androidApplicationProjectionResultSchema } from "../domain/android/andr import { appleApplicationProjectionResultSchema } from "../domain/apple/appleApplication.js"; import { harmonyApplicationProjectionResultSchema } from "../domain/harmony/harmonyApplication.js"; import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { + toolContractMetadata, + evidenceEffects, + toolEffects, +} from "./toolEffects.js"; import { readGuidanceSectionInputSchema, readGuidanceSectionOutputSchema, @@ -100,7 +104,7 @@ export const APPLICATION_TOOL_CONTRACTS = [ ...PLAYWRIGHT_TRACE_TOOL_CONTRACTS, { name: "search_guidance", - ...toolContractMetadata("search_guidance"), + ...toolContractMetadata("search_guidance", toolEffects()), description: "Find installed REA workflow guidance by query words. Returns ranked sections, pages and locators for read_guidance_section; every non-generic word must match, with direct section matches ranked before matches spread across children. Reads documentation only, without accessing a target or provider.", kind: "application", @@ -116,7 +120,7 @@ export const APPLICATION_TOOL_CONTRACTS = [ { name: "guided_workflows", cli: true, - ...toolContractMetadata("guided_workflows"), + ...toolContractMetadata("guided_workflows", toolEffects()), description: "List or render REA's existing guided workflows. Rendering returns guidance only; it does not inspect targets, start analysis, or change session state.", kind: "application", @@ -139,7 +143,7 @@ export const APPLICATION_TOOL_CONTRACTS = [ }, { name: "read_guidance_section", - ...toolContractMetadata("read_guidance_section"), + ...toolContractMetadata("read_guidance_section", toolEffects()), description: "Retrieve a section selected by search_guidance from the installed REA guidance bundle. Reports stale locators and unavailable bundles explicitly. Returns documentation, not target observations or Evidence.", kind: "application", @@ -150,7 +154,7 @@ export const APPLICATION_TOOL_CONTRACTS = [ { name: "trace_application_feature", cli: true, - ...toolContractMetadata("trace_application_feature"), + ...toolContractMetadata("trace_application_feature", evidenceEffects), description: "Trace a typed literal seed through every reachable part of an authenticated JavaScript Application Graph supplied as inline Evidence or exact same-session retained references. Original static, native, passive-runtime, inferred, and unknown authorities remain distinct; native addon handoffs never open a provider or execute the application. An optional view returns selected facts and retains the complete trace.", kind: "application", @@ -175,7 +179,7 @@ export const APPLICATION_TOOL_CONTRACTS = [ { name: "trace_javascript_semantics", cli: true, - ...toolContractMetadata("trace_javascript_semantics"), + ...toolContractMetadata("trace_javascript_semantics", evidenceEffects), description: "Trace static JavaScript data-flow, direct call/return, and closure relations from inline application Evidence or an exact same-session retained reference. Dynamic or unsupported semantics remain explicit unknowns; static reachability never claims runtime execution.", kind: "application", @@ -197,7 +201,7 @@ export const APPLICATION_TOOL_CONTRACTS = [ { name: "compare_application_versions", cli: true, - ...toolContractMetadata("compare_application_versions"), + ...toolContractMetadata("compare_application_versions", evidenceEffects), description: "Compare two authenticated JavaScript Application Graph versions, supplied inline or by exact retained reference. Returns added, removed, changed, ambiguous and unknown entities with the full changed_from graph. Pairing uses unique exact digest, source-map, structural or semantic-key tiers; no fuzzy or module-ordinal pairing.", kind: "application", @@ -225,7 +229,10 @@ export const APPLICATION_TOOL_CONTRACTS = [ { name: "compare_static_and_observed_endpoints", cli: true, - ...toolContractMetadata("compare_static_and_observed_endpoints"), + ...toolContractMetadata( + "compare_static_and_observed_endpoints", + evidenceEffects, + ), description: "Compare static JavaScript endpoints with requests recorded in HAR Evidence, supplied inline or retained; acquires no files, targets or URLs. Returns exact or inferred template pairings and explicit unknowns; root-relative targets need a declared origin. Not-observed requires an exercised origin, all parent records retained and none excluded; it never means hidden, unused or inaccessible. Default summary retains the full comparison for inspect_analysis_view kind endpoint-comparison (static-endpoints, observed-groups, matches); a selected view overrides detail, and detail complete returns all facts. Copies no query strings, fragments, headers or bodies. Sensitive-declaration parents are refused; the 96 MiB representation budget covers source admission and derived state.", kind: "application", @@ -247,7 +254,7 @@ export const APPLICATION_TOOL_CONTRACTS = [ { name: "compare_source_to_bundle", cli: true, - ...toolContractMetadata("compare_source_to_bundle"), + ...toolContractMetadata("compare_source_to_bundle", evidenceEffects), description: 'Map committed historical source to an authenticated JavaScript Application Graph. Supply HistoricalSourceGraph inline or as {kind:"file",path:"/absolute/source.json"}, and graph Evidence inline or retained. Uses explicit digest, source-map and path signals to classify unchanged, modified, removed, split, merged, duplicated or unknown; incomplete coverage and ambiguous weak matches never establish absence or force pairing. Candidate signals are opt-in. Omitted view returns the full report; view {kind:"summary"} or {kind:"source-to-bundle",collection:"mappings"} retains it for later inspect_analysis_view pages. Filters intersect, empty filters select none, and page coverage never upgrades source coverage.', kind: "application", @@ -264,7 +271,10 @@ export const APPLICATION_TOOL_CONTRACTS = [ { name: "compare_javascript_export_shapes", cli: true, - ...toolContractMetadata("compare_javascript_export_shapes"), + ...toolContractMetadata( + "compare_javascript_export_shapes", + evidenceEffects, + ), description: "Compare static return-property shapes for one exact module/export on each authenticated JavaScript Application Graph, inline or retained. Variants pair only by reciprocal unique literal discriminants. Returns JSON Pointer changes while keeping property presence separate from value resolution: complete property coverage can establish an addition/removal even when values are unresolved. Dynamic values, incomplete coverage and unpaired variants stay unknown. Does not execute JavaScript; runtime behavior needs a separate probe.", kind: "application", @@ -293,7 +303,10 @@ export const APPLICATION_TOOL_CONTRACTS = [ { name: "build_reconstruction_obligation_ledger", cli: true, - ...toolContractMetadata("build_reconstruction_obligation_ledger"), + ...toolContractMetadata( + "build_reconstruction_obligation_ledger", + evidenceEffects, + ), description: "Build a deterministic reconstruction-obligation ledger from an authenticated Evidence bundle, reviewed obligations and an explicit reconstruction manifest. Returns the complete ledger, closure digest and typed diagnostics. Duplicate owners, missing cases or parser/type, weak verifier authority, unenumerated claims, contradictions, dependencies and residual unknowns fail closed; static candidates remain candidates.", kind: "application", @@ -325,7 +338,7 @@ export const APPLICATION_TOOL_CONTRACTS = [ { name: "evaluate_reconstruction_coverage", cli: true, - ...toolContractMetadata("evaluate_reconstruction_coverage"), + ...toolContractMetadata("evaluate_reconstruction_coverage", toolEffects()), description: "Check evidence-backed reconstruction coverage for one named boundary. Missing ownership or inventory is partial; stale, weak, truncated, skipped, unresolved or conflicting verifier proof is unknown. Contradictions, failed proof, missing owners and authority-routing failures fail closed.", kind: "application", @@ -378,7 +391,10 @@ export const APPLICATION_TOOL_CONTRACTS = [ { name: "project_android_application_graph", cli: true, - ...toolContractMetadata("project_android_application_graph"), + ...toolContractMetadata( + "project_android_application_graph", + evidenceEffects, + ), description: "Build a static Android application inventory from the authenticated nested inventory Evidence returned by inspect_artifact for an APK. Returns component paths/hashes, runtime-family hints and path-based bridge hypotheses. Does not decode DEX, execute the APK or establish runtime calls.", kind: "application", @@ -395,7 +411,7 @@ export const APPLICATION_TOOL_CONTRACTS = [ { name: "project_apple_application_graph", cli: true, - ...toolContractMetadata("project_apple_application_graph"), + ...toolContractMetadata("project_apple_application_graph", evidenceEffects), description: "Build a static Apple application inventory from the authenticated nested inventory Evidence returned by inspect_artifact for an IPA, .app directory, ZIP or DMG. Returns application roots, nested-bundle roles, launchd plists, component paths/hashes, runtime hints and bridge hypotheses. Roles follow path conventions; plist/CMS semantics and runtime calls are not established.", kind: "application", @@ -416,7 +432,10 @@ export const APPLICATION_TOOL_CONTRACTS = [ { name: "project_harmony_application_graph", cli: true, - ...toolContractMetadata("project_harmony_application_graph"), + ...toolContractMetadata( + "project_harmony_application_graph", + evidenceEffects, + ), description: "Build a static HarmonyOS inventory from the authenticated nested inventory Evidence returned by inspect_artifact for a HAP, HSP or App Pack. Returns packaging hints, component paths/hashes, child packages, runtime hints, unclassified components and path-based N-API bridge hypotheses. Does not decode Ark bytecode, parse manifest semantics or establish runtime calls.", kind: "application", diff --git a/src/contracts/artifactToolContracts.ts b/src/contracts/artifactToolContracts.ts index 0d43cb3da6..77539e1fa1 100644 --- a/src/contracts/artifactToolContracts.ts +++ b/src/contracts/artifactToolContracts.ts @@ -8,7 +8,13 @@ import { artifactOutputSchemas } from "./toolOutputSchemaGroups.js"; import { artifactIntegrityPolicySchema } from "../domain/artifactIntegrityPolicy.js"; import { jsonValueSchema } from "../domain/jsonValue.js"; import { distinctItems } from "../domain/schemaConstraints.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import type { EffectAudit } from "./toolEffects.js"; +import { + toolContractMetadata, + evidenceEffects, + nativeEvidenceEffects, + toolEffects, +} from "./toolEffects.js"; import { appleAssetCatalogInputSchema } from "../domain/apple/appleAssetCatalog.js"; import { dylibResolutionInputSchema } from "../domain/apple/dylibResolution.js"; import { keyedArchiveInputSchema } from "../domain/apple/keyedArchive.js"; @@ -79,6 +85,7 @@ const artifact = < Schema extends z.ZodType>>, >( name: Name, + audit: EffectAudit, description: string, inputSchema: Schema, retainedSummary?: ToolContract["retainedSummary"], @@ -86,7 +93,7 @@ const artifact = < const outputSchema = requireOutputSchema(artifactOutputSchemas, name); return { name, - ...toolContractMetadata(name), + ...toolContractMetadata(name, audit), description, kind: "artifact-provider", cli: true, @@ -107,17 +114,29 @@ const artifact = < export const ARTIFACT_TOOL_CONTRACTS = [ artifact( "inspect_artifact", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), "Inventory the active archive, app package, firmware container or supported packaged executable without running it. Returns nested content-addressed inventory Evidence with integrity observations, unexplored branches and next probes. Default complete returns the full graph; detail summary retains it for inspect_analysis_view kind inventory using parent_evidence_id, exact paths/IDs, fields and paging. Summary changes delivery, not inventory coverage. Bun/Node SEA/Deno carriers expose stored modules/assets and recorded metadata; opaque bytecode and npm snapshots are not decoded. Local Evidence can include environment-file values and certificate bytes. Classic iNES adds file-region/reconstruction facts, not mapper execution. Integrity mismatches fail unless record-and-continue explicitly retains untrusted contradictions. Supported macOS DMGs are mounted read-only. Use extract_artifact to materialize regular contents; DMGs instead need a caller-managed read-only mount.", artifactInspectionInputSchema, { evidenceParameters: "preserve-detail" }, ), artifact( "extract_artifact", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + idempotent: false, + }), "Write all or selected regular files from the active supported archive to an absent absolute output_root, or a fresh temporary directory if omitted. Use exact inventory occurrence_ids to select files. Returns IDs and actual output paths; successful files persist. Nested archives are copied, not recursively unpacked. Never overwrites; rejects traversal/symlink escapes and verifies cleanup. Full-input integrity checks still apply: mismatches fail unless record-and-continue retains explicitly untrusted contradictions. DMG extraction is unavailable; use a caller-managed read-only mount on macOS.", artifactExtractionInputSchema, ), artifact( "decode_interface_builder", + evidenceEffects, "Decode compiled storyboard and nib archives inside the active Apple app bundle, including keyed property lists and NIBArchive object tables, into a bounded object, hierarchy, and connection graph. This is static archive parsing; unrecognized archive classes and unresolved code handlers remain explicit unknowns. A full app graph is often several megabytes; detail summary retains it and returns documents with node, edge and coverage counts, then page rows, optionally one document's, with inspect_analysis_view kind interface-builder.", z.strictObject({ max_documents: z.int().min(1).max(64).default(64), @@ -134,16 +153,19 @@ export const ARTIFACT_TOOL_CONTRACTS = [ ), artifact( "inspect_keyed_archive", + evidenceEffects, "Inspect one Foundation NSKeyedArchiver plist in the active app bundle as original object-table nodes, class descriptors, named roots, and UID edges. Preserves shared and cyclic references without instantiating classes. The path is relative to the bundle; root selection and object pagination preserve original identities.", keyedArchiveInputSchema, ), artifact( "inspect_asset_catalog", + nativeEvidenceEffects, "Inspect compiled Assets.car metadata in an active Apple app bundle. Returns stable paginated catalog and rendition records with raw assetutil metadata and catalog digests; rendition bytes are not extracted.", appleAssetCatalogInputSchema, ), artifact( "trace_dylib_resolution", + evidenceEffects, "Trace how dyld would resolve each Mach-O dylib load for the active Mach-O, or for every executable in the active .app bundle (the main app, XPC services, extensions, login items, helpers). Expands @executable_path, @loader_path, and @rpath through each process's LC_RPATH stack in dependents-first load order, and reports every candidate path with its outcome, the resolved image and digest, weak, re-export, upward, and lazy-load flags, including LC_LAZY_LOAD_DYLIB_INFO linkedit payloads, and derived findings such as unresolved required loads or absent earlier @rpath candidates. Pure header parsing: nothing is executed, and absolute or system paths outside the analyzed root stay undetermined. Select roots or one architecture to narrow large bundles.", dylibResolutionInputSchema, ), diff --git a/src/contracts/browserScenarioToolContracts.ts b/src/contracts/browserScenarioToolContracts.ts index b82dea8fc5..f7c56cbdd9 100644 --- a/src/contracts/browserScenarioToolContracts.ts +++ b/src/contracts/browserScenarioToolContracts.ts @@ -1,5 +1,5 @@ import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, toolEffects } from "./toolEffects.js"; import { analysisDetailOutputSchemaOf, analysisDetailSchema, @@ -29,7 +29,20 @@ export const BROWSER_SCENARIO_TOOL_CONTRACTS = [ { name: "capture_browser_scenario", cli: true, - ...toolContractMetadata("capture_browser_scenario"), + ...toolContractMetadata( + "capture_browser_scenario", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + changesUiState: true, + mayDiscardData: true, + executesForeignCode: true, + idempotent: false, + }), + ), 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. 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.', kind: "browser-provider", diff --git a/src/contracts/browserToolContracts.ts b/src/contracts/browserToolContracts.ts index 1f04ffbf13..74c1fe8162 100644 --- a/src/contracts/browserToolContracts.ts +++ b/src/contracts/browserToolContracts.ts @@ -40,7 +40,12 @@ import { webScreenshotDiffSchema, webScreenshotSchema, } from "../domain/webScreenshot.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { + toolContractMetadata, + browserEvidenceEffects, + evidenceEffects, + toolEffects, +} from "./toolEffects.js"; import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; import { presentRootDiscriminator } from "../domain/schemaAnnotations.js"; @@ -172,7 +177,7 @@ export const BROWSER_TOOL_CONTRACTS = [ { name: "list_browser_targets", cli: true, - ...toolContractMetadata("list_browser_targets"), + ...toolContractMetadata("list_browser_targets", browserEvidenceEffects), description: "List pages exposed by one loopback Chrome DevTools Protocol endpoint, optionally filtered by exact origin. Returns target IDs and URLs; query values and fragments are preserved, with URL userinfo credentials removed. Use a returned target ID with inspect_web_page. discovery_timeout_ms controls discovery; command_timeout_ms does not apply. Browser-socket endpoints remain shared by the active browser provider until it closes or target-session cleanup is unconfirmed; cancellation/deadline on a clean socket releases only this call’s lease.", kind: "browser-provider", @@ -190,7 +195,7 @@ export const BROWSER_TOOL_CONTRACTS = [ { name: "inspect_web_page", cli: true, - ...toolContractMetadata("inspect_web_page"), + ...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.", kind: "browser-provider", @@ -209,7 +214,14 @@ export const BROWSER_TOOL_CONTRACTS = [ { name: "analyze_web_bundle", cli: true, - ...toolContractMetadata("analyze_web_bundle"), + ...toolContractMetadata( + "analyze_web_bundle", + toolEffects({ + ...browserEvidenceEffects, + launchesProcess: true, + writesFilesystem: true, + }), + ), description: 'Recover a static chunk graph, route/endpoint candidates, vendor fingerprints and page-declared WebMCP metadata from JavaScript on one selected CDP page. May fetch source maps only from the target origin or explicitly selected origins; application JavaScript is not executed. detail summary retains complete Evidence; view {kind: "web-bundle", collection: "endpoints"} selects endpoint rows, and javascript-routes views select route patterns/occurrences/sources/unknowns. Read later pages with inspect_analysis_view. Static candidates do not establish runtime reachability or a complete route set.', kind: "browser-provider", @@ -233,7 +245,7 @@ export const BROWSER_TOOL_CONTRACTS = [ { name: "observe_web_session", cli: true, - ...toolContractMetadata("observe_web_session"), + ...toolContractMetadata("observe_web_session", browserEvidenceEffects), description: "Arm a CDP observation window of the requested duration while the user operates the page. By default it follows the selected target's current origin; an explicit origin list controls which origins may be retained. Records navigation, redirect, lifecycle, and failure events.", kind: "browser-provider", @@ -253,7 +265,7 @@ export const BROWSER_TOOL_CONTRACTS = [ { name: "discover_webmcp_tools", cli: true, - ...toolContractMetadata("discover_webmcp_tools"), + ...toolContractMetadata("discover_webmcp_tools", browserEvidenceEffects), description: "Passively inventory every page-registered WebMCP tool and its complete structural input-schema summary using the experimental CDP WebMCP domain. Metadata is page-declared-untrusted; REA never registers or invokes discovered tools.", kind: "browser-provider", @@ -273,7 +285,7 @@ export const BROWSER_TOOL_CONTRACTS = [ { name: "compare_web_captures", cli: true, - ...toolContractMetadata("compare_web_captures"), + ...toolContractMetadata("compare_web_captures", evidenceEffects), description: "Compare two passive page inspections or two recorded browser scenarios. For passive captures, pass before/after with each complete inspect_web_page normalized_result in inspection and optional complete discover_webmcp_tools normalized_result in webmcp. For scenarios, pass complete normalized_result objects as before_scenario/after_scenario; use exactly one input group. Returns artifact differences and alignment failures. Scenario steps align by exact IDs; optional literal normalization is recorded. HTTP requests and ordered WebSocket streams are compared without inventing stable identities for same-URL connections. Missing or truncated Evidence never proves equality.", kind: "browser-provider", @@ -302,7 +314,7 @@ export const BROWSER_TOOL_CONTRACTS = [ { name: "capture_web_screenshot", cli: true, - ...toolContractMetadata("capture_web_screenshot"), + ...toolContractMetadata("capture_web_screenshot", browserEvidenceEffects), description: "Capture the current visible viewport of one configured page as an inline, content-addressed PNG artifact. The operation never scrolls, navigates, or evaluates page JavaScript.", kind: "browser-provider", @@ -321,7 +333,7 @@ export const BROWSER_TOOL_CONTRACTS = [ { name: "compare_web_screenshots", cli: true, - ...toolContractMetadata("compare_web_screenshots"), + ...toolContractMetadata("compare_web_screenshots", evidenceEffects), description: "Compare two self-verifying PNG screenshot artifacts with local pixel metrics. Returns exact changed-pixel ratios and channel deltas without OCR or external services.", kind: "browser-provider", diff --git a/src/contracts/captures/captureToolContracts.ts b/src/contracts/captures/captureToolContracts.ts index 45f1ed58e8..c6f5a2a96a 100644 --- a/src/contracts/captures/captureToolContracts.ts +++ b/src/contracts/captures/captureToolContracts.ts @@ -7,14 +7,21 @@ import { packetCaptureSchema, } from "../../domain/captures/packetCapture.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; export const CAPTURE_TOOL_CONTRACTS = [ { name: "inspect_packet_fields", availability: { host: "packetCapture" }, cli: true, - ...toolContractMetadata("inspect_packet_fields"), + ...toolContractMetadata( + "inspect_packet_fields", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), kind: "artifact-provider", requiresActiveTarget: true, description: @@ -33,7 +40,14 @@ export const CAPTURE_TOOL_CONTRACTS = [ name: "inspect_packet_capture", availability: { host: "packetCapture" }, cli: true, - ...toolContractMetadata("inspect_packet_capture"), + ...toolContractMetadata( + "inspect_packet_capture", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/cutterToolContracts.ts b/src/contracts/cutterToolContracts.ts index 8f6ae85d2c..6a5e35b67b 100644 --- a/src/contracts/cutterToolContracts.ts +++ b/src/contracts/cutterToolContracts.ts @@ -3,7 +3,7 @@ import { jsonValueSchema } from "../domain/jsonValue.js"; import { cutterDiscoverySchema } from "../domain/cutterDiscovery.js"; import type { ToolContract } from "./toolContractTypes.js"; import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, toolEffects } from "./toolEffects.js"; /** List live Cutter plugin bridge sessions. */ export const cutterListInputSchema = z.strictObject({}); @@ -42,7 +42,10 @@ export const CUTTER_TOOL_CONTRACTS = [ { name: "list_cutter_sessions", cli: true, - ...toolContractMetadata("list_cutter_sessions"), + ...toolContractMetadata( + "list_cutter_sessions", + toolEffects({ accessesNetwork: true }), + ), kind: "native-provider", description: "Find live REA bridge sessions in Cutter and return document identity and bridge-directory security status. Examines at most 256 descriptors with up to eight concurrent probes; excess capacity returns bridge_directory_capacity_exceeded, not an empty session list. The fixed discovery budget is separate from REA_BRIDGE_MAX_REQUEST_BYTES and cannot be raised at runtime.", @@ -53,7 +56,19 @@ export const CUTTER_TOOL_CONTRACTS = [ { name: "cutter_command", cli: true, - ...toolContractMetadata("cutter_command"), + ...toolContractMetadata( + "cutter_command", + toolEffects({ + mutatesTarget: true, + executesForeignCode: true, + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + changesUiState: true, + idempotent: false, + }), + ), kind: "native-provider", description: "Run one arbitrary Rizin command in a selected Cutter session; it may persist edits or execute plugin effects. Reports completion uncertainty as Evidence; do not retry automatically. An admitted command retires shared binary analysis: close active Ghidra explicitly first, then reopen with open_binary after command effects settle. Supply session_id and expected_generation from discovery. REA_BRIDGE_MAX_REQUEST_BYTES bounds authenticated request/response payloads excluding LF (default 16777216, range 7464..536870887); mismatched client/Cutter budgets refuse dispatch. An out-of-band Cutter without this setting uses the default.", diff --git a/src/contracts/desktopApplicationToolContracts.ts b/src/contracts/desktopApplicationToolContracts.ts index 1e039a0c3f..71bec5f47a 100644 --- a/src/contracts/desktopApplicationToolContracts.ts +++ b/src/contracts/desktopApplicationToolContracts.ts @@ -5,7 +5,7 @@ import { } from "../domain/desktopApplication.js"; import { desktopApplicationSummaryViewResultSchema } from "../domain/analysisView/analysisViewResult.js"; import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "./toolEffects.js"; import type { ToolContract } from "./toolContractTypes.js"; /** Static directory triage belongs to the existing artifact family. */ @@ -14,7 +14,7 @@ export const DESKTOP_APPLICATION_TOOL_CONTRACTS = [ name: "inspect_desktop_application", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_desktop_application"), + ...toolContractMetadata("inspect_desktop_application", evidenceEffects), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/desktopBuildMeasureContract.ts b/src/contracts/desktopBuildMeasureContract.ts index 8d98454b0b..e6c82666c6 100644 --- a/src/contracts/desktopBuildMeasureContract.ts +++ b/src/contracts/desktopBuildMeasureContract.ts @@ -3,7 +3,7 @@ import { z } from "zod"; import { absoluteLocalPathStringSchema } from "../domain/localPath.js"; import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, toolEffects } from "./toolEffects.js"; const strings = z.array(z.string()); const band = z @@ -35,7 +35,18 @@ const solve = z.strictObject({ /** The tool that runs a bundle's task in fresh computers and records how hard it is. */ export const MEASURE_BUILD_TASK_CONTRACT = { name: "measure_build_task", - ...toolContractMetadata("measure_build_task"), + ...toolContractMetadata( + "measure_build_task", + // Runs the bundle's task in fresh computers and writes its record into the bundle. + toolEffects({ + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + changesUiState: true, + executesForeignCode: true, + idempotent: false, + }), + ), kind: "application", description: "Measure how hard an exported bundle's task is for a model: run it in fresh agentenv computers on this host, each solve the bundle's own steps with the agent deployed as the solver on the model, 3 times, then 2 more unless they passed none or all, and keep it in the band when it passes 1 to 3 of 5. A solve that did not finish is run again, at most twice, and not counted. Before each solve REA stops if the largest cost so far would take the total past budget_usd; a solve's cost is known only when it ends, so the first always runs, and a solve that reports no cost stops the measure. The solver calls the model endpoint agentenv reads where REA starts: LITELLM_BASE_URL and LITELLM_API_KEY, or [model] in .agentenv/config.toml; REA holds no model client and never reads the key. It writes difficulty.json at the bundle's root, each measured task's record by name, and a Measured difficulty section in its README, and returns the record: the band, passes, finished solves (k), turns, cost, failures per check and each solve. Solves run one at a time and take minutes each; REA reports progress meanwhile.", diff --git a/src/contracts/desktopBuildSecretsContract.ts b/src/contracts/desktopBuildSecretsContract.ts index 537bae2037..85ec572c37 100644 --- a/src/contracts/desktopBuildSecretsContract.ts +++ b/src/contracts/desktopBuildSecretsContract.ts @@ -10,7 +10,7 @@ import { SIGN_IN_START, } from "../domain/desktop/appWithheld.js"; import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, toolEffects } from "./toolEffects.js"; const EXAMPLE_ID = "00000000-0000-4000-8000-000000000001"; const strings = z.array(z.string()); @@ -82,7 +82,14 @@ export const withheldOutputFields = { /** Record the person's consent, in their words, for the export to ship and to gate seeding withheld state. */ export const RECORD_BUILD_CONSENT_CONTRACT = { name: "record_build_consent", - ...toolContractMetadata("record_build_consent"), + ...toolContractMetadata( + "record_build_consent", + // Keeps the person's consent with the computer for the export to ship. + toolEffects({ + mutatesSession: true, + idempotent: false, + }), + ), kind: "application", description: "Record a consent the person gave, in their own words, after you asked them: kind licence when they accepted a licence the app or its installer shows, which you then accept on their behalf, or seed_sign_in when they allowed the bundle to hold their sign-in or licence state. Never record one they did not give. The consent is kept with the computer; the export writes every one into the bundle's consent.json, and seeds withheld state only with a seed_sign_in consent.", diff --git a/src/contracts/desktopBuildToolContracts.ts b/src/contracts/desktopBuildToolContracts.ts index 6701c64565..ea3dd2e35b 100644 --- a/src/contracts/desktopBuildToolContracts.ts +++ b/src/contracts/desktopBuildToolContracts.ts @@ -32,7 +32,7 @@ import { jsonObjectSchema } from "../domain/jsonValue.js"; import { absoluteLocalPathStringSchema } from "../domain/localPath.js"; import type { ToolContract } from "./toolContractTypes.js"; import * as secrets from "./desktopBuildSecretsContract.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, toolEffects } from "./toolEffects.js"; const computerId = z.uuid().describe("The id start_build_computer returned."); const driverResult = jsonObjectSchema @@ -134,7 +134,18 @@ const witnessRecord = z.strictObject({ export const DESKTOP_BUILD_TOOL_CONTRACTS = [ { name: "start_build_computer", - ...toolContractMetadata("start_build_computer"), + ...toolContractMetadata( + "start_build_computer", + // Builds and boots a container that installs and runs the requested app. + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + executesForeignCode: true, + idempotent: false, + }), + ), kind: "application", description: "Start a local agentenv computer, installing/downloading app packages as needed; returns computer_id and a first screenshot. Requires Docker and REA_AGENT_ENV_COMMAND. Request sources install from Ubuntu, apt repositories or a .deb URL and add REA from REA_BUILD_COMPUTER_REA_ARCHIVE in a build-only layer. The app starts later: use start_build_capture, or its Applications > Other menu entry when no capture is active. Set source.electron to apply the export launch policy, adding --no-sandbox unless present because the container lacks Chromium user namespaces. Bundle-folder sources run their existing smoke task unchanged. Initial image builds and concurrent agentenv state updates can take minutes. screenshot selects initial region/format/quality. The computer stays reachable until close_build_computer or server shutdown; if failed-start teardown is unconfirmed, use the error's computer_id to retry close_build_computer.", @@ -174,7 +185,17 @@ export const DESKTOP_BUILD_TOOL_CONTRACTS = [ }, { name: "act_on_build_computer", - ...toolContractMetadata("act_on_build_computer"), + ...toolContractMetadata( + "act_on_build_computer", + // Drives the app through the computer's driver on a loopback port. + toolEffects({ + mutatesSession: true, + accessesNetwork: true, + changesUiState: true, + executesForeignCode: true, + idempotent: false, + }), + ), kind: "application", description: `Act on a running build computer with ${COMPUTER_ACTIONS.join(", ")}; actions can change app state. Returns driver content/images and structured results, with each action logged. Points use the latest frame's pixels (take a screenshot first), or space norm on 0..norm_scale; count 2 double-clicks, drag path has 2..50 points, and keys names one W3C chord (ctrl+s is translated). Region screenshots crop the latest frame rather than recapture; use a full screenshot or wait with screenshot true first. After opening a menu/window, wait for its screenshot instead of taking the action's immediate one. type_secret reads the user-created handle file at ${secrets.BUILD_SECRETS_FOLDER} into a focused masked field: only the handle is recorded and no screenshot is taken, but later screenshots can expose unmasked fields. reset restores seed data through data/reset and relaunches; screenshot_error after reset does not undo it. Other actions forward the driver's arguments unchanged; refusals such as stale frames retain its message. Actions, capture steps and checks run sequentially per computer; different computers run independently.`, inputSchema: computerActionInputSchema, @@ -215,7 +236,18 @@ export const DESKTOP_BUILD_TOOL_CONTRACTS = [ }, { name: "start_build_capture", - ...toolContractMetadata("start_build_capture"), + ...toolContractMetadata( + "start_build_capture", + // Downloads package lists and launches the app inside the computer. + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + changesUiState: true, + executesForeignCode: true, + idempotent: false, + }), + ), kind: "application", description: `Launch the app under capture on a request-built computer and return its open-window screenshot. Downloads package lists as the computer user to identify sources; do not open the app from its menu first. Early exit reports code, stderr tail and capture details. Documents are recognized from file names/~/ paths in window titles; supply state_paths when titles name something else. Save the seed through the app, mark_build_checkpoint ${SEED_CHECKPOINT}, make and save the requested change, mark ${END_CHECKPOINT}, then stop_build_capture.`, inputSchema: z.strictObject({ @@ -266,7 +298,14 @@ export const DESKTOP_BUILD_TOOL_CONTRACTS = [ }, { name: "mark_build_checkpoint", - ...toolContractMetadata("mark_build_checkpoint"), + ...toolContractMetadata( + "mark_build_checkpoint", + toolEffects({ + mutatesSession: true, + accessesNetwork: true, + idempotent: false, + }), + ), kind: "application", description: `Checkpoint the running capture under a unique name; returns acknowledged counts and up to ${String(MAX_ACKNOWLEDGED_FILES)} changed files. Files named by window titles rank first, then state_paths/open files, with caches last. Mark ${SEED_CHECKPOINT} after saving the seed and ${END_CHECKPOINT} after saving the first change. For later tasks, build on the preceding change and mark ${END_CHECKPOINT}-; mark near- after saving a near miss that must fail one task check. Duplicate names are refused.`, inputSchema: z.strictObject({ @@ -308,7 +347,17 @@ export const DESKTOP_BUILD_TOOL_CONTRACTS = [ }, { name: "stop_build_capture", - ...toolContractMetadata("stop_build_capture"), + ...toolContractMetadata( + "stop_build_capture", + // Closes the app and drafts the task with REA inside the computer. + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + changesUiState: true, + idempotent: false, + }), + ), kind: "application", description: `Close the captured app and finish its capture. Returns checkpoints, package/sources, limitations and a draft between ${SEED_CHECKPOINT} and ${END_CHECKPOINT} when both exist and no declared secret was used. later_drafts contains one draft per later ${END_CHECKPOINT}-, relative to the preceding end checkpoint. Drafts list owned-path changes, supported before/after structured values, suggested checks and optional unchanged-state guards. Notes explain missing/thin drafts and recovery: add unrecognized documents to state_paths, or make a change saved in a readable file rather than only dconf. After secret use, automatic drafting is withheld; write the tasks manually. Otherwise write each task from its draft in the user's words and pass the tasks to export_build_environment.`, inputSchema: z.strictObject({ computer_id: computerId }), @@ -350,7 +399,18 @@ export const DESKTOP_BUILD_TOOL_CONTRACTS = [ }, { name: "export_build_environment", - ...toolContractMetadata("export_build_environment"), + ...toolContractMetadata( + "export_build_environment", + // Runs the task's readers, commands the task names, on the captured files. + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + executesForeignCode: true, + idempotent: false, + }), + ), kind: "application", description: `Export the stopped capture and given tasks as an agentenv app bundle, seeded at ${SEED_CHECKPOINT}. Each task uses its selected end checkpoint (${END_CHECKPOINT} by default) and its captured near- when present. The bundle's eval lists every task; verified files are copied to a new/empty host directory. Refuses publication if names or contents contain declared secrets, including UTF-16/hex/base64/URL/gzip forms; errors identify handles and files. ${secrets.WITHHELD_EXPORT_DESCRIPTION} A check already passing on the seed or a near miss passing every check refuses the whole export, naming the task and reason. Witness each task on a fresh computer with start_build_computer and check_build_task.`, inputSchema: z.strictObject({ @@ -421,7 +481,18 @@ export const DESKTOP_BUILD_TOOL_CONTRACTS = [ }, { name: "check_build_task", - ...toolContractMetadata("check_build_task"), + ...toolContractMetadata( + "check_build_task", + // A witness stage records the display, runs the task's readers or the bundle's judge, and writes its record here. + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + executesForeignCode: true, + idempotent: false, + }), + ), kind: "application", description: `Evaluate saved-state task checks or run a screen_judge through its configured model endpoint on a running exported app. Returns per-check results, settling status and optional witness state. Reads data/get after files settle using exported verifier semantics; screen_judge captures the screen and uses the agentenv runner with three votes per question. Reads every ${String(SETTLE_TIMING.intervalMs / 1000)} s, waits for ${String(SETTLE_TIMING.windowMs / 1000)} s of stable bytes, and bounds observation at ${String(SETTLE_TIMING.boundMs / 1000)} s; unsettled results use the last completed read, with read_cut for interrupted reads. Witness stages run in order: seed (supply directory to begin recording) must fail a check, after_edit must pass all, near_miss must fail one, and after_reset must restore every seed result. Use the task prompt alone for the edit. Seed rejects exported task/verifier mismatches. Unreadable or truncated views are undecided, not witnessed failures; an undecidable stage is refused for retry. A failed stage or after_reset ends recording and writes witness.json plus recording segments to directory.`, inputSchema: z.strictObject({ @@ -473,7 +544,16 @@ export const DESKTOP_BUILD_TOOL_CONTRACTS = [ secrets.RECORD_BUILD_CONSENT_CONTRACT, { name: "close_build_computer", - ...toolContractMetadata("close_build_computer"), + ...toolContractMetadata( + "close_build_computer", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + mayDiscardData: true, + idempotent: false, + }), + ), kind: "application", description: "Tear down a build computer and discard its state, cancelling its active call and refusing queued calls. Tries agentenv first, then REA_DOCKER_COMMAND on only that sandbox's named/labelled containers. Unconfirmed teardown reports remaining resources and retains the computer for another close attempt.", diff --git a/src/contracts/enhancedToolContracts.ts b/src/contracts/enhancedToolContracts.ts index dd99e7c856..221129cafc 100644 --- a/src/contracts/enhancedToolContracts.ts +++ b/src/contracts/enhancedToolContracts.ts @@ -6,7 +6,16 @@ import { enhancedInputSchemas } from "./enhancedInputs.js"; import { enhancedOutputSchemas } from "./toolOutputSchemaGroups.js"; import { examplesFor } from "./toolContractHelpers.js"; import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import type { EffectAudit } from "./toolEffects.js"; +import { + toolContractMetadata, + evidenceEffects, + providerEffects, + providerNetworkEvidenceEffects, + providerRemoteEffects, + providerUiNetworkEvidenceEffects, + toolEffects, +} from "./toolEffects.js"; import { FUNCTION_WORKFLOW_TOOL_CONTRACTS } from "./functionWorkflowToolContracts.js"; /** The contracts below that the CLI exposes as commands. */ @@ -22,12 +31,13 @@ const enhanced = < Schema extends z.ZodObject, >( name: Name, + audit: EffectAudit, description: string, inputSchema: Schema, ) => ({ name, - ...toolContractMetadata(name), + ...toolContractMetadata(name, audit), description, kind: "enhanced", ...(ENHANCED_CLI_CONTRACTS.has(name) ? { cli: true as const } : {}), @@ -41,21 +51,25 @@ const enhanced = < export const ENHANCED_TOOL_CONTRACTS = [ enhanced( "inspect_native_dispatch_metadata", + evidenceEffects, "Inspect analyzed Objective-C class/method and Swift mangled symbols, with optional exact Objective-C import-pointer binding facts from the selected Mach-O slice. Returns decoded names up to max_records, provider/profile identity, target digest when available, facet coverage and per-record Evidence. Symbol observations do not establish runtime layouts, conformances or witness/class tables. The selected provider owns name discovery. max_input_bytes bounds the whole-file Mach-O read; unresolved bindings remain partial or unsupported.", enhancedInputSchemas.inspect_native_dispatch_metadata, ), enhanced( "get_objc_classes", + evidenceEffects, "Find Objective-C class labels, optionally by literal substring. Labels remain separate unless exact selected-image pointer-fixup Evidence establishes the same imported class binding, including library, ordinal, weak status and addend. Missing binding proof remains unknown, partial or unsupported.", enhancedInputSchemas.get_objc_classes, ), enhanced( "get_objc_protocols", + evidenceEffects, "Discover and deduplicate Objective-C and Swift protocol labels.", enhancedInputSchemas.get_objc_protocols, ), 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. detail summary retains the batch for inspect_analysis_view item/body pages; complete includes every body. Per-function limits do not bound the whole batch.", enhancedInputSchemas.batch_decompile.extend({ detail: analysisDetailSchema, @@ -63,11 +77,20 @@ export const ENHANCED_TOOL_CONTRACTS = [ ), enhanced( "decompile_all", + providerEffects( + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + idempotent: false, + }), + { ...providerRemoteEffects, changesUiState: true }, + ), "Export pseudocode for all or selected analyzed functions to a directory; returns a manifest/index, with bodies kept in files. Existing output requires resume with matching target, provider, profile and layout; verified files are skipped and conflicts preserved. External functions produce no file. Item failures do not stop others; cancellation keeps written files. retry_failed: independent_fresh retries only provider-reported function failures when supported, retaining each attempt and its limitations; independent attempts may use different analysis context. layout dwarf falls back to address filenames when compilation-unit paths are unavailable. Select limit/resume to fit the whole client deadline; per-function limits do not bound the export.", enhancedInputSchemas.decompile_all, ), enhanced( "get_call_graph", + providerEffects(evidenceEffects, providerRemoteEffects), "Traverse the provider-observed caller or callee graph from one symbol/address, returning canonical-address nodes with per-node outcomes. Use trace_call_path for a shortest path to a goal, or build_call_path to compose existing function dossiers without provider reads. Indirect calls may be unresolved; this is not a whole-program CFG. detail summary retains the complete graph for native-observation pages and native-context caveats.", enhancedInputSchemas.get_call_graph.extend({ detail: analysisDetailSchema, @@ -75,37 +98,50 @@ export const ENHANCED_TOOL_CONTRACTS = [ ), enhanced( "analyze_swift_types", + providerEffects(evidenceEffects, providerRemoteEffects), 'Classify analyzed Swift procedure names into classes, structs, enums, protocols and extensions using manglings or same-address symbol aliases. Returns deduplicated procedure-name counts, not unique source types; provider names, mangled_names and unresolved classifications remain available. Category and case-sensitive literal pattern filters do not suppress unclassified rows. Example: {category: "structs", pattern: "Pair"}.', enhancedInputSchemas.analyze_swift_types, ), enhanced( "find_xrefs_to_name", + evidenceEffects, "Find references to an exact analyzed symbol name: resolves the name, then returns its address and referencing addresses. name_not_found means lookup is unresolved, not that a reference search found none or the target lacks the symbol. References are address-only; use inspect_native_instruction for typed incoming references where supported. Kuna lacks the required general name inventory; xrefs can resolve names its inventory knows.", enhancedInputSchemas.find_xrefs_to_name, ), enhanced( "binary_overview", + providerEffects(evidenceEffects, providerRemoteEffects), "Summarize the bound document, complete provider-inventory procedure/string row counts, and segments when supported. Counts do not establish discovery of every function/string and are not comparable across providers. Omitted segments mean unavailable coverage. image_base is returned only when observed segments agree. Use search_procedures, list_procedures or analyze_function directly when the procedure is already known.", enhancedInputSchemas.binary_overview, ), ...FUNCTION_WORKFLOW_TOOL_CONTRACTS, enhanced( "trace_feature", + providerEffects( + 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. detail summary retains matches/references/unknowns for inspect_analysis_view kind native-feature-trace.", enhancedInputSchemas.trace_feature.extend({ detail: analysisDetailSchema }), ), enhanced( "trace_call_path", + providerEffects( + toolEffects({ mutatesSession: true, idempotent: false }), + providerRemoteEffects, + ), "Resolve start and optional goal symbols or addresses, then trace direct callers or callees. Returns observed edges and a shortest path within the provider-observed graph. search_scope distinguishes the observed-graph result from whether discovery is established; a missing goal is unknown when relationship reads or discovery are incomplete. Unresolved indirect calls remain unknown.", enhancedInputSchemas.trace_call_path, ), enhanced( "trace_native_ui_action", + providerNetworkEvidenceEffects, "Trace one unique compiled UI action, object ID, native symbol or exact function address through authored connections, encoded or symbolized Objective-C handlers, and bounded static call references. Typed direct and resolved indirect calls, ambiguous candidates, inferred untyped provider callees, and targetless sites remain distinct. Runtime reachability is unknown; use trace_native_values for recovered value dependencies.", enhancedInputSchemas.trace_native_ui_action, ), enhanced( "trace_native_values", + providerUiNetworkEvidenceEffects, "Trace static value dependencies across resolved calls from one native procedure: high-p-code def-use, constants, operators, memory/branch operations and derived argument/return bindings. Alias effects, missing bindings, persistent state and RNG roles remain unknown. Caller-selected budgets bound traversal and retained facts; nodes are paged. A Ghidra per-function timeout does not bound the traversal: allow startup and every attempted function, or reduce max_functions.", enhancedInputSchemas.trace_native_values, ), diff --git a/src/contracts/environmentToolContracts.ts b/src/contracts/environmentToolContracts.ts index ba0eb1fe5a..a053e715fc 100644 --- a/src/contracts/environmentToolContracts.ts +++ b/src/contracts/environmentToolContracts.ts @@ -3,13 +3,19 @@ import { exportEnvironmentBundleInputSchema, } from "../domain/environmentBundleExport.js"; import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, toolEffects } from "./toolEffects.js"; /** Agent environment bundle contracts shared with the environment-build CLI command. */ export const ENVIRONMENT_TOOL_CONTRACTS = [ { name: "export_environment_bundle", - ...toolContractMetadata("export_environment_bundle"), + ...toolContractMetadata( + "export_environment_bundle", + toolEffects({ + writesFilesystem: true, + idempotent: false, + }), + ), description: "Write an agent environment bundle from capture_browser_scenario Evidence or HAR inspect_web_network_capture Evidence to an absent absolute output_directory whose parent exists. Copies complete capture Evidence, including recorded bodies, and derives replay/state read tools and served/withheld writes with coverage and next-recording hints. Preview the same coverage with inspect_analysis_view kind environment-coverage. dry_run reports without writing but still validates the destination. Uses default template rules, reads only selected Evidence and optional package_tarball, and writes only that directory; no network access. The bundle README explains agentenv use. Destination refusals name this tool; other failures name their export stage.", kind: "application", diff --git a/src/contracts/erlang/beamToolContracts.ts b/src/contracts/erlang/beamToolContracts.ts index 55e9d4722a..0ccc03b41d 100644 --- a/src/contracts/erlang/beamToolContracts.ts +++ b/src/contracts/erlang/beamToolContracts.ts @@ -3,7 +3,7 @@ import { erlangBeamSchema, } from "../../domain/erlang/beam.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "../toolEffects.js"; import { analysisDetailOutputSchemaOf } from "../analysisDetail.js"; import { z } from "zod"; import { @@ -31,7 +31,7 @@ export const ERLANG_BEAM_TOOL_CONTRACTS = [ name: "inspect_erlang_beam", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_erlang_beam"), + ...toolContractMetadata("inspect_erlang_beam", evidenceEffects), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/evm/evmToolContracts.ts b/src/contracts/evm/evmToolContracts.ts index 9aa80c80e8..d6652da85b 100644 --- a/src/contracts/evm/evmToolContracts.ts +++ b/src/contracts/evm/evmToolContracts.ts @@ -3,7 +3,7 @@ import { evmInterfaceSchema, } from "../../domain/evm/evmInterface.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; import { analysisDetailSchema, analysisDetailOutputSchemaOf, @@ -22,7 +22,14 @@ export const INSPECT_EVM_INTERFACE_CONTRACT = { name: "inspect_evm_interface", availability: { host: "evmInterface" }, cli: true, - ...toolContractMetadata("inspect_evm_interface"), + ...toolContractMetadata( + "inspect_evm_interface", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + }), + ), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/firmware/firmwareToolContracts.ts b/src/contracts/firmware/firmwareToolContracts.ts index e461b12f44..77a6a7e960 100644 --- a/src/contracts/firmware/firmwareToolContracts.ts +++ b/src/contracts/firmware/firmwareToolContracts.ts @@ -4,7 +4,7 @@ import { } from "../../domain/firmware/firmwareAnalysis.js"; import type { ToolContract } from "../toolContractTypes.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; import { FIRMWARE_OPERATION_ENGINES, FIRMWARE_TOOL_REQUIREMENTS, @@ -16,7 +16,14 @@ export const FIRMWARE_TOOL_CONTRACTS = [ name: "inspect_firmware_regions", availability: { host: "firmwareInspection" }, cli: true, - ...toolContractMetadata("inspect_firmware_regions"), + ...toolContractMetadata( + "inspect_firmware_regions", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), kind: "firmware-provider", description: `Inspect signature candidates in a local firmware file with ${FIRMWARE_TOOL_REQUIREMENTS[FIRMWARE_OPERATION_ENGINES.inspect_firmware_regions].requirement}. Returns offsets, reported lengths, descriptions and raw confidence values. Length validation and runtime addresses remain unknown. No extraction or target execution. Linux, caller-supplied tool, util-linux prlimit and procps ps required; 128 MiB input limit, one worker. Adjust analysis_timeout_ms for the analysis wall-clock budget (default 120000); fixed per-process limits are unchanged.`, inputSchema: firmwareInputSchemas.inspect_firmware_regions, @@ -34,7 +41,15 @@ export const FIRMWARE_TOOL_CONTRACTS = [ name: "extract_firmware", availability: { host: "firmwareExtraction" }, cli: true, - ...toolContractMetadata("extract_firmware"), + ...toolContractMetadata( + "extract_firmware", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + idempotent: false, + }), + ), kind: "firmware-provider", description: `Extract selected local firmware bytes with ${FIRMWARE_TOOL_REQUIREMENTS[FIRMWARE_OPERATION_ENGINES.extract_firmware].requirement} into an absent output directory. Returns verified child paths/digests, derivations, uncovered ranges, unknown chunks and extraction_gaps with continuation_id recovery instructions. Linux, format-specific extractors, prlimit and procps ps are required. Preserves the sandbox and publishes only regular files; no mounts or extracted-code execution. Select a returned native file with open_binary for analysis. Decompressed offsets are not original-file addresses.`, inputSchema: firmwareInputSchemas.extract_firmware, diff --git a/src/contracts/flutter/flutterToolContracts.ts b/src/contracts/flutter/flutterToolContracts.ts index 2747eb6038..d2e0516d5a 100644 --- a/src/contracts/flutter/flutterToolContracts.ts +++ b/src/contracts/flutter/flutterToolContracts.ts @@ -7,14 +7,20 @@ import { import { dartAotSummaryViewResultSchema } from "../../domain/analysisView/analysisViewResult.js"; import type { ToolContract } from "../toolContractTypes.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; /** Flutter build identification by pure APK parsing. */ export const FLUTTER_TOOL_CONTRACTS = [ { name: "identify_flutter_build", cli: true, - ...toolContractMetadata("identify_flutter_build"), + ...toolContractMetadata( + "identify_flutter_build", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + }), + ), description: "Identify a Flutter app's build facts by pure parsing: observed Dart snapshot hashes from lib//libapp.so, per-ABI library digests, the engine library's GNU build-id, and any labeled Dart version or toolchain strings libflutter.so carries. Complete snapshot coverage currently expects two independent headers in the legacy split VM/isolate profile; unified and other layouts can yield partial build facts. The snapshot hash maps to a Dart SDK release through an external dataset; REA performs no lookup. No engine, no execution, no external tools.", kind: "flutter-provider", @@ -30,7 +36,13 @@ export const FLUTTER_TOOL_CONTRACTS = [ { name: "inspect_dart_aot", cli: true, - ...toolContractMetadata("inspect_dart_aot"), + ...toolContractMetadata( + "inspect_dart_aot", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + }), + ), description: "Inspect one APK ABI's legacy split VM/isolate Dart AOT snapshot without executing it. Structural coverage supports Dart 2.14 FullAOT kind 3; unified snapshot layouts are unsupported. Returns snapshot exports/headers/hash and bounded package:/dart:/identifier-like byte-pattern strings, not deserialized classes/functions. 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.", kind: "flutter-provider", diff --git a/src/contracts/fridaToolContracts.ts b/src/contracts/fridaToolContracts.ts index 9cc62c9da5..de3e7c526b 100644 --- a/src/contracts/fridaToolContracts.ts +++ b/src/contracts/fridaToolContracts.ts @@ -8,7 +8,11 @@ import { localPathStringSchema } from "../domain/localPath.js"; import type { ToolContract } from "./toolContractTypes.js"; import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; import { analysisDetailOutputSchemaOf } from "./analysisDetail.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { + toolContractMetadata, + evidenceEffects, + toolEffects, +} from "./toolEffects.js"; import { isValidFridaRemoteAddress } from "../domain/fridaRemoteAddress.js"; import { fridaSessionObservationSchema, @@ -74,7 +78,10 @@ export const FRIDA_TOOL_CONTRACTS = [ { name: "list_frida_devices", cli: true, - ...toolContractMetadata("list_frida_devices"), + ...toolContractMetadata( + "list_frida_devices", + toolEffects({ launchesProcess: true, accessesNetwork: true }), + ), kind: "native-provider", description: "List Frida devices currently available to this host, optionally connecting to the caller-selected remote Frida endpoint. Remote authentication options are used for this call only and are never returned or recorded.", @@ -85,7 +92,13 @@ export const FRIDA_TOOL_CONTRACTS = [ { name: "list_frida_processes", cli: true, - ...toolContractMetadata("list_frida_processes"), + ...toolContractMetadata( + "list_frida_processes", + toolEffects({ + launchesProcess: true, + accessesNetwork: true, + }), + ), kind: "native-provider", description: "List processes observed on a selected Frida device or caller-supplied remote endpoint. A remote connection is closed after discovery; authentication values are never returned or recorded.", @@ -107,7 +120,16 @@ export const FRIDA_TOOL_CONTRACTS = [ }, { name: "start_frida_session", - ...toolContractMetadata("start_frida_session"), + ...toolContractMetadata( + "start_frida_session", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + idempotent: false, + }), + ), kind: "native-provider", description: "Attach Frida to one selected process or spawn one selected target. Spawned targets remain paused until resume_frida_session, allowing scripts to load before execution. Closing a session detaches instrumentation; it does not kill the target.", @@ -142,7 +164,17 @@ export const FRIDA_TOOL_CONTRACTS = [ }, { name: "load_frida_script", - ...toolContractMetadata("load_frida_script"), + ...toolContractMetadata( + "load_frida_script", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + executesForeignCode: true, + idempotent: false, + }), + ), kind: "native-provider", description: "Load caller-supplied JavaScript into a Frida session. Scripts can read or change target memory and behavior and can access the target process's capabilities. Messages and script errors are returned inline as Evidence; source content is not persisted.", @@ -177,7 +209,17 @@ export const FRIDA_TOOL_CONTRACTS = [ }, { name: "resume_frida_session", - ...toolContractMetadata("resume_frida_session"), + ...toolContractMetadata( + "resume_frida_session", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + executesForeignCode: true, + idempotent: false, + }), + ), kind: "native-provider", description: "Resume the process created by a paused Frida spawn session. Attached processes are already running and cannot be resumed through this operation.", @@ -192,7 +234,16 @@ export const FRIDA_TOOL_CONTRACTS = [ }, { name: "unload_frida_script", - ...toolContractMetadata("unload_frida_script"), + ...toolContractMetadata( + "unload_frida_script", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + idempotent: false, + }), + ), kind: "native-provider", description: "Unload one caller-selected Frida script from a live session. This removes that script's instrumentation from the target.", @@ -213,7 +264,7 @@ export const FRIDA_TOOL_CONTRACTS = [ }, { name: "frida_session_status", - ...toolContractMetadata("frida_session_status"), + ...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.", @@ -231,7 +282,17 @@ export const FRIDA_TOOL_CONTRACTS = [ }, { name: "close_frida_session", - ...toolContractMetadata("close_frida_session"), + ...toolContractMetadata( + "close_frida_session", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + executesForeignCode: true, + idempotent: false, + }), + ), kind: "native-provider", description: "Unload session scripts and attempt to detach REA's Frida session. Then resume a still-paused spawned process if script cleanup or session detach confirms instrumentation was released. Cleanup failures are reported. REA never kills the target; its final state is reported as unknown.", @@ -247,7 +308,17 @@ export const FRIDA_TOOL_CONTRACTS = [ { name: "instrument_with_frida", cli: true, - ...toolContractMetadata("instrument_with_frida"), + ...toolContractMetadata( + "instrument_with_frida", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + executesForeignCode: true, + idempotent: false, + }), + ), kind: "native-provider", description: "Run caller-authored Frida JavaScript against a selected process for one observation window, then detach. Scripts can read/change target memory and behavior and use the process's capabilities. CLI and MCP share this ephemeral workflow; use start_frida_session/load_frida_script for a persistent session. Remote authentication is call-local and excluded from Evidence. Detachment does not establish target termination.", diff --git a/src/contracts/functionWorkflowToolContracts.ts b/src/contracts/functionWorkflowToolContracts.ts index a1e7a415da..7ec1146dfb 100644 --- a/src/contracts/functionWorkflowToolContracts.ts +++ b/src/contracts/functionWorkflowToolContracts.ts @@ -4,7 +4,14 @@ import { analysisDetailSummaryDefaultSchema } from "./analysisDetail.js"; import { enhancedInputSchemas } from "./enhancedInputs.js"; import { TOOL_EXAMPLE_OVERRIDES } from "./toolContractExamples.js"; import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import type { EffectAudit } from "./toolEffects.js"; +import { + toolContractMetadata, + providerEffects, + providerRemoteEffects, + providerUiNetworkEvidenceEffects, + toolEffects, +} from "./toolEffects.js"; import { enhancedOutputSchemas } from "./toolOutputSchemaGroups.js"; type FunctionWorkflowName = "analyze_function" | "inspect_native_api"; @@ -28,13 +35,14 @@ const FUNCTION_WORKFLOW_CLI_CONTRACTS: ReadonlySet = new Set([ const functionWorkflow = ( name: Name, + audit: EffectAudit, description: string, ) => { const inputSchema = functionWorkflowInputSchemas[name]; const outputSchema = requireOutputSchema(enhancedOutputSchemas, name); return { name, - ...toolContractMetadata(name), + ...toolContractMetadata(name, audit), description, kind: "enhanced", ...(FUNCTION_WORKFLOW_CLI_CONTRACTS.has(name) @@ -58,10 +66,15 @@ const functionWorkflow = ( export const FUNCTION_WORKFLOW_TOOL_CONTRACTS = [ functionWorkflow( "analyze_function", + providerUiNetworkEvidenceEffects, "Inspect one native function by symbol or provider-returned address. Default summary returns identity, pseudocode size, facet counts and value-flow availability while retaining the complete dossier. Read selected facts with inspect_analysis_view using normalized_result.parent_evidence_id; detail complete returns everything inline. Facets include pseudocode, assembly, body ranges, comments, calls, references, strings/names, CFG and native API observations. Extents reflect provider analysis; limitations report unknown ranges and possible Ghidra terminal-call truncation.", ), functionWorkflow( "inspect_native_api", + providerEffects(toolEffects({ mutatesSession: true, idempotent: false }), { + ...providerRemoteEffects, + changesUiState: true, + }), "Inspect recovered parameter/return boundary types and jump-table dispatch for one native function selected by symbol or address. Returns confidence, supporting Evidence, case/data/target mappings, unsupported facets and residual unknowns. Null case values are unresolved, never known defaults. Use analyze_function for the broader function dossier.", ), ] as const satisfies readonly ToolContract[]; diff --git a/src/contracts/gdbToolContracts.ts b/src/contracts/gdbToolContracts.ts index 564fb0a3ac..11bcd9281d 100644 --- a/src/contracts/gdbToolContracts.ts +++ b/src/contracts/gdbToolContracts.ts @@ -8,7 +8,7 @@ import { import { gdbCommandSummaryViewResultSchema } from "../domain/analysisView/analysisViewResult.js"; import type { ToolContract } from "./toolContractTypes.js"; import { analysisDetailOutputSchemaOf } from "./analysisDetail.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, toolEffects } from "./toolEffects.js"; const sessionId = z.string().uuid(); @@ -17,7 +17,14 @@ export const GDB_TOOL_CONTRACTS = [ { name: "start_gdb_session", availability: { host: "persistentDebugger" }, - ...toolContractMetadata("start_gdb_session"), + ...toolContractMetadata( + "start_gdb_session", + toolEffects({ + launchesProcess: true, + mutatesSession: true, + idempotent: false, + }), + ), kind: "native-provider", description: "Start a persistent caller-supplied GDB session and return its session ID. Linux only; detaching a live inferior during close requires a verified durable output TTY. Startup suppresses init files and auto-loading, preferring MI3. Optional inferior_tty selects a verified terminal for later inferior runs; keep it available after GDB exits so close can detach a live inferior safely. The session belongs to this REA server process.", @@ -36,7 +43,18 @@ export const GDB_TOOL_CONTRACTS = [ }, { name: "gdb_console", - ...toolContractMetadata("gdb_console"), + ...toolContractMetadata( + "gdb_console", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + executesForeignCode: true, + idempotent: false, + }), + ), 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.", @@ -61,7 +79,7 @@ export const GDB_TOOL_CONTRACTS = [ }, { name: "gdb_session_status", - ...toolContractMetadata("gdb_session_status"), + ...toolContractMetadata("gdb_session_status", toolEffects()), kind: "native-provider", description: "Return the observed lifecycle state and bounded recent MI records and process diagnostics for one persistent REA GDB session; closed_reason says why a closed session stopped, and truncation and invalid-UTF-8 fields report discarded or lossy data.", @@ -96,7 +114,17 @@ export const GDB_TOOL_CONTRACTS = [ }, { name: "close_gdb_session", - ...toolContractMetadata("close_gdb_session"), + ...toolContractMetadata( + "close_gdb_session", + toolEffects({ + launchesProcess: true, + mutatesSession: true, + accessesNetwork: true, + mutatesTarget: true, + executesForeignCode: true, + idempotent: false, + }), + ), kind: "native-provider", description: "Close the owned GDB process after verifying the inferior state. When one live thread group has a verified durable output TTY, REA automatically detaches it, which may resume target execution; otherwise close reports that a disposition is required. REA never kills attached or remote targets as part of debugger cleanup. In a shared MCP server, this admitted close retires any active binary-analysis session; after target effects have settled, call open_binary before further analysis. Close an active Ghidra session explicitly first.", diff --git a/src/contracts/go/goToolContracts.ts b/src/contracts/go/goToolContracts.ts index 05685e53d8..c3304cc14f 100644 --- a/src/contracts/go/goToolContracts.ts +++ b/src/contracts/go/goToolContracts.ts @@ -3,7 +3,7 @@ import { inspectGoBinaryInputSchema, } from "../../domain/go/goBinary.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "../toolEffects.js"; import { analysisDetailOutputSchemaOf } from "../analysisDetail.js"; import { goBinarySummaryViewResultSchema } from "../../domain/analysisView/analysisViewResult.js"; @@ -13,7 +13,7 @@ export const GO_TOOL_CONTRACTS = [ name: "inspect_go_binary", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_go_binary"), + ...toolContractMetadata("inspect_go_binary", evidenceEffects), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/gpu/gpuToolContracts.ts b/src/contracts/gpu/gpuToolContracts.ts index 055d6b6afb..bada9e4147 100644 --- a/src/contracts/gpu/gpuToolContracts.ts +++ b/src/contracts/gpu/gpuToolContracts.ts @@ -8,14 +8,14 @@ import { gpuCodeObjectsPageViewResultSchema, } from "../../domain/analysisView/analysisViewResult.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "../toolEffects.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; export const GPU_TOOL_CONTRACTS = [ { name: "inspect_gpu_code_objects", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_gpu_code_objects"), + ...toolContractMetadata("inspect_gpu_code_objects", evidenceEffects), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/hopperMemoryContracts.ts b/src/contracts/hopperMemoryContracts.ts index 8ff8a6e5d2..82e93c626b 100644 --- a/src/contracts/hopperMemoryContracts.ts +++ b/src/contracts/hopperMemoryContracts.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { evidenceEffects } from "./toolEffects.js"; import { address, document } from "./toolContractHelpers.js"; import { MAX_BYTE_SEARCH_MATCHES, @@ -10,6 +11,7 @@ import { export const HOPPER_MEMORY_TOOL_DEFINITIONS = [ { name: "search_bytes", + effects: evidenceEffects, description: "Find masked byte signatures in initialized analyzed memory. Hex byte pairs and ?? wildcards are supported; an optional equal-length hex mask selects bits. Bounds are inclusive. Without bounds, unloaded blocks and loaded overlays are skipped and listed separately; select an overlay address space with start or end to search it. Matches are ordered by provider address and may span adjacent eligible initialized blocks; gaps and excluded blocks end a contiguous range. A match’s segment and file offset describe its starting address. Coverage describes this page; reuse the same query with next_cursor to continue. Uninitialized blocks are listed separately. Ghidra only; Hopper is unavailable.", inputSchema: z @@ -25,6 +27,7 @@ export const HOPPER_MEMORY_TOOL_DEFINITIONS = [ }, { name: "read_bytes", + effects: evidenceEffects, description: "Read analyzed bytes from one provider-normalized virtual address. Ghidra reads initialized memory, which can include loader fixups; these bytes can differ from the original file. The hexadecimal payload reports the exact returned length; incomplete reads remain explicit and unsupported provider APIs return typed capability unavailability.", inputSchema: z.object({ @@ -35,6 +38,7 @@ export const HOPPER_MEMORY_TOOL_DEFINITIONS = [ }, { name: "address_to_file_offset", + effects: evidenceEffects, description: "Map one provider-normalized virtual address to its original nonnegative file offset. The mapping is for that address; it does not imply a contiguous file range or that analyzed memory bytes equal file bytes. Hopper verifies the original bytes against the selected executable digest and translates FAT image-relative offsets using the loaded header. Results preserve the provider coordinate, image base, and source path. Unmapped addresses fail explicitly; changed or unavailable sources return typed errors retaining native mapping facts as partial evidence.", inputSchema: z.object({ address, document }), diff --git a/src/contracts/il2cpp/il2cppToolContracts.ts b/src/contracts/il2cpp/il2cppToolContracts.ts index 459cc8bf67..941f159583 100644 --- a/src/contracts/il2cpp/il2cppToolContracts.ts +++ b/src/contracts/il2cpp/il2cppToolContracts.ts @@ -5,7 +5,7 @@ import { inspectIl2cppMetadataInputSchema, } from "../../domain/il2cpp/il2cppMetadata.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "../toolEffects.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; /** Static IL2CPP metadata is independent of native-analysis providers and Unity installations. */ @@ -14,7 +14,7 @@ export const IL2CPP_TOOL_CONTRACTS = [ name: "inspect_il2cpp_metadata", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_il2cpp_metadata"), + ...toolContractMetadata("inspect_il2cpp_metadata", evidenceEffects), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/javascript/electronToolContracts.ts b/src/contracts/javascript/electronToolContracts.ts index 4b39b2d5d6..b848393d0d 100644 --- a/src/contracts/javascript/electronToolContracts.ts +++ b/src/contracts/javascript/electronToolContracts.ts @@ -1,7 +1,12 @@ import { z } from "zod"; import { absoluteLocalPathStringSchema } from "../../domain/localPath.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { + toolContractMetadata, + browserEvidenceEffects, + evidenceEffects, + toolEffects, +} from "../toolEffects.js"; import { electronFuseOutputSchemas } from "../toolOutputSchemaGroups.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; import { inspectElectronFusesInputSchema } from "../../domain/electron/electronFuses.js"; @@ -78,7 +83,7 @@ export const ELECTRON_TOOL_CONTRACTS = [ { name: "list_electron_targets", cli: true, - ...toolContractMetadata("list_electron_targets"), + ...toolContractMetadata("list_electron_targets", browserEvidenceEffects), description: "List every Electron file:// page target from a selected loopback CDP endpoint. Local file paths are canonicalized after symlink resolution. Selecting an endpoint exposes every eligible target and its local path metadata.", kind: "electron-provider", @@ -96,7 +101,7 @@ export const ELECTRON_TOOL_CONTRACTS = [ { name: "inspect_electron_page", cli: true, - ...toolContractMetadata("inspect_electron_page"), + ...toolContractMetadata("inspect_electron_page", browserEvidenceEffects), description: "Passively inspect one Electron file page by supplying its loopback CDP endpoint and target ID. The provider rechecks that the target currently exists at that endpoint and is a local file page. Returns frames, DOM structure, resource paths, and scripts without evaluating renderer JavaScript or invoking Electron APIs. The selected endpoint exposes every local file page and its metadata to this tool.", kind: "electron-provider", @@ -116,7 +121,14 @@ export const ELECTRON_TOOL_CONTRACTS = [ name: "analyze_javascript_application", availability: "standalone", cli: true, - ...toolContractMetadata("analyze_javascript_application"), + ...toolContractMetadata( + "analyze_javascript_application", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + }), + ), description: 'Build a static application graph from a local ASAR or extracted JavaScript app without executing it. Supply input_path, e.g. {input_path:"/apps/client",source_paths:["main.js"],detail:"summary"}. Copy source_paths exactly from the inventory, not host-absolute paths inferred from input_path. Returns nodes, edges, semantic relations, integrity contradictions, coverage and unknowns. source_paths limits source analysis to exact inventoried paths without narrowing inventory or artifact identity; dependencies are not implicitly analyzed and unselected sources remain unknown. detail summary reduces delivery, retaining complete Evidence for inspect_analysis_view; it does not reduce analysis. With summary detail, view {kind:"javascript-routes",collection:"routes",offset:0,limit:64} selects static route patterns; static routes do not prove reachability or the complete route set. Integrity mismatches fail by default; record-and-continue retains untrusted observed bytes and partial coverage. analysis_timeout_ms is a per-source provider budget. A host-only timeout needs a longer client deadline, not that budget; do not repeat unchanged work or assume it stopped. If configuration cannot be edited, report the host setting (Codex: mcp_servers..tool_timeout_sec, seconds).', kind: "electron-provider", @@ -152,7 +164,7 @@ export const ELECTRON_TOOL_CONTRACTS = [ name: "reconcile_javascript_runtime", availability: "standalone", cli: true, - ...toolContractMetadata("reconcile_javascript_runtime"), + ...toolContractMetadata("reconcile_javascript_runtime", evidenceEffects), description: "Reconcile verified static JavaScript application graphs with existing passive web/Electron CDP, passive V8 Inspector, or provider-owned active Electron Evidence. Active Electron captures contribute an explicitly partial target-only runtime record; they never invent renderer scripts, frames, workers, or execution claims. Exact captured-source digests take priority over caller-declared file/URL mappings; target, frame, script, and worker ambiguity remains explicit, and source-map authority stays separate.", kind: "electron-provider", @@ -168,7 +180,20 @@ export const ELECTRON_TOOL_CONTRACTS = [ { name: "capture_electron_scenario", cli: true, - ...toolContractMetadata("capture_electron_scenario"), + ...toolContractMetadata( + "capture_electron_scenario", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + changesUiState: true, + mayDiscardData: true, + executesForeignCode: true, + idempotent: false, + }), + ), description: "Launch and exercise an owned Electron app when passive CDP/Inspector observation cannot answer the question. REA owns startup/teardown; selected click/wait, renderer reload/crash and synthetic open-url/second-instance actions change runtime behavior. Returns correlated window/WebContents/process/preload/session/navigation/shell/IPC observations without payload values, plus action targets and coverage/truncation. Actions wait for completion or cancellation; a missing click target can remain pending. External shell, navigation, permission, download, popup, updater and OS-integration effects are blocked and recorded. Cleanup failures retain observations with explicit uncertainty. Use inspect_electron_page or observe_javascript_runtime for passive observation.", kind: "electron-provider", @@ -182,7 +207,7 @@ export const ELECTRON_TOOL_CONTRACTS = [ name: "inspect_electron_fuses", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_electron_fuses"), + ...toolContractMetadata("inspect_electron_fuses", evidenceEffects), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/javascript/javascriptRecoveryToolContracts.ts b/src/contracts/javascript/javascriptRecoveryToolContracts.ts index 77f9eb83a9..f96dd17a63 100644 --- a/src/contracts/javascript/javascriptRecoveryToolContracts.ts +++ b/src/contracts/javascript/javascriptRecoveryToolContracts.ts @@ -2,7 +2,7 @@ import { javascriptRecoveryInputSchema, javascriptRecoveryResultSchema, } from "../../domain/javascript/javascriptRecovery.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; import type { ToolContract } from "../toolContractTypes.js"; @@ -12,7 +12,15 @@ export const JAVASCRIPT_RECOVERY_TOOL_CONTRACTS = [ name: "recover_javascript_sources", availability: { host: "javascriptRecovery" }, cli: true, - ...toolContractMetadata("recover_javascript_sources"), + ...toolContractMetadata( + "recover_javascript_sources", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + idempotent: false, + }), + ), kind: "application", description: "Recover readable modules from local UTF-8 JavaScript bundles into an absent output_directory, without executing application code. Requires caller-supplied Wakaru ^1.13.0 (verified 1.14.0), Linux x64 and util-linux prlimit. additional_paths includes related chunks, preserving each input’s snapshot/provenance. Returns original/derived digests, extraction ranges, source maps, warnings and analysis_input for analyze_javascript_application. Splitting may fall back to one module; original names and runtime equivalence remain unknown. One worker has a fixed 120-second deadline and bounded input/output/report admission; limit failures are explicit and roll back output.", diff --git a/src/contracts/javascript/javascriptRuntimeObservationToolContracts.ts b/src/contracts/javascript/javascriptRuntimeObservationToolContracts.ts index 6d2941fa06..cd109c454a 100644 --- a/src/contracts/javascript/javascriptRuntimeObservationToolContracts.ts +++ b/src/contracts/javascript/javascriptRuntimeObservationToolContracts.ts @@ -1,5 +1,8 @@ import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { + toolContractMetadata, + browserEvidenceEffects, +} from "../toolEffects.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; import { javascriptRuntimeObservationSchema, @@ -15,7 +18,10 @@ export const JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS = [ { name: "list_javascript_runtime_targets", cli: true, - ...toolContractMetadata("list_javascript_runtime_targets"), + ...toolContractMetadata( + "list_javascript_runtime_targets", + browserEvidenceEffects, + ), description: "List every eligible Node/Electron V8 Inspector target from an explicit literal-loopback endpoint. Node discovery file locations that cannot be verified are preserved as unresolved reported URLs; they do not prove filesystem identity. Listing does not attach to targets.", kind: "runtime-provider", @@ -33,7 +39,10 @@ export const JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS = [ { name: "observe_javascript_runtime", cli: true, - ...toolContractMetadata("observe_javascript_runtime"), + ...toolContractMetadata( + "observe_javascript_runtime", + browserEvidenceEffects, + ), description: "Passively observe loaded-script and execution-context metadata on one loopback Node/Electron V8 Inspector target, selected by inspector_endpoint and target_id. Presence/attachability and file locations are rechecked; verified file paths stay separate from reported URLs, including distinct query/fragment identities. Parse failures are counted separately from malformed events. REA does not read source, evaluate, pause/resume or instrument execution; imports, EventEmitter activity and Electron IPC remain unknown. Use reconcile_javascript_runtime with static application Evidence. The selected endpoint exposes every target it serves to this tool.", kind: "runtime-provider", diff --git a/src/contracts/jeb/jebToolContracts.ts b/src/contracts/jeb/jebToolContracts.ts index b74e432167..4ef66d1f01 100644 --- a/src/contracts/jeb/jebToolContracts.ts +++ b/src/contracts/jeb/jebToolContracts.ts @@ -4,14 +4,20 @@ import { } from "../../domain/jeb/jebAnalysis.js"; import type { ToolContract } from "../toolContractTypes.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; /** JEB-backed inspection served by a caller-supplied running engine client. */ export const JEB_TOOL_CONTRACTS = [ { name: "inspect_jeb_client", cli: true, - ...toolContractMetadata("inspect_jeb_client"), + ...toolContractMetadata( + "inspect_jeb_client", + toolEffects({ + mutatesSession: true, + accessesNetwork: true, + }), + ), description: "Inspect the running JEB client serving MCP: engine version, GUI or headless mode, and startup time. Does not open a target. Requires a caller-started JEB client reachable at REA_JEB_MCP_URL (default http://127.0.0.1:8425/mcp); REA never installs or launches JEB.", kind: "jeb-provider", @@ -22,7 +28,14 @@ export const JEB_TOOL_CONTRACTS = [ { name: "open_jeb_project", cli: true, - ...toolContractMetadata("open_jeb_project"), + ...toolContractMetadata( + "open_jeb_project", + toolEffects({ + mutatesSession: true, + accessesNetwork: true, + idempotent: false, + }), + ), description: "Open or create a JEB project from an artifact file or existing .jdb2 database on the engine host. Returns the project's input-file digests and top-level units. The engine analyzes the target itself; REA does not read the file or execute it. Fails when a project is already open.", kind: "jeb-provider", @@ -38,7 +51,13 @@ export const JEB_TOOL_CONTRACTS = [ { name: "list_jeb_units", cli: true, - ...toolContractMetadata("list_jeb_units"), + ...toolContractMetadata( + "list_jeb_units", + toolEffects({ + mutatesSession: true, + accessesNetwork: true, + }), + ), description: "List project units by stable unit path and type, with optional wildcard filter, parent restriction, and pagination. The engine caps pages at 100 units; a full page reports partial coverage because more units may exist. Read-only.", kind: "jeb-provider", @@ -58,7 +77,13 @@ export const JEB_TOOL_CONTRACTS = [ { name: "decompile_jeb_item", cli: true, - ...toolContractMetadata("decompile_jeb_item"), + ...toolContractMetadata( + "decompile_jeb_item", + toolEffects({ + mutatesSession: true, + accessesNetwork: true, + }), + ), description: "Decompile one type or method to engine pseudo-code using its decompiler (Dalvik, Java, or native). item_address comes from the engine's code item listing; unit_path defaults to the engine's first code unit and stays unknown when omitted. Read-only with respect to the target file.", kind: "jeb-provider", diff --git a/src/contracts/managed/managedToolContracts.ts b/src/contracts/managed/managedToolContracts.ts index 0550cfe850..9c9ffdefde 100644 --- a/src/contracts/managed/managedToolContracts.ts +++ b/src/contracts/managed/managedToolContracts.ts @@ -3,7 +3,7 @@ import { z } from "zod"; import type { ToolContract } from "../toolContractTypes.js"; import { managedOutputSchemas } from "../toolOutputSchemaGroups.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "../toolEffects.js"; import { absoluteLocalPathStringSchema } from "../../domain/localPath.js"; import { distinctItems } from "../../domain/schemaConstraints.js"; import { analysisDetailSchema } from "../analysisDetail.js"; @@ -64,7 +64,7 @@ export const MANAGED_TOOL_CONTRACTS = [ name: "inspect_managed_artifact", cli: true, retainedSummary: { evidenceParameters: "omit-detail" }, - ...toolContractMetadata("inspect_managed_artifact"), + ...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.", kind: "managed-provider", @@ -86,7 +86,7 @@ export const MANAGED_TOOL_CONTRACTS = [ name: "inspect_managed_members", cli: true, retainedSummary: { evidenceParameters: "omit-detail" }, - ...toolContractMetadata("inspect_managed_members"), + ...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; 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", @@ -117,7 +117,10 @@ export const MANAGED_TOOL_CONTRACTS = [ { name: "inspect_managed_native_boundaries", cli: true, - ...toolContractMetadata("inspect_managed_native_boundaries"), + ...toolContractMetadata( + "inspect_managed_native_boundaries", + evidenceEffects, + ), description: "Inspect PE/CLI ModuleRef, ImplMap/PInvoke declarations, CLI native-header indicators, and non-IL method implementation flags without loading or executing target code. Results are managed declarations and degraded native-boundary observations, not verified native exports or addresses.", kind: "managed-provider", diff --git a/src/contracts/managed/managedWorkflowToolContracts.ts b/src/contracts/managed/managedWorkflowToolContracts.ts index 631ac785f1..1ce6fc96a9 100644 --- a/src/contracts/managed/managedWorkflowToolContracts.ts +++ b/src/contracts/managed/managedWorkflowToolContracts.ts @@ -12,7 +12,7 @@ import { MANAGED_APPLICATION_GRAPH_EXAMPLE, MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE, } from "./managedWorkflowExamples.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "../toolEffects.js"; const comparisonOutputSchema = requireOutputSchema( managedWorkflowOutputSchemas, @@ -36,7 +36,7 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [ { name: "compare_managed_members", cli: true, - ...toolContractMetadata("compare_managed_members"), + ...toolContractMetadata("compare_managed_members", evidenceEffects), description: "Compare two authenticated inspect_managed_members Evidence records, inline or retained, using unique exact type/name/signature/CIL or decoded structural matches. Names alone never establish correspondence; undecoded signatures, unresolved declaring types and ambiguous candidates remain unknown rather than added/removed. Structural cross-name matching cannot consume a member whose own type/name counterpart remains unpaired. Matched methods compare aligned call-site shapes and observed target names; unaligned or missing facts stay unknown. Tokens remain local to each artifact SHA-256/MVID; tuple hashes do not remap them. Static call names do not prove overload identity or runtime dispatch.", kind: "application", @@ -55,7 +55,10 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [ { name: "verify_managed_native_boundaries", cli: true, - ...toolContractMetadata("verify_managed_native_boundaries"), + ...toolContractMetadata( + "verify_managed_native_boundaries", + evidenceEffects, + ), description: "Verify managed P/Invoke/native-boundary declarations against authenticated native export or function Evidence, with inline or exact retained sources, without executing managed code or translating managed metadata tokens into native addresses. The workflow preserves declaration-only, verified, inferred, contradicted, and unresolved states; a name candidate with missing managed or native module identity remains unresolved with its candidate evidence retained.", kind: "application", @@ -76,7 +79,7 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [ { name: "import_managed_reconstruction", cli: true, - ...toolContractMetadata("import_managed_reconstruction"), + ...toolContractMetadata("import_managed_reconstruction", evidenceEffects), description: "Import decompiler-produced managed reconstruction against authenticated inspect_managed_members Evidence supplied inline or by exact retained reference. The workflow locks each method to artifact SHA-256, MVID, metadata token, signature hash, and the limited decoded-IL tuple hash, records the decompiler identity and options, and marks C# or pseudocode as analyst inference rather than canonical byte observation.", kind: "application", @@ -97,7 +100,10 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [ { name: "project_managed_application_graph", cli: true, - ...toolContractMetadata("project_managed_application_graph"), + ...toolContractMetadata( + "project_managed_application_graph", + evidenceEffects, + ), description: "Project authenticated managed artifact, member, and native-boundary Evidence, supplied inline or by exact retained reference, into the provider-neutral application graph without executing managed code, loading assemblies, or translating managed metadata tokens to native addresses. The graph preserves managed static observations as managed-specific nodes linked to source Evidence, with in-module calls and field-access edges; other call and field-access sites are counted in limitations.", kind: "application", diff --git a/src/contracts/model/modelToolContracts.ts b/src/contracts/model/modelToolContracts.ts index 294f1cee86..12f6095b18 100644 --- a/src/contracts/model/modelToolContracts.ts +++ b/src/contracts/model/modelToolContracts.ts @@ -6,14 +6,14 @@ import { modelArtifactSummaryViewResultSchema, } from "../../domain/analysisView/analysisViewResult.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "../toolEffects.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; export const INSPECT_MODEL_ARTIFACT_CONTRACT = { name: "inspect_model_artifact", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_model_artifact"), + ...toolContractMetadata("inspect_model_artifact", evidenceEffects), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/native/binaryDiagnosticsToolContracts.ts b/src/contracts/native/binaryDiagnosticsToolContracts.ts index e41968647d..ea95f978db 100644 --- a/src/contracts/native/binaryDiagnosticsToolContracts.ts +++ b/src/contracts/native/binaryDiagnosticsToolContracts.ts @@ -34,7 +34,11 @@ import { nativeExportsSchema, } from "../../domain/native/nativeExports.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { + toolContractMetadata, + evidenceEffects, + toolEffects, +} from "../toolEffects.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; import { inspectPeResourcesInputSchema, @@ -94,7 +98,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_devicetree", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_devicetree"), + ...toolContractMetadata("inspect_devicetree", evidenceEffects), kind: "native-provider", description: "Inspect an explicit local flattened devicetree blob (FDT v16/v17) without execution or external tools. Returns validated header, memory reservations, full node/property tree with bounded raw hex, derived standard strings, cells and parent-sized reg tuples, aliases and selected single-cell phandle references with unresolved targets. Binding-specific arrays, overlays and runtime hardware remain unknown. Malformed structure or exhausted named budgets fails without partial success. Complete detail returns all Evidence inline; summary retains it for inspect_analysis_view kind devicetree, collections nodes, properties (requires exact path), reservations and references, with offset/limit pagination.", @@ -116,7 +120,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_pe_load_config", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_pe_load_config"), + ...toolContractMetadata("inspect_pe_load_config", evidenceEffects), kind: "native-provider", description: "Inspect PE32/PE32+ TLS callbacks and sized load configuration without executing the image. Returns callback VA/RVA/file offsets and sections, security cookie, SafeSEH (PE32), CFG flags and table pointers/counts, EH continuation and XFG fields. Flag-derived mitigation claims are labeled inferred. Absent directories are null; malformed structures and exhausted budgets fail without partial success. Reads a stable local regular file without a disassembler.", @@ -133,7 +137,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_binary_hardening", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_binary_hardening"), + ...toolContractMetadata("inspect_binary_hardening", evidenceEffects), kind: "native-provider", description: "Inspect static hardening declarations in a local ELF, PE or Mach-O, including every universal slice. Reports PIE/ASLR, NX, RELRO, stack-protector/FORTIFY signs, control-flow flags and stripped state with supporting header/import facts. Missing signs may be unknown, especially for static/stripped images. Signature presence does not establish validity; use inspect_signature for Mach-O hardened runtime. No target execution or exploitability claim. Malformed headers/budgets may fail; limited symbol/property-note reads retain header facts and mark affected rows unknown.", @@ -151,7 +155,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_native_initializers", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_native_initializers"), + ...toolContractMetadata("inspect_native_initializers", evidenceEffects), kind: "native-provider", description: "List declared initializer/finalizer functions in a local ELF32/64 or selected Mach-O slice without execution. Returns paged slots and resolved target addresses/file offsets, sections, exact symbols and resolution basis from dynamic tags, constructor sections, relocations and fixups. Unestablished slots remain unresolved, never treated as stored zero targets. Missing declarations do not prove no code runs before main.", @@ -169,7 +173,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_elf_notes", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_elf_notes"), + ...toolContractMetadata("inspect_elf_notes", evidenceEffects), kind: "native-provider", description: "Inspect one explicit local ELF32/ELF64 image's PT_NOTE program headers and SHT_NOTE sections without executing it or opening a disassembler. Returns note-table file ranges, owners, types, descriptor SHA-256 and hex previews, plus GNU build-id, ABI-tag and gold-version fields, Linux CORE process, mapping, signal, and auxv notes, and Android .note.android.ident API-level and NDK version/build fields when those descriptors match. A missing table is observed absence of those declarations, not proof the image never carried notes in another container. Reads a stable regular file; malformed ELF headers, truncated notes and exhausted budgets return no partial success. Portable on supported Node hosts; no debug package or catalog is required.", @@ -186,7 +190,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_elf_unwind_ranges", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_elf_unwind_ranges"), + ...toolContractMetadata("inspect_elf_unwind_ranges", evidenceEffects), kind: "native-provider", description: "Inspect ELF32/64 .eh_frame and .eh_frame_hdr for paged FDE function ranges, associated CIE facts, LSDA/personality pointers, symbol matches and search-table agreement. No execution or disassembler. Missing unwind declarations do not prove no functions; truncated records remain incomplete. .debug_frame is detected but not decoded, CFA instructions are not evaluated, and indirect EH pointers are not dereferenced. Malformed headers or exhausted CIE/FDE budgets fail without partial success.", @@ -203,7 +207,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_apple_ips", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_apple_ips"), + ...toolContractMetadata("inspect_apple_ips", evidenceEffects), kind: "native-provider", description: "Inspect a local Apple .ips crash report for process, exception/termination, thread, image and lossless register facts with deterministic classification. Crash parsing supports bug_type string 309; other types, including 288 stackshots, return no crash result. join_path derives static addresses only when image UUID and architecture match a Mach-O slice; it does not symbolicate or read dSYMs. Missing/truncated bodies fail without partial success. No target execution, atos, disassembler or Xcode required.", @@ -227,7 +231,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_kernel_module", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_kernel_module"), + ...toolContractMetadata("inspect_kernel_module", evidenceEffects), kind: "native-provider", description: "Inspect an uncompressed local ELF32/64 ET_REL Linux kernel module for ordered .modinfo entries, symbol CRCs, module/export/init/exit section facts and appended signature ranges/digests. No execution, struct module decoding or certificate validation. Missing known sections describe this image only. gzip/xz/zstd require external decompression; extract_artifact does not decode those module containers. Malformed headers or exhausted entry budgets fail without partial success. Portable on supported Node hosts.", @@ -245,7 +249,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_kernel_build_config", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_kernel_build_config"), + ...toolContractMetadata("inspect_kernel_build_config", evidenceEffects), kind: "native-provider", description: "Inspect a local Linux kernel image (vmlinux, raw arm64 Image, x86 bzImage/zImage or configs.ko) for the version/builder/compiler banner and embedded CONFIG_IKCONFIG. Returns config digest/count and paged, optionally exact-name-filtered CONFIG_* values. Only validated marker-framed gzip config is accepted; a literal marker is insufficient. Supported gzip bzImage payloads are searched; other compressed payloads require external decompression. Truncation is incomplete, not absence; budget exhaustion fails without partial success. No target execution or external tools.", @@ -269,7 +273,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_byte_entropy", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_byte_entropy"), + ...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.", @@ -296,7 +300,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_pe_certificates", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_pe_certificates"), + ...toolContractMetadata("inspect_pe_certificates", evidenceEffects), kind: "native-provider", description: "Inspect a local PE32/PE32+ certificate directory without executing it or verifying signatures. Returns WIN_CERTIFICATE ranges/types/digests and structurally decoded PKCS#7 signer, algorithm and X.509 identity fields when present. Missing directory does not establish globally unsigned status. Authenticode digest coverage, trust chains and timestamp validity remain unobserved. Malformed/truncated structures and unsupported PKCS#7 signed-data shapes fail without partial success. No Windows SDK or disassembler required.", @@ -313,7 +317,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_pe_imports", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_pe_imports"), + ...toolContractMetadata("inspect_pe_imports", evidenceEffects), kind: "native-provider", description: "Inspect local PE32/PE32+ standard and delay-load imports without execution. Returns DLL/named/ordinal imports, ILT/IAT RVAs, descriptors and a pefile-compatible standard-table import hash only when its row sequence is complete and comparable. Missing declarations do not establish no API use; loaded IAT, bound snapshots and forward resolution remain unknown. Unreadable names/thunks or missing tables yield partial coverage; malformed headers or exhausted budgets fail. No Windows SDK or disassembler required.", @@ -330,7 +334,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_windows_shortcut", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_windows_shortcut"), + ...toolContractMetadata("inspect_windows_shortcut", evidenceEffects), kind: "native-provider", description: "Inspect a local Windows Shell Link (.lnk) without resolving or executing its target, COM, or network access. Returns header/time/display facts, target-ID/link-info paths, arguments, working directory/icon and ExtraData observations, with raw hashes for unknown structures. Tracker and behavioral observations are derived. Malformed structures, odd Unicode lengths or exhausted budgets return typed failures or explicitly partial coverage with the failing offset. No Windows SDK required.", @@ -347,7 +351,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_pe_resources", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_pe_resources"), + ...toolContractMetadata("inspect_pe_resources", evidenceEffects), kind: "native-provider", description: "Inspect a local PE32/PE32+ resource tree without execution: type/name/language identities, empty branches, UTF-16 names, payload RVA/file ranges/digests and static group-icon candidates. Language fallback, image decoding and actual UI loading remain unknown. Malformed/ambiguous mappings, non-identical overlaps or exhausted budgets fail without partial success. No Windows SDK or disassembler required.", @@ -364,7 +368,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_native_exports", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_native_exports"), + ...toolContractMetadata("inspect_native_exports", evidenceEffects), kind: "native-provider", description: "Inspect PE/ELF exports without execution or an analysis engine; use inspect_macho for Mach-O. Returns named/ordinal/forwarded PE exports or defined ELF dynamic symbols with binding/type/version, preserving aliases, hidden versions and raw-name qualifications. Unreadable entries are partial; unavailable ELF section metadata can make enumeration unsupported. An empty complete inventory means no declared exports. detail summary retains full Evidence for inspect_analysis_view kind native-exports, collection exports/issues, with exact names/indices, fields and paging; source_index is parent-scoped.", @@ -384,7 +388,14 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_binary_layout", availability: { host: "binaryLayout" }, cli: true, - ...toolContractMetadata("inspect_binary_layout"), + ...toolContractMetadata( + "inspect_binary_layout", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + }), + ), kind: "native-provider", description: "Inspect static ELF section/segment, symbol, relocation, linkage and mitigation facts with artifact SHA-256 Evidence, without launching the image. Linux x64 requires caller-supplied pwntools 4.15.0/pyelftools 0.33/Unicorn 2.1.2; supports ELF64 x86-64/little-endian AArch64 and ELF32 i386/little-endian ARM/little- or big-endian MIPS. Unicorn may emulate PLT instructions for derived maps. Runtime addresses/paths and complete relocation/GOT/PLT discovery remain unknown; RELR per-word locations/addends can be unknown. detail summary retains full Evidence for layout section/symbol/mitigation/linkage views. pwntools_timeout_ms bounds each command independently of producer_limits and inherited OS limits. Unsupported, malformed or oversized inputs fail without partial success.", @@ -408,7 +419,14 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ name: "inspect_recorded_crash", availability: { host: "recordedCrash" }, cli: true, - ...toolContractMetadata("inspect_recorded_crash"), + ...toolContractMetadata( + "inspect_recorded_crash", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + }), + ), kind: "native-provider", description: "Inspect a saved Linux ELF64 little-endian amd64/AArch64 core without launching its target or attaching to a live PID. Returns recorded segments, raw notes/ranges, thread registers and SIGINFO as digest-bound Evidence. Historical PIDs do not establish current identity; note coverage and signal/thread joins remain unknown. Optional caller-configured GDB/pwndbg adds core-only mapping candidates from the same snapshot; zero flags mean unknown permissions. Linux x64 requires the documented pwntools profile, with optional pwndbg 2026.09.15. No implicit executable/library pairing, command language or installation. pwntools_timeout_ms and producer_limits control independent per-command budgets; malformed or oversized input fails without partial success.", diff --git a/src/contracts/native/nativeToolContracts.ts b/src/contracts/native/nativeToolContracts.ts index a8daaf04b8..56eeee6c64 100644 --- a/src/contracts/native/nativeToolContracts.ts +++ b/src/contracts/native/nativeToolContracts.ts @@ -10,7 +10,12 @@ import type { ToolContract } from "../toolContractTypes.js"; import { nativeOutputSchemas } from "../toolOutputSchemaGroups.js"; import { jsonValueSchema } from "../../domain/jsonValue.js"; import { localPathStringSchema } from "../../domain/localPath.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import type { EffectAudit } from "../toolEffects.js"; +import { + toolContractMetadata, + nativeEvidenceEffects, + toolEffects, +} from "../toolEffects.js"; import { analysisDetailSchema } from "../analysisDetail.js"; import { nativeCommandTimeoutField } from "../../domain/native/nativeDeadlines.js"; @@ -46,6 +51,7 @@ const native = < Schema extends z.ZodObject, >( name: Name, + audit: EffectAudit, description: string, inputSchema: Schema, retainedSummary?: ToolContract["retainedSummary"], @@ -54,7 +60,7 @@ const native = < const strictInputSchema = inputSchema.strict(); return { name, - ...toolContractMetadata(name), + ...toolContractMetadata(name, audit), description, kind: "native-provider", cli: true, @@ -86,21 +92,48 @@ export const swiftSymbolsSchema = z.array( export const NATIVE_TOOL_CONTRACTS = [ native( "observe_native_ui", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), "Observe one already-running native app window by PID/window ID, bound to the active Mach-O target. Returns a bounded accessibility tree and window screenshot; screenshot or accessibility must be enabled. Permission denial does not broaden capture or launch the target. native_ui_deadline_ms sets this call's deadline independently of output and wait-step limits. Use capture_native_ui_scenario to interact.", nativeUiObservationInputSchema, ), native( "capture_native_ui_scenario", + toolEffects({ + writesFilesystem: true, + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + changesUiState: true, + mayDiscardData: true, + executesForeignCode: true, + idempotent: false, + }), "Interact with one exact native app window through selected-element press, scroll, AXValue text entry and bounded waits. Returns ordered before/after captures and per-step failures; screenshot or accessibility must be enabled. Actions may change app data, network activity and persistent state; REA leaves that state in place. native_ui_deadline_ms controls the scenario deadline, independently of output allowance and wait-step caps. Use observe_native_ui for observation only.", nativeUiScenarioInputSchema, ), native( "observe_native_calls", + // The owned process can change files, show UI and use the network. + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + changesUiState: true, + executesForeignCode: true, + idempotent: false, + }), "Launch the active Mach-O under LLDB and record selected function/Objective-C method entries; the owned process is killed at max_events or duration_ms. Target execution uses the caller's permissions and may write files, show UI or use network. Hits auto-continue; REA evaluates no expressions and attaches to no other process. Returns addresses, thread/module/symbol, raw argument registers, selector/receiver facts, optional frames, stdout/stderr and limitations. Hardened-runtime targets need get-task-allow. Set capture_limits before launch; later changes cannot recover omitted observations.", nativeCallObservationInputSchema, ), native( "inspect_macho", + { ...nativeEvidenceEffects, writesFilesystem: true }, "Inspect Mach-O slices, load commands, linkage, build metadata, segments/sections and permissions without launching Hopper. Returns command provenance and explicit coverage; segment and section file offsets are slice-relative, so add selected_architecture.container_file_offset for an input-file offset. detail summary retains complete Evidence for inspect_analysis_view kind macho rather than delivering large symbol lists inline. native_command_timeout_ms bounds each Xcode command, independently of output admission.", z.object({ detail: analysisDetailSchema @@ -115,6 +148,7 @@ export const NATIVE_TOOL_CONTRACTS = [ ), native( "inspect_signature", + { ...nativeEvidenceEffects, writesFilesystem: true }, "Inspect the selected Mach-O slice's signing identity, hashes, authorities, requirement, entitlements and hardened-runtime state from a digest-verified snapshot. Other slices are checked for unsigned state with separate metadata coverage. Returns command provenance; native_command_timeout_ms bounds each codesign command independently of output admission.", z.object({ native_command_timeout_ms: nativeCommandTimeoutField, @@ -122,6 +156,7 @@ export const NATIVE_TOOL_CONTRACTS = [ ), native( "inspect_plist", + nativeEvidenceEffects, "Parse Info.plist from an open binary or bundle-resource session, or select path within that session. Use open_binary or open_bundle_resources first; path alone does not open one. Returns normalized JSON. native_command_timeout_ms bounds each file/plutil command, not fixed input/decode/nesting allowances. XML also requires plutil validation and may be refused at a shallower depth; errors name the applicable limit.", z.object({ path: localPathStringSchema @@ -134,6 +169,7 @@ export const NATIVE_TOOL_CONTRACTS = [ ), native( "list_architectures", + nativeEvidenceEffects, "List thin/universal Mach-O slices with file offsets, sizes, alignment, coverage and native-tool provenance. native_command_timeout_ms bounds lipo, independently of output admission.", z.object({ native_command_timeout_ms: nativeCommandTimeoutField, @@ -141,6 +177,7 @@ export const NATIVE_TOOL_CONTRACTS = [ ), native( "demangle_swift", + nativeEvidenceEffects, "Demangle an ordered list of single-line Swift symbols without Hopper. Returns demangled, unchanged or invalid for every input; invalid entries do not discard valid companions. native_command_timeout_ms bounds swift-demangle, independently of output admission.", z.object({ symbols: swiftSymbolsSchema, diff --git a/src/contracts/ntfsJournalToolContracts.ts b/src/contracts/ntfsJournalToolContracts.ts index 640fefe5d8..f7fe774d2f 100644 --- a/src/contracts/ntfsJournalToolContracts.ts +++ b/src/contracts/ntfsJournalToolContracts.ts @@ -4,14 +4,14 @@ import { ntfsJournalResultSchema, } from "../domain/windows/ntfsJournalQuery.js"; import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { evidenceEffects, toolContractMetadata } from "./toolEffects.js"; import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; export const NTFS_JOURNAL_TOOL_CONTRACTS = [ { name: NTFS_JOURNAL_OPERATION, cli: true, - ...toolContractMetadata(NTFS_JOURNAL_OPERATION), + ...toolContractMetadata(NTFS_JOURNAL_OPERATION, evidenceEffects), kind: "application", description: "Inspect USN V2/V3/V4 records from a local acquired NTFS journal with a caller-paired MFT from the same volume. Reads at most 64 MiB per file. Returns source-order events, explicit coverage rows, both SHA-256 identities, and nextFileOffset for another page using the same inputs. V2 MFT references include sequence numbers; opaque V3/V4 IDs remain unresolved. MFT inventory counts are inline by default; select mft_record_limit for up to 32 detailed records, including identity-checked extension attributes and explicit link coverage. V4 returns at most 16 extent samples per event with explicit omissions. History completeness remains unknown. Other journal versions and unverifiable references remain explicit. Reads only the selected acquisition files.", diff --git a/src/contracts/officialToolContracts.ts b/src/contracts/officialToolContracts.ts index 61692d59c6..3535d5dc42 100644 --- a/src/contracts/officialToolContracts.ts +++ b/src/contracts/officialToolContracts.ts @@ -13,7 +13,14 @@ import { procedure, } from "./toolContractHelpers.js"; import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import type { EffectAudit } from "./toolEffects.js"; +import { + toolContractMetadata, + evidenceEffects, + providerNetworkEvidenceEffects, + providerUiNetworkEvidenceEffects, + toolEffects, +} from "./toolEffects.js"; import { nativeDataTypeInputSchema } from "../domain/native/nativeDataType.js"; import { nativeInstructionInputSchema } from "../domain/native/nativeInstruction.js"; import { functionInstructionInputSchema } from "./functionInstructionContract.js"; @@ -46,6 +53,7 @@ const official = < Schema extends z.ZodObject, >( name: Name, + audit: EffectAudit, description: string, inputSchema: Schema, retainedSummary?: ToolContract["retainedSummary"], @@ -53,7 +61,7 @@ const official = < const strictInputSchema = inputSchema.strict(); return { name, - ...toolContractMetadata(name), + ...toolContractMetadata(name, audit), description, kind: "official-proxy", ...(OFFICIAL_CLI_CONTRACTS.has(name) ? { cli: true as const } : {}), @@ -69,77 +77,98 @@ const official = < export const OFFICIAL_TOOL_CONTRACTS = [ official( "annotate_native_function", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + mayDiscardData: true, + }), "Atomically rename one function and/or change entry comments, verify readback, and return its refreshed complete dossier. Ghidra resolves interior addresses to function entries; use procedure_address to select the entry explicitly. Edits change analysis metadata, never executable bytes; empty comment text clears it. Invalid edits roll back together. Ghidra checkpoint mode saves on normal close; ephemeral mode discards edits, including in CLI cleanup. Check binary_session for the mode. Windows P0 and providers without this capability are unsupported.", nativeFunctionAnnotationsInputSchema, ), official( "inspect_native_load_image", + evidenceEffects, "Inspect provider source digests, loaded mappings, relocations, entries and register context without executing or changing the target. Independent snapshot checks support DOS MZ, selected COM, raw binaries and GameCube DOL; other formats retain observations with unsupported verification. Relocation symbols do not prove runtime binding. detail summary retains complete Evidence for inspect_analysis_view kind native-load-image, collection source_files/mappings/relocations/entry_points/entry_context/checks/sections. Null collections are unrecorded/inapplicable; payload bytes require explicit fields. Overlay and uninitialized coverage remain explicit.", z.strictObject({ detail: analysisDetailSchema }), { evidenceParameters: "omit-detail" }, ), official( "inspect_native_data_type", + evidenceEffects, "Inspect one recovered type by exact database category path or defined typed data address. Returns observed size, alignment, packing, fields, bitfields, enum values, and child type identities; source-level authority and flexible-tail semantics remain unknown unless substantiated.", nativeDataTypeInputSchema, ), official( "inspect_native_instruction", + evidenceEffects, "Inspect bytes, mnemonic, operand tokens, flow and typed incoming/outgoing references at one code/data address. Ghidra preserves the query and separately reports a containing listed instruction/data object; unlisted memory is not decoded. References do not establish runtime access, and token-only operands do not establish memory decomposition. Use inspect_native_data_type at a data object's start for layout, without inferring a selected field. Retained references use inspect_analysis_view kind native-instruction-references; null coverage is unavailable or unrecorded.", nativeInstructionInputSchema, ), official( "resolve_native_call_targets", + evidenceEffects, "Resolve one explicit static call site using typed provider call references. Preserves ambiguous targets as candidates and unresolved computed calls as unknown; does not execute code or traverse a call graph.", nativeInstructionInputSchema, ), official( "address_name", + evidenceEffects, "Resolve the primary analyzed name at a code or data address. Headless providers require an explicit address; GUI providers may default to their current cursor. Null means the provider has no primary name at that address.", z.object({ document, address: optionalAddress }), ), official( "comment", + evidenceEffects, "Read the regular analysis comment at an explicit address, or the current cursor where supported. Returns null when absent; use set_comment to write one.", z.object({ document, address: optionalAddress }), ), official( "current_address", + evidenceEffects, "Return Hopper's current cursor address for the selected document. Use only for interactive navigation state; prefer explicit addresses in reproducible investigations.", z.object({ document }), ), official( "current_procedure", + evidenceEffects, "Return the analyzed procedure containing Hopper's current cursor. This uses GUI cursor state and is not a procedure-name lookup.", z.object({ document }), ), official( "current_document", + evidenceEffects, "Return the document currently selected by REA's Hopper bridge.", z.object({}), ), official( "goto_address", + toolEffects({ mutatesSession: true, changesUiState: true }), "Move Hopper's GUI cursor to a mapped address and return the observed cursor address. Interior coordinates snap to the containing analyzed object's start. Unmapped destinations fail without moving the cursor. This changes navigation state but not analysis data; use explicit-address tools for headless workflows.", z.object({ address, document }), ), official( "inline_comment", + evidenceEffects, "Read the inline instruction comment at an explicit address, or the current cursor where supported. Returns null when absent; use set_inline_comment to write one.", z.object({ document, address: optionalAddress }), ), official( "list_bookmarks", + evidenceEffects, "List every bookmark in the selected Hopper document as address and name pairs; unnamed bookmarks retain a null name. Use bookmarks as analyst-authored navigation aids; this does not discover code references.", z.object({ document }), ), official( "list_documents", + providerNetworkEvidenceEffects, "List provider program or document identities. Hopper may expose several documents; a Ghidra headless session contains exactly its one imported Program.", z.object({}), ), 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. Select detail summary for counts and retained native-inventory pages; complete remains the default.", z.object({ document, @@ -150,17 +179,20 @@ export const OFFICIAL_TOOL_CONTRACTS = [ ), 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. Select detail summary for counts and retained native-inventory pages; complete remains the default.", z.object({ document, detail: analysisDetailSchema }), { evidenceParameters: "omit-detail" }, ), official( "list_segments", + evidenceEffects, "List segments or memory blocks using exclusive end addresses. Ghidra reports block permissions, address space, image base, initialization, and overlay facts; Hopper marks unavailable permissions explicitly.", z.object({ document }), ), 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. Select detail summary for counts and retained native-inventory pages; complete remains the default.", z.object({ document, @@ -171,52 +203,62 @@ export const OFFICIAL_TOOL_CONTRACTS = [ ), official( "next_address", + evidenceEffects, "Return the next analyzed object address after an explicit address or current cursor. This is a navigation primitive, not instruction-flow or CFG analysis.", z.object({ document, address: optionalAddress }), ), official( "prev_address", + evidenceEffects, "Return the previous analyzed object start before an explicit address or current cursor. This is a navigation primitive and may fail at document boundaries; data objects and instructions remain distinct from control flow.", z.object({ document, address: optionalAddress }), ), official( "procedure_address", + providerNetworkEvidenceEffects, "Resolve an unambiguous procedure symbol name or provider-normalized address to its canonical entry address. External address spaces remain explicit. Select detail summary for selected facts and a context digest; native-observation and native-context views retain complete source access.", z.object({ procedure, document, detail: analysisDetailSchema }), { evidenceParameters: "omit-detail" }, ), official( "procedure_assembly", + providerUiNetworkEvidenceEffects, "Return assembly for one analyzed procedure identified by symbol or hexadecimal address. Use when pseudocode loses calling-convention or instruction-level detail; output is currently returned as one unpaginated string. Ghidra terminal-call assumptions that may cut the analyzed body are reported in Evidence limitations.", z.object({ procedure, document }), ), official( "procedure_callees", + providerNetworkEvidenceEffects, "Return the provider's resolved direct callees for one procedure identified by symbol or address. Unresolved indirect calls may be absent; use analyze_function and typed references to preserve available edge uncertainty. Ghidra terminal-call assumptions that may cut the analyzed body are reported in Evidence limitations. Select detail summary for selected facts and a context digest; native-observation and native-context views retain complete source access.", z.object({ procedure, document, detail: analysisDetailSchema }), { evidenceParameters: "omit-detail" }, ), official( "procedure_callers", + providerNetworkEvidenceEffects, "Return the provider's resolved direct callers for one procedure identified by symbol or address. Results reflect completed static analysis and may omit unresolved indirect references. Ghidra terminal-call assumptions that may cut the analyzed body are reported in Evidence limitations. Select detail summary for selected facts and a context digest; native-observation and native-context views retain complete source access.", z.object({ procedure, document, detail: analysisDetailSchema }), { evidenceParameters: "omit-detail" }, ), official( "procedure_info", + evidenceEffects, "Return provider metadata for one procedure identified by symbol or address: entrypoint, signature, locals, size, block count, and complete inclusive body ranges when observed. Extents reflect the provider's analyzed body; Ghidra terminal-call assumptions that may cut it are reported in Evidence limitations. Hopper locals preserve observed names and signed stack displacements; source types remain unknown. Body byte count and enclosing span remain distinct; unavailable extent is explicit.", z.object({ procedure, document }), ), official( "read_function_instructions", + providerUiNetworkEvidenceEffects, "Return every raw instruction for one analyzed procedure. Instruction text and body extent are provider-specific. Ghidra terminal-call assumptions that may cut the analyzed body are reported in limitations.", functionInstructionInputSchema, ), - ...HOPPER_MEMORY_TOOL_DEFINITIONS.map(({ name, description, inputSchema }) => - official(name, description, inputSchema), + ...HOPPER_MEMORY_TOOL_DEFINITIONS.map( + ({ name, effects, description, inputSchema }) => + official(name, effects, description, inputSchema), ), official( "procedure_references", + evidenceEffects, "Return incoming or outgoing reference edges for one procedure. Ghidra preserves detailed reference flags; Hopper preserves native CallReference classifications and exact endpoints. Select detail summary to retain complete Evidence and page references or unresolved calls using inspect_analysis_view kind native-procedure-references. Page coverage describes retained observations, not complete discovery or proof the target ran.", z.object({ procedure, @@ -228,6 +270,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. 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, @@ -239,54 +282,88 @@ export const OFFICIAL_TOOL_CONTRACTS = [ ), official( "resolve_containing_procedure", + providerNetworkEvidenceEffects, "Resolve an arbitrary address, including an interior instruction or exact external entry, to its provider-analyzed containing procedure. A negative result distinguishes outside segments from not in a procedure and is never guessed from nearby symbols. Select detail summary for selected facts and a context digest; native-observation and native-context views retain complete source access.", z.object({ address, document, detail: analysisDetailSchema }), { evidenceParameters: "omit-detail" }, ), 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 retains unfiltered candidates; normalized_result holds matches. detail summary retains native-inventory pages. 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; normalized_result holds matches. detail summary retains native-inventory pages. Regex uses Java Pattern in Ghidra and ECMAScript Unicode elsewhere; binary_session/errors report limits.", z.object({ ...nativeSearchInput, detail: analysisDetailSchema }), { evidenceParameters: "omit-detail" }, ), official( "set_address_name", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + mayDiscardData: true, + }), "Assign an analyst name to one mapped hexadecimal address and report whether the native edit succeeded and exact readback matched. Hopper rejects symbol names exceeding 1024 UTF-16 code units before mutation, and rejects names owned by another address; use set_addresses_names to explicitly move or swap labels among selected addresses. This mutates analysis metadata.", z.object({ address, name: z.string(), document }), ), official( "set_addresses_names", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + mayDiscardData: true, + }), "Assign analyst names to multiple mapped addresses in one call and return per-address edit/readback success booleans. Hopper validates mapped destinations, native string representations, its 1024 UTF-16 code-unit symbol-name limit, and unique destinations/names before applying edits; its labels may move or swap only among explicitly selected addresses, and unselected label owners remain unchanged. Ghidra rejects any address whose name another selected address also requests or holds in that namespace; others still apply, with reasons in raw_result.failures. This mutates analysis metadata; verify failures individually.", z.object({ names: jsonRecordSchema(z.string()), document }), ), official( "set_bookmark", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + mayDiscardData: true, + }), "Create or update a bookmark at a mapped hexadecimal address and report readback success. Omit name to preserve an existing name or create an unnamed bookmark; an empty string clears the bookmark name. This mutates navigation metadata; bookmarks are analyst-authored navigation aids, not binary evidence.", z.object({ address, name: z.string().optional(), document }), ), official( "set_comment", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + mayDiscardData: true, + }), "Write a regular analysis comment at a hexadecimal address and return whether readback matched. An empty comment clears it. This mutates the Hopper document; use comments to record evidence IDs or reasoning.", z.object({ address, comment: z.string(), document }), ), official( "set_inline_comment", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + mayDiscardData: true, + }), "Write an inline instruction comment at a hexadecimal address and return whether readback matched. An empty comment clears it; Hopper may flatten newlines, producing false on exact readback. This mutates analysis metadata.", z.object({ address, comment: z.string(), document }), ), official( "unset_bookmark", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + mayDiscardData: true, + }), "Remove the bookmark at a mapped hexadecimal address and return whether it is absent. Hopper also permits removing an existing legacy bookmark outside mapped memory. This mutates navigation metadata and does not alter binary bytes.", z.object({ address, document }), ), official( "xrefs", + providerNetworkEvidenceEffects, "Return analyzed references to a code or data address. Hopper may default to its current cursor; headless providers such as Ghidra require an explicit address. Kuna also accepts names in its own inventory, including data names; an unlisted name may still exist in the target. Use to connect strings, globals, selectors, and functions; bare addresses are untyped and indirect references may be incomplete. Page a retained result with inspect_analysis_view and native-observation; use native-context for source caveats. Use inspect_native_instruction at the target address for typed incoming references where supported.", z.object({ document, address: optionalAddress }), ), diff --git a/src/contracts/pcap/pcapToolContracts.ts b/src/contracts/pcap/pcapToolContracts.ts index 2ed2d240d5..2f98027b11 100644 --- a/src/contracts/pcap/pcapToolContracts.ts +++ b/src/contracts/pcap/pcapToolContracts.ts @@ -4,7 +4,7 @@ import { } from "../../domain/pcap/pcapAnalysis.js"; import type { ToolContract } from "../toolContractTypes.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; import { analysisDetailSchema, analysisDetailOutputSchemaOf, @@ -16,7 +16,14 @@ export const PCAP_TOOL_CONTRACTS = [ { name: "inspect_pcap_client", cli: true, - ...toolContractMetadata("inspect_pcap_client"), + ...toolContractMetadata( + "inspect_pcap_client", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), description: "Inspect the caller-selected tshark and capinfos binaries: selected commands, selection sources, and versions. Both tools must be usable. Reads no capture file. REA never installs the Wireshark suite; select binaries with REA_TSHARK_COMMAND and REA_CAPINFOS_COMMAND (absolute) or from PATH.", kind: "pcap-provider", @@ -28,7 +35,14 @@ export const PCAP_TOOL_CONTRACTS = [ name: "inspect_pcap_capture", availability: { host: "pcapCapture" }, cli: true, - ...toolContractMetadata("inspect_pcap_capture"), + ...toolContractMetadata( + "inspect_pcap_capture", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), 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.", kind: "pcap-provider", diff --git a/src/contracts/playwrightTraceToolContracts.ts b/src/contracts/playwrightTraceToolContracts.ts index 3151dcdb72..b31355c9fd 100644 --- a/src/contracts/playwrightTraceToolContracts.ts +++ b/src/contracts/playwrightTraceToolContracts.ts @@ -6,14 +6,14 @@ import { playwrightTracePageViewResultSchema, } from "../domain/analysisView/analysisViewResult.js"; import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "./toolEffects.js"; import type { ToolContract } from "./toolContractTypes.js"; export const PLAYWRIGHT_TRACE_TOOL_CONTRACTS = [ { name: "inspect_playwright_trace", cli: true, - ...toolContractMetadata("inspect_playwright_trace"), + ...toolContractMetadata("inspect_playwright_trace", evidenceEffects), kind: "application", description: 'Inspect a local Playwright v10 trace ZIP offline, without browser replay or requests to recorded URLs. Returns action boundaries, console/network facts, screenshot/body references and archive/member/line provenance; no cross-stream total order or complete-capture claim. Context options, most action arguments/results, DOM and resource bytes are not analyzed; credentials use HAR/URL projection. Default summary retains supported Evidence. Use view {kind:"playwright-trace",collection:"events",kinds:["network"],limit:10}, or streams/members/diagnostics pages. Text previews cover 256 UTF-16 units; event-text with exact event_id reads further chunks, and fields ["text"] selects full text. Paging does not raise parsing allowances; one archive import is admitted per decoder while retained views remain independent.', diff --git a/src/contracts/python/pythonPycToolContracts.ts b/src/contracts/python/pythonPycToolContracts.ts index d4394ab01f..e0451d3d2a 100644 --- a/src/contracts/python/pythonPycToolContracts.ts +++ b/src/contracts/python/pythonPycToolContracts.ts @@ -3,7 +3,7 @@ import { pythonPycSchema, } from "../../domain/python/pythonPyc.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "../toolEffects.js"; import { analysisDetailOutputSchemaOf } from "../analysisDetail.js"; import { z } from "zod"; import { @@ -31,7 +31,7 @@ export const PYTHON_PYC_TOOL_CONTRACTS = [ name: "inspect_python_pyc", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_python_pyc"), + ...toolContractMetadata("inspect_python_pyc", evidenceEffects), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/releaseExposureToolContracts.ts b/src/contracts/releaseExposureToolContracts.ts index a5821f19d4..d9339bbb6f 100644 --- a/src/contracts/releaseExposureToolContracts.ts +++ b/src/contracts/releaseExposureToolContracts.ts @@ -3,7 +3,7 @@ import { releaseExposureReportSchema, } from "../domain/releaseExposure.js"; import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, toolEffects } from "./toolEffects.js"; import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; /** Read-only report of what static analysis recovers from one shipped artifact. */ @@ -12,7 +12,14 @@ export const RELEASE_EXPOSURE_TOOL_CONTRACTS = [ name: "audit_release_exposure", availability: "standalone", cli: true, - ...toolContractMetadata("audit_release_exposure"), + ...toolContractMetadata( + "audit_release_exposure", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), kind: "artifact-provider", description: "Report what static analysis of a shipped application artifact recovers. Accepts one local .app bundle, installation directory, ASAR, or executable. Each check has a stable id, a status, the observation behind it, and fixed remediation text. Unknown and unassessed checks stay in the report. This does not establish that an application is secure. Reads the selected artifact. When the selection is a file, the parent directory is listed for sibling .pdb, .dSYM, .debug, and .map debug companions.", diff --git a/src/contracts/reverseEngineeringToolContracts.ts b/src/contracts/reverseEngineeringToolContracts.ts index 51cd8f49de..c16e1bbedf 100644 --- a/src/contracts/reverseEngineeringToolContracts.ts +++ b/src/contracts/reverseEngineeringToolContracts.ts @@ -8,14 +8,20 @@ import { import type { ToolContract } from "./toolContractTypes.js"; import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; import { analysisDetailOutputSchemaOf } from "./analysisDetail.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, toolEffects } from "./toolEffects.js"; /** Caller-selected GNU objdump and Rizin observations. */ export const REVERSE_ENGINEERING_TOOL_CONTRACTS = [ { name: "inspect_with_objdump", cli: true, - ...toolContractMetadata("inspect_with_objdump"), + ...toolContractMetadata( + "inspect_with_objdump", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + }), + ), 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.", @@ -38,7 +44,19 @@ export const REVERSE_ENGINEERING_TOOL_CONTRACTS = [ { name: "execute_rizin_command", cli: true, - ...toolContractMetadata("execute_rizin_command"), + ...toolContractMetadata( + "execute_rizin_command", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + mayDiscardData: true, + executesForeignCode: true, + idempotent: false, + }), + ), kind: "native-provider", description: "Run one caller-selected Rizin command on a local artifact. Commands/plugins can execute code, mutate files, access network and read outside the artifact; those external inputs are not Evidence-bound. Suppresses user settings/scripts but retains plugins. Raw stdout/stderr is authoritative, JSON is command-specific, and UTF-8 loss/truncation is explicit; output-limit termination leaves completion unknown. Rizin exits 0 even when its shell refuses a statement; completion_status rejected marks that refusal, and later statements did not run. Other command failures can still exit 0, so inspect stderr before treating empty output as absence. For raw images, asm_arch/asm_bits/asm_cpu select decoding and base_address maps offset 0; base_address also passes -n to skip loaders even on ELF, without REA confirming either. An admitted command retires shared binary analysis: close Ghidra explicitly first, then open_binary after effects settle. command_timeout_ms is per-phase and max_output_bytes bounds combined output (16 MiB default); both apply next call without restart and do not raise client receive limits or persistent debugger deadlines.", diff --git a/src/contracts/rizinDebugToolContracts.ts b/src/contracts/rizinDebugToolContracts.ts index 97d27d2b6c..751b018827 100644 --- a/src/contracts/rizinDebugToolContracts.ts +++ b/src/contracts/rizinDebugToolContracts.ts @@ -3,7 +3,7 @@ import { z } from "zod"; import { localPathStringSchema } from "../domain/localPath.js"; import type { ToolContract } from "./toolContractTypes.js"; import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, toolEffects } from "./toolEffects.js"; const sessionId = z.string().uuid(); const commandResult = z.strictObject({ @@ -21,7 +21,17 @@ export const RIZIN_DEBUG_TOOL_CONTRACTS = [ { name: "start_rizin_debug_session", availability: { host: "persistentDebugger" }, - ...toolContractMetadata("start_rizin_debug_session"), + ...toolContractMetadata( + "start_rizin_debug_session", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + executesForeignCode: true, + idempotent: false, + }), + ), kind: "native-provider", description: "Start a persistent Rizin debugger for one selected target/backend. Linux and a caller-selected TTY for inferior stdin/stdout/stderr are required; the target may use that terminal after detach. Startup suppresses user settings/scripts while retaining plugins. Detach requires verified output sinks, no target access to the debugger command stream, and dbg.exitkills=false. Capabilities depend on the installed backend. This shared-server operation retires binary analysis: close Ghidra explicitly first, then reopen the binary after effects settle.", @@ -43,7 +53,20 @@ export const RIZIN_DEBUG_TOOL_CONTRACTS = [ }, { name: "rizin_debug_command", - ...toolContractMetadata("rizin_debug_command"), + ...toolContractMetadata( + "rizin_debug_command", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + executesForeignCode: true, + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + changesUiState: true, + mayDiscardData: true, + idempotent: false, + }), + ), kind: "native-provider", description: "Run one unrestricted command in a persistent Rizin debugger; it can access target state, plugins, shell, files and network. Returns raw/interleaved session output as Evidence. Output/frame limits stop the owned debugger and retain partial output with output_truncated and unknown completion. Prequeued unsolicited frames refuse the call because correlation is ambiguous. This shared-server operation retires binary analysis: close Ghidra explicitly first, then reopen the binary after effects settle.", @@ -70,7 +93,10 @@ export const RIZIN_DEBUG_TOOL_CONTRACTS = [ }, { name: "rizin_debug_session_status", - ...toolContractMetadata("rizin_debug_session_status"), + ...toolContractMetadata( + "rizin_debug_session_status", + toolEffects({ mutatesSession: true }), + ), kind: "native-provider", description: "Return observed lifecycle state and bounded recent NUL-framed output and process diagnostics for one Rizin debugger session; closed_reason says why a closed session stopped, truncation fields report discarded data, and output_invalid_utf8 reports whether invalid UTF-8 has been observed in session frame bytes; recent output may contain replacement characters.", @@ -99,7 +125,16 @@ export const RIZIN_DEBUG_TOOL_CONTRACTS = [ }, { name: "close_rizin_debug_session", - ...toolContractMetadata("close_rizin_debug_session"), + ...toolContractMetadata( + "close_rizin_debug_session", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + accessesNetwork: true, + mutatesTarget: true, + executesForeignCode: true, + }), + ), kind: "native-provider", description: "Close the REA-owned Rizin debugger only after verifying no inferior remains or detaching one with a verified caller-selected TTY output sink. A detached target may continue running, read from and write to that TTY; target state is otherwise reported as unknown. REA never signals an inferior based on PID or path. In a shared MCP server, this admitted close retires any active binary-analysis session; after target effects have settled, call open_binary before further analysis. Close an active Ghidra session explicitly first.", diff --git a/src/contracts/rust/rustToolContracts.ts b/src/contracts/rust/rustToolContracts.ts index 2736470cfa..f14636a4e3 100644 --- a/src/contracts/rust/rustToolContracts.ts +++ b/src/contracts/rust/rustToolContracts.ts @@ -6,7 +6,7 @@ import { rustBinaryPageViewResultSchema, } from "../../domain/analysisView/analysisViewResult.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "../toolEffects.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; /** Static Rust dependency metadata is independent of active native-analysis providers. */ @@ -15,7 +15,7 @@ export const RUST_TOOL_CONTRACTS = [ name: "inspect_rust_binary", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_rust_binary"), + ...toolContractMetadata("inspect_rust_binary", evidenceEffects), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/sessionToolContracts.ts b/src/contracts/sessionToolContracts.ts index 34b49ba4bd..7489374f3d 100644 --- a/src/contracts/sessionToolContracts.ts +++ b/src/contracts/sessionToolContracts.ts @@ -36,7 +36,14 @@ import { } from "./sessionToolSchemas.js"; import { examplesFor } from "./toolContractHelpers.js"; import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import type { EffectAudit } from "./toolEffects.js"; +import { + toolContractMetadata, + evidenceEffects, + providerEffects, + providerRemoteEffects, + toolEffects, +} from "./toolEffects.js"; /** The contracts below that the CLI exposes as commands. */ const SESSION_CLI_CONTRACTS: ReadonlySet = new Set([ @@ -50,12 +57,13 @@ const session = < Schema extends z.ZodObject, >( name: Name, + audit: EffectAudit, description: string, inputSchema: Schema, ) => ({ name, - ...toolContractMetadata(name), + ...toolContractMetadata(name, audit), description, kind: "session", ...(SESSION_CLI_CONTRACTS.has(name) ? { cli: true as const } : {}), @@ -79,6 +87,16 @@ export const exportEvidenceBundleInputSchema = z.strictObject({ */ export const OPEN_BINARY_TOOL_CONTRACT = session( "open_binary", + // Lifecycle transitions can retire an IDA client, including a pending + // cleanup from an earlier provider, over its configured MCP transport. + // Retiring Ghidra can discard ephemeral edits or save a configured checkpoint. + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + mayDiscardData: true, + }), "Open a validated local artifact or analysis database and bind its analysis provider. Switching target/provider can discard ephemeral Ghidra edits even if the later open fails; retained investigation Evidence does not restore them. Reopening the same target/profile retains the engine and edits. provider_id selects a provider or deterministic auto routing, with no failure fallback. Omitted format uses headers; format dos-com admits 1..65280 headerless bytes, while raw-binary requires architecture and entry_point and maps file offset 0 there. Optional snapshots must match target, provider and analysis profile; close/reopen before importing into a mutated engine. For Ghidra cross-process edits, set a private absolute REA_GHIDRA_CHECKPOINT_DIR at startup (stock ELF/PE/Mach-O on Linux/macOS); normal opens/closes restore/save metadata. Failed opens report selection_at_failure and target/provider at completion; use binary_session for current state. close_binary releases engine resources; reset_investigation clears retained records.", openBinaryInputSchema, ); @@ -88,112 +106,161 @@ export const SESSION_TOOL_CONTRACTS = [ OPEN_BINARY_TOOL_CONTRACT, session( "open_bundle_resources", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + accessesNetwork: true, + mayDiscardData: true, + }), "Open a local app bundle for read-only plist, Interface Builder, asset catalog, and keyed archive inspection without resolving or inventing its executable identity. This switches the shared session to a resource-only lane; executable analysis is unavailable until another target is opened.", openBundleResourcesInputSchema, ), session( "close_binary", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + accessesNetwork: true, + mayDiscardData: true, + idempotent: false, + }), "Release the active engine and owned resources while retaining investigation Evidence and complete Unknown history in memory. Drains earlier requests and queues later ones. If cleanup fails, keep this connection and retry close_binary without snapshot_path after the reported condition settles. Optional snapshot_path saves a target-bound snapshot first; resource-only sessions have no snapshot binding, existing files require overwrite, and failed saves keep the engine open. Metadata edits prevent immutable snapshot saves until recreation. Ghidra checkpoint mode saves metadata on normal close and retains the Program for retry if saving fails. Closing does not persist investigation records: export_evidence_bundle to save them, or reset_investigation to clear them.", closeBinaryInputSchema, ), session( "reset_investigation", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + accessesNetwork: true, + mayDiscardData: true, + idempotent: false, + }), "Discard retained Evidence and Unknown revision history, including engine replay/source bindings, while keeping a healthy active engine open. Drains earlier work and queues later requests. Optional save_path atomically syncs and publishes a complete bundle first; import_evidence_bundle restores its IDs/history. Cancellation, failed save or incomplete cleanup preserves records; any already-published checkpoint is reported. Without save_path, records are lost. binary_session reports the representation budget; no automatic persistence or eviction occurs.", resetInvestigationInputSchema, ), session( "binary_session", + toolEffects({ launchesProcess: true }), "Inspect current target, provider capabilities, analysis and server identity without starting analysis. Default summary reports Ghidra checkpoint/ephemeral mode in capabilities[].shared_limitations; detail complete adds diagnostics, candidate capabilities and tool flags. Set refresh_candidates true to recheck provider readiness without changing the active engine. analysis_provider_candidates_observed distinguishes fresh observations from selection-time facts. open_binary with provider_id can replace the engine and discard ephemeral edits; reopening without it reuses the route. release_verification is optional reported-version evidence, not executable authentication. omitted_fields names facts left out of summary.", binarySessionInputSchema, ), session( "export_evidence_bundle", + toolEffects({ + writesFilesystem: true, + mayDiscardData: true, + }), "Atomically write the session's deterministic Evidence bundle to the requested local path. Existing files require overwrite: true; records and manifests use canonical byte-stable ordering.", exportEvidenceBundleInputSchema, ), session( "import_evidence_bundle", + toolEffects({ mutatesSession: true }), "Read the JSON bundle at the supplied local path, validate every Evidence ID and canonical manifest, then atomically merge it. Imported content is data only and is never executed. Import restores registry entries present in the bundle; questions embedded in Evidence do not automatically become Unknown registry entries.", importEvidenceBundleInputSchema, ), session( "capture_process_scenario", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + executesForeignCode: true, + idempotent: false, + }), "Run a caller-selected command under a PTY and return process capture Evidence and unknowns. It runs with the user's permissions, can change files or use network, and is not a sandbox. dry_run validates and returns a rea.process-scenario-plan without launching. Command names use inherited PATH; cwd defaults to the caller's and environment overrides augment inheritance. Filesystem observation is opt-in through filesystem_observation_paths. Terminal size must satisfy columns × (rows + scrollback) <= 1,000,000 on every resize; dimensions are never clamped and this limit has no override. Environment keys reject =/NUL and REA_PROCESS_RUN_ID is reserved. With positive finalization_ms, timeout/idle sends identity-checked SIGTERM, observes until the interval ends, then sends SIGKILL once; exit.finalization records attempts and observed exit. Cancellation still ends the run immediately.", processScenarioSchema, ), session( "compare_process_captures", + evidenceEffects, 'Compare compatible process captures, inline or by {kind:"retained-evidence",evidence_id}, across terminal, interaction, lifecycle, process, filesystem, command-shim, HTTP and WebSocket observations. Optional trace_spec checks explicit partial-order or finite-trace assertions, including selected timing. Observer timing alone does not establish changed behavior; timestamps or sorting never establish concurrency. Missing, journal-free or truncated observations never establish equivalence.', processComparisonInputSchema, ), session( "compare_artifacts", + evidenceEffects, 'Compare complete artifact inventories by occurrence path, content identity, metadata and graph relations; root . identifies the outer container separately. Accepts complete inline Evidence, {kind:"retained-evidence",evidence_id} for inspect_artifact/nested inventory/retained summary, or {kind:"evidence-file",path:"/absolute/bundle.json"} with optional evidence_id. Summaries resolve to their complete parent in that session/source bundle; summary facts alone are insufficient. Returns every delta inline with both source identities; coverage gaps remain truncated or unknown, never equivalence. Includes FIT and legacy uImage components.', artifactComparisonInputSchema, ), session( "match_native_functions", + evidenceEffects, "Pair two retained list_procedures inventories by unique exact symbols, then unique identical observed bytes. Optional same-context name/body/byte/dossier Evidence adds static facts; compatible CFG/call/string fingerprints propose unresolved groups only. Duplicate candidates stay unresolved, and only_left/right means unpaired within inputs, not proven addition/removal. Default summary retains the full matching for function-matches pages; complete returns every group. byte-sources identifies selected read_bytes Evidence: intersect IDs with function evidence_links. Dossier pairs supply retained-reference compare_functions inputs.", matchNativeFunctionsInputSchema, ), session( "compare_functions", + evidenceEffects, "Compare two explicit analyze_function Evidence records or exact retained session references across identity, exact provider text, calls, references, strings, and address-normalized CFG topology. The same authenticated Evidence record or compatible same-artifact entry coordinates establish correspondence independently of symbol origin; metadata and text changes remain separate. Missing or provider-incompatible facets remain truncated or unknown; every conclusion cites both Evidence sets.", functionComparisonInputSchema, ), session( "compare_bundles", + toolEffects({ mutatesSession: true }), "Compare two canonical Evidence bundles by exact record membership, explicit one-to-one observation pairs, and complete residual-unknown revision histories. Supply absolute local filesystem paths; relative paths are rejected. Missing bundle members describe omission only, never behavioral equivalence; output is digest-anchored and returns every change inline.", bundleComparisonMcpInputSchema, ), session( "find_changed_behavior", + evidenceEffects, "Aggregate validated process, artifact, and function comparison Evidence, supplied inline or by exact retained-evidence references from this session. Original records and their complete source closure remain authenticated; summaries do not substitute for comparisons. Runtime observations remain distinct from static behavior candidates; missing or incomplete comparisons produce unresolved findings, never causal claims. Returns every finding inline.", changedBehaviorInputSchema, ), session( "build_call_path", + evidenceEffects, "Build every shortest direct-callee path from complete analyze_function Evidence supplied inline or by exact retained-evidence references. References reuse the complete parent of an analyze_function summary without resending dossiers. Uses exact canonical addresses; missing dossiers and provider mixing remain unknown, and every node and edge cites source Evidence.", callPathRequestSchema, ), session( "correlate_static_and_runtime", + evidenceEffects, "Evaluate every explicit caller-declared hypothesis between static and runtime comparison Evidence supplied inline or by exact retained-evidence references. Similar names or paths are never auto-matched, consistent cochange never proves causality, and unknown or truncated inputs remain unresolved. Returns all correlations and their complete Evidence closure inline.", staticRuntimeCorrelationRequestSchema, ), session( "verify_reconstruction", + evidenceEffects, "Verify a finite typed behavioral and structural specification against a canonical Evidence bundle. Pass means every declared claim has complete comparable authority—not global source equivalence; changed claims fail and missing, limited, or unresolved evidence stays unknown.", reconstructionVerificationInputSchema, ), session( "list_unknowns", + toolEffects(), "List tracked questions' current revisions in deterministic ID order, with exact status/severity/domain filters. Complete inline by default; offset/limit pages the filtered order, total counts matches and next_offset null means exhausted. Unresolved, contradicted and non-truth dispositions stay distinct. An empty registry does not mean retained Evidence has no residual questions; inspect that Evidence or its analysis view.", listUnknownsInputSchema, ), session( "record_unknown", + toolEffects({ mutatesSession: true, idempotent: false }), "Create one deterministic residual unknown and immutable mutation evidence. Its scope is the active binary analysis target digest, or null without an active target; supporting Evidence does not select the scope. Scope contributes to stable identity. Validates all evidence and relationship references, and rejects duplicate stable identity.", recordUnknownInputSchema, ), session( "update_unknown", + toolEffects({ mutatesSession: true, idempotent: false }), "Append a full-state revision to one tracked question, with immutable mutation Evidence. Requires exact expected_revision; stale writers fail rather than overwrite. The question keeps its original scope, while mutation Evidence uses the active target digest or null and can have a different subject.", updateUnknownInputSchema, ), session( "verify_unknown_resolution", + toolEffects(), "Check a tracked question's current resolution against bundled Evidence, required authority/confidence/environment and revision integrity. Withdrawn and out-of-scope dispositions do not establish truth.", verifyUnknownResolutionInputSchema, ), session( "get_evidence_bundle", + toolEffects(), "Read retained Evidence and tracked questions without rerunning providers. Default complete returns an importable canonical bundle. detail summary lists record metadata; records pages complete records with unchanged IDs and missing direct evidence_links, but is not an importable bundle. detail links inspects retained/missing links without payloads; traversal retained-closure follows retained links and defaults to missing rows. Summary/records/links filters accept Evidence ID, operation, target SHA-256, analysis-profile digest or canonical procedure address. Metadata keeps retention distinct from truncated/unavailable source coverage. Use a discovered evidence_id with a compatible inspect_analysis_view to read selected facts.", getEvidenceBundleInputSchema, ), { ...session( "get_navigation_context", + toolEffects({ mutatesSession: true }), "Return the selected document, current address, and containing/current procedure in one provider-neutral result. The result reflects sequential provider observations, not an atomic cursor snapshot; a cursor outside any procedure returns procedure: null.", navigationContextInputSchema, ), @@ -202,6 +269,10 @@ export const SESSION_TOOL_CONTRACTS = [ { ...session( "inspect_address_context", + providerEffects( + toolEffects({ mutatesSession: true }), + providerRemoteEffects, + ), "Inspect one explicit reproducible address for its analyzed name, containing procedure, regular and inline comments, and matching bookmarks. Each unsupported facet returns a typed unavailable outcome. A facet rejected for invalid input, source Evidence integrity, or a resource constraint retains its canonical error and recovery alongside successful facets. Use xrefs, assembly, or pseudocode for those deeper views.", addressContextInputSchema, ), diff --git a/src/contracts/signals/signalToolContracts.ts b/src/contracts/signals/signalToolContracts.ts index 5d05894832..a5d23f10e0 100644 --- a/src/contracts/signals/signalToolContracts.ts +++ b/src/contracts/signals/signalToolContracts.ts @@ -7,14 +7,21 @@ import { signalRecordingSchema, } from "../../domain/signals/signalRecording.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; export const SIGNAL_TOOL_CONTRACTS = [ { name: "inspect_signal_decoders", availability: { host: "signalRecording" }, cli: true, - ...toolContractMetadata("inspect_signal_decoders"), + ...toolContractMetadata( + "inspect_signal_decoders", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), kind: "artifact-provider", requiresActiveTarget: true, description: @@ -33,7 +40,14 @@ export const SIGNAL_TOOL_CONTRACTS = [ name: "decode_signal_recording", availability: { host: "signalRecording" }, cli: true, - ...toolContractMetadata("decode_signal_recording"), + ...toolContractMetadata( + "decode_signal_recording", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/sqlite/sqliteToolContracts.ts b/src/contracts/sqlite/sqliteToolContracts.ts index 5855c125ea..46cc133246 100644 --- a/src/contracts/sqlite/sqliteToolContracts.ts +++ b/src/contracts/sqlite/sqliteToolContracts.ts @@ -3,7 +3,7 @@ import { sqliteDatabaseSchema, } from "../../domain/sqlite/sqliteDatabase.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; /** Snapshot inspection is independent of any active native-analysis target. */ @@ -11,7 +11,14 @@ export const SQLITE_TOOL_CONTRACTS = [ { name: "inspect_sqlite_database", cli: true, - ...toolContractMetadata("inspect_sqlite_database"), + ...toolContractMetadata( + "inspect_sqlite_database", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + }), + ), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/toolContractTypes.ts b/src/contracts/toolContractTypes.ts index 0a2fba2089..4b33487e5e 100644 --- a/src/contracts/toolContractTypes.ts +++ b/src/contracts/toolContractTypes.ts @@ -64,7 +64,10 @@ export interface ToolContract< }; readonly inputSchema: InputSchema; readonly outputSchema: OutputSchema; + /** Possible effects across every supported provider profile. */ readonly effects: ToolEffects; + /** Effects the tool owns before composing the selected provider. */ + readonly sessionEffects: ToolEffects; readonly annotations: DerivedToolAnnotations; /** * Results, successful or failed, can contain text that originates from the diff --git a/src/contracts/toolEffects.test.ts b/src/contracts/toolEffects.test.ts index 163d955991..1e098a95ef 100644 --- a/src/contracts/toolEffects.test.ts +++ b/src/contracts/toolEffects.test.ts @@ -3,12 +3,7 @@ import { readFileSync } from "node:fs"; import { describe, expect, it } from "vitest"; import { TOOL_CONTRACTS } from "./toolContracts.js"; -import { - TOOL_EFFECTS, - annotationsFromEffects, - toolSessionEffects, - type ToolEffects, -} from "./toolEffects.js"; +import { annotationsFromEffects, type ToolEffects } from "./toolEffects.js"; /** * Reviewed tools whose audited effects make them destructive. The derived set @@ -23,6 +18,9 @@ const REVIEWED_DESTRUCTIVE_TOOLS = JSON.parse( ), ) as readonly string[]; +const contractNamed = (name: string) => + TOOL_CONTRACTS.find((contract) => contract.name === name); + describe("tool effects", () => { it("keeps every reviewed destructive tool destructive", () => { expect(REVIEWED_DESTRUCTIVE_TOOLS).toEqual( @@ -34,7 +32,7 @@ describe("tool effects", () => { for (const name of REVIEWED_DESTRUCTIVE_TOOLS) { const contract = contracts.get(name); expect(contract, `${name} has no contract`).toBeDefined(); - expect(annotationsFromEffects(TOOL_EFFECTS[name]!), name).toMatchObject({ + expect(annotationsFromEffects(contract!.effects), name).toMatchObject({ readOnlyHint: false, destructiveHint: true, }); @@ -93,7 +91,7 @@ describe("tool effects", () => { }); it("marks automatic GDB detach as destructive target execution", () => { - const effects = TOOL_EFFECTS["close_gdb_session"]; + const effects = contractNamed("close_gdb_session")?.effects; if (effects === undefined) throw new Error("close_gdb_session is unaudited"); expect(effects).toMatchObject({ @@ -118,12 +116,12 @@ it("advertises IDA provider effects while retaining session bases", () => { "read_function_instructions", "analyze_function", ]) { - expect(TOOL_EFFECTS[name], name).toMatchObject({ + expect(contractNamed(name)?.effects, name).toMatchObject({ mutatesSession: true, changesUiState: true, accessesNetwork: true, }); - expect(toolSessionEffects(name), name).toMatchObject({ + expect(contractNamed(name)?.sessionEffects, name).toMatchObject({ mutatesSession: true, changesUiState: false, accessesNetwork: false, @@ -143,11 +141,11 @@ it("advertises IDA provider effects while retaining session bases", () => { "trace_native_values", "inspect_native_api", ]) { - expect(TOOL_EFFECTS[name], name).toMatchObject({ + expect(contractNamed(name)?.effects, name).toMatchObject({ changesUiState: true, accessesNetwork: true, }); - expect(toolSessionEffects(name), name).toMatchObject({ + expect(contractNamed(name)?.sessionEffects, name).toMatchObject({ changesUiState: false, accessesNetwork: false, }); @@ -164,8 +162,10 @@ it("audits network access during lifecycle cleanup across provider changes", () "close_rizin_debug_session", "close_gdb_session", ]) { - expect(toolSessionEffects(name).accessesNetwork, name).toBe(true); - expect(TOOL_EFFECTS[name]?.accessesNetwork, name).toBe(true); + expect(contractNamed(name)?.sessionEffects.accessesNetwork, name).toBe( + true, + ); + expect(contractNamed(name)?.effects.accessesNetwork, name).toBe(true); expect( TOOL_CONTRACTS.find((contract) => contract.name === name)?.annotations .openWorldHint, @@ -175,7 +175,7 @@ it("audits network access during lifecycle cleanup across provider changes", () }); it("advertises signature inspection's temporary snapshot filesystem writes", () => { - expect(TOOL_EFFECTS.inspect_signature).toMatchObject({ + expect(contractNamed("inspect_signature")?.effects).toMatchObject({ writesFilesystem: true, mutatesTarget: false, launchesProcess: true, @@ -183,7 +183,7 @@ it("advertises signature inspection's temporary snapshot filesystem writes", () }); it("advertises inspect_macho's temporary private operand filesystem writes", () => { - expect(TOOL_EFFECTS.inspect_macho).toMatchObject({ + expect(contractNamed("inspect_macho")?.effects).toMatchObject({ writesFilesystem: true, mutatesTarget: false, launchesProcess: true, diff --git a/src/contracts/toolEffects.ts b/src/contracts/toolEffects.ts index 317967d132..bd6cad5835 100644 --- a/src/contracts/toolEffects.ts +++ b/src/contracts/toolEffects.ts @@ -1,5 +1,3 @@ -import type { TOOL_CONTRACTS } from "./toolContracts.js"; - /** Possible effects across a tool's supported inputs, including temporary work. */ export interface ToolEffects { readonly mutatesTarget: boolean; @@ -31,7 +29,10 @@ export interface DerivedToolAnnotations { readonly openWorldHint: boolean; } -const effects = (overrides: Partial = {}): ToolEffects => ({ +/** Effects with every possibility off except idempotence, plus the overrides. */ +export const toolEffects = ( + overrides: Partial = {}, +): ToolEffects => ({ mutatesTarget: false, mutatesSession: false, writesFilesystem: false, @@ -45,906 +46,50 @@ const effects = (overrides: Partial = {}): ToolEffects => ({ ...overrides, }); -const evidence = effects({ mutatesSession: true }); -const nativeEvidence = effects({ mutatesSession: true, launchesProcess: true }); -const browserEvidence = effects({ +/** Records Evidence in the session and nothing else. */ +export const evidenceEffects = toolEffects({ mutatesSession: true }); +/** Records Evidence and launches a pinned native helper. */ +export const nativeEvidenceEffects = toolEffects({ + mutatesSession: true, + launchesProcess: true, +}); +/** Records Evidence and reaches the network through a browser. */ +export const browserEvidenceEffects = toolEffects({ mutatesSession: true, accessesNetwork: true, }); -type EffectAudit = +/** + * A tool's audited effects: one set, or the effects the tool owns in a session + * plus the additions possible across every supported provider profile. + */ +export type EffectAudit = | ToolEffects | { readonly session: ToolEffects; readonly global: Partial }; /** Keep provider-neutral effects with the additions possible across profiles. */ -const providerEffects = ( +export const providerEffects = ( session: ToolEffects, global: Partial, ): EffectAudit => ({ session, global }); /** Global possibility across supported provider paths; sessions compose their selected descriptor. */ -const providerRemoteEffects = { +export const providerRemoteEffects = { launchesProcess: true, writesFilesystem: true, accessesNetwork: true, }; -const providerNetworkEvidence = providerEffects( - evidence, +export const providerNetworkEvidenceEffects = providerEffects( + evidenceEffects, providerRemoteEffects, ); -const providerUiNetworkEvidence = providerEffects(evidence, { - ...providerRemoteEffects, - changesUiState: true, -}); - -/** Every public tool name; the audit below must list each one exactly once. */ -type PublicToolName = (typeof TOOL_CONTRACTS)[number]["name"]; - -/** Explicit effect audit for every public tool. */ -const TOOL_EFFECT_AUDIT = { - inspect_analysis_settings: effects(), - update_analysis_settings: effects({ mutatesSession: true }), - list_cutter_sessions: effects({ accessesNetwork: true }), - cutter_command: effects({ - mutatesTarget: true, - executesForeignCode: true, - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, +export const providerUiNetworkEvidenceEffects = providerEffects( + evidenceEffects, + { + ...providerRemoteEffects, changesUiState: true, - idempotent: false, - }), - inspect_with_objdump: effects({ - mutatesSession: true, - launchesProcess: true, - }), - start_gdb_session: effects({ - launchesProcess: true, - mutatesSession: true, - idempotent: false, - }), - gdb_console: effects({ - mutatesTarget: true, - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, - executesForeignCode: true, - idempotent: false, - }), - gdb_session_status: effects(), - start_rizin_debug_session: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - executesForeignCode: true, - idempotent: false, - }), - rizin_debug_command: effects({ - mutatesTarget: true, - mutatesSession: true, - executesForeignCode: true, - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, - changesUiState: true, - mayDiscardData: true, - idempotent: false, - }), - rizin_debug_session_status: effects({ mutatesSession: true }), - close_rizin_debug_session: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - mutatesTarget: true, - executesForeignCode: true, - }), - close_gdb_session: effects({ - launchesProcess: true, - mutatesSession: true, - accessesNetwork: true, - mutatesTarget: true, - executesForeignCode: true, - idempotent: false, - }), - execute_rizin_command: effects({ - mutatesTarget: true, - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, - mayDiscardData: true, - executesForeignCode: true, - idempotent: false, - }), - inspect_desktop_application: evidence, - inspect_go_binary: evidence, - inspect_il2cpp_metadata: evidence, - inspect_model_artifact: evidence, - inspect_api_contract: evidence, - inspect_ntfs_journal: evidence, - inspect_playwright_trace: evidence, - inspect_gpu_code_objects: evidence, - inspect_rust_binary: evidence, - inspect_apk_signature: evidence, - inspect_python_pyc: evidence, - inspect_erlang_beam: evidence, - inspect_sqlite_database: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - }), - inspect_packet_fields: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - inspect_packet_capture: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - inspect_signal_decoders: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - decode_signal_recording: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - inspect_wasm_artifact: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - }), - inspect_evm_interface: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - }), - inspect_web_network_capture: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - }), - observe_web_execution: effects({ - mutatesTarget: true, - mutatesSession: true, - accessesNetwork: true, - mayDiscardData: true, - idempotent: false, - }), - inspect_web_event_listeners: browserEvidence, - trace_web_source_location: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - }), - trace_web_module_imports: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, - }), - inspect_recorded_crash: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - }), - inspect_binary_layout: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - }), - list_frida_devices: effects({ launchesProcess: true, accessesNetwork: true }), - list_frida_processes: effects({ - launchesProcess: true, - accessesNetwork: true, - }), - start_frida_session: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - idempotent: false, - }), - load_frida_script: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - executesForeignCode: true, - idempotent: false, - }), - resume_frida_session: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - executesForeignCode: true, - idempotent: false, - }), - unload_frida_script: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - idempotent: false, - }), - frida_session_status: evidence, - close_frida_session: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - executesForeignCode: true, - idempotent: false, - }), - instrument_with_frida: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - executesForeignCode: true, - idempotent: false, - }), - inspect_byte_entropy: evidence, - inspect_pe_resources: evidence, - inspect_pe_certificates: evidence, - inspect_pe_imports: evidence, - inspect_windows_shortcut: evidence, - inspect_native_exports: evidence, - inspect_elf_notes: evidence, - inspect_native_initializers: evidence, - inspect_elf_unwind_ranges: evidence, - inspect_apple_ips: evidence, - inspect_devicetree: evidence, - inspect_kernel_module: evidence, - inspect_kernel_build_config: evidence, - inspect_v8_code_cache: evidence, - inspect_pe_load_config: evidence, - inspect_binary_hardening: evidence, - inspect_analysis_view: evidence, - inspect_firmware_regions: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - extract_firmware: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - idempotent: false, - }), - inspect_android_package: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - inspect_pcap_client: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - inspect_pcap_capture: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - identify_flutter_build: effects({ - mutatesSession: true, - writesFilesystem: true, - }), - inspect_dart_aot: effects({ - mutatesSession: true, - writesFilesystem: true, - }), - inspect_apktool_client: effects({ - mutatesSession: true, - launchesProcess: true, - }), - decode_android_resources: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - inspect_jeb_client: effects({ - mutatesSession: true, - accessesNetwork: true, - }), - open_jeb_project: effects({ - mutatesSession: true, - accessesNetwork: true, - idempotent: false, - }), - list_jeb_units: effects({ - mutatesSession: true, - accessesNetwork: true, - }), - decompile_jeb_item: effects({ - mutatesSession: true, - accessesNetwork: true, - }), - inspect_adb_client: effects({ - mutatesSession: true, - launchesProcess: true, - }), - list_adb_devices: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - }), - inspect_adb_device: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - }), - list_adb_packages: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - }), - pull_adb_package: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - accessesNetwork: true, - idempotent: false, - }), - read_adb_logcat: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - }), - inspect_adb_package: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - }), - pull_adb_file: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - accessesNetwork: true, - idempotent: false, - }), - push_adb_file: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - accessesNetwork: true, - mutatesDevice: true, - idempotent: false, - }), - capture_adb_screen: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - accessesNetwork: true, - idempotent: false, - }), - list_adb_processes: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - }), - list_adb_directory: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - }), - list_adb_features: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - }), - list_adb_services: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - }), - inspect_adb_display: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - }), - inspect_adb_window: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - }), - read_adb_setting: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - }), - collect_adb_bugreport: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - accessesNetwork: true, - idempotent: false, - }), - resolve_adb_packages: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - }), - install_adb_package: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - mutatesDevice: true, - idempotent: false, - }), - uninstall_adb_package: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - mutatesDevice: true, - idempotent: false, - }), - start_adb_app: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - mutatesDevice: true, - idempotent: false, - }), - start_adb_activity: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - mutatesDevice: true, - idempotent: false, - }), - stop_adb_app: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - mutatesDevice: true, - idempotent: false, - }), - search_android_classes: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - inspect_android_class: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - inspect_android_method: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - inspect_android_jni_bindings: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - trace_android_references: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - annotate_native_function: effects({ - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - mayDiscardData: true, - }), - inspect_native_load_image: evidence, - inspect_native_dispatch_metadata: evidence, - trace_native_ui_action: providerNetworkEvidence, - trace_native_values: providerUiNetworkEvidence, - address_name: evidence, - comment: evidence, - current_address: evidence, - current_procedure: evidence, - current_document: evidence, - goto_address: effects({ mutatesSession: true, changesUiState: true }), - inline_comment: evidence, - list_bookmarks: evidence, - list_documents: providerNetworkEvidence, - list_names: evidence, - list_procedures: providerNetworkEvidence, - list_segments: evidence, - list_strings: providerNetworkEvidence, - next_address: evidence, - prev_address: evidence, - procedure_address: providerNetworkEvidence, - procedure_assembly: providerUiNetworkEvidence, - procedure_callees: providerNetworkEvidence, - procedure_callers: providerNetworkEvidence, - procedure_info: evidence, - read_function_instructions: providerUiNetworkEvidence, - inspect_native_instruction: evidence, - inspect_native_data_type: evidence, - resolve_native_call_targets: evidence, - read_bytes: evidence, - search_bytes: evidence, - address_to_file_offset: evidence, - procedure_references: evidence, - procedure_pseudo_code: providerUiNetworkEvidence, - resolve_containing_procedure: providerNetworkEvidence, - search_procedures: providerNetworkEvidence, - search_strings: providerNetworkEvidence, - set_address_name: effects({ - mutatesTarget: true, - mutatesSession: true, - mayDiscardData: true, - }), - set_addresses_names: effects({ - mutatesTarget: true, - mutatesSession: true, - mayDiscardData: true, - }), - set_bookmark: effects({ - mutatesTarget: true, - mutatesSession: true, - mayDiscardData: true, - }), - set_comment: effects({ - mutatesTarget: true, - mutatesSession: true, - mayDiscardData: true, - }), - set_inline_comment: effects({ - mutatesTarget: true, - mutatesSession: true, - mayDiscardData: true, - }), - unset_bookmark: effects({ - mutatesTarget: true, - mutatesSession: true, - mayDiscardData: true, - }), - xrefs: providerNetworkEvidence, - get_objc_classes: evidence, - get_objc_protocols: evidence, - batch_decompile: providerUiNetworkEvidence, - decompile_all: providerEffects( - effects({ - mutatesSession: true, - writesFilesystem: true, - idempotent: false, - }), - { ...providerRemoteEffects, changesUiState: true }, - ), - get_call_graph: providerEffects(evidence, providerRemoteEffects), - analyze_swift_types: providerEffects(evidence, providerRemoteEffects), - find_xrefs_to_name: evidence, - binary_overview: providerEffects(evidence, providerRemoteEffects), - analyze_function: providerUiNetworkEvidence, - inspect_native_api: providerEffects( - effects({ mutatesSession: true, idempotent: false }), - { ...providerRemoteEffects, changesUiState: true }, - ), - trace_feature: providerEffects( - effects({ mutatesSession: true, idempotent: false }), - providerRemoteEffects, - ), - trace_call_path: providerEffects( - effects({ mutatesSession: true, idempotent: false }), - providerRemoteEffects, - ), - observe_native_ui: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - capture_native_ui_scenario: effects({ - writesFilesystem: true, - mutatesTarget: true, - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - changesUiState: true, - mayDiscardData: true, - executesForeignCode: true, - idempotent: false, - }), - // The owned process can change files, show UI and use the network. - observe_native_calls: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, - changesUiState: true, - executesForeignCode: true, - idempotent: false, - }), - inspect_macho: { ...nativeEvidence, writesFilesystem: true }, - inspect_signature: { ...nativeEvidence, writesFilesystem: true }, - inspect_plist: nativeEvidence, - list_architectures: nativeEvidence, - demangle_swift: nativeEvidence, - inspect_artifact: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - extract_artifact: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - idempotent: false, - }), - decode_interface_builder: evidence, - inspect_asset_catalog: nativeEvidence, - inspect_keyed_archive: evidence, - trace_dylib_resolution: evidence, - inspect_managed_artifact: evidence, - inspect_managed_members: evidence, - inspect_managed_native_boundaries: evidence, - compare_managed_members: evidence, - verify_managed_native_boundaries: evidence, - import_managed_reconstruction: evidence, - project_managed_application_graph: evidence, - list_browser_targets: browserEvidence, - inspect_web_page: browserEvidence, - analyze_web_bundle: effects({ - ...browserEvidence, - launchesProcess: true, - writesFilesystem: true, - }), - observe_web_session: browserEvidence, - discover_webmcp_tools: browserEvidence, - compare_web_captures: evidence, - capture_web_screenshot: browserEvidence, - compare_web_screenshots: evidence, - capture_browser_scenario: effects({ - mutatesTarget: true, - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, - changesUiState: true, - mayDiscardData: true, - executesForeignCode: true, - idempotent: false, - }), - list_electron_targets: browserEvidence, - inspect_electron_page: browserEvidence, - capture_electron_scenario: effects({ - mutatesTarget: true, - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, - changesUiState: true, - mayDiscardData: true, - executesForeignCode: true, - idempotent: false, - }), - list_javascript_runtime_targets: browserEvidence, - observe_javascript_runtime: browserEvidence, - analyze_javascript_application: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - }), - inspect_electron_fuses: evidence, - audit_release_exposure: effects({ - mutatesSession: true, - launchesProcess: true, - writesFilesystem: true, - }), - export_web_scripts: effects({ - mutatesSession: true, - writesFilesystem: true, - idempotent: false, - }), - export_environment_bundle: effects({ - writesFilesystem: true, - idempotent: false, - }), - // Builds and boots a container that installs and runs the requested app. - start_build_computer: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, - executesForeignCode: true, - idempotent: false, - }), - // Drives the app through the computer's driver on a loopback port. - act_on_build_computer: effects({ - mutatesSession: true, - accessesNetwork: true, - changesUiState: true, - executesForeignCode: true, - idempotent: false, - }), - // Downloads package lists and launches the app inside the computer. - start_build_capture: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - changesUiState: true, - executesForeignCode: true, - idempotent: false, - }), - mark_build_checkpoint: effects({ - mutatesSession: true, - accessesNetwork: true, - idempotent: false, - }), - // Closes the app and drafts the task with REA inside the computer. - stop_build_capture: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - changesUiState: true, - idempotent: false, - }), - // Runs the task's readers, commands the task names, on the captured files. - export_build_environment: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, - executesForeignCode: true, - idempotent: false, - }), - // A witness stage records the display, runs the task's readers or the bundle's judge, and writes its record here. - check_build_task: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, - executesForeignCode: true, - idempotent: false, - }), - // Keeps the person's consent with the computer for the export to ship. - record_build_consent: effects({ - mutatesSession: true, - idempotent: false, - }), - // Runs the bundle's task in fresh computers and writes its record into the bundle. - measure_build_task: effects({ - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, - changesUiState: true, - executesForeignCode: true, - idempotent: false, - }), - close_build_computer: effects({ - mutatesSession: true, - launchesProcess: true, - accessesNetwork: true, - mayDiscardData: true, - idempotent: false, - }), - reconcile_javascript_runtime: evidence, - recover_javascript_sources: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - idempotent: false, - }), - trace_application_feature: evidence, - trace_javascript_semantics: evidence, - compare_application_versions: evidence, - compare_static_and_observed_endpoints: evidence, - search_guidance: effects(), - read_guidance_section: effects(), - guided_workflows: effects(), - compare_source_to_bundle: evidence, - compare_javascript_export_shapes: evidence, - build_reconstruction_obligation_ledger: evidence, - evaluate_reconstruction_coverage: effects(), - project_android_application_graph: evidence, - project_apple_application_graph: evidence, - project_harmony_application_graph: evidence, - // Lifecycle transitions can retire an IDA client, including a pending - // cleanup from an earlier provider, over its configured MCP transport. - // Retiring Ghidra can discard ephemeral edits or save a configured checkpoint. - open_binary: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, - mayDiscardData: true, - }), - open_bundle_resources: effects({ - mutatesSession: true, - writesFilesystem: true, - accessesNetwork: true, - mayDiscardData: true, - }), - close_binary: effects({ - mutatesSession: true, - writesFilesystem: true, - accessesNetwork: true, - mayDiscardData: true, - idempotent: false, - }), - reset_investigation: effects({ - mutatesSession: true, - writesFilesystem: true, - accessesNetwork: true, - mayDiscardData: true, - idempotent: false, - }), - binary_session: effects({ launchesProcess: true }), - export_evidence_bundle: effects({ - writesFilesystem: true, - mayDiscardData: true, - }), - get_evidence_bundle: effects(), - get_navigation_context: effects({ mutatesSession: true }), - inspect_address_context: providerEffects( - effects({ mutatesSession: true }), - providerRemoteEffects, - ), - import_evidence_bundle: effects({ mutatesSession: true }), - capture_process_scenario: effects({ - mutatesSession: true, - writesFilesystem: true, - launchesProcess: true, - accessesNetwork: true, - executesForeignCode: true, - idempotent: false, - }), - compare_process_captures: evidence, - compare_artifacts: evidence, - compare_wasm_interfaces: evidence, - compare_functions: evidence, - match_native_functions: evidence, - compare_bundles: effects({ mutatesSession: true }), - find_changed_behavior: evidence, - build_call_path: evidence, - correlate_static_and_runtime: evidence, - verify_reconstruction: evidence, - list_unknowns: effects(), - record_unknown: effects({ mutatesSession: true, idempotent: false }), - update_unknown: effects({ mutatesSession: true, idempotent: false }), - verify_unknown_resolution: effects(), -} satisfies Readonly>; - -/** Lookup by an unchecked name; a missing entry is reported by the caller. */ -const auditedEffects: Readonly> = - TOOL_EFFECT_AUDIT; - -const sessionEffects = (audit: EffectAudit): ToolEffects => - "session" in audit ? audit.session : audit; - -/** Possible effects across every supported provider profile. */ -export const TOOL_EFFECTS: Readonly> = - Object.fromEntries( - Object.entries(TOOL_EFFECT_AUDIT).map( - ([name, audit]: [string, EffectAudit]) => [ - name, - "session" in audit - ? effects({ ...audit.session, ...audit.global }) - : audit, - ], - ), - ); - -/** Effects owned by the tool before composing the selected provider. */ -export const toolSessionEffects = (name: string): ToolEffects => { - const audited = auditedEffects[name]; - if (audited === undefined) - throw new Error(`Missing effect audit for ${name}`); - return sessionEffects(audited); -}; + }, +); /** Derive MCP annotations without tool-name or tool-family heuristics. */ export const annotationsFromEffects = ( @@ -1000,18 +145,25 @@ export const TARGET_CONTENT_FREE_TOOLS: ReadonlySet = new Set([ export const toolReturnsTargetContent = (name: string): boolean => !TARGET_CONTENT_FREE_TOOLS.has(name); -/** Resolve the audited metadata for one public tool. */ -export const toolContractMetadata = (name: string) => { - const audited = TOOL_EFFECTS[name]; - if (audited === undefined) - throw new Error(`Missing effect audit for ${name}`); +/** + * Resolve the metadata for one public tool from the effect audit its contract + * declares. `effects` covers every supported provider profile; `sessionEffects` + * are the effects the tool owns before composing the selected provider. + */ +export const toolContractMetadata = (name: string, audit: EffectAudit) => { + const sessionEffects = "session" in audit ? audit.session : audit; + const effects = + "session" in audit + ? toolEffects({ ...audit.session, ...audit.global }) + : audit; return { title: name .split("_") .map((word) => word[0]?.toUpperCase() + word.slice(1)) .join(" "), - effects: audited, - annotations: annotationsFromEffects(audited), + effects, + sessionEffects, + annotations: annotationsFromEffects(effects), returnsTargetContent: toolReturnsTargetContent(name), }; }; diff --git a/src/contracts/v8/v8CodeCacheToolContracts.ts b/src/contracts/v8/v8CodeCacheToolContracts.ts index 6fa12895b0..d8dc3ab7dd 100644 --- a/src/contracts/v8/v8CodeCacheToolContracts.ts +++ b/src/contracts/v8/v8CodeCacheToolContracts.ts @@ -4,7 +4,7 @@ import { } from "../../domain/v8/v8CodeCache.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "../toolEffects.js"; /** Static V8 code cache inspection is independent of active native-analysis providers. */ export const V8_CODE_CACHE_TOOL_CONTRACTS = [ @@ -12,7 +12,7 @@ export const V8_CODE_CACHE_TOOL_CONTRACTS = [ name: "inspect_v8_code_cache", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_v8_code_cache"), + ...toolContractMetadata("inspect_v8_code_cache", evidenceEffects), kind: "artifact-provider", description: "Inspect a local bytenode .jsc or compatible V8 code-cache container as static bytes, without V8, bytenode, child processes or decompilation. Returns artifact identity, header words with confirmed/inferred roles, producer family, recorded source length, payload identity and printable sequences with file ranges. Only pinned header/magic and exact payload-length layouts are admitted; unknown or malformed layouts fail, not partial-parse. Most header roles are version-dependent inferences, not a fixed ABI. Payload strings are byte patterns, not parsed heap objects; missing literals do not prove absence. The payload is not source: logic recovery needs a separate version-pinned decompiler. Resource refusals remain explicit.", diff --git a/src/contracts/wasm/wasmComparisonContracts.ts b/src/contracts/wasm/wasmComparisonContracts.ts index 730c759622..1a251db56d 100644 --- a/src/contracts/wasm/wasmComparisonContracts.ts +++ b/src/contracts/wasm/wasmComparisonContracts.ts @@ -5,7 +5,7 @@ import { wasmInterfaceSchema, wasmInterfaceByteBudgetSchema, } from "../../domain/wasm/wasmInterface.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, evidenceEffects } from "../toolEffects.js"; import type { ToolContract } from "../toolContractTypes.js"; export const compareWasmInterfacesInputSchema = z.strictObject({ @@ -58,7 +58,7 @@ export const wasmInterfaceComparisonSchema = z.object({ export const COMPARE_WASM_INTERFACES_CONTRACT = { name: "compare_wasm_interfaces", cli: true, - ...toolContractMetadata("compare_wasm_interfaces"), + ...toolContractMetadata("compare_wasm_interfaces", evidenceEffects), kind: "application", description: "Compare typed core WASM import/export names, kinds and exact signatures from two authenticated inspect_wasm_artifact Evidence records. Select imports, exports or both explicitly. MCP references resolve in the current session; CLI references use an explicitly selected --evidence-bundle. max_interface_bytes selects this comparison's independent representation allowance (default 32MiB); raising it cannot restore omitted producer facts. Duplicate names, unsupported types and missing historical interface facets remain unknown. Preserve original module digests and every occurrence; no source acquisition, module execution or runtime-compatibility inference.", diff --git a/src/contracts/wasm/wasmToolContracts.ts b/src/contracts/wasm/wasmToolContracts.ts index 7922463932..66c5ec8596 100644 --- a/src/contracts/wasm/wasmToolContracts.ts +++ b/src/contracts/wasm/wasmToolContracts.ts @@ -4,7 +4,7 @@ import { wasmArtifactSchema, } from "../../domain/wasm/wasmArtifact.js"; import type { ToolContract } from "../toolContractTypes.js"; -import { toolContractMetadata } from "../toolEffects.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; import { analysisDetailSchema, analysisDetailOutputSchemaOf, @@ -20,7 +20,14 @@ export const wasmArtifactInspectionInputSchema = export const INSPECT_WASM_ARTIFACT_CONTRACT = { name: "inspect_wasm_artifact", cli: true, - ...toolContractMetadata("inspect_wasm_artifact"), + ...toolContractMetadata( + "inspect_wasm_artifact", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + }), + ), kind: "artifact-provider", requiresActiveTarget: true, description: diff --git a/src/contracts/webNetworkCaptureToolContracts.ts b/src/contracts/webNetworkCaptureToolContracts.ts index b4c56f0df2..36fa18f4e5 100644 --- a/src/contracts/webNetworkCaptureToolContracts.ts +++ b/src/contracts/webNetworkCaptureToolContracts.ts @@ -3,7 +3,7 @@ import { webNetworkCaptureSchema, } from "../domain/webNetworkCapture.js"; import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, toolEffects } from "./toolEffects.js"; import { analysisDetailSchema, analysisDetailOutputSchemaOf, @@ -15,7 +15,14 @@ export const WEB_NETWORK_CAPTURE_TOOL_CONTRACTS = [ { name: "inspect_web_network_capture", cli: true, - ...toolContractMetadata("inspect_web_network_capture"), + ...toolContractMetadata( + "inspect_web_network_capture", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + }), + ), 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. 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.2.3 on Linux. Malformed or oversized captures return no partial success; browser transaction attribution and HAR text’s original bytes remain unknown.", kind: "application", diff --git a/src/contracts/webRuntimeToolContracts.ts b/src/contracts/webRuntimeToolContracts.ts index 4a425a8dbf..7f5527e36c 100644 --- a/src/contracts/webRuntimeToolContracts.ts +++ b/src/contracts/webRuntimeToolContracts.ts @@ -1,5 +1,9 @@ import type { ToolContract } from "./toolContractTypes.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { + toolContractMetadata, + browserEvidenceEffects, + toolEffects, +} from "./toolEffects.js"; import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; import { observeWebExecutionInputSchema, @@ -16,7 +20,16 @@ export const WEB_RUNTIME_TOOL_CONTRACTS = [ name: "observe_web_execution", availability: "standalone", cli: true, - ...toolContractMetadata("observe_web_execution"), + ...toolContractMetadata( + "observe_web_execution", + toolEffects({ + mutatesTarget: true, + mutatesSession: true, + accessesNetwork: true, + mayDiscardData: true, + idempotent: false, + }), + ), description: "Instrument one selected CDP page for a finite, externally driven precise coverage window. Resets execution counters and prevents optimized execution until stopped. Returns complete nested UTF-16 ranges/counts, independently hashed script text and request initiator associations by session script ID. Does not navigate, click, evaluate selected code or close the externally owned page. Navigation ends document-scoped collection; workers and UI causality remain outside this claim. Emits an actual armed progress notification before external actions.", kind: "browser-provider", @@ -37,7 +50,10 @@ export const WEB_RUNTIME_TOOL_CONTRACTS = [ name: "inspect_web_event_listeners", availability: "standalone", cli: true, - ...toolContractMetadata("inspect_web_event_listeners"), + ...toolContractMetadata( + "inspect_web_event_listeners", + browserEvidenceEffects, + ), description: "Inspect listeners registered directly on the first main-document CSS match in one selected CDP page. Returns event flags, native callback locations, source ownership and exact script text/digests inline. Does not dispatch events, evaluate JavaScript or invoke handlers. Delegated ancestor/framework listeners and execution history remain unknown. Releases REA's object group and transport, preserving the external page.", kind: "browser-provider", diff --git a/src/contracts/webScriptToolContracts.ts b/src/contracts/webScriptToolContracts.ts index 881cca6db7..bbeb4f2484 100644 --- a/src/contracts/webScriptToolContracts.ts +++ b/src/contracts/webScriptToolContracts.ts @@ -18,7 +18,7 @@ import { webModuleTraceInputSchema, webModuleTraceResultSchema, } from "../domain/webModuleTrace.js"; -import { toolContractMetadata } from "./toolEffects.js"; +import { toolContractMetadata, toolEffects } from "./toolEffects.js"; import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; import { webSourceLocationInputSchema, @@ -39,7 +39,14 @@ export const WEB_SCRIPT_TOOL_CONTRACTS = [ { name: "trace_web_source_location", cli: true, - ...toolContractMetadata("trace_web_source_location"), + ...toolContractMetadata( + "trace_web_source_location", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + }), + ), description: 'Map one generated position in an exported script through a caller-paired local source map, verifying manifest/script/map byte identities. Returns all equal-position matches, original positions, resolved source URLs and embedded sourcesContent; pairing does not prove deployment authenticity or execution. Lines are one-based, columns zero-based UTF-16; lookup uses the greatest generated position <= requested across lines. Regular maps and inline indexed sections only; external section URLs are unsupported. No network or application execution; decoding uses an owned codec process. Complete delivery is default. detail summary retains Evidence; view {kind:"source-location",collection:"matches",offset:0,limit:64} pages match metadata. source-text additionally requires match_index and pages UTF-16 text. inspect_analysis_view reuses the retained parent; export_evidence_bundle preserves it. source_map_limits changes byte/record/heap admission per call; decode_timeout_ms is separate. Refusals name the exhausted control; cleanup may outlast the deadline.', kind: "application", @@ -72,7 +79,15 @@ export const WEB_SCRIPT_TOOL_CONTRACTS = [ { name: "trace_web_module_imports", cli: true, - ...toolContractMetadata("trace_web_module_imports"), + ...toolContractMetadata( + "trace_web_module_imports", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + launchesProcess: true, + accessesNetwork: true, + }), + ), description: "Resolve native ES imports/re-exports from one script in a local export_web_scripts manifest. Verifies the selected source digest/size and returns source positions, resolved URLs/errors and every matching captured candidate. URL query/fragment identities remain distinct; computed imports, bundler IDs and execution remain unknown. Supply importer_url when inline/document-base context is unknown and an import_map when needed. Literal resolution requires absolute REA_BROWSER_EXECUTABLE: caller-supplied Chromium runs only a trusted REA resolver stub with page requests fulfilled locally or blocked, without captured app execution or asset refetch. The native deadline is 20 seconds; cleanup may extend it.", kind: "application", @@ -95,7 +110,14 @@ export const WEB_SCRIPT_TOOL_CONTRACTS = [ { name: "export_web_scripts", cli: true, - ...toolContractMetadata("export_web_scripts"), + ...toolContractMetadata( + "export_web_scripts", + toolEffects({ + mutatesSession: true, + writesFilesystem: true, + idempotent: false, + }), + ), description: "Export JavaScript bytes already retained in one local inspect_web_page or capture_browser_scenario JSON capture (normalized result or complete Evidence). Writes scripts and a digest-verified manifest into an absent absolute output_directory. Returns all source URLs, script or transaction/event references, unavailable states, and an analysis_input for analyze_javascript_application when any bytes were exported. Include script sources in inspect_web_page or select capture.network.response_body in scenarios. No refetch or execution. Safe unambiguous URL layouts preserve relative module paths; versions, query variants, inline scripts, and path collisions are isolated with explicit resolution limitations.", kind: "application", diff --git a/tests/boundary/mcp/binaryDiagnosticsMcp.test.ts b/tests/boundary/mcp/binaryDiagnosticsMcp.test.ts index 3b4ab2b982..8b52b1b02d 100644 --- a/tests/boundary/mcp/binaryDiagnosticsMcp.test.ts +++ b/tests/boundary/mcp/binaryDiagnosticsMcp.test.ts @@ -4,7 +4,6 @@ import { join } from "node:path"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { byteEntropySchema } from "../../../src/domain/native/byteEntropy.js"; import { parseEvidence, type Evidence } from "../../../src/domain/evidence.js"; -import { TOOL_EFFECTS } from "../../../src/contracts/toolEffects.js"; import { advertisedMcpToolSchemas, assertRecordedMcpEvidence, @@ -405,7 +404,7 @@ it("profiles real bytes with exact offsets, valid advertised schemas and read-on { offset: 12288, length: 1504 }, ]); expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence); - expect(TOOL_EFFECTS.inspect_byte_entropy).toMatchObject({ + expect(toolContract("inspect_byte_entropy").effects).toMatchObject({ launchesProcess: false, writesFilesystem: false, accessesNetwork: false, diff --git a/tests/boundary/mcp/serverIdentity.test.ts b/tests/boundary/mcp/serverIdentity.test.ts index 77682054cc..af63cee100 100644 --- a/tests/boundary/mcp/serverIdentity.test.ts +++ b/tests/boundary/mcp/serverIdentity.test.ts @@ -21,10 +21,7 @@ import { COMPACT_INPUT_SCHEMA_BUDGET_BYTES } from "../../../src/config/mcpInputS import { PACKAGE_METADATA } from "../../../src/generatedPackageMetadata.js"; import { PRODUCT_IDENTITY, SDK_IDENTITY } from "../../../src/identity.js"; import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js"; -import { - annotationsFromEffects, - toolSessionEffects, -} from "../../../src/contracts/toolEffects.js"; +import { annotationsFromEffects } from "../../../src/contracts/toolEffects.js"; import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js"; import { sessionOutputSchemas } from "../../../src/contracts/toolOutputSchemaGroups.js"; import { PROMPT_CONTRACTS } from "../../../src/contracts/promptContracts.js"; @@ -572,7 +569,7 @@ const assertLiveIdentity = async (client: Client): Promise => { TOOL_CONTRACTS.map(({ name }) => name).sort(), ); for (const contract of TOOL_CONTRACTS) { - const effects = toolSessionEffects(contract.name); + const effects = contract.sessionEffects; const annotations = annotationsFromEffects(effects); expect(availability).toContainEqual( expect.objectContaining({ diff --git a/tests/boundary/mcp/toolResult.test.ts b/tests/boundary/mcp/toolResult.test.ts index f13f941c5b..a8f8ca400c 100644 --- a/tests/boundary/mcp/toolResult.test.ts +++ b/tests/boundary/mcp/toolResult.test.ts @@ -13,6 +13,10 @@ import { } from "../../../src/process/capture/ProcessCaptureLifecycle.js"; import { toolContract } from "../../../src/contracts/toolContracts.js"; import type { ToolContract } from "../../../src/contracts/toolContractTypes.js"; +import { + annotationsFromEffects, + toolEffects, +} from "../../../src/contracts/toolEffects.js"; import { err } from "../../../src/domain/result.js"; import { EvidenceIntegrityError } from "../../../src/domain/evidenceErrors.js"; import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js"; @@ -56,24 +60,9 @@ const contract: ToolContract = { kind: "enhanced", inputSchema: z.object({}), outputSchema: z.object({ value: z.string() }), - effects: { - mutatesTarget: false, - mutatesSession: false, - writesFilesystem: false, - launchesProcess: false, - accessesNetwork: false, - changesUiState: false, - mayDiscardData: false, - executesForeignCode: false, - mutatesDevice: false, - idempotent: true, - }, - annotations: { - readOnlyHint: true, - destructiveHint: false, - idempotentHint: true, - openWorldHint: false, - }, + effects: toolEffects(), + sessionEffects: toolEffects(), + annotations: annotationsFromEffects(toolEffects()), returnsTargetContent: false, examples: [{ title: "Example fixture request", input: {} }], }; diff --git a/tests/boundary/providers/RizinInferiorTty.test.ts b/tests/boundary/providers/RizinInferiorTty.test.ts index 901a2d0ce2..b1f4dbac42 100644 --- a/tests/boundary/providers/RizinInferiorTty.test.ts +++ b/tests/boundary/providers/RizinInferiorTty.test.ts @@ -17,7 +17,7 @@ import { RizinDebugSessionManager, } from "../../../src/rizin/RizinDebugSessionManager.js"; import { evidenceSchema } from "../../../src/domain/evidence.js"; -import { TOOL_EFFECTS } from "../../../src/contracts/toolEffects.js"; +import { RIZIN_DEBUG_TOOL_CONTRACTS } from "../../../src/contracts/rizinDebugToolContracts.js"; import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js"; import { createRizinTestManager, @@ -151,7 +151,11 @@ it.skipIf(process.platform === "win32")( ); it("declares that Rizin close can resume target code and mutate target state", () => { - expect(TOOL_EFFECTS.close_rizin_debug_session).toMatchObject({ + expect( + RIZIN_DEBUG_TOOL_CONTRACTS.find( + ({ name }) => name === "close_rizin_debug_session", + )?.effects, + ).toMatchObject({ mutatesTarget: true, executesForeignCode: true, }); diff --git a/tests/boundary/providers/ida/idaCapabilityInventory.test.ts b/tests/boundary/providers/ida/idaCapabilityInventory.test.ts index 9fa6db9b8d..3ace7dcdf5 100644 --- a/tests/boundary/providers/ida/idaCapabilityInventory.test.ts +++ b/tests/boundary/providers/ida/idaCapabilityInventory.test.ts @@ -5,10 +5,7 @@ import { buildCapabilityInventory } from "../../../../src/application/Capability import { providerCapabilitySets } from "../../../../src/application/binary/BinarySessionStatus.js"; import { idaCapabilities } from "../../../../src/ida/IdaProviderCapabilities.js"; import { IDA_OPERATIONS } from "../../../../src/ida/IdaProviderMetadata.js"; -import { - TOOL_EFFECTS, - toolSessionEffects, -} from "../../../../src/contracts/toolEffects.js"; +import { TOOL_CONTRACTS } from "../../../../src/contracts/toolContracts.js"; const enabledPolicy: Parameters[1] = { processCaptureEnabled: true, @@ -18,10 +15,15 @@ const enabledPolicy: Parameters[1] = { v8InspectorObservationEnabled: true, }; +const contractNamed = (name: string) => + TOOL_CONTRACTS.find((contract) => contract.name === name); + it("audits every IDA operation's network transport without adding it to the session base", () => { for (const name of IDA_OPERATIONS) { - expect(TOOL_EFFECTS[name]?.accessesNetwork, name).toBe(true); - expect(toolSessionEffects(name).accessesNetwork, name).toBe(false); + expect(contractNamed(name)?.effects.accessesNetwork, name).toBe(true); + expect(contractNamed(name)?.sessionEffects.accessesNetwork, name).toBe( + false, + ); } }); @@ -107,7 +109,7 @@ it.each([ IDA_COMPATIBILITY_PROFILES[profileName], stdio, )) { - const audited = TOOL_EFFECTS[descriptor.operation]; + const audited = contractNamed(descriptor.operation)?.effects; expect(audited, descriptor.operation).toBeDefined(); if (descriptor.effects.mayAccessNetwork) expect(audited?.accessesNetwork, descriptor.operation).toBe(true); @@ -174,7 +176,7 @@ it("omits effects of IDA calls hidden behind unavailable workflow prerequisites" enabledPolicy, ); for (const name of ["find_xrefs_to_name", "get_navigation_context"]) { - expect(TOOL_EFFECTS[name], name).toMatchObject({ + expect(contractNamed(name)?.effects, name).toMatchObject({ accessesNetwork: false, launchesProcess: false, writesFilesystem: false, @@ -210,16 +212,18 @@ it("advertises reachable IDA calls through native UI tracing", () => { mayShowUi: false, }, }; - expect(TOOL_EFFECTS.trace_native_ui_action).toMatchObject({ + expect(contractNamed("trace_native_ui_action")?.effects).toMatchObject({ accessesNetwork: true, launchesProcess: true, writesFilesystem: true, }); - expect(toolSessionEffects("trace_native_ui_action")).toMatchObject({ - accessesNetwork: false, - launchesProcess: false, - writesFilesystem: false, - }); + expect(contractNamed("trace_native_ui_action")?.sessionEffects).toMatchObject( + { + accessesNetwork: false, + launchesProcess: false, + writesFilesystem: false, + }, + ); const status = (capabilities: readonly CapabilityDescriptor[]) => ({ open: true, kind: "executable", @@ -246,12 +250,14 @@ it("advertises reachable IDA calls through native UI tracing", () => { it("includes reachable IDA document and procedure effects in address-context discovery", () => { const ida = idaCapabilities(IDA_COMPATIBILITY_PROFILES.modern, false); - expect(TOOL_EFFECTS.inspect_address_context).toMatchObject({ + expect(contractNamed("inspect_address_context")?.effects).toMatchObject({ accessesNetwork: true, launchesProcess: true, writesFilesystem: true, }); - expect(toolSessionEffects("inspect_address_context")).toMatchObject({ + expect( + contractNamed("inspect_address_context")?.sessionEffects, + ).toMatchObject({ accessesNetwork: false, launchesProcess: false, writesFilesystem: false,