diff --git a/.claude/skills/reverse-engineer-anything/SKILL.md b/.claude/skills/reverse-engineer-anything/SKILL.md new file mode 100644 index 0000000..3a8ae41 --- /dev/null +++ b/.claude/skills/reverse-engineer-anything/SKILL.md @@ -0,0 +1,356 @@ +--- +name: reverse-engineer-anything +description: Reverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. +metadata: + version: "42" + tool_count: 207 +--- + +# REA + +Use REA when a claim depends on a shipped binary or package, decompilation, +passive application runtime evidence, or comparison with +behavior not established by available source. For ordinary analysis of a +complete source repository, use normal repository tools and do not run REA +readiness or provider commands. + +## Connect only when needed + +Installing this skill supplies instructions; it does not register the REA MCP +server, install analysis engines, or add tools to an already-running agent. + +If REA tools are available and their registration is not known to be stale, +proceed directly to the target. Do not run diagnostics or setup before every +investigation. Use the connected server's actual tool list and input schemas; +a skill installed from repository main may describe capabilities absent from +an older npm release. Keep complete inline Evidence when that server does not +advertise retained references. + +If tools are absent, a call is blocked by the client, or a required provider is +unavailable, read [connection and recovery](references/connection-and-recovery.md). +Diagnose the observed blocker, continue useful supported work, and resume the +original task after repair. Client approval, shell PATH, registration and engine +availability have different remedies; avoid repeating setup for all of them. + +1. Diagnose without changing REA or client configuration. `npx` may download + the package and write to npm's cache. For Codex, run + `npx -y rea-agents@6.7.0 doctor --client codex --json`. Substitute the current + supported client: `claude_code`, `claude_desktop`, `codex`, `cursor`, + `gemini_cli`, `windsurf`, `devin`, `opencode`, `antigravity`, `copilot_cli`, + `commandcode`, `vscode`, `grok_build`, `omp`, or `grok_bot`. `grok_bot` has no local + file registration: doctor reports the Grok Bot chat step, and setup does not + write `mcp.json`. If the client is unknown, use `doctor --json` and + inspect its registration results before choosing a setup scope. +2. Distinguish the reason. Missing, malformed, or stale registration needs a + scoped configuration repair. An aligned registration with no tools in the + active session needs a restart/reconnection; doctor cannot prove that the + current agent has connected. A missing provider affects only tasks requiring + that provider: static JavaScript inspection needs neither Hopper nor Ghidra, + and Android inspection has separate bring-your-own JADX/Java prerequisites. +3. For a configuration repair, prepare the read-only plan: + `npx -y rea-agents@6.7.0 setup --client codex --dry-run --json`. + Use the current client's ID, show its exact proposed paths, backups, and + changes, and obtain approval before setup writes configuration or installs + Hopper. Setup normally installs the matching bundled skill too; include that + replacement in the reviewed plan. After approval, apply the same scope with + `npx -y rea-agents@6.7.0 setup --client codex --yes`. Add `--install-hopper` + only if that separate installation was needed and explicitly approved. +4. Restart/reconnect the affected agent. Verify that REA tools actually appear + in the session, then resume the original investigation. If they remain + absent, inspect the client's MCP launch error rather than repeating setup. + +REA setup never installs or upgrades Node.js, npm, Homebrew, Java, Ghidra, IDA, +JADX, Kuna, Binwalk, or Unblob. Use existing prerequisites; do not install unrelated +software to repair +MCP registration. For an unsupported client, use manual stdio registration +with a version-pinned `rea-agents` package or continue through the CLI. + +A concrete CLI fallback for an operator-supplied JavaScript tree or ASAR is: + +```bash +npx -y rea-agents@6.7.0 analyze-javascript-application /absolute/path/to/app --json +``` + +No MCP registration or native engine is required. Read the returned Evidence, +graph, limitations, and unknowns with the same care as an MCP result; the CLI +returns the Evidence record directly. This fallback does not establish that +MCP is configured. Native CLI tasks still require their selected engine. +Prefer an existing `rea` CLI. When none is installed and REA package acquisition +is within the authorized scope, use `npx -y rea-agents@6.7.0` in its place. +Configuration repair starts with a read-only setup plan; show paths, backups and +skill replacement before applying authorized changes. Preserve existing approval +and target-execution boundaries. REA setup never installs or upgrades unrelated +software, including Node.js, npm, Homebrew, Java, Ghidra, IDA, JADX, Kuna, Binwalk or Unblob. + +## Route the target first + +Choose the first tool from the target the user supplied. Use `open_binary` for +active-target native or archive workflows; target-free tools take their own +explicit path or endpoint and do not need it. + +- ASAR or extracted JavaScript/Electron tree: + `analyze_javascript_application`. +- Archive/package member inventory (ZIP/APK/IPA/MSIX/AppX or DMG): + `open_binary` with the supplied local path; use `inspect_artifact` when its + graph and findings help answer the question. +- Android APK code, classes, methods, or incoming references: + `inspect_android_package`, then focused Android tools when advertised. + Archive member inventory still uses the archive route above. +- Managed PE/CLI assembly: `inspect_managed_artifact`. +- Firmware image: `inspect_firmware_regions` when advertised. Use + `extract_firmware` when extraction is requested, with a caller-selected new + absolute output directory. These tools use caller-supplied Binwalk/Unblob on + Linux; see the [firmware guide](https://github.com/morluto/rea/blob/main/docs/firmware-analysis.md). +- .NET NativeAOT PE/ELF: native Ghidra analysis. Native code can yield pseudocode; + consult the NativeAOT workflow in `references/native-and-artifacts.md` for + optional metadata recovery and its supported host/layout boundary. +- User-owned browser page already open: `list_browser_targets`. +- Browser action the agent must perform (click, type, navigate): + `capture_browser_scenario` with declared actions. See + [runtime observation](references/runtime-observation.md) for connect/launch + and the focused follow-up browser tools. +- Fiddler Everywhere traffic or a native `.saz` capture: read the + [Fiddler workflow](references/runtime-observation.md#fiddler-everywhere-traffic-debugging). + Inspect saved SAZ with `inspect_web_network_capture` and `format: "saz"`; + connect Everywhere's separate MCP server for live traffic. +- Retained HAR/SAZ/native mitmproxy/aioquic qlog capture: `inspect_web_network_capture`. Select + original record ordinals when useful; inspect producer fields and byte/number + sidecars without fetching recorded URLs or claiming live attribution. See + [historical captures](https://github.com/morluto/rea/blob/main/docs/web-network-captures.md) for the exact upstream + profile and credential exclusions. Qlog support starts with aioquic 1.5.0 + JSON 0.3; stream coverage and endpoint loss declarations do not recover bodies + or establish network loss. Prefer detail summary, then kind qlog trace/stream + pages; select one trace, stream ID and direction for contribution/range pages. + Facts retain all-recorded-events-before-selection scope. Other qlog layouts + and PCAP correlation are unsupported. +- User-owned Electron runtime already open: `list_electron_targets`. Before an electron-main Inspector attempt, check packaged fuses with `inspect_electron_fuses`; disabled `EnableNodeCliInspectArguments` means the app ignores `--inspect`. +- Packet-field discovery: `inspect_packet_fields` searches installed protocols + and field names/types before choosing fields for `inspect_packet_capture`. + Query/page the relevant records; registrations do not establish observed traffic. +- Recorded packet captures: `inspect_packet_capture` with selected TShark fields, + display filters and decode-as rules. Requires Linux, util-linux prlimit and `REA_TSHARK_COMMAND`; see + [capture guide](https://github.com/morluto/rea/blob/main/docs/packet-captures.md). + Packet limits count input packets before filtering. Output defaults to 50 matching + frames; use `match_offset` / `match_limit` for later pages, or explicit null + limit for complete matching output. Preserve the source digest across pages. + This does not perform live capture. + For address/DNS/SNI/protocol summaries use `inspect_pcap_capture` with MCP + detail summary, then retained kind pcap pages. Requires Wireshark 4.x tshark + and capinfos, with Linux prlimit or Windows Job Objects; see + [packet summaries](https://github.com/morluto/rea/blob/main/docs/pcap-analysis.md). + Select an exact DNS question for address pages; page exhaustion does not prove + network completeness. This reads recordings and does not acquire traffic. +- Decoder discovery: `inspect_signal_decoders` searches installed decoder IDs + or selected decoder help, including channels and options. Query and page the + relevant details before choosing settings; this does not scan hardware. +- Recorded logic/signal traces: `decode_signal_recording` with explicit decoder, + channel and protocol settings. On Linux with util-linux prlimit, supply sigrok-cli 0.7.2 through + `REA_SIGROK_COMMAND`; see [recording guide](https://github.com/morluto/rea/blob/main/docs/signal-recordings.md). + Output defaults to 50 literal lines; select annotation classes and page with + `line_offset` / `line_limit`, or explicit null for all remaining output. + Window counts are display lines, not annotations or samples. Preserve source digests across pages. + This reads existing files; it does not acquire hardware signals. +- Explicit local WebAssembly artifact: `inspect_wasm_artifact`. Supply WABT 1.0.42 + through `REA_WABT_BIN_DIRECTORY`; retain exact byte/tool identity and decoded WAT. + Select JavaScript glue and candidate paths explicitly and preserve URL/path + ambiguity. No implicit fetch or target execution; WAT is not original source. + See the [WASM guide](https://github.com/morluto/rea/blob/main/docs/wasm-artifacts.md). +- Explicit local EVM bytecode carrier: `inspect_evm_interface` with caller-selected + `raw` or `hex` encoding. Preserve carrier/decoded digests and treat selectors, + argument strings and mutability as inferred candidates; this performs no chain + lookup or target execution. For the complete inferred interface without hex or + duplicate stdout, discover support and select `detail: "summary"`; complete + Evidence stays retained under its original identity. Use the returned + `parent_evidence_id` for exact function or `bytecode_hex`/stdout/stderr pages. + Candidate coverage does not establish interface completeness. See the + [EVM bytecode guide](https://github.com/morluto/rea/blob/main/docs/evm-bytecode.md). +- Embedded Go compiler, module or build-setting metadata: `inspect_go_binary` + with the explicit local file. This built-in target-free inspection requires no + Go installation or disassembler. Preserve raw module bytes and source ranges; + absent metadata does not prove a binary is not Go, and unparsed text records + remain explicit. See the + [Go binary guide](https://github.com/morluto/rea/blob/main/docs/go-binaries.md). +- Embedded cargo-auditable Rust dependency metadata: `inspect_rust_binary` + with the explicit local ELF, PE, or thin Mach-O file. This built-in + target-free inspection requires no Rust installation or disassembler. Preserve + package order, dependency indices, and the section file range. A missing + `.dep-v0` section is null metadata, not proof the binary has no dependencies. + A rustc commit hash is an inference from a read-only `/rustc/<40-hex>/` path. + See the + [Rust binary guide](https://github.com/morluto/rea/blob/main/docs/rust-binaries.md). + +- Explicit local SQLite database snapshot: `inspect_sqlite_database`. Inspect + with Node.js 24.x >=24.15 or 26+ providing native SQLite limits. Read schema + first (compact inventory by default), or select an exact ordinary table + and `columns` when rows are needed. Defaults are selected-table schema and + 20 rows; request `schema_scope: "database"` for the complete stored schema. Preserve both database and existing sibling WAL identity; row samples + report truncation and have unspecified order. Use a quiescent snapshot rather + than assuming a live database/WAL pair was copied atomically. See the + [SQLite guide](https://github.com/morluto/rea/blob/main/docs/sqlite-databases.md). +- Explicit Linux ELF file for offline layout, symbols, relocations or static + mitigation evidence: `inspect_binary_layout`. This target-free operation uses + caller-supplied pwntools without opening a disassembler database. Preserve its + raw locations and inference/coverage limits; see the + [offline binary guide](https://github.com/morluto/rea/blob/main/docs/binary-diagnostics.md). +- Supplied Linux x86-64 ELF core: `inspect_recorded_crash`. Read every recorded + thread, raw note and source-bound register without opening a live target. + Historical PIDs do not select live processes. Request `include_debugger_context` + only when core-only mapping candidates help; see the + [recorded crash guide](https://github.com/morluto/rea/blob/main/docs/recorded-crashes.md). +- PE resource type/name/language trees and static icon group references: + `inspect_pe_resources` with an explicit path. This portable operation requires + no active target or engine; opaque payloads retain file ranges and SHA-256. +- Native executable, library, or analysis database: `open_binary`, then + use focused analysis tools directly; call `binary_overview` when metadata or + inventory context is useful and available from the selected provider. + +For an existing IDA MCP configuration, use `open_binary` with the original +input binary and `provider_id: "ida"`; do not pass an `.idb` or `.i64` database. +The legacy attached profile binds the already-open GUI input by SHA-256 and +leaves its database open. The modern headless profile creates and closes an +owned private database without saving. Installation and registration reuse +[mrexodia/ida-pro-mcp](https://github.com/mrexodia/ida-pro-mcp); see the +[IDA provider guide](https://github.com/morluto/rea/blob/main/docs/ida-provider.md). +Proceed directly to `analyze_function`, pseudocode, or function/string searches +after opening; IDA does not supply `binary_overview`. Consult session availability +when composing broader workflows. Modern direct callers and unsupported dossier +facets remain unknown; live IDA results are not replayed from snapshots. + +With `REA_KUNA_COMMAND` configured, `provider_id: "kuna"` answers procedure +lists, lookups, pseudocode, assembly and `analyze_function` from Kuna's cached +whole-program export. Callers/callees use a separate body-free graph shared by +the session; `xrefs` returns exact-address incoming sites and filters forwarding +aliases. These queries and inventory lookups do not trigger a C export. Indirect +targets remain unknown and can make relationship coverage partial. Reference +caches expire on close; a fresh CLI process repeats the native reference walk. +Typed references, CFG, raw-memory tools and annotations remain unsupported. A cold first +answer can come from a single-function run (its limitations say so); assembly +waits for the export. For pseudocode and assembly, `raw_result.source` names the +cached `.c`/`.asm` file and byte span, which you may search directly instead of +calling per function. See the +[Kuna provider guide](https://github.com/morluto/rea/blob/main/docs/kuna-provider.md). + +If the user says only "my app" without a name, path, or target already selected +for this task, ask which app before searching for artifacts. Paths in unrelated +saved reports and nearby test fixtures do not select the user's target. Resolve +an actual human-readable app name to one clear installed artifact when possible; +ask when matches are ambiguous. Never choose an example app on the user's behalf. + +In a target-free session, use `open_binary` to bind any archive/package or +native target whose analysis tool operates on the active target. Do not call an +unadvertised tool; inspect `binary_session` with `{}` and its +`result.tool_availability` for availability reasons and remediation. Expand each +group's `names` into entries, inheriting the inventory-level client requirements +unless the group overrides them. In its closed effect and annotation vocabularies, +listed flags are true and omitted known flags are false. The grouped name union +is the complete tool inventory; use `tools/list` for canonical tool schemas. +Provider candidate facts describe possible providers, while top-level session +capabilities describe the current route and `analysis_provider_binding` names the +selected provider. Do not treat those scopes as interchangeable. + +## Work summary-first + +Start with the default result and use its inline Evidence and graph context. +For a JavaScript application or ELF layout whose size is unknown or large, +call `analyze_javascript_application` or `inspect_binary_layout` with +`"detail": "summary"`, then inspect the retained `parent_evidence_id` with +`inspect_analysis_view`. +Page module identities and select the returned `node_id` before requesting an +item; a single file path can represent several graph roles. Do not repeat an +identical analysis or rejected call without a changed input or resolved blocker. +Recheck session state when a lifecycle change makes that status useful. +Make a focused follow-up only when the +returned result leaves a specific question unanswered. + +If MCP reports `resource_constraint` with `details.resource: "transport"`, call +`inspect_analysis_view` with its reported same-session Evidence reference for a +summary, one section/module, or a stable page. Use `trace_application_feature` +once a seed is known, or call `export_evidence_bundle` to write the complete +session to a selected path. The analysis remains complete in the ledger; avoid +repeating it merely to request the same oversized response. Complete CLI JSON +output also streams without a single MCP frame. + +When the retained parent ID is unknown, use `get_evidence_bundle` with +`detail: "summary"` and exact filters for operation, target SHA-256, +analysis-profile digest or canonical procedure address. Select its returned +Evidence ID for the next view instead of requesting the complete bundle. +`retention: "complete-record"` means the whole record is stored; native +value-flow truncation and unknown metadata remain separate. For an exported +portable bundle, use `rea inspect-evidence-bundle` with JSON containing `path`, +`detail: "summary"` and the same `filters`. Reading that file still requires +validating its full contents within the local memory budget. + +A client can also truncate a successful tool result without a REA transport +error. Treat that preview as incomplete; use the retained parent ID for smaller +views or export when the full record is needed. Do not parse the preview as +canonical JSON or repeat the producer. For JavaScript, read the +[module-view and trace recipes](references/javascript-applications.md) before +drilling into a large graph; a broad bidirectional trace can expand unrelated +containment relationships even after summary analysis. + +Every conclusion must distinguish observations, inferences, and unknowns. Cite +Evidence IDs, preserve limitations and incomplete coverage, and never imply +that static analysis observed execution. Runtime requests execute the declared +target and lifecycle; do not broaden the target or action beyond those fields. + +Within the user's requested investigation, call available analysis tools +directly. REA does not require permission grants or per-call approval flags. +The agent client can independently require approval. Follow the declared request +scope and the host's actual access requirements; use the recovery guide for an +observed client-policy rejection. + +## Plan broader investigations + +For requests that span multiple features or subsystems, use a staged workflow: + +1. Turn the request into a checklist of questions and the evidence each answer + needs. Resolve target identity and constraints from the conversation and + workspace before asking for information again. +2. Inspect the current REA session, artifact identity, saved analysis database, + bookmarks, and prior evidence. Reuse matching state; do not open duplicate + sessions or repeat identical analysis. +3. Start with the smallest useful overview or inventory. Follow each question + from its entry point through relevant data and state changes to its result. + Batch related operations around a specific hypothesis, then expand only when + the returned evidence leaves a concrete gap. +4. Inspect relevant packaged resources and configuration alongside code when + they affect the question. Use format-aware inventory and parsers; do not + infer behavior from filenames, strings, or layout alone. +5. Corroborate a conclusion with the evidence type it requires. Use runtime + observation only when static evidence cannot answer the question and the + required host runtime and OS access are available. For JavaScript behavior, + run probes against the actual app through the available browser, Electron, + or process capture workflow. +6. Decompose work into independent questions. When parallel workers are + available and the questions do not depend on one another, assign distinct + scopes, point workers to existing evidence, and ask them to return sources, + conclusions, and unresolved gaps. Otherwise, work sequentially. +7. Keep a concise finding ledger linking each conclusion to Evidence IDs, + confidence/evidence type, search boundary, and remaining unknowns. Update + the shared index or investigation report so later passes can reuse results. + +Before finishing, revisit the original checklist. Mark each question as +answered, partially answered, or unresolved based on its evidence; keep +bounded negative searches bounded, and do not describe a broad investigation +as complete while required questions remain open. + +## Read only the relevant guide + +- Native binaries, managed assemblies, archives, and extraction: + [references/native-and-artifacts.md](references/native-and-artifacts.md) +- ASARs, extracted JavaScript, feature tracing, and version comparison: + [references/javascript-applications.md](references/javascript-applications.md) +- Android APK declarations, classes, methods, and static references: + [references/android-applications.md](references/android-applications.md) +- Browser/Electron observation (passive and scenario) and static/runtime + reconciliation: + [references/runtime-observation.md](references/runtime-observation.md) +- Evidence paging, comparisons, residual unknowns, and verification: + [references/evidence-workflows.md](references/evidence-workflows.md) + +## Finish the task + +Explain findings in plain language and tie them to returned evidence. When the +user asks to build something, use normal coding tools and separate observed +behavior from design choices. Close an opened native session with +`close_binary` when the investigation is complete. diff --git a/.claude/skills/reverse-engineer-anything/references/android-applications.md b/.claude/skills/reverse-engineer-anything/references/android-applications.md new file mode 100644 index 0000000..912a42f --- /dev/null +++ b/.claude/skills/reverse-engineer-anything/references/android-applications.md @@ -0,0 +1,36 @@ +# Android application artifacts + +Use the connected server's advertised Android tools. Repository main and npm +4.1.0 include this family. A skill installation alone cannot add it to an +older server. + +Start with `inspect_android_package` on the caller's APK path for package +identity, manifest declarations, coverage, and inline Evidence. Use +`search_android_classes` to find candidates, `inspect_android_class` for one +class's members, `inspect_android_method` for decompilation, and +`trace_android_references` for incoming static references. Each call takes its +own APK path and explicit selectors; do not open a native session first. +Choose an `overload_index` from the class inventory when methods are ambiguous +instead of guessing. + +The provider requires a separately supplied headless JADX MCP JAR 0.7.1 and +Java 17 or newer. `REA_JADX_MCP_JAR` selects the absolute JAR path; `JAVA_HOME` +can select Java. REA setup does not install or configure that JAR, and doctor +provider scopes cover Hopper/Ghidra rather than JADX. Use existing tools and +report missing prerequisites for the Android task specifically. + +Linux and macOS use the POSIX owned-process boundary. Windows x64 requires the +matching bundled native controls and uses an owned Job Object with bidirectional +stdio. A full JDK, including `jdk.compiler`, is required on every host; Windows +`JAVA_HOME` selects `bin\java.exe`. Consult the Android guide for actual host +verification coverage. Calls use one worker and provider deadlines; optional +`REA_JADX_HEAP_MIB` selects the JVM heap and `REA_JADX_OPERATION_TIMEOUT_MS` +the per-operation deadline (default 120000 ms; the MCP client's tool timeout +must also allow it). The APK is never launched, +and no emulator is required. + +Manifest entries and decompiled text are static observations, not execution or +policy enforcement. Incoming references are recovered static relationships; +reflection, dynamic loading, and unresolved calls remain unknown. Preserve +artifact digests, locations, diagnostics, and incomplete coverage. For archive +members rather than code analysis, use `open_binary` and `inspect_artifact`. diff --git a/.claude/skills/reverse-engineer-anything/references/connection-and-recovery.md b/.claude/skills/reverse-engineer-anything/references/connection-and-recovery.md new file mode 100644 index 0000000..0feae3a --- /dev/null +++ b/.claude/skills/reverse-engineer-anything/references/connection-and-recovery.md @@ -0,0 +1,127 @@ +# Connection and task recovery + +Read this guide only for an observed connection, command, approval or provider +blocker. Keep the user's target and question in view. Explain what prevented the +operation and the next useful step; after repair, continue the investigation. + +Commands below use an installed `rea`. If none is available, use the package +invocation in `SKILL.md` when acquiring REA is authorized. Follow the connected +server's schemas and the installed CLI's help rather than assuming repository +main and an older release expose the same arguments. + +## Choose the remedy from the observed failure + +| Observation | Meaning and next step | +| --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| No REA tools in the active session | Inspect registration with `rea doctor --client codex --json`. A skill installation alone does not register MCP. | +| Missing, malformed or stale registration | Prepare a scoped setup plan; apply only authorized changes with backups. | +| Aligned registration, but no connected tools | Restart/reconnect the client. Doctor checks registration; it cannot establish the current agent's connection. Inspect the client's launch error if reconnection fails. | +| `MCP tool call requires approval, but approval policy is never` | Codex rejected the call before REA executed it. Do not install an engine or repeat setup to solve this client-policy decision. See the approval section below. | +| REA returns `provider_unavailable` or an unavailable tool entry | Read that operation's provider diagnostics or `binary_session.result.tool_availability`. Expand each group's tool names and inherit the shared client requirements unless overridden. Use the operation's availability, reason, and remediation; a complete tool catalog does not imply every operation is available. | +| `rea` is missing in a child shell, or Node is incompatible | Inspect the actual shell PATH and launcher/runtime. A prefix installation may be absent from a login shell's PATH; this does not establish a broken MCP registration. | + +If the client cannot launch its shell/sandbox helper or read the installed skill, +inspect its launch diagnostic. For example, Codex can refuse helper aliases when +CODEX_HOME is under `/tmp`; use an authorized profile outside the OS temporary +directory. REA setup cannot repair the client's executor. Preserve the sandbox +instead of silently disabling it to make an analysis command work. + +Static JavaScript and ordinary ZIP inventory need neither Hopper nor Ghidra. +HAR inspection is offline and does not require a live browser. Native +decompilation, Android analysis and firmware extraction have their own +bring-your-own prerequisites. Use supported inventory/static evidence when it +answers part of the question, and name the unavailable evidence separately. +Do not substitute another target. Label observations from ordinary shell tools +as such; only actual REA output supplies REA Evidence. + +## Repair registration when needed + +For Codex: + +```bash +rea doctor --client codex --json +rea setup --client codex --dry-run --json +``` + +Use the current supported client's ID: `claude_code`, `claude_desktop`, `codex`, +`cursor`, `gemini_cli`, `windsurf`, `devin`, `opencode`, `antigravity`, +`copilot_cli`, `commandcode`, `qwen_code`, `vscode`, `trae`, `grok_build`, `omp`, `pi`, +`hermes`, `qoder`, `droid`, `zcode`, `dsh`, or `grok_bot`. If unknown, inspect `doctor --json` before choosing a +scope. `grok_bot` uses a chat registration step rather than local `mcp.json`. +For unsupported clients, use version-pinned manual stdio registration or CLI. + +Show the plan's exact paths, backups, changes and bundled-skill replacement. +Obtain approval for writes when that concrete scope is not already authorized, +then apply the same scope with `rea setup --client codex --yes`. Add +`--install-hopper` only when separately needed and explicitly approved. Do not +install or upgrade unrelated prerequisites. Restart/reconnect, verify tools +actually appear, and resume the original task. If they remain absent, inspect +the launch failure rather than looping through setup. + +## Codex tool approval is separate from REA readiness + +REA tools have no permission-grant handshake. Codex can still require approval +because an operation creates owned resources, launches a helper or has cleanup +effects. An advertised tool or successful doctor result does not override that +client policy. `workspace-write` alone does not resolve an MCP approval +rejection, and `approval_policy = "never"` does not mean every MCP tool is +preapproved. + +When interactive approval is available, use the client's approval flow for the +requested operation. In an unattended run, continue through an authorized CLI +workflow if the execution environment permits it, or report the blocked +operation and the approval needed to proceed. Do not retry the same rejected +call, silently broaden approvals, or rewrite MCP effects as read-only. + +For an operator who explicitly wants to preapprove named operations in a +disposable Codex profile, current Codex supports per-tool configuration. For +example, opening and closing an analysis session can be scoped independently: + +```toml +[mcp_servers.rea.tools.open_binary] +approval_mode = "approve" + +[mcp_servers.rea.tools.close_binary] +approval_mode = "approve" +``` + +Use the actual server ID and only the operations whose effects were approved; +this example does not approve inspection, extraction or runtime execution. +Show the proposed config edit and preserve unrelated entries and backups before +writing. Managed policy can constrain client settings. Consult the +[Codex configuration reference](https://learn.chatgpt.com/docs/config-file/config-reference) +for the installed client's supported settings. This is an optional recovery +choice, not a prerequisite for every REA task. + +## Continue through an installed CLI + +Check the command environment only if the launcher fails: + +```bash +command -v rea +command -v node +node --version +rea --version +``` + +Use the public launcher at its known installation path with a supported existing +Node on PATH when the child shell loses a prefix installation. Avoid internal +`dist/cli.js` entrypoints or global toolchain changes. MCP may have its own valid +launcher even when a shell cannot resolve `rea`. + +For a user-supplied JavaScript tree or ASAR, select output files in the authorized +workspace and save complete Evidence before reading a view: + +```bash +rea analyze-javascript-application /absolute/path/to/app --json > app-evidence.json +jq -c '{source: {kind: "inline", evidence: .}, view: {kind: "summary"}}' app-evidence.json > app-view.json +rea inspect-analysis-view app-view.json +``` + +These commands do not register MCP or install an analysis engine. CLI JavaScript +JSON is complete and can be very large; redirect it rather than loading it into +context. Use an existing JSON processor if `jq` is absent, without installing +one just for this recipe. Inspect a module page or item using the same inline +source and the [JavaScript recipes](javascript-applications.md). Preserve graph +coverage, limitations and unknowns. Native CLI analysis still requires its +selected engine, and all CLI operations retain the host's execution permissions. diff --git a/.claude/skills/reverse-engineer-anything/references/evidence-workflows.md b/.claude/skills/reverse-engineer-anything/references/evidence-workflows.md new file mode 100644 index 0000000..539bfb6 --- /dev/null +++ b/.claude/skills/reverse-engineer-anything/references/evidence-workflows.md @@ -0,0 +1,71 @@ +# Evidence, comparison, and verification workflows + +Evidence-producing tools return the complete Evidence record directly in MCP +`structuredContent` and CLI JSON. Read `normalized_result` for operation data, +and cite `evidence_id` when another tool or your explanation needs a stable +reference. Preserve authority, limitations, coverage, and residual unknowns. If a result +is incomplete or paginated, continue only when the remaining data matters to +the task; do not fetch a bundle or resource merely to read a result already +returned inline. When complete `inspect_binary_layout` or +`analyze_javascript_application` Evidence is already retained, call +`inspect_analysis_view` for a summary, one section/symbol/module, or a stable +page instead of repeating the producer. + +Completed `inspect_artifact` inventory also supports a summary and +`view: {kind: "inventory", collection: "occurrences", logical_paths: ["package.json", "main.js"]}`. +Omit `logical_paths` to page all available occurrences; `[]` selects none. +Other inventory collections are `nodes`, `edges` and +`integrity_contradictions`. Keep `source_complete` separate from page exhaustion: +a missing match in partial source Evidence does not establish absence. Use the +returned parent Evidence ID for subsequent views and export before closing the +session when the source must survive it. +When `tools/list` advertises `inspect_artifact.detail`, request `"summary"` to +retain its complete source and receive that view immediately. Without that +advertised choice, keep the existing complete call. CLI inspection returns +portable complete Evidence; save it before projecting a selected inline view. + +Use `record_unknown` to track unresolved questions in the user's investigation +and name the authority or environment still required. Supply supporting and +contradicting evidence IDs. It updates the session registry directly. +Use `update_unknown` with the current revision; reread after a stale revision +instead of retrying blindly. Only qualifying observed evidence can verify a +resolution. + +Use comparisons with complete, compatible page sets when claiming equivalence +or absence: + +- `compare_artifacts` compares inventory pages by occurrence path, content, + metadata, and graph relations. +- `compare_functions` compares explicit function Evidence, not fuzzy + whole-binary matches. +- `compare_bundles` compares canonical bundle membership and unknown history. +- `find_changed_behavior` combines existing comparisons; static differences + remain candidates, not causal proof. +- `build_call_path` needs explicit function dossiers from one artifact/provider; + an incomplete frontier makes absence unknown. +- `correlate_static_and_runtime` uses explicit mappings; matching patterns are + hypotheses, not causality. +- `verify_reconstruction` evaluates a finite typed specification. A pass covers + only declared comparable claims, not global equivalence. + +Process captures are opt-in behavioral evidence, not a security sandbox. V3 +captures cannot be upgraded to V4; rerun the original scenario. Distinguish root +exit from descendant settlement and require freshness when the task needs it. +A timed-out target that must write a final report needs `finalization_ms`: REA +sends SIGTERM to the captured root, keeps observing, and sends SIGKILL once +only if the target has not exited by the end of the interval. +`exit.finalization.signals` lists each attempt with its delivery result; the +observed exit signal stays in `exit.signal`, `exit.code` is null for every +deadline exit, and the code of a finalizer that exited on its own is in +`exit.finalization.exit_code` (null on a signal exit or when no exit was +observed). + +Use `inspect_analysis_view` with `view: {kind: "api-surface"}` on retained +`inspect_web_network_capture` HAR Evidence to group observed request lines by +method, origin and path template. Format matches are inferences, not handler +identity or schemas. Group pages cite parent record ordinals; consult record +coverage and exclusions before claiming completeness. No requests are replayed. +When the connected schema advertises `include_query_parameter_names`, select +it in the view for distinct observed names with original record ordinals. Query +values are omitted; the names establish neither required parameters nor a +complete server schema. Keep the original parent Evidence for exact URLs. diff --git a/.claude/skills/reverse-engineer-anything/references/javascript-applications.md b/.claude/skills/reverse-engineer-anything/references/javascript-applications.md new file mode 100644 index 0000000..d1f82e1 --- /dev/null +++ b/.claude/skills/reverse-engineer-anything/references/javascript-applications.md @@ -0,0 +1,218 @@ +# JavaScript and Electron application artifacts + +For captured or bundled JavaScript that needs readable source recovery, use +`recover_javascript_sources` with an absolute `path` and absent +`output_directory`. Supply related runtime/shared/lazy files in +`additional_paths` when advertised, then analyze the returned `analysis_input` +directory together. Each input retains its own snapshot, digest and byte-range +provenance; inputs and recovered code are never executed. Recovery requires a +caller-supplied Wakaru on Linux x64; see [the recovery guide](https://github.com/morluto/rea/blob/main/docs/javascript-recovery.md). + +Use `analyze_javascript_application` directly on the operator-supplied ASAR or +extracted tree. When the question concerns known source paths and the connected +schema advertises `source_paths`, select exact inventoried paths such as +`["package.json", "main.js", "preload.js"]`. Include supporting manifests or +source maps explicitly; dependencies are not implicitly analyzed. REA retains +the complete artifact inventory and identity but reads source text and analyzes +only selected files. The result and summary record `source_selection`; files +outside scope and their relationships remain unknown, so partial application +coverage does not mean the selected source failed. Use repeated `--source-path` +on either static application CLI route. Omit the selection when the question +requires complete application analysis. `detail: "summary"` reduces delivery +and does not by itself reduce analysis work. + +Exact `#alias` specifiers resolve through the importer's +enclosing package `imports` map to package-local files; nested `node_modules` +packages use their own map. Wildcard, recursive, and external-package import +targets stay unresolved with that limitation. When size is unknown or large and the connected schema advertises +`detail`, request `detail: "summary"`. This returns an `inspect_analysis_view` +Evidence record with a distinct ID and a `normalized_result.parent_evidence_id` +for the complete retained application analysis. Source-map contents are part of +that static analysis. Read findings, coverage, limitations and unknowns, then +follow a specific unanswered question. Older servers without `detail` return +the complete application Evidence inline when it fits. + +When the connected schema advertises `max_heap_mb` and `analysis_timeout_ms`, +these select the isolated source analyzer's old-space heap and per-source +deadline. Defaults are 1024 MiB and 300000 ms. They do not change the MCP +process heap. A Bun-hosted REA does not enforce the heap choice; on Windows it +instead limits the analyzer's committed memory to that choice plus a 512 MiB +runtime reserve. +Resource-limited analyses preserve completed static facts and +report partial semantic coverage with specific unknown scopes; this does not +mean the source is malformed. Inspect those limits before retrying a source. +When expanded relationships exceed the parent's available memory, inspect the +file's modules item view for retained `static_analysis` and +`semantic_module_analysis`. Their facts remain available even when graph links +are unknown. Cumulative result exhaustion can stop analysis before every file +is examined; the inventory and remaining unknown scopes distinguish that case. +Timeout or cancellation after source analysis begins retains partial Evidence +in the same session. A returned `error.details.partial_observation` reference +can be supplied directly to `inspect_analysis_view`. If the SDK cancels locally, retrieve its recorded ID from +the Evidence bundle before inspecting the partial analysis. + +## Read a module without repeating analysis + +Use the actual returned parent ID, on the same connection, as `source.evidence_id`. +The following IDs are placeholders to replace with returned values. When the +module's node ID is not already known, page identities before selecting an item. +Pages return only node IDs, paths and roles; choose a useful page size and follow +`coverage.next_offset` when another page matters: + +```json +{ + "source": { + "kind": "retained-evidence", + "evidence_id": "ev_ACTUAL_PARENT_ID" + }, + "view": { "kind": "page", "collection": "modules", "offset": 0, "limit": 16 } +} +``` + +Select the relevant page entry by its exact `node_id` and recorded role: + +```json +{ + "source": { + "kind": "retained-evidence", + "evidence_id": "ev_ACTUAL_PARENT_ID" + }, + "view": { + "kind": "item", + "collection": "modules", + "selector": { "node_id": "jag_node_ACTUAL_NODE_ID" } + } +} +``` + +Module pages include asset, bundled and source module roles, so one path can +identify several entries. Use `selector.path` only when uniqueness is established; +the returned node ID avoids needing a complete inventory to prove uniqueness. On ambiguity, +select the matching node ID from the page or the error's candidates. Follow +`next_offset` when another page matters. An item exposes that module node's +recorded observations, identity, hashes, exports and source ranges; it does not +include every child syntax observation, related edge or original source file. +An absent item fact is not evidence of absence from the whole application. + +For canonical identities and retained source-range counts, use a typed reference +page instead of reading every full item: + +```json +{ + "source": { + "kind": "retained-evidence", + "evidence_id": "ev_ACTUAL_PARENT_ID" + }, + "view": { + "kind": "javascript", + "collection": "modules", + "projection": "references", + "where": { "path": "main.js", "kind": "javascript-module" }, + "offset": 0, + "limit": 16 + } +} +``` + +Filters match exact retained strings; omit a filter to include all values, use +`path: null` for unavailable paths, and `path: ""` for a recorded empty path. +Rows preserve canonical `identity` and distinct observation support states in +`basis`. `retained_source_range_count` counts retained source-range observations, +not runtime imports or unique reference sites. Use a row's `node_id` with the item +view above for exact locations and full supporting observations. Follow +`coverage.next_offset`; page exhaustion describes matching retained rows only. +Check `source_coverage` for source selection, partial/unknown graph coverage and +unknown counts before drawing a negative conclusion. + +## Trace only the remaining question + +Use `trace_application_feature` on the parent application Evidence for one +literal node ID, route, string, API, IPC channel, module, or native export. +Select `incoming` for relationships leading to the seed, `outgoing` for those +leaving it, and `both` when the question needs both. Trace traversal includes +containment relationships, so even a narrow seed can expand many nodes; a +bidirectional trace can reach unrelated sibling modules. A module item or page +is preferable when its observations already answer the question. Do not treat +all reached nodes as participants in the feature. + +Reuse retained parent Evidence when the server advertises it, or supply complete +Evidence inline. Include Hopper or Ghidra Evidence only when its artifact digest +matches exactly. + +## Recover an oversized display + +An oversized response reports `resource_constraint` and +`details.resource: "transport"`. Reuse +`details.reported_limits.evidence_reference` with `inspect_analysis_view` for a +summary, one module, or a stable page of module identities. +`export_evidence_bundle` writes the complete canonical session to a +caller-selected file. These workflows keep the original Evidence and coverage; +a broad follow-up can also exceed framing. + +A client can truncate a successful result inside its text envelope without a +REA `resource_constraint`. Treat a truncation notice or incomplete JSON as a +display limitation; do not claim the full record was examined. Reuse the known +parent ID for smaller views, or export complete Evidence to a selected file +while the session remains open. If the parent ID was lost from the preview, +use the prior analysis summary or explicit ledger entries to recover it; do +not invent an ID or rerun analysis just to reproduce the same display. + +BrowserWindow preferences, preload and contextBridge surfaces, IPC +registrations, utility processes, and native binding requests are static syntax +observations. Only a unique exact literal IPC channel match supports an inferred +pairing. Dynamic or ambiguous channels remain unresolved. A requested `.node` +member is not a verified native export. Never claim runtime reachability, +registration, defaults, or policy enforcement from static analysis. + +For version comparison, analyze each version once, then call +`compare_application_versions`. Accept only its digest, source-map, structural +fingerprint, or non-module semantic matches. Module ordinals and minified names +are not persistent identity. Report added or removed only with complete +opposite-side coverage; otherwise report unknown. + +When the question asks how one exact exported callable's returned object shape +changed, analyze each version once and then call +`compare_javascript_export_shapes` with explicit module paths and export names. +Use the returned IDs on the same connection, or complete inline Evidence +records, from both analysis calls. Accept variant +pairing only through the tool's unique exact literal discriminant. Read +`property_inventories` and each change's `presence` before treating `unknown` as +"the name was not observed": inventories list observed property names even when +values stay unknown, with a `source_range` for each paired or unpaired variant. +Array holes and mutation-invalidated slots are not observed properties. +Complete parent coverage reports presence-only +`added`/`removed` independently of unresolved values. Cite the +comparison Evidence and report JSON Pointer changes; dynamic values, ambiguous +variants, and incomplete parent-property coverage stay unknown. This is static +inference, not runtime behavior. When runtime semantics are needed, run +behavioral probes against the relevant application versions and capture them +through the available browser, Electron, or process workflows. + +## Reusing application Evidence + +When advertised by the connected server, application trace and compare tools +accept complete inline Evidence or +`{"kind":"retained-evidence","evidence_id":"ev_<64 lowercase hex characters>"}` +for their application input (`application`, or `left`/`right`). `inspect_analysis_view` +uses the same retained-reference form in `source`, or portable inline Evidence, +to project a summary, module page, or one module with its recorded observations. +This notation is +a template: replace it with the actual returned ID. Versions before 4.1.0 accept only full +inline Evidence. Use the exact ID +returned by the producer on the same MCP connection. Resolution does not run +analysis or select a provider; findings remain inline. Native observation +arrays still take full Evidence. `close_binary` clears retained references; +export a bundle before closing, or supply portable inline Evidence in another +connection. A missing reference includes its ID and recovery guidance. + +For exact file/native metadata or processing gaps, use +`view: {kind: "javascript-facts", where: {paths: ["package.json"]}, property_keys: ["name", "operation", "analysis_status"], limit: 32}`. +Rows retain canonical node/observation identity and original Evidence. Paths +match Evidence artifact-path/source-range locations; missing properties remain +omitted and source coverage stays separate from page exhaustion. Batch paths and +select only needed property keys; complete Evidence remains accessible by export. +If names are unknown, opt into `include_available_property_keys: true`; it lists +the original keys per returned observation without unselected values. Keep each +row's node/observation identity paired when composing facts. +These rows select application-graph observations; semantic relationships and +semantic unknown records remain in the complete parent Evidence and trace tools. diff --git a/.claude/skills/reverse-engineer-anything/references/native-and-artifacts.md b/.claude/skills/reverse-engineer-anything/references/native-and-artifacts.md new file mode 100644 index 0000000..d3926ec --- /dev/null +++ b/.claude/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -0,0 +1,297 @@ +# Native, managed, and packaged artifacts + +## Go build metadata + +Use `inspect_go_binary` for an explicit local ELF, PE or thin Mach-O when the +question concerns the embedded compiler version, module/dependency versions, +local replacements or build settings. No `open_binary`, Go installation or +target execution is required. The CLI equivalent is `inspect-go-binary PATH`. +Preserve artifact SHA-256, original file ranges, framed module bytes and every +unparsed module-text line. A missing record is an unknown, not proof of a +non-Go binary; observed metadata does not authenticate its claims. Function, +source and type recovery remain a separate native-analysis question. + +## Rust dependency metadata + +Use `inspect_rust_binary` for an explicit local ELF, PE, or thin Mach-O when +the question concerns the cargo-auditable crate list embedded in `.dep-v0` +(Mach-O: `__DATA,.dep-v0`). No `open_binary`, Rust installation, or target +execution is required. The CLI equivalent is `inspect-rust-binary PATH`. +Preserve artifact SHA-256, package order, dependency indices, and the section +file range. A missing section is null metadata, not proof the binary has no +dependencies. An omitted package kind stays null. A rustc commit hash is +inferred from a read-only `/rustc/<40-hex>/` path and does not by itself +identify the compiler. See [Rust binaries](https://github.com/morluto/rea/blob/main/docs/rust-binaries.md). + +## SQLite snapshots + +Use `inspect_sqlite_database` with an explicit local database snapshot for its +schema and optional rows from one exact ordinary table. It requires Node.js +24.x >=24.15 or 26+ with the native `DatabaseSync.limits` API. It also consumes the +existing sibling `-wal`; retain both original digests when citing its result. +Default output is a compact inventory; a selected table expands only its own +schema and samples 20 rows. Select `columns` to avoid irrelevant or large cells, +and request `schema_scope: "database"` only for complete schema details. +Choose `row_limit` when a finite sample is useful and keep truncation and +unspecified row order explicit. Virtual tables, shadow tables and views are +schema facts, not row-read targets. REA inspects private copies and leaves +the source files untouched; obtain a coherent quiescent database/WAL snapshot +before inspection. See [SQLite snapshots](https://github.com/morluto/rea/blob/main/docs/sqlite-databases.md). + +## Recorded Linux crashes + +Use `inspect_recorded_crash` with an explicit Linux x86-64 ELF core path to +inspect historical thread registers, signals, raw notes and original file +ranges. It is independent of the active disassembler target. Source-bound +register values and note bytes are observations; missing notes, signal-thread +association and current executable/library identity remain unknown. PIDs are +historical metadata and never authorize live attach or control. + +The optional `include_debugger_context` facet adds mapping candidates through +caller-supplied GDB/pwndbg in an owned core-only session. Display names do not +establish current file identity; zero reported flags leave permissions unknown. +Requested unavailable context fails with setup guidance. See +[recorded crashes](https://github.com/morluto/rea/blob/main/docs/recorded-crashes.md) +for exact upstream profiles, bounds and verification coverage. + +## Offline ELF layout + +Use `inspect_binary_layout` with an explicit local ELF path for file-backed +sections, symbols, relocations, linkage names, and static mitigation inferences +without opening a disassembler target. When that complete record is already +retained, call `inspect_analysis_view` for a summary, mitigations or linkage +facet, one section or symbol, or a stable page. Do not re-run the decoder to +read a single object. + +## Offline WASM + +Use `inspect_wasm_artifact` with caller-supplied WABT for selected local bytes. +For counts, validation and WAT identity, select `detail: "summary"` on the first +MCP call. The complete original Evidence stays retained; use +`normalized_result.parent_evidence_id` for exact exports or text pages. Omitted +or complete detail keeps the existing complete result. +For a completed result, use `inspect_analysis_view` with its reported retained +reference for a summary or `view: {kind: "wasm", facet: "exports", offset: 0, limit: 32}`. +Facets also include sections, imports, candidates, glue, WAT, headers, details +and tool profile. Text offsets count UTF-16 code units; follow `next_offset`. +The complete source remains retained after an oversized MCP reply. No target +execution or network acquisition is implied, and WAT is decoded representation. + +## Native targets + +After `open_binary`, use focused search, procedure, or function tools directly. +Use `binary_overview` when target metadata or inventory context helps answer the +question. Prefer literal search, names, decompilation, callers, callees, and +cross-references. Addresses and recovered pseudocode are analysis observations, +not original source. Provider unavailability and unsupported metadata remain +unknown rather than false. + +For a completed `analyze_function` dossier, use `inspect_analysis_view` with +`view: {kind: "native", facet: "value_flow_operations", offset: 0, limit: 32}` +and the exact retained Evidence ID to read selected facts without reanalysis. +Native facets also include procedure, pseudocode, assembly, basic blocks, +comments, callers/callees, references, unresolved calls, referenced strings and +names, the native API record, and value-flow summaries. Pseudocode offsets and limits count UTF-16 +code units; use the returned `next_offset` for continuation. Provider limitations +and unavailable facts remain explicit; the complete parent Evidence is retained. + +`inspect_macho` on a large framework returns megabytes of imports and exports. +Select `detail: "summary"` for slice identity, UUID and per-collection counts, +then page rows with `view: {kind: "macho", facet: "exports", offset: 0, limit: 64}` +and `normalized_result.parent_evidence_id`. Facets are entrypoints, +architectures, build_metadata, load_commands, dependencies, imports, exports, +segments and provenance. `source_exhaustive: false` means unreturned symbols +may exist. + +To see which functions or Objective-C methods a Mach-O actually calls in one +run, use `observe_native_calls` with explicit breakpoints and a bounded +`duration_ms`/`max_events`. It launches a new process under LLDB, so the target +runs and may change files or use the network. Hardened-runtime targets need the +`get-task-allow` entitlement. + +Use `binary_session` with no arguments to check the open target, selected +provider, and alignment. Its default `result.tool_availability` carries a +complete inventory grouped by shared facts. Expand each group's `names` and +inherit the inventory-level client requirements unless a group overrides them; +availability, reasons, remediation, modes, and flags remain inline. The +`effects` and `annotations` arrays name true flags from fixed vocabularies, so an +omitted known flag is false. `tools/list` remains the canonical source for full +tool schemas when target or provider state changes. + +Provider capability groups carry provider identity and ordered limitations. +Prepend each set's `shared_limitations` to a group's `limitations` to recover the +operation's full ordered list. Candidate capabilities describe possible +providers. Top-level session capabilities describe the current route, and +`analysis_provider_binding` identifies the selected provider. + +## Static memory and original file bytes + +For Ghidra, `read_bytes` reads initialized analysis memory, including loader +fixups; it does not read a running process. Check `returned_bytes` and `complete` +before decoding a table. An incomplete read is missing coverage, not a zero-filled +tail. Use `list_segments` to inspect the selected block's initialization and address-space +facts, and retain unavailable facts as unknown. + +Use `address_to_file_offset` to anchor one observed address to original file +bytes. A mapping for the first address does not establish a contiguous mapping +for an entire table, and loader fixups can make analysis bytes differ from source +bytes. Keep source ranges and analysis-memory observations separate. + +A pointer table can refer to writable slots populated by a constructor rather +than directly to immutable resources. An uninitialized block or an observed zero +does not establish the slot's later runtime value. Follow `xrefs` and the relevant +writer's assembly or pseudocode; distinguish recorded assignments from inferred +execution order. Do not replace unreadable bytes with zeros or conclude that a +resource is absent without the necessary initialization evidence. + +## DOS MZ with Ghidra + +For an admitted DOS MZ target, use `inspect_native_load_image` to check measured +loaded bytes, file mappings, relocations and the entry against the immutable +snapshot. Keep `mismatch` and `unsupported` explicit. Verified import covers the +reported static image, not runtime DOS or PC-98 hardware behavior. + +For Ghidra decompilation, `procedure_pseudo_code` also accepts `procedure: "file-offset:0x..."`; CLI `rea decompile --file-offset=0x... --provider ghidra` resolves the source byte offset internally. An unresolved 0x-prefixed numeric procedure selector also falls back to a unique file mapping. Existing symbols and analysis addresses win; multiple mappings fail as ambiguous. Preserve the returned file-offset and address locations and raw selection observations. ELF virtual addresses are distinct from file offsets; never assume an arbitrary offset plus image base is an analysis address. + +Complete function body ranges use inclusive ends and can contain gaps. Do not +treat the enclosing span as code. +For packed targets, retain the original and separately derived artifact identities; +decompiling an unpacking stub does not recover the unpacked program. + +When reading Objective-C dispatch metadata, distinguish class implementation +methods from protocol requirements: class methods report null requirement +flags, while decoded protocol declarations retain required and optional facts. +Property attributes remain raw name/value tokens; use the property's +`atomicity` field for the decoded `N` marker or the default atomic behavior. +Null class/meta flags, ivar counts, atomicity, or read-only values mean the +selected provider did not establish that fact. Symbol names alone do not prove +that a class is a root class or has no ivars. + +## Managed PE/CLI + +Start with `inspect_managed_artifact`. REA's canonical managed inspection is +execution-free: do not claim it loaded, reflected, executed, or resolved the +assembly. Keep managed/native boundaries and unavailable reconstruction facts +explicit. A bring-your-own reconstruction oracle is separate from the canonical +parser and must not become an implicit setup dependency. + +For identity/classification questions, `inspect_managed_artifact` can explicitly +select `detail: "summary"` on the first MCP call. It retains complete metadata +and returns a linked overview with full classification/evidence, nullable +module/MVID, frameworks, metadata coverage/issues/limitations and returned-row +counts. Default complete requests remain unchanged. Read original rows with +`inspect_analysis_view`, source `normalized_result.parent_evidence_id`, and +`view: {kind: "managed", collection: "attributes", offset: 0, limit: 16}`. +Collections are `references`, `resources` and `attributes`. Paging does not +repeat parsing. Returned-row exhaustion +does not prove complete metadata or absence under partial/unavailable coverage; +preserve build-local tokens and their artifact/MVID scope. + +`inspect_managed_members` always returns the assembly-wide `member_refs`, even +for one selected type. For questions about a selected type, select +`detail: "summary"` with `type_names`; it returns the selection (with unmatched +names), coverage and per-collection counts. Page rows with +`view: {kind: "managed-members", collection: "call_edges", offset: 0, limit: 64}` +over `types`, `exported_types`, `fields`, `methods`, `member_refs`, `call_edges`, +`field_accesses` or `user_strings`. + +### .NET NativeAOT + +NativeAOT binaries contain native machine code, so ordinary CIL decompilers +cannot recover the original method bodies. When managed metadata/CIL is absent, +classify that as a native-analysis route rather than claiming source recovery. +Open the native image with the selected deep provider and inspect functions, +strings, calls, and references; describe decompiler output as pseudocode and +inference. + +NativeAOT images can be PE/COFF, ELF, or Mach-O executables and shared +libraries. Use file bytes and loader metadata rather than suffixes to identify +them. For packaged apps, inventory/extract with REA's artifact tools and retain +the exact contained image identity. PDB, ELF debug, or dSYM sidecars are +additional evidence only when the provider accepts and matches them. + +REA has a built-in read-only snapshot parser for x64 PE targets with .NET 8 RTR +9.1 metadata. An optional headless Ghidra adapter adds database annotations and +broader metadata recovery on Linux; it requires an explicitly configured +NativeAOT JAR. These are separate routes. The built-in parser also runs on +Windows Ghidra P0; read frozen literals from its report, because +`search_strings` does not include them. See the +[NativeAOT guide](https://github.com/morluto/rea/blob/main/docs/ghidra-nativeaot.md) +for setup, supported layouts, and host restrictions. Preserve binary identity +and distinguish derived metadata from Ghidra database observations. Recovered +types and native pseudocode are not original C# source. Windows Ghidra P0 has +no database mutation authority. + +## Packages and extraction + +Use `inspect_artifact` for application bundles, archives, ZIP/APK/IPA/MSIX/AppX, +ASAR, or DMG inputs when the artifact graph and findings help answer the +question. It returns the complete artifact graph inline. Cite graph manifest +IDs when using them. + +For an IPA or a macOS `.app`, ZIP, or DMG, pass the inventory Evidence to +`project_apple_application_graph`. It reports application roots and nested +bundles by path convention: app extensions, XPC services, frameworks, login +items, system and driver extensions, and plug-ins. It also lists privileged +helpers, launchd plists, symlinks, and each bundle's `info_plist_path` and +executable candidates. Roles are path conventions, not parsed plists; read the +listed plists with `inspect_plist`. + +After `open_binary` on a `.app` or Mach-O, use `trace_dylib_resolution` to see +which file each `@rpath`, `@loader_path` and `@executable_path` load reaches for +every executable in the bundle. It also lists missing or weak loads and earlier +`@rpath` candidates that are absent. Narrow large bundles with `roots` or +`architecture`. System paths stay undetermined because the dyld shared cache +provides them. + +Use `extract_artifact` when materialized files are needed. It extracts the active +target and accepts optional `integrity_policy`; see the [MCP contracts](https://github.com/morluto/rea/blob/main/docs/mcp-contracts.md). +It materializes all regular files into a fresh temporary directory chosen by +REA. Symlinks and encrypted entries are inventory facts, not extractable files. +The result reports the materialized directory; callers do not choose the +destination. No separate permission grant is needed. + +Native DMG traversal automatically uses a read-only mount on supported macOS +hosts, with an owned temporary mount directory and cleanup. It needs no approval +flag. Unsupported hosts or mount failures remain explicit limitations; do not +claim child inventory when only root identity is available. Extraction is a +separate filesystem-writing operation. + +For headerless DOS COM, explicitly open with `format: "dos-com"` (CLI +`--target-format dos-com`). Inspect the load image before trusting function +analysis: the entry is `0x10100`, file offset zero, with imposed real-mode segment +context. PSP/stack/device state remains unmodeled. See [DOS guide](https://github.com/morluto/rea/blob/main/docs/ghidra-dos.md). + +For other headerless images (embedded firmware without ELF/Mach-O/PE/MZ +headers), open with `format: "raw-binary"`, `architecture` (`x86`, `x86_64`, +`arm`, `arm64`, `6502`, or `m68k`), and `entry_point` (`0x` hex). File offset 0 is mapped at +that address. Hopper and IDA refuse this interpretation; Ghidra uses +`BinaryLoader` with a generic language: big-endian for `m68k`, little-endian +otherwise. Big-endian ARM, Thumb-only, and Cortex-M variants are unsupported. +`6502` selects NMOS 6502; the entry and complete file mapping must fit within +`0x0000..0xffff`. 65C02, 65816, cartridge containers, bank switching, and mapper +semantics are unsupported. `m68k` requires an even entry and decodes the 68040 +superset of the 68000 family; Amiga/Atari containers and vector-table entry +discovery are unsupported. Windows Ghidra P0 admits raw images only for `6502`. See [raw binary guide](https://github.com/morluto/rea/blob/main/docs/raw-binary.md). + +### Function annotations in Ghidra + +Use `annotate_native_function` for one function name and/or entry comments, with at least one explicit change. Review its annotation readback and refreshed dossier inline. Changes are atomic and session-scoped; empty comments clear them, omitted fields preserve them. Later MCP calls observe edits until close. CLI `annotate-native-function` returns the updated analysis before discarding the session. Original executable bytes are unchanged; edits invalidate immutable snapshots. Windows P0 does not admit database mutations. For naming only, `set_address_name` / `set_addresses_names` also work with Ghidra: they name function entries or data addresses (primary labels) and return compact per-address success booleans instead of a dossier. + +## Offline PE resource inventory + +Use `inspect_pe_resources` with an absolute `path`, or +`rea inspect-pe-resources ./selected.exe --json`, for portable PE32/PE32+ +resource inspection without opening a native target. Preserve returned Evidence: +type/name/language IDs and UTF-16 names, original directory/data/payload ranges, +code pages, payload hashes and static icon-group references. Same-language icon +resolution is explicit; missing references and size mismatch remain visible. +Other payloads are opaque, and this operation does not decode images or simulate +Windows resource loading. Consult the budgets and supported tree profile in +[offline binary diagnostics](https://github.com/morluto/rea/blob/main/docs/binary-diagnostics.md). + +For exact core-module import/export differences, use `compare_wasm_interfaces` +with two complete inspection Evidence records (or current-session retained +references) and explicit scope. Preserve unknown types/duplicate names; static +interface equality is not runtime compatibility. CLI accepts complete inline +Evidence in `rea compare-wasm-interfaces input.json --json`. diff --git a/.claude/skills/reverse-engineer-anything/references/runtime-observation.md b/.claude/skills/reverse-engineer-anything/references/runtime-observation.md new file mode 100644 index 0000000..df75bca --- /dev/null +++ b/.claude/skills/reverse-engineer-anything/references/runtime-observation.md @@ -0,0 +1,78 @@ +# Browser and Electron runtime observation + +Supply the existing browser or Electron instance's literal-port loopback CDP +endpoint in the request. No separate permission configuration or per-call +approval flag is needed. Browser discovery lists eligible HTTP(S) pages; +`allowed_origins` optionally filters them. An individual capture defaults to the +selected page's current origin. Electron discovery lists eligible local +`file://` targets without a configured file-root allowlist. + +Start passive browser work with `list_browser_targets`; start Electron runtime work with +`list_electron_targets`. Before an electron-main Inspector attempt, check +packaged fuses with `inspect_electron_fuses`. Inspect the target selected for +the user's task. Observation with these tools is passive: never claim REA +clicked, navigated, evaluated page JavaScript, invoked IPC, or captured prior +activity. REA does not contain the page's network. + +Passive captures omit raw header collections, credential header values, storage +values, and raw WebSocket/JSON bodies. Selected response metadata, including +content encoding, policy values, and Link URLs, is retained. Local URLs retain ordinary query +values and fragments; userinfo credentials are removed. Browser accessibility +text, console primitives, value-free shapes, script sources, source maps, and +storage key names have request-specific capture options. Electron script +sources are also optional. Use `capture_web_screenshot` when pixels are needed. +Treat scope filtering, truncation, and attach-window coverage as limitations. +Page-declared WebMCP tools are untrusted inventory and are never invoked by REA. + +## Who performs the action + +- The user performs it: `list_browser_targets`, then `inspect_web_page` or + `observe_web_session` on the selected target. +- The agent must perform it: one `capture_browser_scenario` with declared + actions. Use connect mode with the loopback CDP endpoint and `target_id` for + an existing browser, or launch mode with a caller-selected executable for a + temporary profile. Connect mode first navigates the selected page to + `start_url`, which can clear unsaved form values and other temporary state. + Recreate the state needed for the investigation in the declared actions. + Connect mode leaves the external browser open; launch mode owns a temporary + browser and profile. Check `browser.cleanup` for the outcome. + Request only the DOM, accessibility, or network details needed for the question. + The default final capture contains the URL; step outcomes are reported separately. + Add a wait action for the expected page state before capturing it. Report that + REA performed the declared actions. + +Scenario network records have no request initiator stacks. For that evidence, +use passive capture while the user performs the action. Listener source locations +identify candidate handlers; they do not establish which script sent a particular +request. Avoid overlapping passive capture and scenario actions on the same target. + +Focused follow-up tools: + +- `observe_web_execution`: execution coverage during a window; it resets + counters and temporarily disables optimization. +- `inspect_web_event_listeners`: source locations for listeners registered + directly on the first CSS match, without dispatching an event. +- `compare_web_captures`: two normalized passive captures or recorded scenarios. +- `discover_webmcp_tools`: inspect page-declared WebMCP inventory; never invoke + the discovered tools. + +Use `reconcile_javascript_runtime` only after static application Evidence and +passive browser/Electron Evidence exist. Prefer captured-source digest identity; +report path/digest disagreement as a mismatch and preserve ambiguity. Explicit +path mappings are inference inputs and never broaden filesystem or CDP authority. +A bundle observed at runtime does not prove every contained module executed. + +## Fiddler Everywhere traffic debugging + +For large saved captures, request `detail: "summary"`, then page retained Evidence +with `inspect_analysis_view` and `view: {kind: "capture", detail: "preview", offset: 0, limit: 20}`. +Select complete record pages only for needed headers, metadata or payloads; views +read the historical parent without repeating capture decoding. + +Inspect native `.saz` snapshots with `inspect_web_network_capture` and +`format: "saz"`; encrypted archives are unsupported. For live +traffic analysis, connect Everywhere's separate MCP server and use its +advertised session tools with an explicit `sessionsSource` (`LiveTraffic` or +`AgentCalls`). Preserve existing sessions and filters when inspecting a +recorded run. See the [capture and MCP guide](https://github.com/morluto/rea/blob/main/docs/web-network-captures.md) +for the workflow and Telerik's public setup and traffic-debugging skills.