AIStoreHub Package Vault: REA: Reverse Engineer Anything (MCP Server & CLI)
Package Slug: rea
Archetype: mcp_server
Upstream Repository: https://github.com/morluto/rea
Workspace Files & Specifications (67 files)
- .agents/plugins/marketplace.json (372 bytes)
{ "name": "rea", "interface": { "displayName": "REA" }, "plugins": [ { "name": "rea", "source": { "source": "npm", "package": "rea-agents", "version": "6.10.1" }, "policy": { "installation": "AVAILABLE", "authentication": "ON_INSTALL" }, "category": "Developer Tools" } ] } - .agents/skills/rea-analysis-optimization/agents/openai.yaml (283 bytes)
interface: display_name: "REA analysis optimization" short_description: "Optimize analysis with preserved Evidence and measured costs" default_prompt: "Use $rea-analysis-optimization to find and verify a concrete analysis bottleneck while preserving correctness and Evidence."
- .agents/skills/rea-analysis-optimization/references/kuna-case-study.md (6520 bytes)
# Kuna: reuse before adding machinery Read this reference for concrete examples of the skill's decisions. The records below concern static Linux analysis with caller-supplied Kuna. They do not establish parity with another provider or a general advantage for Code Mode, atomic tools, or any particular orchestration design. ## Exact-address lookup: a measured, narrow improvement [PR #4695](https://github.com/morluto/rea/pull/4695) reused the validated string inventory's numeric address order. Previously, each `list_strings(address)` filtered all cached facts. The owner now performs a binary lower-bound lookup and returns every encoding at that address: O(log n + matches), without a second retained lookup index. The owning implementation is [`KunaStringInventory.ts`](../../../../src/kuna/KunaStringInventory.ts), consumed by [`KunaStringQueries.ts`](../../../../src/kuna/KunaStringQueries.ts). Inspect their current versions before adapting the example. Numeric u64 addresses, same-address encodings, duplicate rejection, source digests, caller selection, and the existing session lifetime were part of the contract. Full listings and literal/regex searches kept their semantics. An attempted removal of the duplicate-detection set was dropped: no stable memory benefit was established, and it delayed malformed-input rejection. ### Recorded workload and results The benchmark used unmodified Kuna 1.833 and LLVM 16 on Linux x86-64, with 602,544 string facts. Baseline was `be0b2d138`; the final feature was `5f564962da0e1b17f00a68a74a312539f0209a01`, subsequently integrated in `c6b62754b095a134d6d67877508fa34311a2eda2`. These are historical observations, not a benchmark of every subsequent main revision. The same production stdio MCP task discovered the catalog, opened the binary, made one cold selected read and 28 warm exact reads, checked retained Evidence, and closed the session. Five selected addresses and two absent selectors were read four times. A native filtered scan selected the strings; an independent ELF load-header mapping checked the source bytes and terminators. Returned facts, source linkage, target digests, and cleanup were checked. Three alternating fresh sessions per implementation used one CPU, a 4 GiB process-family hard limit, a 3 GiB early stop, and no swap. OS file caches were warm. Whole-harness costs include the independent native oracle, hashing, catalog/client work, and correctness checks. | Median | Before | After | | ---------------------------------------- | ---------: | ---------: | | 28 warm exact MCP reads | 495.2 ms | 90.8 ms | | Cold selected MCP read | 11.30 s | 11.01 s | | Whole harness elapsed | 28.24 s | 27.43 s | | Whole process-family CPU | 27.71 s | 26.89 s | | Kernel family peak, including file cache | 2237.6 MiB | 2240.6 MiB | Warm totals ranged from 491.7–544.3 ms before to 84.8–99.5 ms after: about 5.5 times faster at this phase. Cold/whole-task timing and memory overlapped; no stable improvement in those costs was established. One small SQLite pair (7,985 facts) measured 20 warm reads at 88.6 → 80.5 ms and the whole harness at 13.68 → 13.94 s. The large-inventory lookup benefit does not generalize to a whole-task speedup on small inputs. Catalog hashes, call counts, and normalized facts were unchanged. A `cl100k_base` estimate over one pass of raw catalog JSON, arguments, and replies was about 846,000 tokens in both lanes, with about 802,562 from the catalog. This was transport serialization, not rendered model context or actual usage; client discovery, prompts, replay, and protocol framing were unmeasured. **No token reduction or improved agent investigation outcome was established.** Pinned target SHA-256: `f62d254b7f2bf42df8c8b07d46ee3bb4c2cafeca436b2e6bc6ccbe4581f58f40`. Pinned engine SHA-256: `d858918b0766435cd96b999a77f2d5a31a0cc4f07256421c883b5b9dc4dd58e4`. All six normalized-result sequence digests were `4d2f90269da8568984090b20274163c4a7c2a0538aab63530bd2fe44840a0bba`. Selected byte agreement does not prove native discovery completeness; missing strings and relationships can remain unknown. ## Other transferable changes and their limits - [Cached string inventory and search, #4095](https://github.com/morluto/rea/pull/4095): share validated facts across queries in a defined session. Audit key inputs and lifetime before extending reuse across targets or engine revisions. - [Shared single-function work, #4045](https://github.com/morluto/rea/pull/4045) and [repeat-request reuse, #4169](https://github.com/morluto/rea/pull/4169): avoid duplicate native work while retaining per-caller cancellation and cleanup ownership. A query count alone cannot reveal duplicate subprocesses. - [Streamed strings, #4318](https://github.com/morluto/rea/pull/4318) and [streamed call graph, #4329](https://github.com/morluto/rea/pull/4329): remove fixed aggregate transport-buffer failures through incremental parsing. Streaming transport does not bound every retained object or final reply. These links establish changes; no numerical speedup is asserted here. Typed reference facts, native string-query projection, and shared native byte reads remained experimental at the 2026-10-17 checkpoint `65f2f9a22bc892f61d2b00f9a4611124f57d4bff` on `experiment/atomic-codemode-20261016`. Some experiments used a patched native engine. Check current integration and bring-your-own engine capabilities before proposing them; a working experiment is not a stock-provider guarantee. ## Applying the reasoning elsewhere For another provider or format, inspect its actual representation and native capabilities before borrowing the implementation. Existing numeric ordering may support range reads; an on-disk native query may avoid materializing an inventory; an immutable parse may support several views. Measure the relevant alternative rather than requiring every provider to use Kuna's cached array. For live observations, immutable artifact caching rules are insufficient: validate the process/session identity and freshness required by the caller. For compact replies, preserve access to source Evidence and report examined coverage; projection must not silently turn an unresolved edge into no edge. For batching, test mixed successes and failures and measure the entire task, including discovery, extra calls, native work, and serialization.
- .agents/skills/rea-analysis-optimization/SKILL.md (7762 bytes)
--- name: rea-analysis-optimization description: Optimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit. --- # REA analysis optimization Find a concrete source of unnecessary work, change it at its owner, and verify equivalent completed investigations. A useful outcome can also be a measured decision to leave an implementation alone. Follow the checkout's [performance priorities](../../../AGENTS.md#performance), [tool design](../../../docs/development/tool-design.md), and [testing guide](../../../docs/development/testing.md). This skill supplies an optimization workflow, not additional permission to execute targets, publish, or merge. Use the current contracts, provider prerequisites, and user authorization. Reserve performance measurements for changes that target performance or have a concrete regression concern. Routine cleanup uses correctness checks and does not require this optimization workflow or synthetic benchmarks merely because helper calls, imports, or representations change. Read [the Kuna case study](references/kuna-case-study.md) when selecting a reuse strategy or interpreting a benchmark. Its pinned observations illustrate tradeoffs; they are not current-provider guarantees or universal speedups. ## Pin the question and the correctness oracle Describe the analyst's completed task, including the facts and relationships needed to answer it, requested detail, source access, and meaningful unknowns. Choose a representative real artifact and a small or empty case. Record the baseline revision, target digest, engine identity, options, host, and entrypoint. Use a separate checkout for changes without disturbing other work. Establish an oracle independent of the changed implementation: source-built fixture expectations, independently mapped file bytes, or a native producer paired with checks of its interpretation. Comparing two wrappers around the same faulty decoder does not establish correctness. Preserve address widths, same-address alternatives, unresolved endpoints, coverage, and source linkage. An empty result proves absence only within the actually examined scope. ## Locate the earliest unnecessary work Trace one public CLI or MCP task through shared application code to its producer. Measure relevant phases: admission and identity checks, native analysis, decoding, lookup, projection, serialization, Evidence retention, and cleanup. Include catalog discovery and extra calls when they affect the completed task. Use the evidence to choose the smallest structural correction: | Observed cost | Candidate correction | Condition to establish | | --------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------ | | Repeated scans of validated facts | Reuse existing order or lookup structure | The owner establishes ordering and identity; every matching alternative survives | | Repeated equivalent engine work | Share a validated result or in-flight producer | Inputs, freshness, lifetime, and per-caller outcomes remain explicit | | Full reports for selected facts | Push selection or projection to the earliest capable owner | Required facts and evidence remain reachable; examined coverage is reported | | Large temporary transport buffers | Decode incrementally or use bounded source reads | Validate the whole admitted document; retained facts and copies still consume memory | | Many repeated homogeneous reads | Share admission, decoding, or batch work | Preserve item identity, order where required, and individual failures | Do not introduce an index, generic cache, batch endpoint, or orchestration layer without identifying the work it removes and its maintenance/resource cost. Projection after materializing a full report may reduce output while leaving analysis time and peak memory unchanged. Fix missing or incorrect facts before benchmarking an alternative composition against a better-covered workflow. ## Keep one interpretation and a defined reuse lifetime Let the producer boundary validate and normalize facts once. Consumers query that representation through the shared CLI/MCP implementation; adapters should not rebuild relationships or independently reinterpret raw reports. Keep lookup identity separate from display formatting. Reuse contracts when their intent matches, honoring requested detail and complete Evidence access. For every cache or shared producer, state its key, owner, invalidation, retained size, and lifetime. Account for result-affecting target bytes, engine contents, analysis options, architecture/load mapping, and parser/schema versions where they affect reuse. Validate live state before calling a cached observation current. Cache a refusal only when it is deterministic for that validated key; malformed, partial, transient, or cancelled attempts need explicit retry policy. One cancelled waiter must not invalidate a successful peer. Preserve producer failure context and each caller's cancellation reason. Retain ownership and capacity charges until shared work and cleanup settle; preserve completed observations when cleanup fails. Exercise invalidation, concurrent consumers, last-waiter cancellation, close, and cleanup retry when those paths change. Bound the process family and retained state, not just a parent heap or worker count. Account for decoding and serialization expansion before allocation. Choose CPU, memory, concurrency, and disk limits from the host and workload; stop before OOM and verify owned cleanup. A guard-stopped task is incomplete. Do not replace a transport buffer cap with an unbounded retained inventory or hide partial results behind a success status. ## Compare completed tasks and limit the claim Run the affected real public workflow before and after with equivalent inputs, results, coverage, and Evidence semantics. Include small inputs so setup costs and regressions are visible. Distinguish fresh sessions, warm runtime caches, and OS file caches. Alternate or repeat runs when variance affects the decision. Choose meaningful boundary regressions for cases the actual engine cannot reliably reproduce; a fake engine does not qualify a real provider. Report task outcome, relevant phase timings, total elapsed and CPU time, peak process-family memory and its accounting method, resource stops, and cleanup. Check the payload exit status as well as the profiler's. Keep failed attempts and identify unmeasured costs; a passing retry does not explain a failure. For token claims, count schemas/discovery, arguments, replies, retries, and continuations needed to finish the task. Label tokenizer estimates separately from actual model usage and record the client/catalog behavior. Smaller JSON alone establishes neither fewer model tokens nor better investigation quality. Do not claim a complex-software advantage without completed representative investigations and comparable correctness/coverage. Finish with the bottleneck, owning change, preserved semantics, executed checks, before/after measurements, and remaining limits. Keep any integration record current with its tested revision and distinguish merged production work from experiment-only code. Stop when the demonstrated bottleneck is resolved or further benefit remains speculative.
- .agents/skills/rea-changelog-update/SKILL.md (7626 bytes)
--- name: rea-changelog-update description: Prepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization. --- # REA changelog update Use this for release-note preparation and contributor attribution. Read [docs/development/releasing.md](../../../docs/development/releasing.md) from the repository root for publication authority and the existing checkpoint checks. This skill prepares notes; it does not authorize merging, tagging, or publishing. ## Inventory before prose Fetch complete history and tags. Select the published baseline tag from `.release-please-manifest.json` on the release PR's **base branch**, and pin that branch's exact SHA as the editorial target. REA tags are `rea-agents-VERSION`. Use the proposed version, including its prerelease suffix; do not change the `always-bump-minor` strategy to imitate OpenClaw's calendar versions. ```bash node scripts/release-notes.mjs inventory \ --repository morluto/rea --base rea-agents-PREVIOUS \ --target FULL_BASE_BRANCH_SHA --version VERSION \ --manifest /tmp/rea-VERSION.contributions.json node scripts/release-notes.mjs record \ --manifest /tmp/rea-VERSION.contributions.json \ --summary \ --output /tmp/rea-VERSION.record.md ``` Read the inventory, not just the existing bot draft. It includes side-branch commits, GitHub-associated PRs whose merge commits are in the range, commit authors/co-authors, and confirmed closing issues with their reporters. GitHub connections are paginated. Network errors stop generation; rerun into a new output file after recovery. Existing output files are never overwritten. Unresolved commit identities are retained as names/emails with `user: null`; never guess a handle or thank the merger as a substitute. The report preserves unknowns. This is a reviewed metadata snapshot, not independent proof that a human authored a patch. For unattributed identities, unusual merge strategies, backports, reversions, or references that GitHub did not associate, inspect the source PRs and diffs and report the limitation. The current collector uses confirmed PR-closing relationships for issue-reporter credit; unrelated issue mentions are not automatically credited. Do not claim that merely inventoried work still ships after a revert. ## Write for users and retain credit Rewrite only the newest `## [VERSION]` section in `CHANGELOG.md`, preserving its version/date/link heading. Use single-line Markdown list items under: - `### Highlights`: a few release-defining user outcomes; no quota for small releases. - `### Changes`: capabilities and meaningful behavior changes. - `### Fixes`: reliability, correctness, compatibility, and safety fixes. - `### ⚠ BREAKING CHANGES`: retain when applicable, with migrations and original PR/commit references required by the existing checkpoint validator. Group related work by analyst workflow or user impact. Explain the resulting behavior in short, concrete entries. Highlights summarize the release; avoid repeating their full descriptions in Changes. Internal cleanup, tests, CI, and routine documentation generally belong only in the provenance file. Read ambiguous PRs/diffs before making claims. Distinguish simulated-provider checks from real-provider verification. Credit each represented contribution once in the public notes with its link and `Thanks @...` for its verified human author, known co-authors, and confirmed closing-issue reporters. Grouping preserves all those credits in one line. When Highlights, detailed entries or migrations reference the same work, put its thanks in one of those entries, not all of them. Include issue links. Direct-commit bullets carry the commit link and known human credit. Exclude GitHub bots and known agent accounts. REA's observed Anthropic, Cursor, Codex, and Copilot co-author trailers resolve to `@claude`, `@cursoragent`, `@codex`, and `@Copilot` with GitHub type `User`; the credit policy excludes them while retaining their metadata. At the REA maintainer's request, omit `@morluto` self-thanks while preserving authorship in the inventory. Other human contributors remain eligible. Use explicit GitHub links for cross-repository references to avoid ambiguous `#NNN` numbers. Unknown handles stay unknown; they are not fabricated credit. Append the generated `record --summary` provenance link verbatim at the end of this release. The linked inventory accounts for every discovered in-range PR and direct contribution, including internal work omitted from the prose. Do not paste the full `record` output into public notes: it duplicates thanks and obscures the user-facing changes. Full records remain available for review. Do not hand-edit generated credits to make validation pass. Refresh the inventory when product history changes; a prose-only correction can reuse the snapshot. ## Finalize with Release Please Before changing the live release PR, have authorization for that PR update. Local preparation and validation can proceed independently. 1. Add `rea:release-notes-finalized` to the selected open release PR **before** editing its branch/body. Main proposal pushes respect this label. This is our workflow guard, not Release Please's `autorelease: snooze` mechanism. A proposal already running must finish before editing. Do not dispatch manual preparation over finalized notes. 2. On that release branch, save the reviewed inventory as `docs/releases/VERSION.contributions.json`. This is durable public release provenance, not a temporary planning file. Do not add credentials or local environment dumps. Keep the existing version artifacts aligned. 3. Run the existing checkpoint validator and the new checker: ```bash node scripts/release-notes.mjs check \ --manifest docs/releases/VERSION.contributions.json node scripts/release-notes.mjs render \ --manifest docs/releases/VERSION.contributions.json \ --output /tmp/rea-VERSION.notes.md ``` The checker supports inline PR bodies, including their surrounding metadata, up to GitHub's 65,536-character limit. It fails on larger notes rather than truncating credit; Release Please's overflow-link bodies are not integrated. 4. Update the release PR body with the rendered section while preserving its Release Please header/footer and component/version structure. Use a body file for `gh pr edit --body-file`; changing only `CHANGELOG.md` does not change Release Please's release body. Push only authorized changes. 5. Freshly fetch the PR body to a file and run `check --pr-body FILE`. Review the complete diff and wait for current CI. Publication checks the body again before release creation. Avoid further body edits while publishing. The finalization label freezes bot refreshes, not main. New product changes after the inventory target require refreshing the notes before publication. The workflow checks target ancestry and allows only release metadata paths after that target. It also requires the inventory target to equal the reviewed merge's first parent, so intervening main commits require a fresh inventory. Review diffs within the allowed release metadata paths too: the path guard does not prove that package dependency/script edits are version-only changes. To resume automatic proposals, remove the finalization label and let the bot regenerate; expect editorial changes to be replaced. Existing releases without a contribution inventory retain their current publication path. Never retag or republish a package to correct release prose. - .agents/skills/rea-ci-tests-audit/agents/openai.yaml (259 bytes)
interface: display_name: "REA CI and tests audit" short_description: "Audit CI/test correctness and measured performance" default_prompt: "Use $rea-ci-tests-audit to investigate CI and test correctness, drift, and performance before proposing changes."
- .agents/skills/rea-ci-tests-audit/references/measurement-and-ci.md (3894 bytes)
# Measurement and CI checks ## Equivalent completed work Record the source/workflow SHA, command, test identities and counts, skips, assertions or output contract, exit status, coverage scope and thresholds, toolchain/provider versions, host resources, and prepared artifacts. Inspect both the child result and its report: a profiling wrapper may exit successfully after the measured command failed. Focused tests can pass while global coverage thresholds fail; describe both rather than calling the command green. Measure wall time, user/system CPU, and peak process-family memory for relevant completed tasks. Parent-only RSS misses workers and their children. On Linux, summed RSS can double-count shared pages; report RSS/PSS semantics, sampling interval, missing samples, and observed cleanup limits. Use equivalent host tools elsewhere. State unknown costs, including agent tokens; fewer log bytes alone prove neither fewer tokens nor faster tests. Separate cold execution, warm build/file caches, and warm runtime caches. Use repeated or alternating runs when variance affects the decision, with enough observations to distinguish the proposed benefit from noise. Keep workload, instrumentation, and host conditions comparable; record interference. A run with fewer tests, early rejection, lost coverage, or a different runner does not prove suite acceleration. CI-wide claims need end-to-end measurements, not an extrapolation from one improved family. ## Workflow, caches, and shared artifacts Trace each reused result from producer to consumers and identify its lifetime. Check key/input coverage against the actual file inventory and result-affecting configuration, environment, generated data, tool versions, and host state. Exercise an affected input change to prove invalidation; exercise an irrelevant change to support reuse where useful. Cache deterministic preparation and static analysis only when their inputs fully describe the result. Verify downloaded artifacts match the expected revision, platform, runtime, and schema. Check restore misses, failed/partial producers, stale reports, removed output files, and consumers after producer failures. Shared writers need output ownership or locks; tests need isolated state, not an unnecessary global lock. Worker counts do not bound children spawned within each test. Preserve intentionally concurrent scenarios while bounding unrelated batches. Check matrix expansion and all job pages before saying CI passed. Inspect required gates after failed, cancelled, and skipped dependencies. `always()` alone does not preserve failures; inspect the aggregation logic. Test/report uploads should retain available diagnostics after failure, while absent or malformed required results must fail closed. Do not demand an optional report from a lane intentionally excluded by the selector. ## Runner waits and console noise Use per-job and per-step timestamps where available. Workflow creation to job start includes dependencies and other delays; it is not necessarily runner queue time. Identify when the job became eligible before attributing waits to runner capacity. If eligibility/queue timestamps are unavailable, report the combined delay and unknown split. Compare equivalent lanes and runner types across enough runs; a single busy runner is not a workflow regression. For console reductions, retain checker exit codes, actionable errors, useful summary counts, and complete machine-readable artifacts. Verify authored code remains in the actual checker inventory when excluding generated outputs. Introduce an authored error as a control; it must still fail. An ignore pattern can hide real source as well as noise. Show that cached reports are restored, stale successful reports cannot mask current failures, and report parse errors remain failures. Measure readability or byte reduction separately from runtime.
- .agents/skills/rea-ci-tests-audit/SKILL.md (7036 bytes)
--- name: rea-ci-tests-audit description: Audit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure. --- # REA CI and tests audit Establish which checks still catch real regressions and which costs can be removed without losing that protection. The outcome may be a verified fix, an evidence-backed recommendation, or an explicit decision to stop. Follow the checkout's `AGENTS.md`, [testing guide](../../../docs/development/testing.md), and [contribution rules](../../../CONTRIBUTING.md). Use their current commands and pinned toolchain, rather than commands remembered from an earlier audit. Preserve the requested scope: investigation alone does not authorize edits; this skill does not grant permission to publish issues, push, or merge. Existing user authorization still applies. Keep audit notes and raw results outside the tracked tree, normally in a task-specific `/tmp` directory. ## Establish the executed baseline Fetch when the user asks for latest main. Pin the baseline SHA and inspected workflow revision; use an isolated worktree when changing or comparing code. Do not modify another task's checkout. Record dirty changes and the exact command, toolchain, host, selected tests, instrumentation, and prerequisites. An old run is evidence for its executed revision, even if main advances. Trace workflow triggers, changed-path selection, job dependencies, reusable actions, package scripts, test discovery, artifact producers, and report gates through to the commands that actually execute. Include scripts, generated data, runtime registration, and subprocess boundaries missing from import graphs. Check positive and negative selection paths: required files must be discovered once per intended test configuration; deliberate platform/configuration repeats are separate coverage. A missing explicit test or missing required report must not turn green. Optional lanes may skip; preserve their stated prerequisites. Use existing timing and failure artifacts to select suspicious families. Run relevant checks to establish a baseline; reserve a full local suite for broad CI diagnosis or uncertainty that focused checks cannot resolve. Do not rebuild or rerun an unchanged complete suite after every documentation edit. ## Prove the failure or protection For each candidate, state the expected observable behavior and its owner, then construct the smallest reproduction against production behavior. Follow the producer and affected consumers before deciding where to fix it. - For drift, compare fixtures with current admission requirements, protocol replies, named contracts, tool versions, and actual public entrypoints. A plausible-looking mock can fail before the behavior its test claims to cover. Search the whole affected fixture family, including other version strings. Preserve intentionally malformed fixtures and test their intended rejection. - For a suspicious green test, perturb the relevant behavior in an isolated copy or inject a controlled failure. Verify that the existing assertion or gate detects it. A test may merely repeat its mock, import abandoned code, or hide a subprocess/checker failure. Restore mutations after the experiment. - For shared setup or pruning, map distinct assertions to their retained scenarios. Preserve malformed inputs, cancellation, cleanup failure, permissions, capacity, identity, and meaningful concurrency interactions. A faster run that skips a case or weakens its oracle is not an improvement. - For provider coverage, separate fake-producer, boundary, and actual-engine evidence. Inspect named skips and prerequisites; fixtures do not establish real Ghidra, LLDB, browser, or other provider behavior. Classify findings as reproduced defects, supported costs, hypotheses, or unavailable evidence. Record the baseline command, observed output/exit status, expected result, affected scope, and competing explanation. A failure on main may be pre-existing; that does not by itself make it irrelevant to a CI audit. Attribute PR failures using the executed revision and a clean baseline, not just their resemblance to a previous failure. Retry only to test a specific transient explanation; retain the original failure and stop when repetition adds no evidence. A passing retry does not establish a root cause or a fix. ## Assess efficiency without losing the gate Read [measurement and CI checks](references/measurement-and-ci.md) when investigating slowness, caching, runner waits, shared artifacts, or log noise. Compare equivalent completed work before claiming a speedup. Distinguish setup/build time, test execution, coverage instrumentation, dependency waits, and runner scheduling; state which costs remain unmeasured. Prefer removing proven duplicate preparation, reusing immutable setup, and reducing repeated subprocess work before shrinking correctness coverage. Preserve independent sessions where lifecycle or concurrency is the oracle. Keep live tests fresh; a cached previous pass cannot validate current host, installed provider contents, permissions, or external state. ## Fix, verify, and hand off within scope If implementation is authorized, make the smallest structural change at the owning boundary and add a regression that fails on the baseline for the right reason. Retest affected consumers and meaningful negative paths; verify cache invalidation or discovery when those mechanisms change. Read the installed Turbo documentation before changing its configuration or commands. Run the repository's applicable checks and inspect complete current-head CI results before an authorized merge. Preserve required coverage and discovery gates. Do not suppress a failure, add blanket retries, raise timeouts, or delete distinct assertions solely to make CI green. Changes to these controls need their own demonstrated reason and retained failure detection. A slow-host failure at a literal test, child, or wait deadline belongs to the [test deadline policy](../../../docs/development/testing.md#developer-commands): remove the literal rather than raise it, and keep promptness oracles explicit. Report each confirmed issue with exact revision, reproduction, consequence, proposed correction, and validation limits. Report performance with workload and measurements, not just a percentage. Use English issue/PR records when requested; follow the user's assignment, commit identity, review, and merge preferences without assuming them for other users. Open ready-for-review PRs only when that lifecycle is authorized. Resolve necessary review findings and check final main against the tested tree after merging. Stop when the authorized work is verified, remaining benefits are unproven, or further changes would trade correctness for speculative speed. List genuine uncertainties without turning them into additional optimization rounds.
- .agents/skills/rea-tool-design/SKILL.md (2546 bytes)
--- name: rea-tool-design description: Audit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics. --- # REA tool design Use the [tool-design guide](../../../docs/development/tool-design.md) for tool boundaries, contract semantics, provider ownership, and discoverability. Inspect the current contract and nearest existing tool relevant to the analyst question; source, documentation, and live catalogs may describe different versions. For provider-backed work, exercise the analyst's task through REA and compare relevant native provider and independent artifact observations where available. Check applicable partial results, recovery and session boundaries; report what was not exercised. For failure guidance, follow [design recovery around the failure](../../../docs/development/tool-design.md#design-recovery-around-the-failure). Use [workflow verification](../../../docs/development/testing.md#provider-backed-workflow-verification) to select evidence for the proposed contract instead of seeking provider API parity. For an audit, follow [audit existing tools](../../../docs/development/tool-design.md#audit-existing-tools): scope representative tasks, exercise the live workflow, and distinguish reproduced bugs, supported limitations, design opportunities and unverified claims. Check relevant rendered MCP prompts, guided workflows and packaged skill advice against the live contracts and exercise their suggested handoffs. Report working alternatives and evidence limits as well as findings. For wording audits and agent trials, use [focused tool-description trials](../../../docs/development/client-verification.md#focused-tool-description-trials). Start with representative workflow boundaries and repeat failures or ambiguous outcomes; keep actual arguments and supported final claims separate. Reuse the repository's evaluation tooling and report actual runtime/model versions and synthetic versus production coverage rather than copying a harness into a skill. For a design request, return the proposed boundary, input/result shape, Evidence semantics, nearest alternative, and verification approach. Implement when requested, preserving the user's scope and existing authorization. For implementation or verification, consult [testing](../../../docs/development/testing.md) for the affected consumer and provider lanes, and [contributing](../../../CONTRIBUTING.md) for generated-file ownership. Read provider/workflow guides only as the task requires.
- .agents/skills/reverse-engineer-anything/references/android-applications.md (4092 bytes)
# 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. For JNI implementations, discover `inspect_android_jni_bindings`. Select raw DEX class/method identities and optional descriptors, ABI or logical library paths. Prefer `detail: "summary"`; complete Evidence remains retained and `android-jni` views page declarations, libraries, candidates or binding rows with exact fields. Global native-pair ambiguity survives class selection. Preserve slot/relocation provenance and source coverage: matched means observed candidate presence; partial scans do not establish uniqueness or absence. This reads DEX/ELF bytes without loading the APK into the decompiler or executing target code. Runtime registration and loading remain unknown. See the [JNI guide](https://github.com/morluto/rea/blob/main/docs/guides/android/android-analysis.md#link-native-declarations-to-jni-candidates). For an R8/ProGuard release build with its `mapping.txt`, pass the absolute `mapping_path` to `inspect_android_class` or `inspect_android_method`. Prefer `detail: "summary"` to receive normalized symbols or the selected body without duplicate raw class metadata. Complete Evidence stays retained under the linked parent ID and can be exported; CLI summary delivery requires `--evidence_output`. Omitted or complete detail preserves the full inline response. Keep selecting by observed names; the separate `mapping` block reports each symbol as `mapped`, `ambiguous` or `unmapped` after checking DEX types and prototypes. REA does not verify that the mapping belongs to the APK build. 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. Use `rea doctor --provider jadx --json` to check the JADX configuration and obtain remediation for missing prerequisites. Java and the headless JADX MCP JAR remain caller-supplied; REA setup does not install or configure them. Configuration readiness does not establish successful analysis of a particular APK. 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 (integer milliseconds from 1 to 2147483647, default 120000). To change that deadline on a running MCP server, set `jadx.operation_timeout_ms` through `update_analysis_settings`, then retry after work and cleanup settle. Newly accepted operations use the override; accepted work keeps its budget. Changing the launch environment requires a new process. The MCP client's tool timeout must also allow the selected deadline. 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`.
- .agents/skills/reverse-engineer-anything/references/connection-and-recovery.md (19728 bytes)
# 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. Tool-name prefixes belong to the client: find the canonical REA operation in its actual tool listing and server association before concluding that it is absent. A shared prefix alone does not establish which server an approval wildcard covers. See [client tool names and discovery](https://github.com/morluto/rea/blob/main/docs/getting-started/client-configuration.md#client-tool-names-and-discovery). ## Choose the remedy from the observed failure | Observation | Meaning and next step | | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | No REA tools in the active session | If REA was installed as a client plugin, follow the plugin section below. Otherwise 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 connection dropped or REA could not start | If the connection drops, retry that call once only when it is safe to repeat or known not to have started. If it may already have changed the target, or the same failure returns, tell the user REA's connection failed and ask them to restart the MCP client. If REA could not start its connection, retry once, then tell the user and ask them to restart the MCP client. Do not retry a startup failure that returns the same unchanged result. Run `rea doctor` when REA could not start or tools stay missing after restart. Doctor cannot restore a live connection by itself. | | `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. Request `{"detail": "complete"}` only for provider diagnostics. | | `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. ## Distinguish client and server deadlines A host message such as `timed out awaiting tools/call` with no REA result means the client's deadline expired before a result arrived. It does not establish that REA finished, canceled successfully, or released all resources. Do not repeat the unchanged analysis. Inspect available session/provider state and retained Evidence only when useful; an idle `binary_session` is not proof that every target-free operation stopped. Never invent a missing Evidence reference. Allow the host tool deadline to cover execution, cancellation/cleanup, and response delivery. In Codex, the setting is `mcp_servers.<server-id>.tool_timeout_sec` in **seconds**, not `startup_timeout_sec`. Select a value for the actual operation budget and headroom, not a universal timeout. See the [official MCP configuration reference](https://learn.chatgpt.com/docs/extend/mcp?surface=cli). Apply configuration changes only within the authorized scope, preserving unrelated entries and backups; reconnect/restart as required by the host. When configuration is not editable, report the setting needed or use an authorized CLI fallback. Do not silently broaden permissions or switch targets. A returned REA `provider_timeout` instead means the **server/provider** reached its deadline. Follow its `remediation.action`, reuse accessible partial Evidence, and resolve reported incomplete cleanup before retrying. Change a request field or a `REA_*` setting only when the returned remediation explicitly recommends that change. Restart REA when that text says the value is read at startup. A mention that a control does not raise the deadline is not a recommendation to change it. Do not invent a setting the remediation does not name. Raising only the client deadline does not change this server budget. For static JavaScript, `analysis_timeout_ms` (CLI `rea analyze-javascript-application <path> --analysis-timeout-ms <milliseconds>`) controls each source's startup, analysis and transfer deadline in **milliseconds**. Increase that budget or reduce semantic work / select exact inventoried `source_paths` when the task permits. Omit `source_paths` for all sources; `[]` is invalid. `detail: "summary"` reduces delivery, not analysis work. A per-source budget does not bound the elapsed time for an entire multi-source application. Partial-Evidence inspection can avoid recomputation; an unavailable reader is not itself a reason to block a corrected static-analysis retry. The shorthand `rea analyze <path>` does not expose this timeout flag; use the explicit JavaScript command when changing that budget. For invalid arguments, use the connected tool's current input schema, or the installed CLI's command help. Refresh the catalog if stale; do not guess fields from an older skill or return the entire catalog to repair one field. Correct all reported fields before retrying. ## Recovery ladder Follow the returned remediation. Change a request field or a `REA_*` setting only when that text explicitly recommends the change. Restart REA when it says the value is read at startup. A mention that a control does not raise a limit is not a recommendation to change it. Do not invent a setting. Host memory and `NODE_OPTIONS` do not raise a REA admission unless that remediation says so. - MCP connection dropped: retry that call once only when it is safe to repeat or known not to have started. If it may already have changed the target, or it fails again, tell the user REA's connection failed and ask them to restart the MCP client. Do not run `rea doctor` for the drop itself. - REA could not start its connection: retry once, then tell the user and ask them to restart the MCP client. Run `rea doctor` when REA could not start or tools stay missing after that restart. Do not retry a startup failure that returns the same unchanged result. - `cleanup_incomplete`, or retained cleanup owners in the error details: retry that exact cleanup owner. Do not start new work that needs those resources until that owner confirms release. Repeating the original call is not that retry. - Capacity, when the result is `resource_constraint` and `retryable` is true: wait for the active admission to finish, then retry within the reported limits. Do not restart REA to free the slot. - `configuration_invalid`: when the error reports `update_mode: "runtime"`, call `update_analysis_settings` for that setting. When it reports `update_mode: "parameter"`, change that call's argument; the setter does not accept it. Otherwise correct the named setting in the environment that starts REA (the shell or the MCP registration) and start REA again. Run `rea doctor` to see the `runtime-configuration:` check. Re-run `rea setup` for that client when the registration must carry the new setting, then reconnect. - `invalid_request`: correct the reported fields from the current schema. Do not repeat the unchanged call. ## REA installed as a client plugin A Claude Code, Codex, or Cursor Marketplace plugin owns its `rea` server and this skill. Doctor's `--client` and `--skill` checks and `rea setup` read and write only setup-owned state, so for a plugin-only install they report `missing`, and applying setup would add a second `rea` server. If this skill was loaded from a plugin, or the client lists a `rea` plugin, do not prepare a setup plan for missing tools. Instead: - Check that the plugin is installed and enabled with the client's own listing: `claude plugin list` and `/mcp` in Claude Code, `codex plugin list` in Codex, and Cursor's plugin settings for a Marketplace install. - Restart or reconnect the client, then read its launch error for the `rea` server if tools are still absent. Claude Code and Codex start the plugin's bundled runtime; a missing build or version mismatch requires a reinstall, or a fresh build when developing from source. A Cursor Marketplace install starts `npx` at the version pinned in the plugin's `mcp.json`. A failed download needs network access to that published version. - Check analysis engines through the connected server's `binary_session.result.tool_availability`. `rea doctor --provider <id> --json` from a shell reports that shell's environment, which can differ from the environment the client gave the plugin server. If you still run it through the package runner, use the version pinned in the plugin manifest's server entry (`rea-agents@<version>`), not `@latest`, so it matches the server the plugin starts. Use the setup repair below only when the user wants a setup-owned registration instead of the plugin, and remove or disable the plugin first. ## 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`, `codebuddy`, `cline`, `gemini_cli`, `windsurf`, `devin`, `opencode`, `antigravity`, `copilot_cli`, `commandcode`, `qwen_code`, `kimi`, `vscode`, `trae`, `workbuddy`, `lm_studio`, `grok_build`, `omp`, `pi`, `hermes`, `qoder`, `droid`, `zcode`, `dsh`, `freebuff`, `cline_vscode`, `cline_vscode_insiders`, `cline_vscodium`, `cline_cursor`, `cline_windsurf`, `kiro`, `mastracode`, `zed`, `amp`, `mcporter`, `fx`, `junie`, `goose`, `kilo`, or `grok_ - .agents/skills/reverse-engineer-anything/references/desktop-build.md (51806 bytes)
# Desktop app environments from a request Use this when someone asks for an environment of a Linux desktop app with a task, such as "Build me an Inkscape environment where the agent changes a poster's headline and saves it". You are the building agent: you drive the app on a build computer through REA's MCP tools, write the task, export the bundle and witness it in a fresh computer. REA runs no model. The tools are MCP-only and need a Linux host with Docker, agentenv and REA's packed runtime. When a start reports one missing, tell the person to run `rea doctor --provider desktop_build` and apply its fixes, or `rea setup --client <client> --desktop-build` and restart the client, and stop. For the whole build: - Drive the app only with `act_on_build_computer`. Never script it, run commands in the computer or write its files another way. The one command you write for the computer is a task's reader, which REA runs to check a file; it never makes the seed or the edit. - Ask the upfront questions once, then work on your own. Pause only when blocked. - The seed's content is synthetic. Never put real personal data in it. - Close every computer you start, on success and on failure. - Note the time you start; the report gives the build time. ## Ask once, upfront In one message, ask only what the request leaves open, and keep the list for the report. Skip each question the request answers; when it answers them all, start without asking: 1. The app and the task, if either is unclear: what changes, in which document. 2. Whether they have a starting file of their own; otherwise you make one. 3. Whether they want the tasks measured after the witness: with which model, within which budget, and whether to harden a task until it lands in the band. 4. If so, whether they want to review the tasks before those solves. When you cannot ask, as in a headless `claude -p` run, do not stop: take these defaults for whatever the request leaves open, say which you took in your first message and in the report, and go on. Install from the Ubuntu archive, make a synthetic seed, skip the review, and measure each task within $4 in all, with the model the request names, without hardening. ## When you are blocked Stop, say what you need and wait only for: - a licence the app or its installer asks someone to accept: never accept it on your own; name it and where to read it, and go on only once the person says they accept it. Then record their words with `record_build_consent`, kind `licence`, and accept it on their behalf; - credentials: ask the person to write each secret, and nothing else, in a file named after a handle you choose, such as `keepassxc-master`, in `~/.config/rea/build-secrets/` on this host (under `$XDG_CONFIG_HOME` when it is set), readable only by them (`chmod 600`), and wait until they say it is there; then type it with `type_secret` (see Drive the app). Never ask for a password or key in chat, and never read, list or print that folder; - a signed-in state in the seed: by default the export withholds it (see Sign-in and licence state). Seed it only when the person says the bundle may hold it: record their words with `record_build_consent`, kind `seed_sign_in`, and export with `seed_sign_in: true`; - an install this flow cannot do, below. Decide everything else yourself and note it in the report. ## Sign-in and licence state What an app writes when someone signs in or activates a licence is withheld from the seed: the bundle's receiver supplies their own. Mark `pre-sign-in` with `mark_build_checkpoint` just before the sign-in or activation and `post-sign-in` just after, both before `seed`: every file under the owned paths that changed between them is withheld, and the draft leaves it out. A file the app writes at first launch, such as a trial's licence file, changes before you can mark anything: name it in `export_build_environment`'s `withhold`. The export lists each withheld file in `withheld_files` with the environment variable a deploy reads it from and the handle of the secret REA keeps its bytes in; a check may not name one. The export refuses a seed file holding a withheld file's exact bytes, such as a `.bak` copy, but a backup that differs from it is not caught: trash backups before `seed`. Explicitly withhold any other files the person identifies as sensitive; REA does not infer secrecy from a value's shape or a file name. ## Choose the install The computer is Ubuntu 24.04 (noble) on this host's architecture only. Use the first source that has the app: | Source | `install` | | ---------------------------- | ------------------------------------------------------------------------------------------- | | Ubuntu archive | `{"kind": "archive", "package": "inkscape"}` | | PPA or vendor apt repository | `{"kind": "apt_repository", "package", "uri", "suite", "components", "key_file"}` | | `.deb` by URL | `{"kind": "package_file", "url", "sha256", "architecture", "dependencies"}` | | AppImage by URL | `{"kind": "appimage", "url", "sha256", "architecture", "extra_packages"}` | | Tarball by URL | `{"kind": "tarball", "url", "sha256", "architecture", "program", "name", "extra_packages"}` | - A PPA's `uri` is `https://ppa.launchpadcontent.net/OWNER/NAME/ubuntu`, `suite` `noble`, `components` `["main"]`. `key_file` is the repository's signing key saved on this host; for a PPA, fetch it from keyserver.ubuntu.com by the fingerprint its Launchpad page shows. - When the app exits at launch for want of a runtime piece its package does not install, start a new build computer with that package in `extra_packages`, up to 16 archive names; the export installs them too. MyPaint needs `{"kind": "archive", "package": "mypaint", "extra_packages": ["librsvg2-common"]}` for its SVG icons, and Freeplane `["openjdk-17-jre"]`, since its launcher refuses noble's Java 21. Name one up front, too, when a package the app only recommends holds its content, such as QElectroTech's element library `qelectrotech-data`, without which no component can be placed. - Take the `.deb` path only when the app is not in the archive at all, not to add a package. Ask the requester for its URL and SHA-256; do not fetch a vendor's download page yourself. List its `Depends` as `dependencies`, with any runtime piece it lacks: it installs with the network off. - Take an AppImage or a tarball only when no package has the app. Pin it by the release file's URL for this host's architecture and the SHA-256 its project publishes, such as a GitHub release asset's digest or the release's `SHA256SUMS`; ask the requester when the project publishes none. The computer downloads it when the bundle is put, refuses other bytes, and unpacks it under `/opt/rea-apps/<desktop_entry>` with the network off; the export downloads the same file. - An AppImage installs its own desktop entry, so `desktop_entry` is the `.desktop` file at the top of the image, such as FreeCAD's `org.freecad.FreeCAD`. A wrong name fails the start with the entries the image has: start again with one of them. The image brings its libraries, so `extra_packages` is rarely needed; FreeCAD 1.1.4's needs none. - A tarball has no entry of its own. `program` is the program's path inside the archive, such as `firefox/firefox`; REA writes an entry named `desktop_entry` that runs it with the files it opens, and `name` is what the Applications menu shows. A tarball uses the computer's libraries: name what its program lacks in `extra_packages`. gzip, bzip2 and xz archives are read, zstd ones are not. - Flatpak and snaps are not supported: say so and stop. Flatpak's sandbox needs user namespaces the computer's container does not grant, so a Flathub app installs but never opens; ask for the project's AppImage, tarball or `.deb` when it ships one. An archive package that only installs a snap, such as noble's `firefox`, counts as a snap. A package with no build for this host's architecture (some PPAs are amd64 only) cannot be installed either. - `desktop_entry` is the package's `.desktop` file name under `/usr/share/applications` without `.desktop`, such as `org.inkscape.Inkscape`. Add `window_class` when you know it; Inkscape's is `Inkscape`. AbiWord's entry is `abiword` and its class `Abiword`. - To find the entry, read the package's file list: its page on packages.ubuntu.com, or `apt-get download PKG && dpkg -c PKG_*.deb` where apt runs. The entry may ship in a companion `-data` or `-common` package, as Planner's in `planner-data`: read that package's list too. The entry's `StartupWMClass` may not be the window's real class, so do not take `window_class` from it: MuseScore 3's says `mscore3`, its window's is `MuseScore3`. The export uses the class the capture saw. ## Drive the app - Pass `computer_id` and the action's fields at the top level: click `{x, y, count}`, scroll `{x, y, direction, amount}`, a screenshot region `[x0, y0, x1, y1]`. The rest are in [the build-computer guide](https://github.com/morluto/rea/blob/main/docs/desktop-build-computer.md). - Take a `screenshot` before pointing: points are pixels of the latest frame. If a response is too large, ask for a `region`, or `jpeg` with a lower `quality`. A screenshot with `region` does not capture the screen again; it crops the latest frame, so take a full screenshot, or a `wait` with `screenshot: true`, first. The crop then becomes the latest frame: take a full screenshot before pointing again. - A drawn caret does not prove keyboard focus. After using a toolbar control, click into the document, then type a few characters and look before a long text. - Confirm a dialog with `key` Return, not a trailing `\n` in `type`. - An action's own screenshot is taken at once. After opening a menu, a dialog or a window, look with `{"action": "wait", "ms": 500, "screenshot": true}`. - On a computer started from a request the app is not open at first, and `start_build_capture` opens it: never open it yourself before that. Do not close it while capturing; the capture ends when the app exits. When the app is closed at any other time, open it from Applications → Other → the environment's name. - Type a secret with `{"action": "type_secret", "secret": "<handle>"}`, only into a field that masks what is typed: check in a screenshot that it is a password field, which shows dots. A screenshot shows any field that shows its text, such as many licence-key boxes, so never type a secret into one: say the app needs a secret the build cannot type unseen, and stop. `type_secret` takes no `screenshot`; look with a `wait` after it. A refusal names the secret's file and what is wrong with it: tell the person, never the value. - Prefer shortcuts and typing to long pointer paths: `key` takes `keys`, an array holding one chord's keys, such as `{"action": "key", "keys": ["Control", "s"]}`, and `type` turns `\n` into Enter. - Before `type`, check in a screenshot that a text cursor or a focused field is there. In apps with single-key shortcuts, such as Inkscape, text typed without one runs as commands. - Save As differs by app. Check the dialog's current folder first: most open in the home, so click Documents in the sidebar, but Scribus opens in `~/Documents` and its sidebar has no Documents entry. Type only the file name. A dialog taller than the 1280×800 screen hides its buttons: maximize it from its title bar, or confirm it with `key` Return, as when HomeBank's Save button is off-screen. When a GTK Save dialog ignores clicks or runs off the screen, type `~/Documents/<name>` in its Name field and press Return. - Answer the app's save questions, such as keeping the format, then check the saved path in the title or status bar, or the dialog's folder when the app shows only the name, and that it shows no unsaved mark, before you mark a checkpoint or check. Where the title never shows one, as in HomeBank, a greyed Save or Revert, or the file reopened from recent files, confirms the save. - Qt spin boxes change their value on scroll: move the pointer off them before you scroll. - gLabels edits an object's text in Object properties → Text, not on the canvas. - In Grisbi's transaction form Return moves to the next field; only Return in the last field, Notes, records the transaction. - ghostwriter autosaves a new document as `~/Documents/untitled-1.md`: name it with File → Rename, not Save As; Ctrl+Shift+S does nothing, and Enter after a checklist item starts another `- [ ]` item. - KMyMoney's first launch opens the New File Setup wizard; Finish asks for a storage type (XML), then a Save As where typing `Documents/<name>.kmy` works. Its date field is a sectioned Qt editor: double-click the month and type each part, since Ctrl+A garbles it. A new transaction's payee comes prefilled and selected. Amounts are saved as reduced fractions, such as `-1749/20`, so compare them exactly. Untick Help → Tip of the Day → "Show tips on startup" before `seed`, or the tip appears at every boot. - QElectroTech: an element dropped from Collections follows the pointer until a click on the folio places it. Its title shows only the app, so it needs `state_paths`; its settings are in `~/.qet`. - Rosegarden: after a dialog its Transport window can take keyboard focus, so save with File → Save. - Pencil2D: the Tools dock is too narrow for its buttons, so use shortcuts (B for the brush); double-click a layer's name to rename it. - Umbrello: the title shows no unsaved mark, so confirm a save with a probe checkpoint. An Untitled document autosaves `~/autosave.xmi`: delete it before `seed`. Add attributes from the tree: right-click the class → New → Attribute. - Hydrogen: the computer has no audio device, so Hydrogen falls back to a null driver and its BPM field snaps back to 120 within about 100 ms. Before `seed`, set Preferences → Audio System → ALSA with device `null` and click "Apply and restart output", which `~/.hydrogen/hydrogen.conf` keeps for the seed; also set autosaves per hour to 0, and dismiss the development-version dialog with "Don't show again". `pulseaudio` as an extra package does not help. - Poedit cannot add entries by hand. Use File → New, pick the language and save to `Documents` first (Sources Paths stays locked until then), then Properties → Sources Paths → + → Add Files with a source such as `/usr/lib/python3.12/argparse.py`. It writes `fr.mo` beside the `.po`, and the language box's autocomplete popup takes the first OK click. - CherryTree: its first-run autosave "Choose Storage Type" dialog swallows - .agents/skills/reverse-engineer-anything/references/environments.md (22010 bytes)
# Agent environments from a live application Use this when the user asks for an agent environment (an AgentEnv bundle) of a web application: a folder `agent-env` deploys, whose MCP tools answer from what one recording of the application observed and serve the writes that recording confirmed. The workflow records the application once with `capture_browser_scenario`, checks what the environment would serve, records again if a hint names a gap, then writes the bundle with `export_environment_bundle`. For a HAR the user already has, skip to [export](#export-and-hand-off) through `inspect_web_network_capture`, or use `rea environment-build <capture.har> <dir>`. For a task in a desktop application's exported environment, read [its section](#tasks-for-a-desktop-application-environment). ## Before recording - Record only against an instance the user says is disposable or seeded for this purpose: every write step creates, edits or deletes its data. If the user has not said so, ask before any scenario that writes. REA does not start, seed or reset applications. - Credentials come from environment variables the user names. Declare each as a scenario secret, `{secret_id, environment_variable}`; the variable must be set in the environment REA's MCP server started with. Never ask for a password in chat. Declared secrets are redacted as the capture records. - Map the application first with `inspect_web_page` (and `capture_web_screenshot` when layout matters): the login form's locators, and the API calls behind the pages that list and edit the entities the user asked about. - `inspect_web_page` cannot sign in. To see pages behind sign-in, run a short `capture_browser_scenario` that signs in and opens them, with `"capture": {"after_each_step": ["accessibility"]}` (`"dom"` for markup). Read a step's tree with `inspect_analysis_view`, `view: {kind: "browser-scenario", collection: "text", step_index, artifact: "accessibility", offset: 0, limit: 2048}`, paging with `offset`. Capture options are only `after_each_step`, `at_end`, `events`, `network` and `limits`. ## Record a session an environment can learn writes from One `capture_browser_scenario` records the whole session. Start from this shape, with the application's own locators, paths and headers: ```json { "browser": { "mode": "launch", "executable_path": "/usr/bin/chromium" }, "start_url": { "url": "http://127.0.0.1:3000/login" }, "secrets": [ { "secret_id": "admin_password", "environment_variable": "APP_PASSWORD" } ], "capture": { "network": { "request_body": true, "response_body": true, "header_values": true } }, "actions": [ { "step_id": "user", "action": "fill", "timeout_ms": 15000, "locator": { "kind": "css", "selector": "input[name=username]" }, "value": { "source": "literal", "value": "admin" } }, { "step_id": "password", "action": "fill", "timeout_ms": 15000, "locator": { "kind": "css", "selector": "input[name=password]" }, "value": { "source": "secret", "secret_id": "admin_password" } }, { "step_id": "sign-in", "action": "press", "timeout_ms": 15000, "locator": { "kind": "css", "selector": "input[name=password]" }, "key": "Enter" }, { "step_id": "signed-in", "action": "wait_for", "timeout_ms": 15000, "locator": { "kind": "css", "selector": "nav a[href='/settings']" }, "state": "visible" }, { "step_id": "folders-1", "action": "request", "timeout_ms": 15000, "method": "GET", "path": "/api/folders", "expected_status": [200] }, { "step_id": "new-folder-1", "action": "click", "timeout_ms": 15000, "locator": { "kind": "role", "role": "button", "name": "New folder" } }, { "step_id": "folder-title-1", "action": "fill", "timeout_ms": 15000, "locator": { "kind": "css", "selector": "input[name=title]" }, "value": { "source": "literal", "value": "Scratch folder 1" } }, { "step_id": "create-folder-1", "action": "click", "timeout_ms": 15000, "locator": { "kind": "role", "role": "button", "name": "Create" }, "save_response": { "method": "POST", "path": "/api/folders", "save": [{ "name": "folder_1", "json_pointer": "/id" }] } }, { "step_id": "read-folder-1", "action": "request", "timeout_ms": 15000, "method": "GET", "path": "/api/folders/{saved:folder_1}", "expected_status": [200] } ] } ``` Give each step that accepts `timeout_ms` a deadline. Without one, a step waits until it completes or the scenario is cancelled, so a locator that never matches hangs the capture and the client with it. The `wait_for_timeout` pause instead uses `duration_ms` and does not accept `timeout_ms`. Match `wait_for` locators to exactly one element. 1. Sign in through the UI: `fill` the user and password fields (the password as a secret reference), submit, then `wait_for` an element only a signed-in user sees. 2. Read with `request` steps: each collection the environment needs, twice before any write, so fields that change on their own show up; then each object a list shows by id, up to ten per collection. An object known only from a list that leaves out fields its own read shows cannot be read by id or updated in the environment. 3. Write the way the application's UI does: fill its forms and click its buttons, so each request carries the fields the UI sends, including ones the server would otherwise derive. Give the click or key press that submits a create `save_response` to keep the new object's ID, then `goto` its page (`/items/{saved:item_1}`) or read it with a `request` step. Never guess an ID, and never create a probe object to learn the next one. Write with `request` steps instead only when the UI cannot reach the operation (an API-only resource, or a UI that does not call the JSON API), or when coverage withholds the UI-shaped write as `unexplained-change` or `contradicted`; that counts as one of the two re-recordings. A `request` step write that coverage withholds that way usually lacks fields the UI sends: record it through the UI instead. If a journey cannot be scripted, leave the write unserved and report the limitation. Record two numbered scratch objects per write type, with varied free text. After each write, and before the next one, read the object back by id and then its list: create 1, read 1, list, create 2, read 2, list; never several writes before their reads. 4. Leave more than a second between two creates and between a create and its first edit (`wait_for_timeout` with `duration_ms: 1100`), so lists sorted by creation time show them in order. 5. Update both objects and read each back, changing the fields a person would change (a name, an email address, a status, a due date) rather than only a description: a served update accepts only the members a recorded update stored. Run an action that turns something on or off (star, bookmark, archive) twice in a row on one object, reading it back after each: the second call shows whether it sets or flips the field, and the environment serves the action only once a call has shown it. Delete both and read each back (expect 404, or the object marked deleted) and the list. 6. Vary what the two creates send, however you write them: the first every field the application takes, the second only what a person must give (its title or name), with the other fields left out or empty. A served create requires each member both creates filled in and lets a caller leave out one a create left out or sent empty, so an agent that names only a title is not refused for fields it had no reason to set. About `request` steps: - `path` is on the start URL's origin; the page must be on that origin. - Header values are literals, declared secrets, a cookie the browser holds (`{source: "cookie", name}`), a local storage entry (`{source: "local_storage", key, json_pointer}`), a saved value (`{source: "saved", name}`), or Basic credentials (`{source: "basic_credentials", parts: [username, password]}`, sent as the base64 of `username:password` and redacted), with an optional `prefix` such as `"Bearer "` or `"Basic "`. Each credential part is a literal, secret, saved value, cookie or local storage entry, so a header the frontend builds from a login token (the username and the token) can be copied too; the password is a secret or saved value, never a literal. Copy the headers the application's own requests send (a CSRF header such as `X-CSRFToken` from the `csrftoken` cookie, a bearer token). Values read from the page are redacted from records made after they are read, not from the login response that returned them, and values shorter than 8 characters are not redacted at all. - `save: [{name, json_pointer, secret}]` keeps a string or number from the step's JSON response, such as the created object's `/id`, for later steps; `secret: true` redacts it, as for a token the API returns, so mark every saved token, key or session value secret. This also protects the selected source response before its body or headers are retained. Compressed or unknown-size UI responses cannot supply saved values. On a `click` or `press`, `save_response: {method, path, save}` keeps values from the response to the new request observed while the step waits (`{*}` in `path` matches one segment). Matching does not prove UI causality: choose a path distinct from polling; multiple observed matches fail as ambiguous. The step fails unless a 2xx JSON response arrives before its `timeout_ms`. Later steps send a saved value as `{saved:name}` in a request `path` (and its query) or a `goto` URL; in the `json` body, where a string that is only `{saved:name}` keeps the saved JSON type; or as `{source: "saved", name}` in a header or credential part. - Reading a page value makes later bodies costlier to keep: after a CSRF token, bodies over about 47 KiB are kept as `unavailable`. When the API returns larger responses, raise `capture.limits` (`max_network_body_allocation_bytes`, `max_total_event_allocation_bytes`). - Request steps follow no redirects: a redirect fails the step, and `expected_status` cannot name a 3xx status. Use the path the redirect names, such as the one with the trailing slash. - Set `expected_status` on every step, so a refused call fails its step and the later steps report not having run, instead of recording read-backs of nothing. Keep it to about 60 to 160 requests. A scenario with no `request` step is recorded exactly as before. The capture returns its whole Evidence, every recorded body included, which is often more than a client shows inline. Before checking coverage, confirm that every entry of `normalized_result.steps` has `status: "completed"`; if the client saved the result to a file, search it for `"status":"failed"` and read that step's `error`. A failed sign-in or write cancels every step after it. Use the result's `evidence_id` for coverage and export; do not paste the Evidence back into another tool. ## Check coverage `inspect_analysis_view` with `source: {kind: "retained-evidence", evidence_id}` (the capture's id) and `view: {kind: "environment-coverage", template_rules: ["after-uid-literal", "opaque-token", "sibling-variance", "prefix-variance"]}`. It reports read tools answered from the state or replayed (`reads.recorded_reasons`), the served write tools, and each withheld write with its `reason` and `hint`. It does not apply the serve-time catalog and state size checks; the export reports those. Re-record a withheld write at most twice, and only for a recording gap. Stop at once when the reason is application behaviour, and report the write as withheld with its hint: | Reason | What to do | | --------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `no-state-target` | Check the path template and recorded views; record missing reads. The route form may not be supported as a mutation target. | | `no-observation` | Re-record: read the entity back by id after the write; read it first for an update or delete. | | `unconfirmed` | Re-record: read the entity and its list after the write. | | `incomplete-entities` | Re-record: read the entity through every view that lists it. | | `unexplained-change` | Re-record once with a second, different call of the same write. | | `no-call` | Re-record once with a write that succeeds. | | `side-effect` | Stop: the application changes other entities. | | `contradicted` | Stop: a later read disagrees with the modelled effect. | | `body-unusable` | Re-record a UI write once with `request` steps (its body was not exposed); else stop. | Use new scratch names on each attempt, and delete what an earlier attempt created before recording again (through the UI, or a `request` step with the id that capture shows): the environment starts from what the recording first reads, so a leftover object becomes seeded data that write tasks then find. New browser scenario captures include request times, so a fully timed capture can learn a write clock and serve updates that stamp modification times. Older captures or ones missing a request start keep record order and learn no clock. When coverage reports that limitation, record again with the current version before concluding that the timestamp change cannot be served. ## Export and hand off `export_environment_bundle` with `source: {kind: "retained-evidence", evidence_id}` (or `{kind: "evidence-file", path}`), an absolute `output_directory` that does not exist yet and whose parent does, and a `name` (required when the application runs on `localhost` or an IP address). It returns the coverage again, `tool_count`, the written files and warnings; `dry_run: true` reports without writing. The bundle installs `rea-agents` of this REA's version from the registry; when the user runs an unreleased REA build, pass the `package_tarball` they give you - .agents/skills/reverse-engineer-anything/references/evidence-workflows.md (12418 bytes)
# 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. For any logical Evidence source that advertises retained references, pass `{kind: "retained-evidence", evidence_id}` instead of copying the complete record back into a call. The same contract covers individual, optional, array and nested sources across native, process, JavaScript, managed, mobile and WASM workflows. Sources can independently mix inline records and exact references. Resolution preserves the source's identity, provenance, coverage, partial facts and unknowns; it neither reruns analysis nor makes incomplete facts complete. Keep domain role and identity requirements: a native dossier cannot substitute for a managed member observation, for example. When starting from a summary or inspection page, use its `normalized_result.parent_evidence_id` to reference the complete source. The view's own `evidence_id` names only that view. `compare_artifacts` explicitly supports artifact summary inputs and resolves their parents; do not assume every consumer does. When a workflow follows source links, keep those linked records available too. MCP references belong to the current connection's ledger. If the ID is known, pass it directly; no discovery call or provider setup is needed. If it is missing, import the exported bundle or supply complete inline Evidence. Do not retry an unchanged reference or rerun a producer merely to move an existing record. Export before closing the session when the source must survive it. For CLI JSON workflows that advertise `--evidence-bundle`, the same reference JSON resolves against one explicitly selected authenticated bundle: ```bash rea trace-application-feature request.json --evidence-bundle /absolute/path/evidence.json --json ``` This includes JavaScript traces/comparisons and runtime reconciliation, managed reconstruction/native verification/graph projection, Android/Apple/Harmony graph projection, WASM interface comparison and retained analysis views. The managed member comparison CLI still takes two assembly paths; process comparison takes two capture Evidence JSON paths. Check command help for the installed version. An input bundle grants no implicit file lookup: `evidence-file` and historical graph file selectors are accepted only by contracts advertising them. See the [CLI reuse guide](https://github.com/morluto/rea/blob/main/docs/getting-started/cli.md#import-export-and-compare-evidence). 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. For native procedure/name/string inventories, select `detail: "summary"` when the connected tool advertises it and the task needs counts or selected rows. Use its parent Evidence ID with `view: {kind: "native-inventory", offset: 0, limit: 32, fields: ["value"]}`. Search tools retain the existing pattern/mode/case/document selection. Omit `fields` for complete records; `record.address` and `source_index` remain on selected rows. Selecting `value` keeps its string/decoding qualifications. Parent Evidence ID plus source index preserves same-address alternatives. Follow `coverage.next_offset` only as far as the question needs; exhausting retained rows does not establish complete program discovery. `batch_decompile` returns every body unless you select `detail: "summary"` when the connected tool advertises it. Use its parent Evidence ID with `view: {kind: "batch-decompile", collection: "items"}` for body-free rows and exact `where.indices`, `addresses`, `procedure_addresses` or `statuses`. Add `include_pseudocode: true` for several chosen bodies, or use `collection: "pseudocode"` with one row's `index` to page a large body. Batch limitations aggregate every item, so do not attribute them to one successful row. Use `record_unknown` to track unresolved questions in the user's investigation and name the authority or environment still required. Supply supporting and contradicting evidence IDs. It updates the session registry directly. 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. Name each side as `{kind: "retained-evidence", evidence_id}` (an `inspect_artifact` result, its nested inventory or its summary) or `{kind: "evidence-file", path, evidence_id?}` instead of resending Evidence. - `compare_functions` compares explicit function Evidence, not fuzzy whole-binary matches. It rejects an `analyze_function` summary reply; pass the summary's `parent_evidence_id` as a `retained-evidence` reference or the complete dossier. - `compare_bundles` compares canonical bundle membership and unknown history. - `find_changed_behavior` combines existing comparisons; static differences remain candidates, not causal proof. Its `comparisons` accept exact references. - `build_call_path` needs explicit function dossiers from one artifact/provider; pass complete parent IDs in `functions`. An incomplete frontier makes absence unknown. - `correlate_static_and_runtime` uses explicit mappings; matching patterns are hypotheses, not causality. Both comparison arrays accept exact references. - `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. Use `inspect_analysis_view` with `view: {kind: "environment-manifest"}` on the same retained HAR Evidence to project the primary origin's request lines into named tools with path templates, parameters, observed query names, value-free body shapes and record pointers for an agent environment. Opt into `template_rules` only when recorded identifiers need them; every template, parameter and merged sibling is an inference, no header, cookie or body value is copied, and the three stated unknowns stay unresolved. Use `view: {kind: "environment-state"}` with the manifest's `template_rules` to extract the data those reads observed instead: entity types and identity fields, entities with recorded values, documents, and per-tool render plans checked against the recordings. The state comes only from reads before the first related write; types, identity and list membership are inferences. The view also gives each state-changing tool a write plan, served only when a later recorded read confirms its effect and none contradicts it. `rea environment-serve manifest.json --evidence capture.json` derives that state at startup, answers read tools from it, serves the write tools whose plan is served, each applying its effect to that state, and serves `data/reset`, `data/add` and `data/get` on `/agentenv`; other write tools are not served, and each plan states why in its `reason`. It replays the capture instead with `--replay-only` or when the state is unavailable (not derivable, or a catalog over the discovery budget), and its stopped document's `state` says which applied. Use `view: {kind: "environment-coverage"}` with the same rules to see what an environment built from a capture would serve: read tools answered from the state or replayed with their reason, and each write tool served or withheld with a hint about what to record next; it does not apply the serve-time catalog and state size checks. `rea environment-build <capture.har> <dir>` inspects, projects and exports in one step and prints the same coverage, or `null` when the bundle serves replay. For a PE/ELF export question, `inspect_native_exports` accepts `detail: "summary"` and retains the complete table. Query `inspect_analysis_view` with `view: {kind: "native-exports", collection: "exports", names: ["selected_name"], fields: ["name"], offset: 0, limit: 32}` and the reported parent Evidence ID. All same-name versions and aliases survive; use `source_index` with the parent ID for stable identity. `collection: "issues"` pages interpretation failures. Page coverage describes selected retained rows; `summary.coverage` or `exports.coverage` still describes the source table, so an empty partial page does not prove absence. CLI `inspect-native-exports --detail summary --evidence_output PATH` saves the complete bundle for later `inspect-analysis-view --evidence-bundle PATH` requests. For an ELF load-time dependency question, `inspect_elf_dependencies` accepts `detail: "summary"` and retains the complete inventory. Query `inspect_analysis_view` with `view: {kind: "elf-dependencies", collection: "needed" | "versions" | "definitions" | "maxima" | "imports", names: ["selected_name"], fields: ["name"], offset: 0, limit: 32}` and the reported parent Evidence ID. Collection `"maxima"` matches `names` against namespaces such as `GLIBC` and selects `fields` from `namespace`, `maximum`, and `evidence_kind`, for example `fields: ["namespace", "maximum"]`. Collection `"issues"` takes only `indices`, `offset`, and `limit`. Duplicate `DT_NEEDED` names survive; use `source_index` with the parent ID for stable identity. Page coverage describes selected retained rows; `summary.coverage` or `dependencies.coverage` still describes the source tables, so an empty partial page does not prove absence. CLI `inspect-elf-dependencies --detail summary --evidence_output PATH` saves the complete bundle for later `inspect-analysis-view --evidence-bundle PATH` requests. - .agents/skills/reverse-engineer-anything/references/javascript-applications.md (16246 bytes)
# 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/guides/javascript/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, or `--source-paths-json` with a JSON file for selections too long for one command line. Omit the selection when the question requires complete application analysis; `source_paths: []` is invalid, not an unfiltered request. `detail: "summary"` reduces delivery and does not by itself reduce analysis work. To locate member paths in a packaged `app.asar`, call `open_binary` and then `inspect_artifact` with `detail: "summary"`. Use `normalized_result.parent_evidence_id` with `inspect_analysis_view` to find member paths. Pass the selected paths as `source_paths` to `analyze_javascript_application`. Narrowing the source selection reduces analysis work. The inventory still examines the archive. If unpacked companions differ from their declared digests after re-signing and you intend to preserve those contradictions, pass `integrity_policy: "record-and-continue"` to `inspect_artifact`, `analyze_javascript_application`, and `extract_artifact` when you call them. The default `fail` policy returns `artifact_integrity_mismatch` when an operation encounters the contradiction, including the initial inventory. ASAR header/index admission defaults to 16 MiB / 16777216 bytes; an admission error names `asar.max_header_bytes` and its bounds (at most 256 MiB). Call `update_analysis_settings` with that setting, `action: "set"` and enough bytes, then retry the same full-archive request. No inspection or REA restart is required. `REA_ASAR_MAX_HEADER_BYTES` seeds future REA processes. `source_paths`, `detail`, and `max_heap_mb` do not bypass or raise header admission. Runtime JavaScript timeout/heap defaults are also editable; explicit per-call `analysis_timeout_ms` and `max_heap_mb` take precedence. 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 or the client's tool deadline. For a host timeout without REA output, use the [deadline recovery guide](connection-and-recovery.md#distinguish-client-and-server-deadlines) instead of raising the server budget. 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. ## Inventory route candidates without returning the application graph When the advertised schema supports `view`, use `detail: "summary"` with `view: {kind: "javascript-routes", collection: "routes", fields: ["path", "confidence"], limit: 20}`. The same view works with `analyze_web_bundle` on already selected captured sources. The complete source Evidence is retained; use its `parent_evidence_id` with `inspect_analysis_view` for `summary`, `routes`, `occurrences`, `sources`, or `unknowns`. Filter and batch IDs before requesting more fields, and follow `coverage.next_offset`. CLI selections require `--evidence_output` to keep the complete record. Static patterns, inferred deployment bases, heuristic system classification, and unavailable sources never establish route reachability or the complete application route denominator. See the [route inventory guide](https://github.com/morluto/rea/blob/main/docs/javascript-route-inventory.md). For captured endpoint observations and inference facts, `analyze_web_bundle` also accepts `view: {kind: "web-bundle", collection: "endpoints", limit: 32}` with `detail: "summary"`. Read later `endpoints`, `inferences`, or `summary` pages from the retained parent. Filter before requesting detail; retain `source_index` together with parent ID and collection, and request `location` or `basis` when tracing sources. Page exhaustion does not mean producer completeness: check `completeness`, structured `source_unknowns`, and limitations. Endpoint candidates remain inferences rather than confirmed network behavior. ## 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. For a broad trace, pass `view: {"kind": "feature-trace", "collection": "paths"}` (or `summary`) to retain the complete trace and read terminal paths first; page `nodes` or `edges` with exact `where.node_ids` through `inspect_analysis_view` as needed. 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. For summary or inspection replies, select the complete `normalized_result.parent_evidence_id`. Native observation arrays and runtime reconciliation's `static_layers[].analysis` and `runtime_observations[]` also accept exact references where advertised. Each source can independently be inline or retained, preserving identity, coverage and unknowns. CLI workflows advertising `--evidence-bundle` resolve these inputs from the explicitly selected bundle. `close_binary` releases the engine while retaining references and complete Unknown history on the same MCP connection. `reset_inv - .agents/skills/reverse-engineer-anything/references/native-and-artifacts.md (67757 bytes)
# Native, managed, and packaged artifacts For release comparisons on one MCP connection, retain `list_procedures` Evidence from each target and reuse its exact IDs after target switches or `close_binary`. For a handoff or new process, export the complete bundle and import it there, including its source closure. `reset_investigation` explicitly clears retained records; optional `save_path` checkpoints them before clearing. `match_native_functions` pairs unique exact names and, when supplied, complete observed body bytes. Reuse optional same-context `list_names`, `procedure_info`, `read_bytes` and existing `analyze_function` dossiers as `left_observations`/`right_observations`; an MCP `analyze_function` summary reply contributes its `parent_evidence_id` as a `retained-evidence` reference, not the summary itself. Avoid decompiling every function merely to match it. Its summary retains a parent for `inspect_analysis_view` `function-matches` collections `matches` and `functions`. Select columns, batch IDs and page individual facts; aliases remain unresolved. Unpaired observations do not prove additions/removals. Existing matched dossier pairs include inputs for `compare_functions`; otherwise analyze just chosen pairs. Aggregate completed comparisons with `find_changed_behavior`, selecting each comparison's exact `retained-evidence` ID instead of resending full records. Inline comparison Evidence remains accepted. References belong to the current server: after handoff, import the original bundle including its source closure. Do not substitute dossier IDs or summary views. Static differences remain behavior candidates, with runtime behavior unknown unless separately observed. For a matching representation refusal, inspect `details.limit` and raise `native.matching_representation_bytes` with `update_analysis_settings` before retrying the unchanged MCP request. CLI launch seed: `REA_NATIVE_MATCHING_REPRESENTATION_BYTES`. The default is 96 MiB; the policy range is 1 byte to 1 GiB and does not bound process RSS. Keep the complete inventories: splitting them changes global name/body uniqueness. ## Apple app resources Use `open_bundle_resources` with the selected app path, then `inspect_plist`, `decode_interface_builder`, `inspect_asset_catalog`, or `inspect_keyed_archive`. The resource session reads the app without resolving `CFBundleExecutable` or starting a deep provider. Preserve `resource_root` provenance, per-resource hashes where reported, and null executable identity; a directory path is not an executable digest. Export retained Evidence before closing or switching roots. Binary analysis snapshots do not apply. Use `open_binary` to switch to executable analysis, and `close_binary` to release either session kind. The four matching CLI commands accept the app path directly. For an archive inside the app, use `inspect-keyed-archive APP_PATH RELATIVE_ARCHIVE_PATH`. Host requirements for plist and compiled asset/Interface Builder tooling still apply; a resource-only session does not establish provider availability. ## Desktop installation directories When an installation directory is supplied and its runtime is unknown, use `inspect_desktop_application` with its absolute path. Default MCP summary delivery retains complete Evidence. Read `files`, `omissions`, `candidates`, `components` or `next_probes` with `inspect_analysis_view` kind `desktop-application`, selecting exact paths, batched file/omission IDs or families and only needed fields and pages. Summary `probe_issues` retains counts and bounded previews. Select files with `has_issues: true` and fields `path`, `read_status`, `issues` to retrieve exact failures directly; preview text is display data, while `file_id` selects full facts. Preserve source coverage, read-range identity and unknowns; directory snapshot identity is not a digest of every file's contents. Component path markers do not establish runtime presence. For compact CLI output, use `inspect-desktop-application PATH --detail summary --evidence_output BUNDLE`. See [desktop installations](https://github.com/morluto/rea/blob/main/docs/desktop-applications.md). ## Release exposure Use `audit_release_exposure` (`rea audit-release-exposure PATH`) when the question is what static analysis of a shipped `.app`, install directory, ASAR, or executable recovers. Each check has a stable id, a status, the observation behind it, and fixed remediation. Unknown and unassessed checks stay in the report. The report does not establish that the application is secure. `text.credential_markers` reports a rule id and location only. Matched bytes, previews, lengths, and hashes of matched bytes are omitted. `native.hardening`, `macho.hardened_runtime`, and `android.manifest` are not assessed here. Their next probes are `inspect_binary_hardening`, `inspect_signature`, and `inspect_android_package`. See [release exposure](https://github.com/morluto/rea/blob/main/docs/release-exposure.md). ## Go build metadata Use `inspect_go_binary` for an explicit local ELF, PE or Mach-O (universal files need `architecture`) when the question concerns the embedded compiler version, module/dependency versions, local replacements, build settings, or static Go string literals packed without NUL terminators. Pass `include_string_literals: true` (`--include-string-literals`, optional `max_string_literals` / `--max-string-literals`) to recover bounded inferred word-aligned `(ptr, len)` UTF-8 string slices from read-only data and page them through `go` `string_literals` views. 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, and static `(ptr, len)` string recovery excludes compiler-inlined stack/immediate strings without proving runtime reachability. Function, source and type recovery remain a separate native-analysis question. For a scanner, project the retained parent with `inspect_analysis_view` kind `cyclonedx`. That document is CycloneDX 1.6, reads no target bytes, and states `compositions` as incomplete or unknown. See [CycloneDX dependencies](https://github.com/morluto/rea/blob/main/docs/guides/native/cyclonedx-view.md). ## Model files Use `inspect_model_artifact` (`inspect-model-artifact PATH`) for local GGUF v2/v3 and safetensors declarations without a model runtime. Header-only mode does not read weights or establish full-file identity. `hash: "full"` explicitly streams all bytes. Retained `model-artifact` views page `metadata`, `tensors` and derived `types`, with exact batch filters and selected fields. Arrays retain typed counts and eight-element previews; omitted values, unknown types and runtime behavior stay explicit. See [model files](https://github.com/morluto/rea/blob/main/docs/model-artifacts.md). ## IL2CPP metadata Use `inspect_il2cpp_metadata` for an explicit local Unity `global-metadata.dat` (versions 24, 27, 29, 31 and 39) when the question concerns assembly images, names, member owners, string literals, namespaces or index ranges. No `open_binary`, Unity installation or target execution is required. The CLI equivalent is `inspect-il2cpp-metadata PATH`. MCP defaults to counts with complete retained Evidence. Query `sections`, `images`, `types`, `methods`, `fields`, `properties`, `events`, `parameters` or `string_literals` through `inspect_analysis_view`; use exact names, batch indices and selected fields. Row indices are scoped by artifact SHA-256 and collection; page offsets count filtered matches. Parameters support batch `method_indices` to read one method's parameters directly. Historical reports without member collections retain unknown counts rather than empty inventories. Preserve artifact SHA-256 and index widths. Unrecognized magic may mean encryption and is unsupported, not decrypted. Linking names to `GameAssembly` or `UnityFramework` code addresses remains a separate native-analysis question. See [IL2CPP metadata](https://github.com/morluto/rea/blob/main/docs/il2cpp-metadata.md). ## Rust dependency metadata Use `inspect_rust_binary` for an explicit local ELF, PE, Mach-O (universal files need `architecture`), or WebAssembly core module when the question concerns the cargo-auditable crate list embedded in `.dep-v0` (Mach-O: `__DATA,.dep-v0`; WebAssembly: a custom section). 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. WebAssembly reports `bits: null` on a `32 | 64 | null` word size; null means the container declares no word size and must not be coerced to a number. ELF, PE and Mach-O stay 32 or 64. Components such as `wasm32-wasip2` output are unsupported. A rustc commit hash is inferred from a `/rustc/<40-hex>/` path in read-only data or a WebAssembly data section and does not by itself identify the compiler. Project the retained parent with `inspect_analysis_view` kind `cyclonedx` for one CycloneDX 1.6 document. Build-kind packages are `scope: excluded`. See [Rust binaries](https://github.com/morluto/rea/blob/main/docs/rust-binaries.md) and [CycloneDX dependencies](https://github.com/morluto/rea/blob/main/docs/guides/native/cyclonedx-view.md). ## Maven POM and Gradle module metadata Use `inspect_maven_gradle_metadata` for an explicit local Maven `pom.xml` or Gradle `.module` file when the question concerns declared coordinates, dependency scopes and exclusions, BOM or platform constraints, or unresolved property and parent references. No `open_binary`, Maven, Gradle, or repository access is required. The CLI equivalent is `inspect-maven-gradle-metadata PATH`. Preserve artifact SHA-256, versions as spelled, and `unresolved` entries. Interpolation and inheritance are not performed. A missing version is not a resolved BOM selection. See [Maven POM and Gradle module metadata](https://github.com/morluto/rea/blob/main/docs/maven-gradle-metadata.md). ## PE Authenticode certificate tables Use `inspect_pe_certificates` for an explicit local PE32/PE32+ image when the question concerns the Authenticode certificate table, WIN_CERTIFICATE types, or embedded PKCS#7 signer and X.509 identity fields. No `open_binary`, Windows SDK, or target execution is required. The CLI equivalent is `inspect-pe-certificates PATH`. Preserve artifact SHA-256, table file ranges, payload hashes, original validity-time spellings, and `subject_key_identifier_hex` when the signer uses that form. A missing `IMAGE_DIRECTORY_ENTRY_SECURITY` directory is observed absence of that table, not proof the image is unsigned in every catalog or overlay sense. Signatures, chains, timestamps, and Authenticode digest coverage remain unobserved. See [PE Authenticode certificate tables](https://github.com/morluto/rea/blob/main/docs/pe-certificates.md). ## PE import and delay-load tables Use `inspect_pe_imports` for an explicit local PE32/PE32+ image when the question concerns imported DLL and function names, ordinals, delay-load descriptors, or the pefile import hash. No `open_binary`, Windows SDK, or target execution is required. The CLI equivalent is `inspect-pe-imports PATH`. Preserve artifact SHA-256, directory file ranges, original DLL spellings, and ILT/IAT RVAs. A missing `IMAGE_DIRECTORY_ENTRY_IMPORT` directory is observed absence of that table, not proof the image never imported APIs through another table or overlay. Bound snapshots, loaded IAT contents, and export-forward resolution remain unobserved. See [PE import and delay-load tables](https://github.com/morluto/rea/blob/main/docs/pe-imports.md). ## Windows Shell Link shortcuts Use `inspect_windows_shortcut` for an explicit local `.lnk` file when the question concerns the recorded target path, arguments, working directory, icon location, volume serial, network share names, ExtraData blocks, or Tracker droid identifiers. No `open_binary`, Windows SDK, COM, or target execution is required. The CLI equivalent is `inspect-windows-shortcut PATH`. Preserve artifact SHA-256, FILETIME raw decimals, IDList type bytes, and ExtraData signatures. Unknown IDList items and ExtraData signatures remain raw with SHA-256; they are not guessed. Version-1 UUID MAC and timestamp values are labelled derived. A missing optional section is observed absence of that structure. See [Windows Shell Link shortcuts](https://github.com/morluto/rea/blob/main/docs/guides/native/windows-shortcut.md). ## PE TLS callbacks and load configuration Use `inspect_pe_load_config` for an explicit local PE32/PE32+ image when the question concerns code that runs before the entry point through TLS callbacks, or the security cookie, SafeSEH, CFG, EH-continuation and XFG declarations in the load configuration. No `open_binary`, Windows SDK, or target execution is required. The CLI equivalent is `inspect-pe-load-config PATH`. Preserve artifact SHA-256, directory and callback-array file ranges, and callback VAs as hexadecimal strings. Fields outside the declared `Size` are `null`. Guard-flag mitigations carry `evidence_kind: "inferred"`; enforcement remains unobserved. See [PE TLS callbacks and load configuration](https://github.com/morluto/rea/blob/main/docs/pe-load-config.md). ## Binary hardening Use `inspect_binary_hardening` for an explicit local ELF, PE, or Mach-O file when the question concerns PIE or ASLR, NX, RELRO, stack-protector or FORTIFY signs, control-flow flags, or stripped state. No `open_binary`, pwntools, or target execution is required. The CLI equivalent is `inspect-binary-hardening PATH`. Universal Mach-O files return one image per slice. A missing import is `unknown`, not proof the protection was omitted. Authenticode and Mach-O code-signature rows report presence, not validity. `hardened_runtime` stays unknown and names `inspect_signature`. See [binary hardening](https://github.com/morluto/rea/blob/main/docs/binary-hardening.md). ## ELF note tables Use `inspect_elf_notes` for an explicit local ELF32/ELF64 image when the question concerns PT_NOTE/SHT_NOTE owners or supported note metadata. Treat FDO package and dlopen fields as producer declarations. No `open_binary` or target execution is required. The CLI equivalent is `inspect-elf-notes PATH`. Preserve artifact SHA-256, table file ranges, descriptor hashes, and original owner spellings. A missing table is observed absence of those declarations, not proof the image never carried notes in another container. See [ELF note tables](https://github.com/morluto/rea/blob/main/docs/elf-notes.md). ## DWARF compile units Use `inspect_dwarf_units` for an explicit local ELF, Mach-O, or PE image when the questio
- .agents/skills/reverse-engineer-anything/references/runtime-observation.md (13171 bytes)
# Runtime observation ## Native runtime questions Start from the requested observation. State the selected target, input, expected result, failure signal and stopping condition before a run. Reuse static Evidence to choose a function or hypothesis; `trace_native_values` follows recovered static value dependencies and does not measure runtime values. Prefer static inspection or existing capture comparison when it already answers the question. | Question | Existing workflow | Host and effects | | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Which selected native entry is reached, with which integer argument registers? | `observe_native_calls` on the active Mach-O, with exact function/Objective-C breakpoints and a duration/event bound | macOS with LLDB and required debugger access. Launches a new owned process, stops at entries, records and continues; target execution may write files, show UI or use the network. It never attaches to an existing process. Inspect termination and partial coverage after the run. | | What does caller-authored instrumentation observe? | `list_frida_devices` / `list_frida_processes` when discovery is needed; `start_frida_session`, `load_frida_script`, then status/unload/close | Requires compatible installed Frida bindings and selected device access; the real REA verifier covers Linux. Attach selects an existing PID; spawn selects a program and starts it paused until `resume_frida_session`. Scripts execute in the target and can change memory, files, network activity and behavior. This is not passive inspection. | | Which debugger state or controlled execution explains the behavior? | `start_gdb_session` and `gdb_console`, or `start_rizin_debug_session` and `rizin_debug_command` | Persistent debugger workflows are Linux-only. GDB can hash/load an initial `executable` without running it; select it at startup when initial file identity matters. Console commands can load/attach/run other targets without rebinding that initial identity. Rizin debug start launches the selected target and requires a durable `inferior_tty`. Both consoles are unrestricted and can change target memory/registers, run shell commands, write files and use the network. | | How do terminal output, process lifetime and selected files differ between runs? | `capture_process_scenario`, then `compare_process_captures` with compatible recorded inputs | New captures require Linux or macOS and a working native PTY backend; macOS also needs `xcrun`/Swift for ownership inspection. Capture launches an owned command with ordinary user permissions. Observation paths select snapshots, not a filesystem sandbox. Comparing retained captures does not execute targets and is also available on Windows. | | What does an existing desktop window show, or what changes after a declared UI action? | `observe_native_ui`; use `capture_native_ui_scenario` only for requested actions | macOS 14+ with required Screen Recording/Accessibility access. Select an existing PID/window. Observation does not launch or own the app; scenario actions can change its data or trigger network activity, and leave its state as-is. | Close each persistent session with its matching tool. `close_frida_session` unloads scripts and detaches; it does not kill the target. A still-paused spawn is resumed only after instrumentation cleanup is confirmed. GDB and Rizin close can detach a live inferior and let it continue only after verifying its durable output terminal. When disposition or cleanup is unresolved, preserve the owned session and reported recovery; do not assume that closing the debugger terminated the target. Process capture and LLDB call observation instead own their launched processes and report their termination/cleanup outcome. Cancellation is not proof that cleanup completed. Unrestricted GDB/Rizin commands and relevant start/close operations retire an active binary-analysis session in the same MCP server. Close an active Ghidra session explicitly first; after target effects settle, reopen the artifact before new static analysis. A Cutter bridge command is likewise unrestricted and may affect its GUI/target; it is not a passive native observation substitute. To test a static hypothesis across two builds, retain compatible static comparison Evidence and `compare_process_captures` Evidence. Supply explicit finding/dimension mappings to `correlate_static_and_runtime`. It does not ingest arbitrary Frida, LLDB or debugger traces, auto-match names, or prove causality from cochange. Preserve those traces as their own Evidence and leave unobserved behavior unknown. Record truncation, unmatched breakpoints, changed target identity and cleanup uncertainty as limitations, rather than treating no retained event as proof that the behavior never occurs. For same-session MCP comparisons, pass each capture inline or reuse it as `{"kind":"retained-evidence","evidence_id":"ev_..."}`. Default comparison keeps capture-local timing as provenance without treating scheduler or observer latency as a behavior change; use an exact `trace_spec` event when timing is part of the analyst question. Detailed contracts and prerequisites: [Frida](https://github.com/morluto/rea/blob/main/docs/guides/runtime/frida-instrumentation.md), [GDB/Rizin/Cutter](https://github.com/morluto/rea/blob/main/docs/reverse-engineering-tools.md), [process capture](https://github.com/morluto/rea/blob/main/docs/guides/runtime/process-capture.md), and [native calls/UI](https://github.com/morluto/rea/blob/main/docs/guides/native/native-investigation.md#native-desktop-observation). ## Browser and Electron 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. For multi-step flows with trees or events, select `detail: "summary"` and page exact steps, transactions, text slices or events with `inspect_analysis_view` kind `browser-scenario`. 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. For selected protobuf/gRPC bodies, keep raw bytes as the source and use `inspect_analysis_view` kind `protobuf`, collection `bodies`, `frames` or `fields`. Batch exact record ordinals and field numbers/IDs, and select `schema_value` or `text` only when needed. Supply a local descriptor set and message type for schema interpretation; compressed payloads remain unknown. 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/guides/web/web-network-captures.md) for the workflow and Telerik's public setup and traffic-debugging skills. - .agents/skills/reverse-engineer-anything/SKILL.md (48345 bytes)
--- name: reverse-engineer-anything description: Reverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. 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: "63" --- # REA Use REA when a claim depends on a shipped binary or package, decompilation, requested 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. The exception is a Claude Code, Codex, or Cursor Marketplace plugin install: the plugin bundles this skill and registers its own `rea` server, outside the state that `rea setup` and `rea doctor` manage. 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. If the host times out without a REA result, do not repeat the unchanged call or assume work stopped. Read the recovery guide's deadline distinction before retrying. If the MCP connection drops, retry that call once only when it is safe to repeat or known not to have started. If it may already have changed the target, or it fails again, tell the user and ask them to restart the MCP client. If REA could not start its connection, retry once, then tell the user and ask them to restart the MCP client. Do not retry a startup failure that returns the same unchanged result. For plugin installs, follow [plugin recovery](references/connection-and-recovery.md#rea-installed-as-a-client-plugin). For setup-owned registrations, run `rea doctor` when REA could not start or tools stay missing after that restart. For `cleanup_incomplete`, a retryable capacity limit, or `configuration_invalid`, follow the recovery guide's ladder before asking for a restart. Read that guide before a second repair attempt. Choose the installation owner before repairing registration. Plugin installs use [plugin recovery](references/connection-and-recovery.md#rea-installed-as-a-client-plugin); only setup-owned registrations use the guide's [registration repair plan](references/connection-and-recovery.md#repair-registration-when-needed). A plugin-only doctor result of `missing` does not call for `rea 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 an existing installation’s absolute runtime and entry script, or continue through the CLI. A concrete CLI fallback for an operator-supplied JavaScript tree or ASAR is: ```bash npx -y rea-agents@latest 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@latest` in its place from a trusted directory outside the target project, with absolute target paths. Managed setup binds the current installation directly; retain its runtime and package cache entry, or restore that installation before repairing its registration. For setup-owned registration, 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. ## 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`. To find a few files in a packaged `app.asar`, open it with `open_binary`, start with `inspect_artifact` using `detail: "summary"`, then analyze the selected files with `source_paths`. When you intend to retain digest contradictions from re-signed unpacked companions, pass `integrity_policy: "record-and-continue"` starting with `inspect_artifact`. See the [JavaScript applications reference](references/javascript-applications.md). - Archive/package member inventory (ZIP/APK/IPA/MSIX/AppX, DMG, or a PyInstaller executable): `open_binary` with the supplied local path; use `inspect_artifact` when its graph and findings help answer the question. A PyInstaller CArchive is the application layer; the bootloader is only the native prefix. Start with `detail: "summary"` for large inventories, then use retained inventory views for selected member fields/pages. A complete small inventory can cost less than extra calls and schemas. Runtime options are metadata, not files. Compact delivery still inventories and hashes members. See the [Python packaged applications guide](https://github.com/morluto/rea/blob/main/docs/python-packaged-applications.md). - Bun `--compile` executable: `open_binary`, then `inspect_artifact`; the Bun module graph is the application layer. Extract stored modules and analyze the JavaScript. See [Bun standalone executables](https://github.com/morluto/rea/blob/main/docs/bun-standalone.md). - Deno `deno compile` executable: `open_binary`, then `inspect_artifact`; the embedded virtual filesystem is the application layer. Extract stored files and analyze compatible JavaScript. Environment-file values and CA certificate bytes are retained in local Evidence with their counts and byte lengths. The npm snapshot length is reported and not decoded, and the executable is not run. See [Deno compile executables](https://github.com/morluto/rea/blob/main/docs/deno-standalone.md). - Apple app plist, Interface Builder, asset catalog, or keyed archive resources: `open_bundle_resources`, then the selected resource tool. This does not require `CFBundleExecutable` or a deep provider. Resource sessions have no executable digest or binary snapshot; use `open_binary` for native code. - 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`. - UEFI firmware volumes and NVAR stores: use bundled `inspect_artifact`. For external firmware scanning or extraction on Linux, use `inspect_firmware_regions` or `extract_firmware` with caller-supplied Binwalk or Unblob. Extraction needs a caller-selected new absolute output directory. See the [firmware guide](https://github.com/morluto/rea/blob/main/docs/guides/firmware/firmware-analysis.md). - ESP32-family app or bootloader image (`0xE9` magic): `inspect_artifact` without a provider; see the ESP section of `references/native-and-artifacts.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. - Native program behavior, live calls, instrumentation, or command-run effects: choose the matching [native runtime workflow](references/runtime-observation.md#native-runtime-questions). `open_binary` and `trace_native_values` establish static facts; they do not observe execution. Runtime tools have distinct launch, attach, mutation and cleanup effects, and do not require a preliminary static session unless their own contract says so. - User-owned browser page already open: `list_browser_targets`. - Passive traffic capture of a SPA: the default scope is the page's own origin, and data APIs usually live on another origin. Discover API origins from absolute URLs in loaded bundles or script text via JavaScript analysis tools (another passive capture without those origins still scopes to the page origin, and `completeness.excluded` counts lack URLs). Pass both the page origin and those API origins in `allowed_origins` — the list replaces the default scope — and read `completeness.excluded` before reporting that an API is absent. For long captures with body shapes, use `export_evidence_bundle` instead of expecting an inline result. - 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. - Agent environment (AgentEnv bundle) of a web application: read [environments](references/environments.md) before recording; it records with `capture_browser_scenario` and writes the bundle with `export_environment_bundle`. - Task for a desktop application's exported environment, from a `capture-desktop-application` folder: read [desktop application tasks](references/environments.md#tasks-for-a-desktop-application-environment). - Environment of a Linux desktop app with a task, from a request such as "build me an Inkscape environment where the agent changes a poster's headline": read [desktop builds](references/desktop-build.md). You drive the app on a build computer from `start_build_computer`, then export and witness. - 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. HAR/SAZ/qlog old-generation heap is `REA_CAPTURE_DECODER_OLD_GENERATION_MIB` (default 192 MiB, floor 8, maximum 16384), set where REA starts. Host memory and `NODE_OPTIONS` do not raise it. See [historical captures](https://github.com/morluto/rea/blob/main/docs/guides/web/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`. - Shipped application exposure for a local `.app`, install directory, ASAR, or executable: `audit_release_exposure` / `rea audit-release-exposure`. Each check has a stable id, a status, and fixed remediation. Unknown and unassessed checks stay in the report. This does not establish that an application is secure. Credential-marker hits report the rule id and location only. See [release exposure](https://github.com/morluto/rea/blob/main/docs/release-exposure.md). - 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 TShark 4.x on an absolute `PATH` entry or via the optional absolute `REA_TSHARK_COMMAND` override; see [capture guide](https://github.com/morluto/rea/blob/main/docs/guides/data/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/guides/data/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/guides/signals/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
- .claude-plugin/marketplace.json (581 bytes)
{ "$schema": "https://anthropic.com/claude-code/marketplace.schema.json", "name": "rea", "description": "Reverse engineer anything with agents, from app behavior down to native binaries.", "owner": { "name": "morluto", "url": "https://github.com/morluto" }, "plugins": [ { "name": "rea", "description": "Reverse engineer anything with agents, from app behavior down to native binaries.", "source": { "source": "npm", "package": "rea-agents", "version": "6.10.1" }, "category": "development" } ] } - .claude-plugin/plugin.json (673 bytes)
{ "name": "rea", "version": "6.10.1", "description": "Reverse engineer anything with agents, from app behavior down to native binaries.", "author": { "name": "morluto", "url": "https://github.com/morluto" }, "homepage": "https://rea.tools/", "repository": "https://github.com/morluto/rea", "license": "MIT", "keywords": [ "reverse-engineering", "binary-analysis", "decompiler", "mcp-server" ], "skills": "./skills", "mcpServers": { "rea": { "command": "node", "args": [ "${CLAUDE_PLUGIN_ROOT}/scripts/plugin-mcp-launcher.mjs", "6.10.1" ] } }, "icon": "./assets/rea-plugin.png" } - .codex-plugin/mcp.json (207 bytes)
{ "mcpServers": { "rea": { "command": "node", "args": [ "./scripts/plugin-mcp-launcher.mjs", "6.10.1" ], "cwd": ".", "startup_timeout_sec": 30 } } } - .codex-plugin/plugin.json (1212 bytes)
{ "name": "rea", "version": "6.10.1", "description": "Reverse engineer anything with agents, from app behavior down to native binaries.", "author": { "name": "morluto", "url": "https://github.com/morluto" }, "homepage": "https://rea.tools/", "repository": "https://github.com/morluto/rea", "license": "MIT", "keywords": [ "reverse-engineering", "binary-analysis", "decompiler", "mcp-server" ], "skills": "./skills", "mcpServers": "./.codex-plugin/mcp.json", "interface": { "displayName": "REA", "shortDescription": "Reverse engineer anything", "longDescription": "Reverse engineer anything with agents, from app behavior down to native binaries.", "developerName": "morluto", "category": "Developer Tools", "capabilities": [ "Interactive", "Read", "Write" ], "websiteURL": "https://rea.tools/", "defaultPrompt": [ "Use REA to explain how this binary implements a feature.", "Use REA to compare two versions of this application.", "Use REA to recover the sources from this JavaScript bundle." ], "composerIcon": "./assets/rea-plugin.png", "logo": "./assets/rea-plugin.png" } } - AGENTS.md (13407 bytes)
# Repository Guidelines ## Product and Authority REA is a local-only reverse-engineering tool with shared CLI/MCP workflows. Distinguish observations, derivations, inferences, and unknowns; preserve Evidence provenance and session semantics through both adapters. Provider support and setup live in [README.md](README.md#choosing-a-deep-analysis-provider) and its linked guides. Follow the [contribution scope and fail-closed integration rule](CONTRIBUTING.md#contribution-scope). Do not integrate capabilities while material scope, authority, side-effect, or required verification questions remain unresolved. For new providers or capabilities involving target execution, injection, mutation, or protection recovery, seek the required maintainer scope decision before substantial implementation for integration. Welcome early proposals, small exploratory prototypes, and draft PRs that help resolve questions; they do not authorize integration. Ghidra uses ephemeral databases without modifying executable bytes or controlling a GUI; Windows Ghidra P0 has no mutation authority. IDA analysis is read-only; never save or close an attached GUI database. Configuration changes must be additive and idempotent, with backups. Installers must not install or upgrade unrelated software, including Homebrew, Node.js, npm, Java, or Ghidra. Ghidra and IDA are bring-your-own. `rea setup` must show its planned changes and require approval before writing files or installing Hopper. Preserve caller-selected inputs and local evidence, including output, URLs, paths, digests, and metadata. Redact transport authentication credentials and explicitly marked sensitive values; do not infer secrecy from names or text patterns. Do not persist the ambient environment merely because a child inherits it. ## Architecture and Cleanup Dependencies flow inward: domain semantics and contracts, provider adapters, shared application workflows, then CLI/MCP adapters. Keep engine protocols and provider-specific code out of domain/application layers. Read the relevant wiring in `src/composition/` when changing composition. Give each interpretation and resource a clear owner. Consumers must use that owner's parsed facts rather than reinterpret raw source. Preserve identity, omission, uncertainty, and source evidence across boundaries. Retain ownership of resources whose cleanup failed. Reuse `src/process/` supervision and identity primitives; a PID and executable path alone do not establish ownership after exit or reuse. Keep proof of ownership separate from validity, editability, and readiness. Malformed owned data may still be safely removable. Unresolved identity or applicability must remain unknown rather than be treated as absent, foreign, or aligned. For lifecycle changes, follow [ownership and completion invariants](docs/development/tool-design.md#own-the-lifecycle) and select the applicable [lifecycle regressions](docs/development/testing.md#lifecycle-regressions). Include late handshakes, cancellation during final cleanup, mixed child outcomes, and cleanup retry where those stages exist; active-execution cancellation alone does not cover finalization. Before adding complexity for a speculative or vanishingly unlikely race or security edge case, explain the concrete failure mode, likelihood, and complexity cost to the user and get their buy-in. Do not silently expand scope for theoretical robustness. Check touched code for brittleness during implementation, debugging, review, and maintenance. Look for duplicated decisions, unclear ownership, and assumptions about state or lifecycle. Trace affected behavior through its consumers. Fix the producing representation or ownership rule before adding downstream repairs. When interpreting formatted input, [normalize once at the owning boundary using a format-aware parser](docs/development/tool-design.md#interpret-boundary-facts-once). Include directly related refactoring in the fix. Passing regressions alone cannot establish that the root cause is gone. Remove superseded representations, aliases, wrappers, and redundant tests after verifying affected consumers. Introduce abstractions only when they remove observed complexity. Explain any remaining cleanup and why it remains. Check sibling paths for the same failure, verify suspected matches with working controls, and group findings by root cause. Before resolving a review thread, explain the root cause, structural fix, validation, and any remaining cleanup. Parse unknown boundary values and model expected failures with the tagged error algebra and `Result`. Preserve partial facts and meaningful failure reasons. Keep identity and lookup values separate from display formatting; preserve source values and explicit unknowns when normalization loses information. Absolute paths, file URLs, and HTTP paths have different semantics. Validate advertised JSON Schemas after SDK conversion against their declared dialect and actual clients. Bind handlers to named contracts with exact types; catalog ordering must never select an operation or schema. ## Performance Design analysis workflows and agent interfaces for efficiency from the first implementation. Correctness, useful answers, Evidence provenance, caller choices, compatibility and safe resource bounds remain required. Optimize in this order: 1. Agent tokens and context. Return the smallest sufficient answer with necessary provenance, coverage and limitations. Use task selection, summaries, paging and retained Evidence where supported; honor requested detail and keep complete Evidence accessible. Count the whole task, including schemas, extra calls and retries. 2. Analysis time. Reuse validated results and shared work. Cache keys must cover result-affecting inputs; define invalidation and lifetime. Validate freshness before reporting cached live state as current. 3. CPU and memory. Avoid unnecessary work and copies; bound concurrency, retained state and serialization growth. Reserve performance measurements for changes that target performance or have a concrete regression concern. Routine cleanup uses correctness checks; changes to helper calls, imports, or representations alone do not require synthetic benchmarks. When measurement is warranted, measure representative completed tasks and compare equivalent workflows before and after where available. Report token usage, elapsed time, CPU time and peak process-family memory. Separate cold and warm runs, label estimates, and state unmeasured costs. Fewer bytes alone do not establish fewer tokens or faster analysis. ## Development Treat code as the source of truth for implemented behavior and architecture. Keep specs, implementation plans, task lists, ADRs, and architecture diagrams in issue or pull request discussions or in local drafts outside Git. Use the [documentation directory](docs/README.md) and [authoring guide](docs/development/documentation.md) for guides and references. Use [.nvmrc](.nvmrc) and `package.json#packageManager` for the pinned toolchain. Cursor Cloud may place older Node.js first on `PATH`; environment setup installs the pinned toolchain under `/usr/local/bin`. Prefix `PATH="/usr/local/bin:$PATH"` before `node` and `npm`. - `npm ci`: install locked dependencies. - `npm run build:cached`: build the runtime and packaged skill. - `npm run test:local -- PATH...`: source tests without building. - `npm run test:focused -- PATH...`: exact tests with their required artifacts. - `npm run check:fast`: cached typecheck and lint, plus architecture guards. - `npm run docs:check`: validate generated documentation. Use relevant checks for the change. The complete local gate, `npm run check:pr`, is optional for broad changes or CI diagnosis. See [CONTRIBUTING.md](CONTRIBUTING.md) for development, generated-file ownership, and release conventions. When changing installers or setup recovery, follow [Checking installers and publisher downloads](docs/development/testing.md#checking-installers-and-publisher-downloads). Coordinate expensive checks across agents. If a test unexpectedly consumes heavy CPU, stop its owned process family and profile a bounded representative case before retrying. Inspect production work, fixture generation, subprocesses, and repeated setup; preserve regression coverage when optimizing. Follow the [test resource guidance](docs/development/testing.md#developer-commands). `docs/public/product-catalog.json`, `docs/verification/managed-conformance-*.json`, and `skills/` are ignored outputs. Edit source contracts and `.agents/skills/reverse-engineer-anything/`, then regenerate as needed. Never commit binaries, provider project documents, credentials, `dist/`, `node_modules/`, or local planning artifacts. ## Tool and Test Changes For tool design, follow [docs/development/tool-design.md](docs/development/tool-design.md): start from the analyst question, reuse existing contracts, preserve caller choices, and return useful evidence inline. Limits must follow real format, protocol, authority, or resource constraints. Account for representation expansion before allocation; derive completeness from examined coverage. Choose the scope of a new limit from [analysis settings, limits, and recovery](docs/reference/limits-and-recovery.md). A registered runtime setting may have an optional launch seed. Per-call and launch-only controls have their own contracts. Report the effective limit and recovery for the control that stopped the work, and document the setting ID and `update_analysis_settings` for changes that apply at runtime. For user- or agent-facing tool problems, prioritize fixing the owning behavior, contract, and actionable result or recovery at the point of use. Document the result in product docs when explanation is needed. Add skill guidance only for workflow judgment or context that the tool cannot reasonably convey; do not use a skill as the primary repair for a discoverability or contract defect. For test changes or provider claims, use [docs/development/testing.md](docs/development/testing.md). Select applicable [boundary regressions](docs/development/testing.md#boundary-regressions) for parser, inventory, snapshot, and projection fixes. Prefer real public CLI/MCP workflows, then production-boundary integration, then producer goldens. Keep module tests for distinct semantics stronger workflows cannot reliably reproduce. Preserve malformed-input, cancellation, cleanup, permission, capacity, and target-identity coverage when pruning. Report unverified coverage explicitly; simulated providers do not establish real-provider behavior. Use structured facts to test behavior and assert wording when wording is part of the contract. Follow [test design and pruning](docs/development/testing.md#test-design-and-pruning) and use the [supervised command owner](docs/development/testing.md#verifier-scripts) for commands launched by a verifier. Use Conventional Commit subjects and PR titles as specified under [pull request ownership and readiness](CONTRIBUTING.md#pull-request-ownership-and-readiness). Mark breaking changes with `!` or a `BREAKING CHANGE:` footer. Describe behavior changes, relevant validation, and real-provider verification scope. ## Issue Reports Follow [issue reporting guidance](CONTRIBUTING.md#reporting-issues) and the matching issue form. Keep reports concise and cite the smallest useful evidence. Distinguish observed results, source-derived reasoning, hypotheses, and proposed checks. Never claim runtime reproduction or measurements you did not perform. Use `NOT_ENOUGH_INFO` with an explanation for missing narrative answers or evidence. Incomplete reports, source-only findings, and early feature or design ideas are welcome when their limitations are explicit; a completed diagnosis or fix is not required to open an issue. ## Pull Request Readiness Follow [human ownership and readiness](CONTRIBUTING.md#pull-request-ownership-and-readiness) when preparing a PR. Leave human readiness declarations to the human owner. <!-- BEGIN:turborepo-agent-rules --> # This is NOT the Turborepo you know Turborepo configuration, task behavior, and CLI commands can vary between installed versions and may differ from your training data. Resolve the `turbo` package from this file's directory or relevant workspace; in monorepos, it may not be visible from the repository root. For example, run `node -p "require.resolve('turbo/package.json')"` from a workspace that depends on `turbo`. Read `docs/README.md` inside that installed package first, then read the relevant pages from its `docs/` directory before changing Turborepo configuration or commands. Heed deprecation notices. These bundled docs match the installed package version and are available without network access. This block is written and re-added by `turbo` before repository-scoped commands when an AI agent is detected. In the Turborepo source repository, its template is defined in `crates/turborepo-cli/src/cli/agent_guidance.rs`. Removing the managed block while updates are enabled means a later qualifying invocation will add it again. Set `"agentGuidance": false` in the root `turbo.json` or `turbo.jsonc` to opt out; this does not remove an existing block. Keep the block committed with your work to avoid an uncommitted change on the next agent invocation. <!-- END:turborepo-agent-rules --> - aistorehub.json (746 bytes)
{ "name": "REA: Reverse Engineer Anything (MCP Server & CLI)", "slug": "rea", "version": "1.0.0", "type": "mcp_server", "description": "Reverse Engineer Anything (REA): Let AI agents reverse engineer software, applications, and native binaries locally. Built as an MCP server and CLI connecting AI coding assistants (Claude Code, Cursor) to Ghidra, Hopper, IDA, and Electron inspection engines.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/morluto/rea", "tags": [ "claude-code", "ghidra", "typescript", "mcp-server", "native-binaries", "security", "reverse-engineering", "cursor", "binary-analysis" ], "imported_at": "2026-11-22T00:08:40.383Z" } - CONTRIBUTING.md (27437 bytes)
# Contributing to REA REA welcomes focused bug fixes, documentation improvements, tests, and reverse-engineering workflows. For large contract or architecture changes, explain the intended scope and link the relevant issue or design discussion. ## Choosing a contribution Explain the concrete problem, keep related corrections together, and report verification and unavailable coverage. Contributions should justify their review and maintenance cost. Keep cosmetic polish with useful fixes; confusing or incorrect user instructions warrant standalone corrections. Collect other cosmetic-only suggestions in an issue rather than separate PRs. For provider wiring, start with [`src/composition/binary.ts`](src/composition/binary.ts) for deep candidates and the other `src/composition/` factories for tool services, including [`gpu.ts`](src/composition/gpu.ts) and [`model.ts`](src/composition/model.ts). Live Frida, Cutter, GDB and Rizin construction also uses shared composition factories. Start with [capability declarations](src/composition/capabilityDeclarations.ts) for catalog metadata and [service bindings](src/composition/capabilityServices.ts) for construction, availability and cleanup. Production factories construct fresh providers without starting engines or acquiring targets; optional adapter failures must preserve successful peers. Run `npm run verify:test-discovery` after adding or moving tests. Resolved import boundaries are checked by `npm run verify:module-boundaries`, included in lint. It also checks each top-level `src/` unit against its layer in [`scripts/lib/module-layers.mjs`](scripts/lib/module-layers.mjs) (a new directory must declare one) and against the counted outward, mutual, cross-provider and past-entry imports in `scripts/lib/module-layers.baseline.json`. Application, composition and the adapters import a provider through the entry files it declares in that table. A new entry file widens the provider's public surface. The baseline may only shrink: a change that removes such imports lowers it with `node scripts/verify-module-boundaries.mjs --shrink-layer-baseline`. Before retiring an alias or facade, trace runtime registration, dynamic imports, JavaScript verifiers, subprocess scripts, and packaged entrypoints as well as TypeScript references. Tests may be the last consumers of a superseded internal path; migrate their distinct assertions to the current production path before removing it. Preserve validation, lazy loading, caller policy, and resource acquisition and cleanup supplied by the old boundary. Published APIs, persisted formats, and independently versioned bridges require an explicit compatibility decision; an internal representation alone does not establish that obligation. See [interpreting boundary facts once](docs/development/tool-design.md#interpret-boundary-facts-once) for admission ownership and the distinction between repeated validation and independent checks. For analysis workflows and agent interfaces, follow the [performance priorities](AGENTS.md#performance). Explain the selected output scope, reuse/cache decisions, and relevant before/after measurements when these costs change. Use the [analysis optimization skill](.agents/skills/rea-analysis-optimization/SKILL.md) to locate provider and shared-workflow bottlenecks, preserve Evidence, and compare equivalent real tasks before claiming an improvement. When adding or changing an MCP tool, follow the [tool design guide](docs/development/tool-design.md) and preserve the canonical contracts and generated catalog. When adding or changing an admission ceiling, budget, or deadline, follow [analysis settings, limits, and recovery](docs/reference/limits-and-recovery.md) for the steps for adding a runtime setting and documenting recovery. ## Reporting issues Use the issue form that fits the report and keep it concise. For bugs, include the actual result, the shortest reproduction you ran, the tested version and environment, and the smallest useful output, artifact, screenshot, or source reference. Ground expected behavior in documentation, source, or a known-good version when available. State observed impact and frequency; keep untested scope and suspected causes explicit. Incomplete reports and intermittent failures are welcome. If a narrative answer or supporting evidence is unavailable, write `NOT_ENOUGH_INFO` and explain the gap. Clearly label source-only findings and proposed checks; do not claim runtime reproduction or results you did not observe. A root-cause analysis or fix is not required to report a problem. Documentation reports should identify the relevant passage or missing guidance and explain the correction or confusion. Feature and design proposals can start with a problem and desired outcome. Examples, prior art, and measurements help when available; ideas without them are welcome. Maintainers can investigate reports and help resolve open questions. Human ownership and readiness declarations apply to PRs as described below. ## Pull request ownership and readiness AI-assisted contributions are welcome. Every PR must have a human owner who takes responsibility for the complete change, including code, tests, documentation, and claims produced with AI assistance. The PR author is the owner unless another human is named in the PR and explicitly accepts ownership. These requirements also apply to maintainer-authored PRs. Before requesting maintainer review, the human owner must: - Review the final diff and relevant existing code. Be able to explain the problem, the chosen approach, how it fits REA, and meaningful edge cases. - Provide evidence that the change works. Summarize what was checked, the observed results, and meaningful gaps in the PR body. Use focused tests, representative CLI/MCP output, CI artifacts, screenshots, or other checks appropriate to the change. For fixes, show the original failure and why the regression coverage catches it when practical. Documentation-only changes can use source, link, or rendered-document checks. Label source-derived conclusions and proposed checks accurately; never report an unrun check as passing. Follow the [verification requirements](#development-feedback-and-pr-verification) for required checks and real-provider coverage. - Complete the **Author readiness** declaration in the PR template, explicitly stating that the PR is ready for initial review, unless the PR author is exempt from the declaration as listed below. Keep the PR description concise and current. Explain the problem, observable outcome, approach, and useful evidence; link long logs or put them in optional details. Address actionable automated review findings and explain disagreements. Human ownership and review remain required when CI or an automated reviewer reports success. Readiness requests maintainer review; it does not grant scope approval or permission to merge. Pull request titles must match the Conventional Commits check in [`.github/workflows/pr-title.yml`](.github/workflows/pr-title.yml): ```text /^(?:feat|fix|docs|refactor|perf|test|build|ci|chore|revert)(?:\([a-z0-9._/-]+\))?!?: .+/u ``` The type is `feat`, `fix`, `docs`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, or `revert`. An optional scope, in parentheses, uses only lowercase `[a-z0-9._/-]`. An optional `!` may precede the colon. The title then has `: ` and a non-empty outcome, for example `feat: add historical source import`. The type `style` fails, and an uppercase scope fails. Draft status is optional. Draft PRs may request early feedback with open questions and incomplete checks. Agents preserve the current draft status unless asked to change it; missing readiness declarations or later updates do not require a PR to become a draft. Leave the readiness declaration unchecked until the human owner has completed it. The declaration records initial readiness; later pushes do not invalidate it or require another human sign-off. Keep the PR description and affected validation current as work changes. AI agents must leave human declarations to the human owner and must not attest to a human review on their behalf. Maintainers review the **Author readiness** declaration in the PR body. PRs authored by @morluto, @kaoru0822-kitauji, @N0zoM1z0, @gensokyo-dev, or @vincentkoc are exempt from the declaration. Their human ownership, review, and evidence responsibilities above still apply. Existing PRs can copy the **Author readiness** section from the current template. When an open PR may overlap another open change or a recently landed fix, note the related PR, issue, or commit in the description or a comment as soon as the overlap is known. Prefer one clear pointer over repeated status updates. If an overlapping change merges while a PR awaits review, link that commit on the open PR and state what remains useful. Rebase or otherwise align with the current base when the remaining work is still wanted, narrow the PR to the uncovered portion, or close it when the change is fully superseded. Keep the description and validation current after that update. Maintainers may also note the expected disposition (rebase, narrow, or close) when they land or recognize an overlapping fix. Readiness still does not grant merge permission or a review date. Maintainers may return a PR to the author or close it when the problem is unsupported, validation is missing, or the owner cannot explain the change. Contributors are responsible for completing this work before requesting review. ## Contribution scope REA focuses on software structure, runtime behavior, and evidence through general-purpose reverse-engineering workflows. Evaluate a proposal by its actual capabilities, side effects, defaults, and complete workflow. A tool name or a reference to vulnerability research, malware analysis, or CTFs does not determine whether it belongs in REA. Supported contributions include format inspection, ordinary archive and standard compression extraction, disassembly, decompilation, cross-references, general static deobfuscation, vulnerability analysis, and evidence reporting. Static protection detection is distinct from defeating that protection. Security fixes and isolated regression tests remain in scope. Runtime investigation needs explicit boundaries. Launching or attaching to a process, injecting instrumentation, running scripts, and changing memory or registers require review of target selection, execution and mutation authority, provenance, resource limits, cancellation, and cleanup. General Frida or debugger support is not inherently read-only, and existing support does not authorize every workflow built on it. General-purpose interfaces are not classified as dedicated bypass workflows solely because caller-provided code could be misused; their execution and mutation authority must still be reviewed. REA does not integrate or officially distribute: - Purpose-built workflows to defeat commercial packing or code-virtualization protections and automatically recover protected code. - Anti-debugging or anti-instrumentation evasion, or DRM, license, anti-cheat, or access-control bypass workflows. - Exploit or attack-payload automation, credential theft, covert persistence, unauthorized access, or bulk attack workflows. These boundaries apply to first-party providers, adapters, plugins, bundled scripts, defaults, examples, and documentation. Moving a capability into an optional dependency or plugin does not exempt it. Review what the integration exposes, including upstream defaults and raw-command or script execution paths. Ordinary extraction and general static deobfuscation are not excluded merely because the input is packed or obfuscated; assess added bypass or execution behavior separately. This is a product and maintenance boundary, not a judgment about a contributor's intentions or a declaration that all excluded research is unlawful. Contributors must have the rights and authorization needed for their work. A local-only design or an "authorized use only" disclaimer does not establish containment or settle legal and scope questions. ### Fail-closed integration If scope fit, target or authorization boundaries, side effects, or the verification needed to establish those boundaries remain materially unresolved, **do not merge, enable, or include the capability in official packages or distributions**. Keep the proposal pending, narrow it, or decline it. Record unknowns explicitly; do not turn them into "none" or assumed safety. Passing CI, completed implementation, upstream popularity, or silence from maintainers is not scope approval. For a new provider or a capability involving target execution, injection, mutation, or protection recovery, seek an explicit maintainer scope decision in the linked issue or design discussion before substantial implementation intended for integration. Small exploratory prototypes and draft PRs may help inform that decision; they do not authorize integration. The decision must cover the final proposed behavior; a scope expansion needs a new decision. Routine fixes and documentation changes within existing boundaries do not need a separate advance decision, but must not silently expand those boundaries. ### Starting a proposal To open a feature request or design discussion, describe the problem and desired outcome or decision. Short answers and the forms' "Not sure yet" options are welcome. You do not need code, a complete design or test plan, legal analysis, or private proof-of-authorization documents to start a discussion. Share what you know and leave optional details blank when you need help. Form selections guide triage; they are not proof of authorization or scope approval. Unselected effects must not be treated as established absence. Maintainers and implementers work together to resolve the following before integration: - The concrete analyst question, requested inputs and outputs, and why existing REA operations are insufficient. - Why the workflow fits this scope, its non-goals, and any protection recovery, bypass, or attack automation it would expose. - The selected targets and every execution, injection, mutation, network, or persistence effect, including behavior inherited from upstream tools. - How the boundaries and outcome will be verified with self-owned or appropriately licensed samples; identify real CLI/MCP and provider coverage, cleanup and resource checks, and remaining unknowns. Do not publish private binaries, credentials, or sensitive target data; follow [SECURITY.md](SECURITY.md) for private vulnerability reports. Mixed proposals should separate acceptable analysis capabilities from excluded workflows so each can be decided independently. An issue may discuss unresolved questions; opening an issue or PR does not authorize integration. This is a maintainer integration gate, not a per-call confirmation requirement or a sandbox guarantee. ## Devel
- DISCLAIMER.md (7105 bytes)
# Disclaimer ## Responsible use REA is built for lawful analysis: security research, malware and incident analysis, vulnerability research and coordinated disclosure, CTFs and education, interoperability, software preservation, and debugging or auditing software you own or are authorized to examine. The REA project does not support, and will not help with: - circumventing DRM, license checks, anti-cheat systems or other technical protection measures; - developing game cheats or tampering with online services; - bypassing authentication, bot protection or access controls on systems you are not authorized to test; - copying proprietary software or reproducing its protected code and assets; - evading the usage policies or safety measures of AI model providers; - reselling or sharing AI accounts or API access. You are responsible for obtaining any required authorization and for complying with applicable laws, license agreements and terms of service. Reverse engineering may be restricted in your jurisdiction or by the license of the software you analyze. Requests for help with the uses above will be closed without response in issues and discussions, and may result in removal from the REA community. ## User responsibility Do not use REA for unauthorized access or exploitation, credential theft, malicious deployment of malware, unlawful collection or disclosure of data, unauthorized service disruption, or unlawful circumvention of access controls or licensing restrictions. Legitimate security research and malware analysis must remain within the rights and permissions applicable to the work. You are responsible for your use of REA, including commands, configurations, scripts, and actions you direct an AI agent to perform. Establish the legal authority and scope required for the targets, accounts, devices, software, data, and operations involved. Comply with applicable laws, contracts, intellectual-property rights, privacy obligations, and tool licenses. Public availability of software, possession of a file, or access to a debugging endpoint does not by itself establish permission for every operation. ## Runtime, network, and device operations Some REA workflows execute or observe programs, attach to runtime or browser endpoints, capture network traffic, interact with applications, or operate on connected devices. These actions can affect application state, files, accounts, devices, and services. Authorization to inspect an artifact does not necessarily authorize execution, interception, device changes, or interaction with another party's system. Review the operations you request, including agent-generated plans and scripts, and use an appropriate environment for untrusted targets. You are responsible for protecting credentials, personal data, captured traffic, and investigation artifacts, and for obtaining any permission required to collect, retain, process, or share them. Local operation does not establish authorization or guarantee that executed targets and third-party tools have no external effects. ## Analysis results and generated output Decompilation, reconstruction, heuristics, and AI-assisted analysis may be incomplete or incorrect. Results do not guarantee accuracy, completeness, security, compatibility, or legal compliance. Review the underlying evidence and verify consequential conclusions before relying on them. Obtaining source-like output or an analysis report does not grant rights to the original program, its data, or the generated output. Check the target's rights and the producing tool's applicable terms before publishing, sharing, or using results in another product or service. ## Third-party tools and licenses Third-party components and analysis tools retain their own licenses, copyright notices, and usage conditions. Consult [Third-party notices](THIRD_PARTY_NOTICES.md) for their roles, licensing records, and preserved upstream texts. You must legally obtain IDA Pro and Hex-Rays decompilers, Hopper, JEB, and any other proprietary tools, together with the rights required for your use. REA provides no commercial-tool license, key, or activation entitlement. Permitted trials and demos remain subject to vendor terms. An open-source bridge or accessible API does not grant additional user, machine, feature, automation, hosting, or output-sharing rights. Cracked copies, stolen keys, unauthorized key sharing, and bypassing license restrictions are not authorized by REA. ## Disclaimer of warranty REA is provided **AS IS**, without express or implied warranties, including merchantability, fitness for a particular purpose, and noninfringement, as set out in the [MIT License](LICENSE). You assume the risks of using the software and deciding whether it is suitable for your task. No project description, example, analysis result, or third-party integration guarantees a particular outcome or establishes that your intended use is lawful or safe. ## Limitation of liability The warranty and liability provisions of the [MIT License](LICENSE) govern REA's authors and copyright holders, subject to applicable law. That license disclaims liability for claims, damages, and other liability arising from or in connection with the software or its use, whether in contract, tort, or otherwise. This document does not expand those provisions or override rights and obligations that cannot be excluded under applicable law. ## Disclaimer of endorsement References to third-party projects, contributors, products, services, and trademarks identify their work and REA's integrations. Credits and thanks do not imply affiliation, sponsorship, approval, or endorsement by the named parties, including the National Security Agency and commercial tool vendors. Redistribution, bundling, or hosting by a third party does not by itself imply affiliation with or endorsement by the REA project. ## Relationship to software licenses This document explains REA's intended use, user responsibilities, and community support boundaries. It does not amend the MIT license, impose additional copyright-license conditions, replace upstream licenses, or grant rights to third-party software or targets. The applicable software licenses and agreements retain their own terms. ## Versions, distribution channels, and platforms The project's position on lawful use and non-endorsement of illegal or unauthorized activity covers all REA versions, distribution forms, and platforms. This includes historical releases and Git commits, npm packages, bundled or separately distributed REA skills, source checkouts, release archives, and redistributed copies, regardless of installation method, agent client, operating system, or platform. Using an older version or another distribution channel does not imply project endorsement or remove obligations under applicable law or to respect third-party rights. Each copy remains subject to the licenses accompanying that copy. This statement does not retroactively amend existing license grants, add license conditions, or expand historical warranty or liability exclusions.
- install.sh (8350 bytes)
#!/bin/bash { # Truncation guard: this brace group opens on line 2 and closes on the last # line, so bash must read the entire file before it runs any command. On the # `curl ... | bash` path, a download cut off anywhere before the final `}` is # an unterminated compound command, which bash reports as a syntax error at # EOF without running anything. Without the guard, a cut right after `set` # would run the bare builtin and print every shell variable, and a cut right # after `main` would run the installer without the caller's flags. set -euo pipefail PACKAGE="rea-agents" REPOSITORY="morluto/rea" numeric_identifier='(0|[1-9][0-9]*)' prerelease_identifier="(${numeric_identifier}|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)" build_identifier='[0-9A-Za-z-]+' version_pattern="${numeric_identifier}\\.${numeric_identifier}\\.${numeric_identifier}(-${prerelease_identifier}(\\.${prerelease_identifier})*)?(\\+${build_identifier}(\\.${build_identifier})*)?" version="${REA_VERSION:-}" version_requested=false dry_run=false start_setup=true verbose=false fail() { printf 'REA installation failed: %s\n' "$1" >&2 exit 1 } # Bash can return status 0 while parsing an incomplete [[ condition. Keep that # grammar in a constant quoted expression so truncated downloads fail while # parsing the outer brace group. eval parses only this literal; the arguments # are expanded as data by the conditional, not interpolated into shell code. matches() { eval '[[ "$1" =~ $2 ]]' } # Resolve the current host's Node.js tarball label pair; a label we cannot map # is kept verbatim so the operator can still read it. Falls back on the raw # `uname` outputs rather than inventing a label the Node.js release index does # not publish, so a mismatch is obvious instead of silently wrong. node_host_labels() { case "$(uname -m)" in arm64|aarch64) node_arch_label="arm64" ;; x86_64|amd64) node_arch_label="x64" ;; *) node_arch_label="$(uname -m)" ;; esac case "$(uname -s)" in Darwin) node_os_label="darwin" ;; Linux) node_os_label="linux" ;; *) node_os_label="$(uname -s | tr '[:upper:]' '[:lower:]')" ;; esac } # Exit with actionable remediation when the active Node.js is unsupported. # The engine floor stays in sync with package.json#engines.node — change both. fail_node_version() { local observed="$1" node_host_labels printf 'REA installation failed: Node.js %s is unsupported.\n\n' "$observed" >&2 printf 'REA requires Node.js 22.x (>=22.23.4), 24.x (>=24.22.1), or 26.12.1+. Install one via:\n' >&2 printf ' nvm: nvm install 24 && nvm use 24 (https://github.com/nvm-sh/nvm)\n' >&2 printf ' fnm: fnm install 24 && fnm use 24 (https://github.com/Schniz/fnm)\n' >&2 printf ' Direct download for %s/%s:\n' "$node_os_label" "$node_arch_label" >&2 printf ' https://nodejs.org/dist/latest-v24.x/ (grab the %s-%s tarball)\n' "$node_os_label" "$node_arch_label" >&2 printf 'Then rerun this installer.\n' >&2 exit 1 } usage() { cat <<'EOF' Usage: install.sh [--version VERSION] [--dry-run] [--no-setup] [--no-prompt] [--verbose] Installs the REA CLI, then starts `rea setup` interactively to configure Hopper and agents when a terminal is available. Pass --no-setup (or --no-prompt) to skip setup and run `rea setup` later. EOF } main() { while (($# > 0)); do case "$1" in --version) (($# >= 2)) || fail "--version requires a value." version="$2" version_requested=true shift 2 ;; --dry-run) dry_run=true shift ;; --no-setup|--no-prompt) start_setup=false shift ;; --verbose) verbose=true shift ;; --help|-h) usage exit 0 ;; *) fail "unknown option: $1" ;; esac done if [ "$verbose" = true ]; then set -x fi platform="$(uname -s)" [ "$platform" = "Darwin" ] || [ "$platform" = "Linux" ] || fail "REA supports macOS and selected 64-bit Linux distributions." command -v curl >/dev/null 2>&1 || fail "curl is required. Install curl, then rerun this installer." command -v node >/dev/null 2>&1 || fail "Node.js 22.x (>=22.23.4), 24.x (>=24.22.1), or 26.12.1+ is required; install it from https://nodejs.org and retry." command -v npm >/dev/null 2>&1 || fail "npm is required; install it with Node.js and retry." node_version="$(node -p 'process.versions.node' 2>/dev/null || true)" IFS=. read -r node_major node_minor _node_patch <<<"$node_version" matches "$node_major" '^[0-9]+$' && matches "$node_minor" '^[0-9]+$' || fail "the active Node.js version could not be read. Check that node works and is on PATH, then retry." node_patch="${_node_patch%%+*}" if ! matches "$_node_patch" '^[0-9]+(\+[0-9A-Za-z.-]+)?$' || ! ((node_major == 22 && (node_minor > 23 || node_minor == 23 && node_patch >= 4) || node_major == 24 && (node_minor > 22 || node_minor == 22 && node_patch >= 1) || node_major == 26 && (node_minor > 12 || node_minor == 12 && node_patch >= 1) || node_major > 26)); then fail_node_version "$node_version" fi if [ "$version_requested" = true ] || [ -n "$version" ]; then matches "$version" "^${version_pattern}$" || fail "version must be an exact semantic version." else release_json="$(curl -fsSL --proto '=https' --tlsv1.2 --retry 3 -H 'Accept: application/vnd.github+json' "https://api.github.com/repos/$REPOSITORY/releases/latest")" || fail "the latest REA release could not be resolved. Check network access or pass --version VERSION, then retry." tag="$(printf '%s' "$release_json" | node -e 'let s="";process.stdin.on("data",c=>s+=c).on("end",()=>{const v=JSON.parse(s).tag_name;if(typeof v!=="string")process.exit(1);process.stdout.write(v)})' 2>/dev/null)" || fail "the release response was invalid. Retry later or pass --version VERSION." matches "$tag" "^rea-agents-(${version_pattern})$" || fail "the latest release tag was invalid. Retry later or pass --version VERSION." version="${BASH_REMATCH[1]}" fi # npm's exact-version resolver cleans build metadata from the requested version, # so it may install the base release and make the post-install identity check fail. if matches "$version" '\+'; then fail "npm cannot install an exact version with build metadata. Pass a version without build metadata, then retry." fi install_args=(install --global) if [ "$platform" = "Linux" ]; then install_args+=(--prefix "$HOME/.local") install_bin="$HOME/.local/bin/rea" else npm_prefix="$(npm prefix --global)" || fail "the npm global prefix could not be read. Repair the npm configuration, then retry." install_bin="$npm_prefix/bin/rea" fi install_args+=("$PACKAGE@$version") printf 'REA install plan\n' printf ' Version: %s\n' "$version" printf ' Runtime: Node.js %s\n' "$node_version" printf ' Command:' printf ' %q' npm "${install_args[@]}" printf '\n' printf ' Binary: %s\n' "$install_bin" printf ' Setup: %s\n' "$([ "$start_setup" = true ] && printf 'start when a terminal is available' || printf 'skipped')" if [ "$dry_run" = true ]; then printf 'Dry run complete; no changes made.\n' exit 0 fi printf 'Installing %s@%s...\n' "$PACKAGE" "$version" npm "${install_args[@]}" || fail "npm could not install REA. Check registry access and npm permissions, then retry." [ -x "$install_bin" ] || fail "npm completed without installing the rea command. Check the npm global bin directory and PATH, then retry." installed_version="$("$install_bin" --version 2>/dev/null | tr -d '[:space:]')" || fail "the installed REA version could not be read. Reinstall the requested version, then retry." [ -n "$installed_version" ] || fail "the installed REA version could not be read. Reinstall the requested version, then retry." [ "$installed_version" = "$version" ] || fail "installed version $installed_version does not match $version. Reinstall the requested version, then retry." printf 'REA %s is installed.\n' "$version" if [ "$start_setup" = true ] && [ -r /dev/tty ] && [ -w /dev/tty ] && [ -t 1 ] && [ -t 2 ]; then printf 'Starting REA setup...\n' "$install_bin" setup </dev/tty >/dev/tty else printf 'Run %s setup to configure Hopper and agents.\n' "$install_bin" fi } main "$@" exit $? } - INSTRUCTIONS.md (48345 bytes)
--- name: reverse-engineer-anything description: Reverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. 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: "63" --- # REA Use REA when a claim depends on a shipped binary or package, decompilation, requested 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. The exception is a Claude Code, Codex, or Cursor Marketplace plugin install: the plugin bundles this skill and registers its own `rea` server, outside the state that `rea setup` and `rea doctor` manage. 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. If the host times out without a REA result, do not repeat the unchanged call or assume work stopped. Read the recovery guide's deadline distinction before retrying. If the MCP connection drops, retry that call once only when it is safe to repeat or known not to have started. If it may already have changed the target, or it fails again, tell the user and ask them to restart the MCP client. If REA could not start its connection, retry once, then tell the user and ask them to restart the MCP client. Do not retry a startup failure that returns the same unchanged result. For plugin installs, follow [plugin recovery](references/connection-and-recovery.md#rea-installed-as-a-client-plugin). For setup-owned registrations, run `rea doctor` when REA could not start or tools stay missing after that restart. For `cleanup_incomplete`, a retryable capacity limit, or `configuration_invalid`, follow the recovery guide's ladder before asking for a restart. Read that guide before a second repair attempt. Choose the installation owner before repairing registration. Plugin installs use [plugin recovery](references/connection-and-recovery.md#rea-installed-as-a-client-plugin); only setup-owned registrations use the guide's [registration repair plan](references/connection-and-recovery.md#repair-registration-when-needed). A plugin-only doctor result of `missing` does not call for `rea 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 an existing installation’s absolute runtime and entry script, or continue through the CLI. A concrete CLI fallback for an operator-supplied JavaScript tree or ASAR is: ```bash npx -y rea-agents@latest 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@latest` in its place from a trusted directory outside the target project, with absolute target paths. Managed setup binds the current installation directly; retain its runtime and package cache entry, or restore that installation before repairing its registration. For setup-owned registration, 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. ## 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`. To find a few files in a packaged `app.asar`, open it with `open_binary`, start with `inspect_artifact` using `detail: "summary"`, then analyze the selected files with `source_paths`. When you intend to retain digest contradictions from re-signed unpacked companions, pass `integrity_policy: "record-and-continue"` starting with `inspect_artifact`. See the [JavaScript applications reference](references/javascript-applications.md). - Archive/package member inventory (ZIP/APK/IPA/MSIX/AppX, DMG, or a PyInstaller executable): `open_binary` with the supplied local path; use `inspect_artifact` when its graph and findings help answer the question. A PyInstaller CArchive is the application layer; the bootloader is only the native prefix. Start with `detail: "summary"` for large inventories, then use retained inventory views for selected member fields/pages. A complete small inventory can cost less than extra calls and schemas. Runtime options are metadata, not files. Compact delivery still inventories and hashes members. See the [Python packaged applications guide](https://github.com/morluto/rea/blob/main/docs/python-packaged-applications.md). - Bun `--compile` executable: `open_binary`, then `inspect_artifact`; the Bun module graph is the application layer. Extract stored modules and analyze the JavaScript. See [Bun standalone executables](https://github.com/morluto/rea/blob/main/docs/bun-standalone.md). - Deno `deno compile` executable: `open_binary`, then `inspect_artifact`; the embedded virtual filesystem is the application layer. Extract stored files and analyze compatible JavaScript. Environment-file values and CA certificate bytes are retained in local Evidence with their counts and byte lengths. The npm snapshot length is reported and not decoded, and the executable is not run. See [Deno compile executables](https://github.com/morluto/rea/blob/main/docs/deno-standalone.md). - Apple app plist, Interface Builder, asset catalog, or keyed archive resources: `open_bundle_resources`, then the selected resource tool. This does not require `CFBundleExecutable` or a deep provider. Resource sessions have no executable digest or binary snapshot; use `open_binary` for native code. - 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`. - UEFI firmware volumes and NVAR stores: use bundled `inspect_artifact`. For external firmware scanning or extraction on Linux, use `inspect_firmware_regions` or `extract_firmware` with caller-supplied Binwalk or Unblob. Extraction needs a caller-selected new absolute output directory. See the [firmware guide](https://github.com/morluto/rea/blob/main/docs/guides/firmware/firmware-analysis.md). - ESP32-family app or bootloader image (`0xE9` magic): `inspect_artifact` without a provider; see the ESP section of `references/native-and-artifacts.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. - Native program behavior, live calls, instrumentation, or command-run effects: choose the matching [native runtime workflow](references/runtime-observation.md#native-runtime-questions). `open_binary` and `trace_native_values` establish static facts; they do not observe execution. Runtime tools have distinct launch, attach, mutation and cleanup effects, and do not require a preliminary static session unless their own contract says so. - User-owned browser page already open: `list_browser_targets`. - Passive traffic capture of a SPA: the default scope is the page's own origin, and data APIs usually live on another origin. Discover API origins from absolute URLs in loaded bundles or script text via JavaScript analysis tools (another passive capture without those origins still scopes to the page origin, and `completeness.excluded` counts lack URLs). Pass both the page origin and those API origins in `allowed_origins` — the list replaces the default scope — and read `completeness.excluded` before reporting that an API is absent. For long captures with body shapes, use `export_evidence_bundle` instead of expecting an inline result. - 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. - Agent environment (AgentEnv bundle) of a web application: read [environments](references/environments.md) before recording; it records with `capture_browser_scenario` and writes the bundle with `export_environment_bundle`. - Task for a desktop application's exported environment, from a `capture-desktop-application` folder: read [desktop application tasks](references/environments.md#tasks-for-a-desktop-application-environment). - Environment of a Linux desktop app with a task, from a request such as "build me an Inkscape environment where the agent changes a poster's headline": read [desktop builds](references/desktop-build.md). You drive the app on a build computer from `start_build_computer`, then export and witness. - 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. HAR/SAZ/qlog old-generation heap is `REA_CAPTURE_DECODER_OLD_GENERATION_MIB` (default 192 MiB, floor 8, maximum 16384), set where REA starts. Host memory and `NODE_OPTIONS` do not raise it. See [historical captures](https://github.com/morluto/rea/blob/main/docs/guides/web/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`. - Shipped application exposure for a local `.app`, install directory, ASAR, or executable: `audit_release_exposure` / `rea audit-release-exposure`. Each check has a stable id, a status, and fixed remediation. Unknown and unassessed checks stay in the report. This does not establish that an application is secure. Credential-marker hits report the rule id and location only. See [release exposure](https://github.com/morluto/rea/blob/main/docs/release-exposure.md). - 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 TShark 4.x on an absolute `PATH` entry or via the optional absolute `REA_TSHARK_COMMAND` override; see [capture guide](https://github.com/morluto/rea/blob/main/docs/guides/data/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/guides/data/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/guides/signals/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
- knip.json (1395 bytes)
{ "$schema": "./node_modules/knip/schema.json", "entry": [ "src/main.ts", "src/cli.ts", "src/cliOneShot.ts", "src/cliOutput.ts", "src/cliBuiltinArguments.ts", "src/cli/cliResultOutput.ts", "src/mcpDoctor.ts", "src/composition/javascriptAnalysisWorkerProcess.ts", "src/composition/webBundleAnalysisWorkerProcess.ts", "src/contracts/errorSchemas.ts", "scripts/read-authored-skill-manifest.mjs", "scripts/verify/fridaBindingsCompatibility.ts", "scripts/verify/termux/browser.mjs", "scripts/verify-real-ghidra-noreturn.mjs", "scripts/verify-real-ghidra-decompiler-failure.mjs", "scripts/verify-real-ghidra-decompile-timeout.mjs", "scripts/verify-real-ghidra-function-bundle.mjs", "tests/processOwnershipRunner.ts" ], "project": ["src/**/*.ts", "tests/**/*.ts", "scripts/**/*.mjs"], "vitepress": { "entry": ["docs/.vitepress/config.ts"] }, "ignoreBinaries": ["^g\\+\\+$", "mkfifo"], "ignoreDependencies": [ "@stryker-mutator/command-runner", "electron", "esbuild", "webpack" ], "ignoreExportsUsedInFile": true, "rules": { "files": "error", "dependencies": "error", "devDependencies": "error", "unlisted": "error", "exports": "error", "nsExports": "error", "types": "error", "nsTypes": "error", "enumMembers": "error", "duplicates": "error" } } - knip.production.json (1050 bytes)
{ "$schema": "./node_modules/knip/schema.json", "entry": [ "src/main.ts!", "src/cli.ts!", "src/cliOneShot.ts!", "src/cliOutput.ts!", "src/cliBuiltinArguments.ts!", "src/cli/cliResultOutput.ts!", "src/mcpDoctor.ts!", "src/composition/javascriptAnalysisWorkerProcess.ts!", "src/composition/webBundleAnalysisWorkerProcess.ts!", "src/sqlite/SqliteDatabaseWorker.ts!", "src/evm/EvmoleInterfaceWorker.ts!", "src/browser/history/NodeCaptureProcess.ts!", "src/javascript/sourceMaps/SourceMapCodecProcess.ts!", "scripts/rea.mjs!", "scripts/rea-android-workspace-guardian.mjs!", "scripts/electron-active-hook.cjs!", "scripts/prepack.mjs!", "scripts/prepare.mjs!", "scripts/verify-windows-native-artifact.mjs!" ], "project": ["src/**/*.ts!", "!src/**/*.test.ts", "!src/**/*.fixture.ts"], "ignoreExportsUsedInFile": true, "include": [ "files", "exports", "nsExports", "types", "nsTypes", "enumMembers", "namespaceMembers", "duplicates" ] } - LICENSE (1064 bytes)
MIT License Copyright (c) 2026 morluto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- mcp.json (150 bytes)
{ "mcpServers": { "rea": { "command": "npx", "args": [ "-y", "[email protected]", "mcp" ] } } } - package.json (29283 bytes)
{ "name": "rea-agents", "mcpName": "io.github.morluto/rea", "version": "6.10.1", "description": "Reverse engineer anything from your terminal or agent with one CLI and MCP server.", "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/morluto/rea.git" }, "homepage": "https://github.com/morluto/rea#readme", "bugs": { "url": "https://github.com/morluto/rea/issues" }, "keywords": [ "reverse-engineering", "binary-analysis", "agents", "agent-skills", "cli", "mcp-server", "model-context-protocol", "static-analysis", "rea", "decompiler", "mcp", "hopper", "electron", "javascript-analysis", "ghidra", "ida" ], "publishConfig": { "access": "public" }, "type": "module", "imports": { "#dist/*": "./dist/*", "#javascript-analysis-worker": "./dist/composition/javascriptAnalysisWorkerProcess.js", "#web-bundle-analysis-worker": "./dist/composition/webBundleAnalysisWorkerProcess.js" }, "bin": { "rea": "scripts/rea.mjs", "rea-agents": "scripts/rea.mjs" }, "engines": { "node": "^22.23.4 || ^24.22.1 || >=26.12.1" }, "packageManager": "[email protected]", "files": [ "dist", "install.sh", "bridge/hopper_bridge.py", "bridge/ida/hexrays_queries.py", "bridge/cutter/rea_bridge.py", "bridge/native/NativeUIChildren.swift", "bridge/native/NativeUIValues.swift", "bridge/native/ReaNativeUI.swift", "bridge/native/rea_lldb_tracer.py", "bridge/process/ProcessRunTokenReader.swift", "bridge/process/ProcessRunTokenReaderMain.swift", "bridge/ghidra/ReaGhidraBridge.java", "bridge/ghidra/ReaGhidraBundleActivator.java", "bridge/ghidra/ReaGhidraExtensions.java", "bridge/ghidra/ReaGhidraPrepareCom.java", "bridge/ghidra/ReaGhidraApplySeeds.java", "bridge/ghidra/ReaGhidraAnalysisOptions.java", "bridge/ghidra/ReaGhidraNoReturnFix.java", "bridge/ghidra/ReaGhidraMipsSoftFloat.java", "bridge/ghidra/ReaGhidraRiscvCallingConvention.java", "bridge/ghidra/ReaGhidraPrepareRaw.java", "bridge/ghidra/ReaGhidraPrepareDol.java", "bridge/android/ReaJadxBridge.java", "bridge/mitmproxy/capture.py", "bridge/agentenv/capture.py", "bridge/agentenv/computer.py", "bridge/agentenv/solve.py", "bridge/agentenv/solve_cleanup.py", "scripts/rea.mjs", "scripts/lib/cli-process-environment.mjs", "scripts/lib/runtime-admission.mjs", "scripts/rea-android-workspace-guardian.mjs", "scripts/electron-active-hook.cjs", "scripts/electron-active-hook-boundaries.cjs", "scripts/hopper-demo-x11.py", "scripts/prepack.mjs", "scripts/prepare.mjs", "skills", "README.md", "DISCLAIMER.md", "THIRD_PARTY_NOTICES.md", "website/public/assets/licenses/dinosaur.txt", "LICENSE", "native/windows/build/manifest.json", "native/windows/build/rea-windows-x64.node", "scripts/verify-windows-native-artifact.mjs", "bridge/pwntools/layout.py", "bridge/pwntools/layout_impl.py", "third_party/pwntools/README.md", "third_party/wabt/README.md", "third_party/evmole/README.md", "third_party/evmole/LICENSE", "bridge/pwntools/decoder_runtime.py", "bridge/pwntools/recorded_crash.py", "bridge/pwntools/recorded_crash_impl.py", "bridge/pwndbg/launch.py", "bridge/pwndbg/launch_impl.py", "bridge/pwndbg/core_context.py", "third_party/pwndbg/README.md", "third_party/pwndbg/LICENSE.md", "licenses", "assets/rea-plugin.png", ".claude-plugin/plugin.json", ".codex-plugin/plugin.json", ".codex-plugin/mcp.json", ".cursor-plugin/plugin.json", ".cursor-plugin/skills", "mcp.json", "scripts/plugin-mcp-launcher.mjs", "npm-shrinkwrap.json" ], "scripts": { "release:notes": "node scripts/release-notes.mjs", "deps:check": "node scripts/check-dependency-install.mjs", "pack:build-computer-runtime": "node scripts/pack-build-computer-runtime.mjs", "metadata:generate": "node scripts/run-exclusive.mjs artifacts node scripts/generate-package-metadata.mjs", "metadata:check": "node scripts/generate-package-metadata.mjs --check", "mcp-registry:check": "node scripts/verify-mcp-registry-metadata.mjs", "prebuild": "npm run deps:check", "build": "node scripts/run-exclusive.mjs artifacts node scripts/run-turbo.mjs run artifacts:skills --force", "precheck": "npm run deps:check", "check": "node scripts/run-exclusive.mjs artifacts node scripts/run-turbo.mjs run typecheck lint format:check knip metadata:check && npm run verify:architecture-guards && npm run knip:production && npm run lint:typed", "precheck:fast": "npm run deps:check", "check:fast": "node scripts/run-turbo.mjs run typecheck lint --output-logs=errors-only && npm run verify:architecture-guards", "precheck:changed": "npm run deps:check", "check:changed": "npm run check:fast && npm run test:changed", "precheck:test": "npm run deps:check", "check:test": "node scripts/run-exclusive.mjs artifacts node scripts/run-turbo.mjs run typecheck lint format:check knip metadata:check test:run", "precheck:pr": "npm run deps:check", "check:pr": "node scripts/run-exclusive.mjs artifacts node scripts/run-turbo.mjs run typecheck lint format:check knip metadata:check test:run && npm run test:python && npm run docs:check && npm run jscpd && npm run scan:todos && npm run knip:production && npm run lint:typed", "precheck:ci": "npm run deps:check", "precheck:ci:fast": "npm run deps:check", "precheck:ci:deep": "npm run deps:check", "check:ci": "npm run check:ci:fast && npm run check:ci:deep", "check:ci:fast": "node scripts/run-exclusive.mjs artifacts npm run check:ci:fast:tasks", "check:ci:fast:tasks": "node scripts/run-turbo.mjs run typecheck lint format:check", "check:ci:deep": "node scripts/run-exclusive.mjs artifacts npm run check:ci:deep:tasks && npm run verify:architecture-guards && npm run verify:test-discovery && npm run test:python && npm run knip:production && npm run lint:typed", "check:ci:deep:tasks": "node scripts/run-turbo.mjs run knip metadata:check jscpd scan:todos", "ci:static-context": "node scripts/ci/static-task-context.mjs", "build:cached": "node scripts/check-dependency-install.mjs && node scripts/run-exclusive.mjs artifacts node scripts/run-turbo.mjs run artifacts:skills", "build:termux": "node scripts/run-exclusive.mjs artifacts npm run build:termux:run", "build:termux:run": "npm run compile:termux && npm run artifacts:skills", "format": "oxfmt .", "format:check": "oxfmt --check .", "lint": "node scripts/ci/static-check-report.mjs lint && npm run verify:module-boundaries && node scripts/verify/rea-numeric-limits.mjs", "lint:details": "oxlint && npm run verify:module-boundaries", "lint:fix": "oxlint --fix && npm run verify:module-boundaries", "knip": "knip --cache", "jscpd": "node scripts/ci/static-check-report.mjs duplicates", "jscpd:details": "jscpd src/ tests/ --no-tips", "scan:todos": "node scripts/scan-todos.mjs", "start": "node scripts/rea.mjs mcp", "test": "npm run test:with-build", "test:with-build": "npm run test:prepare && vitest run", "test:run": "vitest run", "test:python": "python3 scripts/run-python-tests.py", "eval:mcp-catalog": "node scripts/run-exclusive.mjs artifacts python3 tests/support/analysis-efficiency/catalog-eval.py", "test:local": "node scripts/run-development-tests.mjs local", "test:fast": "node scripts/ci/test-group.mjs source", "test:built": "node scripts/ci/test-group.mjs built", "pretest:boundary": "npm run test:prepare", "test:boundary": "vitest run --project boundary --project cli-boundary --project process-boundary --project mcp-boundary --project process-global", "pretest:mcp": "node scripts/check-dependency-install.mjs && node scripts/run-exclusive.mjs artifacts node scripts/run-turbo.mjs run artifacts:skills", "test:mcp": "vitest run --project mcp-boundary", "pretest:acceptance": "npm run build:cached", "test:acceptance": "vitest run --project acceptance", "test:changed": "node scripts/run-development-tests.mjs changed", "pretest:integration": "npm run test:prepare", "test:integration": "vitest run --project boundary --project cli-boundary --project process-boundary --project mcp-boundary --project process-global --project acceptance", "pretest:coverage": "npm run test:prepare", "test:coverage": "vitest run --coverage.enabled --coverage.provider=v8", "test:coverage:reverse-tools": "vitest run --config vitest.reverse-tools.config.ts --coverage.enabled", "pretest:coverage:reverse-tools": "npm run test:prepare", "test:mutation:reverse-tools": "node scripts/prepare-reverse-tools-mutation.mjs && stryker run stryker.config.mjs && stryker run stryker.semantics.config.mjs", "pretest:mutation:reverse-tools": "npm run test:prepare", "test:ci": "npm run test:coverage -- --reporter=default --reporter=junit --outputFile.junit=test-results.xml", "pretest:ci:shard": "npm run test:prepare", "test:ci:shard": "npm run test:ci:shard:run", "test:ci:shard:run": "vitest run --coverage.enabled --coverage.provider=v8 --coverage.thresholds.lines=0 --coverage.thresholds.functions=0 --coverage.thresholds.branches=0 --coverage.thresholds.statements=0 --reporter=default --reporter=blob", "test:ci:merge": "vitest --merge-reports --coverage.enabled --coverage.provider=v8", "pretest:verbose": "npm run test:prepare", "test:verbose": "vitest run --reporter=verbose", "test:watch": "vitest --project domain --project services --project adapters --project composition --project conformance --project evaluation --changed", "pretest:watch:all": "npm run test:prepare", "test:watch:all": "vitest --changed", "typecheck": "node scripts/run-typescript.mjs --noEmit && node scripts/run-typescript.mjs --noEmit -p tsconfig.scripts.json", "verify:test-temp-hygiene": "npm run test:prepare && node scripts/verify-test-temp-hygiene.mjs", "verify:hopper": "npm run verify:fixtures && npm run build:cached && node scripts/verify-real-hopper.mjs", "verify:hopper:callers": "npm run build:cached && node scripts/verify-real-hopper-callers.mjs", "verify:hopper:deadlines": "npm run verify:fixtures && npm run build:cached && node scripts/verify-real-hopper-deadlines.mjs", "verify:hopper:fat": "npm run build:cached && node scripts/verify-real-hopper-fat.mjs", "verify:hopper:fat64": "npm run build:cached && node scripts/verify-real-hopper-fat.mjs --fat64", "verify:apple-dispatch": "npm run build:cached && node scripts/verify/apple/dispatch.mjs", "verify:native-ui": "npm run build:cached && node scripts/verify-native-ui.mjs", "verify:keyed-archive": "npm run build:cached && node scripts/verify/apple/keyed-archive.mjs", "verify:macos-bundle": "npm run build:cached && node scripts/verify/apple/macos-bundle.mjs", "verify:legacy-simulator": "npm run build:cached && node scripts/verify/apple/legacy-simulator.mjs", "verify:node-sea": "npm run build:cached && node scripts/verify-node-sea.mjs", "verify:architecture-guards": "node scripts/verify/architecture-guards.mjs", "verify:apktool": "npm run build:cached && node scripts/verify-apktool.mjs", "verify:pcap": "npm run build:cached && node scripts/verify-pcap.mjs", "verify:pe:load-config": "npm run build:cached && node scripts/verify-pe-load-config.mjs", "verify:release-exposure": "npm run build:cached && node scripts/verify-release-exposure.mjs", "verify:dwarf-units": "node scripts/verify-dwarf-units.mjs", "verify:binary-hardening": "node scripts/verify-binary-hardening.mjs", "verify:elf:unwind-ranges": "npm run build:cached && node scripts/verify-elf-unwind-ranges.mjs", "verify:flutter": "npm run build:cached && node scripts/verify-flutter.mjs", "verify:adb": "npm run build:cached && node scripts/verify-adb.mjs", "verify:ghidra": "npm run build:cached && node scripts/verify-real-ghidra.mjs", "verify:ghidra:project-coverage": "npm run build:cached && node scripts/verify-real-ghidra-project-coverage.mjs", "verify:ghidra:checkpoints": "npm run build:cached && node scripts/verify-real-ghidra-checkpoints.mjs", "verify:ghidra:seeds": "npm run build:cached && node scripts/verify/ghidra/seeds.mjs", "verify:ghidra:mips": "npm run build:cached && node scripts/verify-real-ghidra-mips.mjs", "verify:ghidra:ppc": "npm run build:cached && node scripts/verify-real-ghidra-ppc.mjs", "verify:ghidra:ppc64": "npm run build:cached && node scripts/verify-real-ghidra-ppc64.mjs", "verify:ghidra:dol": "npm run build:cached && node scripts/verify-real-ghidra-dol.mjs", "verify:ghidra:riscv": "npm run build:cached && node scripts/verify-real-ghidra-riscv.mjs", "verify:ghidra:6502": "npm run build:cached && node scripts/verify-real-ghidra-6502.mjs", "verify:ghidra:m68k": "npm run build:cached && node scripts/verify-real-ghidra-m68k.mjs", "verify:ghidra:mips-shared": "npm run build:cached && node scripts/verify-real-ghidra-mips-shared.mjs", "verify:ghidra:mips32-shared": "npm run build:cached && node scripts/verify-real-ghidra-mips32-shared.mjs", "verify:ghidra:mips-relocatable": "npm run build:cached && node scripts/verify-real-ghidra-mips-relocatable.mjs", "verify:ghidra:swift": "npm run build:cached && node scripts/verify-real-ghidra-swift.mjs", "verify:ida": "npm run build:cached && node scripts/verify-real-ida.mjs", "verify:ghidra:switch": "npm run build:cached && node scripts/verify-real-ghidra-switch.mjs", "verify:kuna": "npm run build:cached && node scripts/verify-real-kuna.mjs", "verify:ghidra:dos": "npm run build:cached && node scripts/verify-real-ghidra-dos.mjs", "verify:ghidra:loader-relocation": "npm run build:cached && node scripts/verify-ghidra-loader-relocation.mjs", "verify:ghidra:com": "npm run build:cached && node scripts/verify-real-ghidra-com.mjs", "verify:ghidra:raw": "npm run build:cached && node scripts/verify-real-ghidra-raw.mjs", "verify:ghidra:address-context": "npm run build:cached && node scripts/verify-real-ghidra-address-context.mjs", "verify:ghidra:aarch64-jump-table": "npm run build:cached && node scripts/verify-real-ghidra.mjs --aarch64-jump-table", "verify:interface-builder": "npm run build:cached && node scripts/verify/apple/interface-builder.mjs", "verify:ghidra:cross-format": "npm run build:cached && node scripts/verify-real-ghidra.mjs --cross-format", "verify:ghidra:windows": "npm run build:cached && npm run build:ghidra-windows-fixture && node scripts/verify-real-ghidra-windows.mjs", "verify:browser": "npm run build:cached && node scripts/verify-real-browser.mjs", "verify:frida": "npm run build:cached && node scripts/verify-frida.mjs", "verify:frida - README.md (16339 bytes)
<div align="center"> **English** · [简体中文](docs/readme/README_zh.md) · [繁體中文](docs/readme/README_zh-TW.md) · [日本語](docs/readme/README_ja.md) · [한국어](docs/readme/README_ko.md) · [Türkçe](docs/readme/README_tr.md) · [Русский](docs/readme/README_ru.md) · [Tiếng Việt](docs/readme/README_vi.md) · [ไทย](docs/readme/README_th.md) · [Deutsch](docs/readme/README_de.md) · [Español](docs/readme/README_es.md) · [Français](docs/readme/README_fr.md) · [Українська](docs/readme/README_uk.md) · [Polski](docs/readme/README_pl.md) · [Português (Brasil)](docs/readme/README_pt-BR.md) · [العربية](docs/readme/README_ar.md) · [فارسی](docs/readme/README_fa.md) · [Bahasa Indonesia](docs/readme/README_id.md) · [Italiano](docs/readme/README_it.md) · [Ελληνικά](docs/readme/README_el.md) · [മലയാളം](docs/readme/README_ml.md) · [Roman Urdu](docs/readme/README_ur-Latn.md) · [Română](docs/readme/README_ro.md) · [Български](docs/readme/README_bg.md) # REA: Reverse Engineer Anything ### One MCP for reverse engineering across binaries, applications, and runtime behavior. **See a feature you like. Understand how it works, down to the binary level.** [](https://github.com/morluto/rea/stargazers) [](https://www.npmjs.com/package/rea-agents) [](LICENSE) [](https://discord.gg/GkcryMnJDM) [](https://x.com/reatools) [](docs/getting-started/installation.md) [](https://skills.sh/morluto/rea/reverse-engineer-anything) **[Website](https://rea.tools/) · [Guides](https://rea.tools/guides/) · [Showcases](https://rea.tools/showcase/)** <a href="https://discord.com/invite/GkcryMnJDM"><img alt="Join the REA community on Discord" src="https://img.shields.io/badge/Join%20us%20on%20Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white" height="40"></a> [Quick start](#quick-start) · [Showcases](#showcases) · [How REA works](#how-rea-works) · [What you can analyze](#what-you-can-analyze) · [Build RL environments](#build-rl-environments) · [FAQ](#faq) · [Documentation](#documentation) <code>npx rea-agents setup</code> </div> > [!IMPORTANT] > Get REA from [morluto/rea](https://github.com/morluto/rea), > [rea.tools](https://rea.tools/), or the [rea-agents npm package](https://www.npmjs.com/package/rea-agents). > Follow the installation and release links from these official sources. A similar > repository name or copied README does not establish that a download is official. <div align="center"> <br /> <img src="docs/assets/rea-hopper-analysis.png" alt="REA launching its analysis bridge inside Hopper while inspecting a native binary" width="1200" /> <br /><br /> <table aria-label="REA community"> <tr> <td align="center" width="360"> <a href="https://discord.gg/GkcryMnJDM"> <img src="docs/assets/discord.svg" height="42" alt="Discord" /><br /> <strong>Join the Reverse Engineering Community</strong> </a><br /> <sub>Discord · Q&A · Show and Tell</sub> </td> </tr> </table> <br /> </div> --- See a feature in an app that you want in your own product? Ask your agent to investigate it with REA. It can inspect the app without its source code, explain how the feature works, show the evidence, and build a version for your project. REA connects your agent to tools for inspecting native binaries, JavaScript and Electron apps, .NET assemblies, and websites. You can also use the same tools from your terminal. Analysis runs locally, and results include the evidence and limitations behind each conclusion. Setup registers REA with your agent and installs matching workflow instructions. Native analysis can use an existing Hopper, Ghidra, IDA or Kuna installation; setup can optionally install Hopper with approval. Static JavaScript analysis needs no native analysis engine. ## Quick start **[Get started at rea.tools](https://rea.tools/get-started/)** for step-by-step instructions by operating system, agent, and analysis provider. ### Connect your agent (MCP) With [Node.js and npm](docs/reference/supported-targets.md) installed, run this from a trusted directory outside the project you plan to analyze. ```bash npx rea-agents setup ``` Choose your agent, review and approve the setup plan, then restart your agent. Setup backs up existing configuration and adds REA's MCP connection and investigation skill. See the [installation guide](docs/getting-started/installation.md) for supported clients, plugins, manual registration, and troubleshooting. Try asking your agent: ```text Understand how search works in the Notes app, show me the evidence, and build a similar feature for my project. ``` Replace Notes with your target app and the feature you want to understand. ### Use REA from the terminal (CLI) Inspect an extracted JavaScript/Electron app directory or ASAR: ```bash npx -y rea-agents@latest analyze-javascript-application /absolute/path/to/app --json ``` The result includes modules, imports, Electron boundaries and their evidence. Replace the path with your target, such as `"D:/apps/example"` on Windows. To install the `rea` command for regular use: ```bash npm install --global rea-agents rea --help ``` For native analysis, configure a provider first. The [CLI and Evidence guide](docs/getting-started/cli.md) covers provider selection, native commands, snapshots, and scripting. For Linux prerequisites, see the [installation guide](docs/getting-started/installation.md#linux-owned-process-prerequisite). ### Update REA For a global npm or Bun installation, run the updater and follow its setup instructions. ```bash rea update ``` If you use `npx`, refresh your agent setup with: ```bash npx rea-agents@latest setup ``` Review the setup changes and restart your agent. See [update and uninstall instructions](docs/getting-started/installation.md#diagnose-update-and-remove) for package runner options and troubleshooting. ## Showcases <a href="https://rea.tools/showcase/"> <picture> <source media="(prefers-color-scheme: dark)" srcset="docs/assets/rea-showcases-dark.svg" /> <img alt="Illustrations of the DX-Ball sound-pan, Notion clipboard-bridge, and TH04 bullet-ring showcases" src="docs/assets/rea-showcases.svg" /> </picture> </a> <table> <tbody> <tr> <td> <h3>DX-Ball: reconstruct a sound-pan calculation</h3> <p>Recover a position-to-pan helper from x86 instructions and verify the C reconstruction against 3,205 original-x86 cases and all 63 compiled function bytes.</p> <a href="https://rea.tools/showcase/dx-ball/">Read the case study</a> · <a href="https://github.com/N0zoM1z0/dx-ball">Reconstruction repository</a> </td> </tr> <tr> <td> <h3>Notion: trace the Electron clipboard bridge</h3> <p>Follow the renderer’s clipboard API through preload and IPC into the main process to see how Notion handles rich clipboard data.</p> <a href="https://rea.tools/showcase/notion/">Read the case study</a> </td> </tr> <tr> <td> <h3>TH04: recover a DOS bullet-ring calculation</h3> <p>Recover fixed and aimed angle calculations from the PC-98 game’s 16-bit instructions and compare the reconstructed C++ with historical compiler output.</p> <a href="https://rea.tools/showcase/th04/">Read the case study</a> · <a href="https://github.com/N0zoM1z0/th04">Reconstruction repository</a> </td> </tr> </tbody> </table> If you've used REA on something interesting, we'd love to see it. Share your case in an [issue](https://github.com/morluto/rea/issues) or a [pull request](https://github.com/morluto/rea/pulls), including the target, your question, how REA helped, and what you found. ## How REA works Your agent uses REA through MCP to inspect a target and trace the relevant code. It can use the evidence REA returns to ask follow-up questions, explain behavior, or build and test an implementation. The CLI uses the same workflows.  [Open the full-size figure](website/public/assets/figures/rea-investigation-flow.svg). <a id="current-status"></a> ## What you can analyze REA covers native binaries, JavaScript and Electron apps, websites, .NET assemblies, Android apps, firmware, and recorded runtime and network activity. [Supported targets and requirements](docs/reference/supported-targets.md) <a id="choosing-a-deep-analysis-provider"></a> For native decompilation, choose a provider that supports your target format and host OS. See [choosing a deep analysis provider](docs/reference/supported-targets.md#choosing-a-deep-analysis-provider). ## Build RL environments Build a local environment from a recorded web session or a Linux desktop app so an agent can practice a task and check its result. [Build an RL environment with REA](https://rea.tools/guides/rl-environments/). ## FAQ <details> <summary><strong>Which agents can use REA?</strong></summary> Any agent that supports local MCP servers. Setup configures the [supported agents](docs/getting-started/installation.md#supported-agents); other clients can use [manual MCP registration](docs/getting-started/installation.md#mcp-registry). </details> <details> <summary><strong>Do I need a native analysis engine?</strong></summary> Deep native analysis uses Hopper, Ghidra, IDA or Kuna, depending on the target and operation. Static JavaScript and .NET inspection work without a native analysis engine. Setup can install Hopper after approval; Ghidra, IDA and Kuna use your existing installations. See [provider setup](docs/getting-started/installation.md#hopper) for the options and their supported targets. </details> <details> <summary><strong>Do I need to start Hopper first?</strong></summary> REA starts Hopper when an operation needs it. On macOS, a first-run dialog may ask you to choose demo mode or activate your license. Complete that prompt in the same user session before your first CLI/MCP operation or unattended job. Open Hopper manually if needed. See [Hopper startup and troubleshooting](docs/getting-started/installation.md#launcher-paths-and-troubleshooting). </details> <details> <summary><strong>What does installing the skill from skills.sh do?</strong></summary> The skill supplies investigation instructions for your agent. Use `npx rea-agents setup` to register REA's MCP server and install the matching instructions, then restart your agent. See [skill-only installation](docs/getting-started/installation.md#skill-only-installation). </details> <details> <summary><strong>What code does REA return?</strong></summary> Native analysis returns pseudocode and assembly. JavaScript/Electron analysis recovers modules and their relationships. Your agent uses these findings to write and test an implementation; the [showcases](#showcases) give worked examples. </details> <details> <summary><strong>Does REA upload my app?</strong></summary> REA analyzes targets locally. Your agent receives the tool results, and its model provider has its own data policy. </details> <details> <summary><strong>What should I do if I hit a bug?</strong></summary> Update first; a recent release may already fix it. For a CLI installed with `npm install --global` or `bun add --global`: ```bash rea update ``` For agent setup through `npx`: ```bash npx rea-agents@latest setup ``` If you're using an agent, complete the [setup refresh](#update-rea) and restart it. Retry the same task. If the problem persists, [open an issue](https://github.com/morluto/rea/issues) with your REA version, target type, steps to reproduce and error output. </details> ## Documentation Start with the website's [worked guides](https://rea.tools/guides/). For exact options, prerequisites and result contracts: - [Installation and setup](docs/getting-started/installation.md): agent registration, provider configuration, updates and uninstall. - [Readiness and troubleshooting](docs/getting-started/installation.md#check-readiness-for-your-task): diagnose one agent or analysis engine. - [CLI and Evidence](docs/getting-started/cli.md): commands, provider selection, snapshots, import/export and exit statuses. - [MCP contracts](docs/reference/mcp-contracts.md) and [agent prompts](docs/getting-started/mcp-prompts.md): tool results, sessions and guided investigations. - [Tool catalog](docs/reference/mcp-contracts.md#generated-catalog): generated inventory of tools, providers and CLI commands. Report vulnerabilities through [SECURITY.md](SECURITY.md). ## Community & Support - **Discord** — Ask questions and share what you’re investigating with our passionate community of over 50,000 reverse engineers and builders! [](https://discord.gg/GkcryMnJDM) - **Twitter / X** — Follow [@reatools](https://x.com/reatools) for updates and announcements. - **Feedback & Ideas** — Want a new feature or support for a file format? [Open a GitHub issue](https://github.com/morluto/rea/issues) or [join our Discord](https://discord.gg/GkcryMnJDM) and let us know. ## Star history 🎉 **400,000 GitHub stars — thank you!** Thanks to everyone using REA, reporting bugs, requesting features, testing builds, and contributing fixes. <a href="https://rea.tools/contributors/"> <img src="website/public/contributors/avatars.png" alt="REA contributors" /> </a> <a href="https://www.star-history.com/?repos=morluto%2Frea&type=date"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=morluto/rea&type=date&theme=dark&legend=top-left" /> <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=morluto/rea&type=date" /> <img alt="REA GitHub star history" src="https://api.star-history.com/chart?repos=morluto/rea&type=date" /> </picture> </a> ## Contributing We'd love your help with REA! [Open an issue](https://github.com/morluto/rea/issues) to report a bug or suggest a feature, or [send a pull request](https://github.com/morluto/rea/pulls) to improve the code or docs. See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and checks. See the [testing guide](docs/development/testing.md) for v - release-please-config.json (2404 bytes)
{ "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", "release-type": "node", "versioning": "always-bump-minor", "include-v-in-tag": false, "changelog-sections": [ { "type": "feat", "section": "Features", "hidden": false }, { "type": "fix", "section": "Bug Fixes", "hidden": false }, { "type": "perf", "section": "Performance Improvements", "hidden": false }, { "type": "refactor", "section": "Code Refactoring", "hidden": false }, { "type": "docs", "section": "Documentation", "hidden": false }, { "type": "test", "section": "Tests", "hidden": false }, { "type": "chore", "section": "Chores", "hidden": true }, { "type": "ci", "section": "Continuous Integration", "hidden": false } ], "packages": { ".": { "package-name": "rea-agents", "extra-files": [ { "type": "generic", "path": "docs/getting-started/installation.md" }, { "type": "generic", "path": "src/generatedPackageMetadata.ts" }, { "type": "json", "path": "server.json", "jsonpath": "$.version" }, { "type": "json", "path": "server.json", "jsonpath": "$.packages[0].version" }, { "type": "json", "path": ".claude-plugin/plugin.json", "jsonpath": "$.version" }, { "type": "json", "path": ".claude-plugin/plugin.json", "jsonpath": "$.mcpServers.rea.args[1]" }, { "type": "json", "path": ".codex-plugin/plugin.json", "jsonpath": "$.version" }, { "type": "json", "path": ".codex-plugin/mcp.json", "jsonpath": "$.mcpServers.rea.args[1]" }, { "type": "json", "path": ".cursor-plugin/plugin.json", "jsonpath": "$.version" }, { "type": "json", "path": "mcp.json", "jsonpath": "$.mcpServers.rea.args[1]" }, { "type": "json", "path": ".claude-plugin/marketplace.json", "jsonpath": "$.plugins[0].source.version" }, { "type": "json", "path": ".agents/plugins/marketplace.json", "jsonpath": "$.plugins[0].source.version" } ] } } } - scripts/verify-tools/skills/package.json (201 bytes)
{ "name": "rea-verify-skills-cli", "private": true, "description": "Lockfile-pinned Skills CLI for the repository skill check in verify:package.", "dependencies": { "skills": "1.7.2" } } - SECURITY.md (8027 bytes)
# Security Policy ## Supported versions Security fixes are provided for the latest published version of REA. Upgrade to the latest release before reporting a problem that may already have been resolved. ## Security boundary REA is a local reverse-engineering and automation tool. CLI and MCP use the same application workflows and run with the host process's permissions. REA is not a general-purpose sandbox or a multi-tenant authorization service. ### Threat model - **Trusted authority:** the operating-system account running REA, the caller or agent host that selects operations, and configured analysis providers, their executables and extensions, and service endpoints. An MCP client can invoke the operations exposed to it; its host must enforce the user's tool permissions and approvals. - **Untrusted data:** target binaries, archives, source files, project contents, captures, web pages and returned target content can be malicious. Selecting an input for static inspection does not authorize commands embedded in that input. Agents must treat target text and Evidence as data rather than instructions granting additional authority. - **Operation-specific effects:** static inspection parses target data and may launch an analysis engine. Runtime, debugger, instrumentation, browser, desktop and environment workflows can deliberately execute code, attach to processes, make network requests, write files or interact with applications and devices. Review the selected operation's effects and limitations; static inspection does not authorize launching or interacting with the target application. See [runtime and network responsibilities](DISCLAIMER.md#runtime-network-and-device-operations). Standard client registrations use a dedicated stdio process. Opt-in [HTTP MCP](docs/reference/mcp-contracts.md#transports) uses plain HTTP without TLS or client authentication and shares provider/active-target state across protocol sessions. Its session ID is not a user-authentication or isolation boundary. Keep this endpoint within a trusted local or isolated environment. ### Intended security properties Static JavaScript and .NET inspection do not run the target application. Unexpected execution of input code through a data-only analysis path is a security concern. Analysis engines themselves are executable software trusted with the host account's permissions; parsing an input in an external engine does not isolate that engine from the host. REA authenticates its managed Hopper and Ghidra bridges with per-session random capability tokens transferred through private session files, rather than process arguments or environment variables. POSIX uses current-user Unix sockets. Windows Ghidra uses authenticated loopback TCP and a private NTFS runtime whose DACL admits only the current user and SYSTEM. These controls protect the managed session boundary, not every external provider or debugger endpoint. See [Windows Ghidra transport and lifecycle](docs/providers/windows-ghidra-p0.md#private-runtime-transport-and-lifecycle). Provider ownership and mutation rules remain specific to each workflow: - Ghidra's working projects are temporary and owned by REA. Opt-in [checkpoints](docs/getting-started/installation.md#automatically-checkpoint-an-owned-ghidra-program) retain REA-owned Program state. A [caller-selected existing project](docs/getting-started/installation.md#reuse-an-existing-ghidra-project) is fingerprinted and copied into an owned runtime for read-only processing; Ghidra does not open or save the original database through that workflow. - [IDA analysis](docs/providers/ida-provider.md) is read-only. An attached GUI database is never saved or closed by REA; owned headless sessions have a separate lifecycle. - Cleanup must stay within resources REA owns. Failed or unverified cleanup can retain a workspace or session for retry; closing a session does not imply that every investigation artifact has been erased. `rea setup` shows planned configuration and installation changes and requires approval before applying them. Ghidra, Java and IDA are user-managed. Approved Linux Hopper installation authenticates the package's detached PGP signature against the pinned publisher identity and checks the signed launcher against the selected release's digest. The release feed's display version is separate from that authenticated identity. See [installation and publisher verification](docs/getting-started/installation.md#hopper). ### Limits and caller responsibilities - **Host isolation:** private runtimes and capability tokens do not protect against malicious software already running as the same operating-system user, or a compromised trusted client or provider. Use an appropriately isolated account, VM or restricted environment when handling hostile targets. - **Resource bounds:** timeouts, cancellation, streaming and size limits are operation-specific. They are not a universal CPU, memory, disk or wall-time limit on every target and third-party tool. Enforce hard host resource limits externally when needed. Failures of a documented boundary or cancellation control still warrant investigation. - **Data and network exposure:** Evidence, caches, checkpoints, exports and captures can retain private target data, paths, URLs and memory contents. Local execution does not make these outputs safe to publish. Requested network operations, agent hosts and provider features such as [IDA Free's cloud decompiler](docs/providers/ida-provider.md) can communicate outside the host. Review their data handling and secure any exposed endpoint. - **Interpretation:** analysis, reconstruction and generated environments can be incomplete or incorrect. Identity checks, signatures and successful analysis do not establish that a target, provider or generated program is safe to execute. Review the Evidence and proposed actions before relying on them. ### Vulnerability scope Please report suspected violations of these boundaries privately. Examples include unintended code execution during data-only inspection, escaping a documented extraction/output boundary, bypassing bridge authentication or target/session identity checks, unauthorized effects on an unrelated resource, and disclosure of transport credentials or explicitly marked sensitive values. An attacker-triggered bypass of a documented resource or cancellation control can also be security-relevant without code execution. Incorrect analysis, unsupported formats, crashes, hangs and high resource use without a security-boundary impact are generally ordinary bug reports. Effects explicitly requested through an execution or interaction workflow are not by themselves a vulnerability. A dependency advisory needs its actual REA exposure assessed; a complete exploit or diagnosis is not required to report a concern. If you are unsure whether a boundary is affected, use the private channel below. ## Reporting a vulnerability Do not disclose vulnerabilities, proof-of-concept exploits, credentials, private binaries, Hopper documents, or private Ghidra projects in a public issue. Use **Report a vulnerability** in the repository's **Security** tab as the preferred way to submit the report privately. If GitHub private reporting is unavailable to you, email [[email protected]](mailto:[email protected]). Do not open a public issue to request a private contact channel. Include the affected REA version, operating system/distribution, selected provider and version, impact, reproduction conditions, and any suggested mitigation in the private report. Remove credentials, proprietary binaries, Hopper documents, Ghidra project contents, socket capability tokens, and unrelated local paths from logs or examples. The maintainer will acknowledge the report, assess its scope, and coordinate remediation and disclosure timing with the reporter. Please allow time for provider-dependent behavior to be reproduced safely.
- server.json (789 bytes)
{ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "name": "io.github.morluto/rea", "title": "REA", "description": "Reverse engineer anything from your terminal or agent with one CLI and MCP server.", "websiteUrl": "https://github.com/morluto/rea", "repository": { "url": "https://github.com/morluto/rea", "source": "github" }, "version": "6.10.1", "packages": [ { "registryType": "npm", "registryBaseUrl": "https://registry.npmjs.org", "identifier": "rea-agents", "version": "6.10.1", "runtimeHint": "npx", "transport": { "type": "stdio" }, "packageArguments": [ { "type": "positional", "value": "mcp" } ] } ] } - SKILL.md (7762 bytes)
--- name: rea-analysis-optimization description: Optimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit. --- # REA analysis optimization Find a concrete source of unnecessary work, change it at its owner, and verify equivalent completed investigations. A useful outcome can also be a measured decision to leave an implementation alone. Follow the checkout's [performance priorities](../../../AGENTS.md#performance), [tool design](../../../docs/development/tool-design.md), and [testing guide](../../../docs/development/testing.md). This skill supplies an optimization workflow, not additional permission to execute targets, publish, or merge. Use the current contracts, provider prerequisites, and user authorization. Reserve performance measurements for changes that target performance or have a concrete regression concern. Routine cleanup uses correctness checks and does not require this optimization workflow or synthetic benchmarks merely because helper calls, imports, or representations change. Read [the Kuna case study](references/kuna-case-study.md) when selecting a reuse strategy or interpreting a benchmark. Its pinned observations illustrate tradeoffs; they are not current-provider guarantees or universal speedups. ## Pin the question and the correctness oracle Describe the analyst's completed task, including the facts and relationships needed to answer it, requested detail, source access, and meaningful unknowns. Choose a representative real artifact and a small or empty case. Record the baseline revision, target digest, engine identity, options, host, and entrypoint. Use a separate checkout for changes without disturbing other work. Establish an oracle independent of the changed implementation: source-built fixture expectations, independently mapped file bytes, or a native producer paired with checks of its interpretation. Comparing two wrappers around the same faulty decoder does not establish correctness. Preserve address widths, same-address alternatives, unresolved endpoints, coverage, and source linkage. An empty result proves absence only within the actually examined scope. ## Locate the earliest unnecessary work Trace one public CLI or MCP task through shared application code to its producer. Measure relevant phases: admission and identity checks, native analysis, decoding, lookup, projection, serialization, Evidence retention, and cleanup. Include catalog discovery and extra calls when they affect the completed task. Use the evidence to choose the smallest structural correction: | Observed cost | Candidate correction | Condition to establish | | --------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------ | | Repeated scans of validated facts | Reuse existing order or lookup structure | The owner establishes ordering and identity; every matching alternative survives | | Repeated equivalent engine work | Share a validated result or in-flight producer | Inputs, freshness, lifetime, and per-caller outcomes remain explicit | | Full reports for selected facts | Push selection or projection to the earliest capable owner | Required facts and evidence remain reachable; examined coverage is reported | | Large temporary transport buffers | Decode incrementally or use bounded source reads | Validate the whole admitted document; retained facts and copies still consume memory | | Many repeated homogeneous reads | Share admission, decoding, or batch work | Preserve item identity, order where required, and individual failures | Do not introduce an index, generic cache, batch endpoint, or orchestration layer without identifying the work it removes and its maintenance/resource cost. Projection after materializing a full report may reduce output while leaving analysis time and peak memory unchanged. Fix missing or incorrect facts before benchmarking an alternative composition against a better-covered workflow. ## Keep one interpretation and a defined reuse lifetime Let the producer boundary validate and normalize facts once. Consumers query that representation through the shared CLI/MCP implementation; adapters should not rebuild relationships or independently reinterpret raw reports. Keep lookup identity separate from display formatting. Reuse contracts when their intent matches, honoring requested detail and complete Evidence access. For every cache or shared producer, state its key, owner, invalidation, retained size, and lifetime. Account for result-affecting target bytes, engine contents, analysis options, architecture/load mapping, and parser/schema versions where they affect reuse. Validate live state before calling a cached observation current. Cache a refusal only when it is deterministic for that validated key; malformed, partial, transient, or cancelled attempts need explicit retry policy. One cancelled waiter must not invalidate a successful peer. Preserve producer failure context and each caller's cancellation reason. Retain ownership and capacity charges until shared work and cleanup settle; preserve completed observations when cleanup fails. Exercise invalidation, concurrent consumers, last-waiter cancellation, close, and cleanup retry when those paths change. Bound the process family and retained state, not just a parent heap or worker count. Account for decoding and serialization expansion before allocation. Choose CPU, memory, concurrency, and disk limits from the host and workload; stop before OOM and verify owned cleanup. A guard-stopped task is incomplete. Do not replace a transport buffer cap with an unbounded retained inventory or hide partial results behind a success status. ## Compare completed tasks and limit the claim Run the affected real public workflow before and after with equivalent inputs, results, coverage, and Evidence semantics. Include small inputs so setup costs and regressions are visible. Distinguish fresh sessions, warm runtime caches, and OS file caches. Alternate or repeat runs when variance affects the decision. Choose meaningful boundary regressions for cases the actual engine cannot reliably reproduce; a fake engine does not qualify a real provider. Report task outcome, relevant phase timings, total elapsed and CPU time, peak process-family memory and its accounting method, resource stops, and cleanup. Check the payload exit status as well as the profiler's. Keep failed attempts and identify unmeasured costs; a passing retry does not explain a failure. For token claims, count schemas/discovery, arguments, replies, retries, and continuations needed to finish the task. Label tokenizer estimates separately from actual model usage and record the client/catalog behavior. Smaller JSON alone establishes neither fewer model tokens nor better investigation quality. Do not claim a complex-software advantage without completed representative investigations and comparable correctness/coverage. Finish with the bottleneck, owning change, preserved semantics, executed checks, before/after measurements, and remaining limits. Keep any integration record current with its tested revision and distinguish merged production work from experiment-only code. Stop when the demonstrated bottleneck is resolved or further benefit remains speculative.
- src/adb/AdbCommand.capture.test.ts (4012 bytes)
import { afterAll, expect, it } from "vitest"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { ArtifactResourceScope } from "../resources/index.js"; import { runAdbCapture } from "./AdbCommand.js"; const resources = new ArtifactResourceScope(); afterAll(() => resources.close()); // Exercise the real subprocess capture and public error projection, substituting // only the bring-your-own executable. These are not Android-device checks. it.each([ { name: "overflow", source: 'process.stdout.write("X".repeat(4096))', maxOutputBytes: 64, code: "resource_constraint", stdout: "X".repeat(64), stderr: "", truncated: true, }, { name: "timeout", source: 'process.stdout.write("partial-雪"); process.stderr.write("waiting\\n"); setInterval(() => {}, 1000)', code: "provider_timeout", timeoutMs: 500, stdout: "partial-雪", stderr: "waiting\n", }, { name: "offline device", source: 'process.stdout.write("partial-雪"); process.stderr.write("adb: error: device offline\\n"); process.exitCode = 1', code: "unsupported_target", expectedPath: "caller-device", stdout: "partial-雪", stderr: "adb: error: device offline\n", }, { name: "local path refusal", source: 'process.stdout.write("partial-雪"); process.stderr.write("adb: error: cannot stat \'/host/token file\': Permission denied\\n"); process.exitCode = 1', code: "unsupported_target", expectedPath: "/host/token file", stdout: "partial-雪", stderr: "adb: error: cannot stat '/host/token file': Permission denied\n", }, ])("preserves bounded capture on $name", async (testCase) => { const result = await runAdbCapture( "pull_adb_file", { device: "caller-device", path: "/remote/source", localPath: "/host/token file", }, { binary: process.execPath, pathSource: "environment", environment: { REA_TEST_PRIVATE: "ambient-value-must-not-be-persisted" }, resources, }, ["-e", testCase.source], { timeoutMs: testCase.timeoutMs ?? 5_000, maxOutputBytes: testCase.maxOutputBytes ?? 1024, }, undefined, ); expect(result.ok).toBe(false); if (result.ok) return; const projected = projectAnalysisError(result.error); expect(projected).toMatchObject({ code: testCase.code, details: { captured_output: { stdout: testCase.stdout, stderr: testCase.stderr, stdout_bytes: Buffer.byteLength(testCase.stdout), stderr_bytes: Buffer.byteLength(testCase.stderr), truncated: testCase.truncated ?? false, }, }, }); if (testCase.code === "unsupported_target") expect(projected.details?.path).toBe(testCase.expectedPath); if (testCase.code === "provider_timeout") { expect(projected.details?.timeout_ms).toBe(testCase.timeoutMs); expect(projected.details?.limit).toBeUndefined(); } expect(JSON.stringify(projected)).not.toContain( "ambient-value-must-not-be-persisted", ); }); it.each([true, false])( "projects a truncated adb capture as retryable only for volatile output (%s)", async (volatileOutput) => { const result = await runAdbCapture( volatileOutput ? "read_adb_logcat" : "install_adb_package", { device: "device" }, { binary: process.execPath, pathSource: "environment", environment: {}, resources, }, ["-e", 'process.stdout.write("X".repeat(4096))'], { timeoutMs: 5_000, maxOutputBytes: 1024, volatileOutput }, undefined, ); if (result.ok) throw new Error("Expected a capture allowance refusal"); const projected = projectAnalysisError(result.error); expect(projected.retryable).toBe(volatileOutput); expect(projected).toMatchObject({ code: "resource_constraint", details: { reported_limits: { max_output_bytes: 1024 } }, }); expect(projected.details?.limit).toBeUndefined(); }, ); - src/adb/AdbCommand.test.ts (14519 bytes)
import { afterAll, beforeAll, expect, it } from "vitest"; import { primaryAnalysisError } from "../domain/analysisErrorBase.js"; import { probeAdbPathExistence, runAdbCapture } from "./AdbCommand.js"; import type { AdbCommandHost } from "./AdbProcess.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { spawnOwnedProviderProcess } from "../process/ProviderProcess.js"; import { prepareProcessOwnershipInspection } from "../process/ProcessOwnershipObservation.js"; import { ArtifactResourceScope } from "../resources/index.js"; import { spawnFailure } from "../../tests/support/process/spawnFailure.js"; const resources = new ArtifactResourceScope(); beforeAll(() => prepareProcessOwnershipInspection()); afterAll(() => resources.close()); const selection = { binary: "/host/adb", pathSource: "environment", environment: {}, resources, } as const; /** A real owned process standing in for adb, running `script` under Node. */ const scripted = ( script: string, observe?: (stream: "stdout" | "stderr", text: string) => void, ): AdbCommandHost => ({ ...selection, launcher: async (input) => { const launched = await spawnOwnedProviderProcess({ ...input, command: process.execPath, arguments: ["-e", script], }); if (observe !== undefined) for (const stream of ["stdout", "stderr"] as const) launched.process[stream]?.on("data", (chunk: Buffer) => observe(stream, chunk.toString("utf8")), ); return launched; }, }); /** adb exits on its own with this output and status. */ const exits = ( code: number, output: { readonly stdout?: string; readonly stderr?: string } = {}, ): AdbCommandHost => scripted( `process.stdout.write(${JSON.stringify(output.stdout ?? "")});` + `process.stderr.write(${JSON.stringify(output.stderr ?? "")});` + `process.exitCode = ${String(code)};`, ); /** The host refuses to start adb with this launcher error. */ const refused = (failure: unknown): AdbCommandHost => ({ ...selection, launcher: async () => { throw failure; }, }); const probe = (host: AdbCommandHost, signal?: AbortSignal) => probeAdbPathExistence( "push_adb_file", "device", "/device/path", host, { timeoutMs: 10_000, maxOutputBytes: 1024, }, signal, ); it("classifies the complete diagnostic before shortening its displayed reason", async () => { const localPath = `/host/${"directory/".repeat(60)}payload.bin`; const stderr = `adb: error: cannot create '${localPath}': Permission denied`; await expect( runAdbCapture( "pull_adb_file", { device: "device", path: "/remote/file", localPath }, exits(1, { stderr }), [], { timeoutMs: 10_000, maxOutputBytes: 2048 }, undefined, ), ).resolves.toMatchObject({ ok: false, error: { _tag: "AnalysisUnsupportedTargetError", path: localPath, reason: `${stderr.slice(0, 512)}…`, }, }); }); it("recognizes only the completed empty false result as absence", async () => { await expect(probe(exits(1))).resolves.toEqual({ ok: true, value: { matches: false, capturedOutput: { exit_code: 1, stdout: "", stderr: "", stdout_bytes: 0, stderr_bytes: 0, signal: null, truncated: false, }, }, }); }); it.each([ ["exit status 2", exits(2)], ["a refused launch", refused(spawnFailure("ENOENT", "/host/adb"))], [ "a signal exit", scripted( "process.kill(process.pid, 'SIGTERM'); setInterval(() => {}, 1000)", ), ], ["unexpected stdout", exits(1, { stdout: "unexpected" })], ["unrecognized stderr", exits(1, { stderr: " " })], ] as const)( "keeps nonstandard false completion unknown: %s", async (_case, host) => { expect(await probe(host)).toMatchObject({ ok: false, error: { _tag: "AnalysisProtocolError" }, }); }, ); it("keeps a nonstandard false completion's destination status unknown", async () => { expect(await probe(exits(2))).toMatchObject({ ok: false, error: { _tag: "AnalysisProtocolError", diagnostics: { destination_existence: "unknown" }, capturedOutput: { exit_code: 2 }, }, }); }); it("preserves a probe stopped at its deadline", async () => { const result = await probeAdbPathExistence( "push_adb_file", "device", "/device/path", scripted("setInterval(() => {}, 1000)"), { timeoutMs: 100, maxOutputBytes: 1024 }, undefined, ); expect(result).toMatchObject({ ok: false, error: { _tag: "AnalysisTimeoutError" }, }); }); it.each([ [true, "live", true], [undefined, "capture", false], ] as const)( "stops output beyond the capture allowance and names its byte value (volatile output: %s)", async (volatileOutput, kind, retryable) => { const result = await runAdbCapture( "list_adb_devices", { device: "device" }, scripted( "process.stdout.write('x'.repeat(64 * 1024)); setInterval(() => {}, 1000)", ), ["devices"], { timeoutMs: 10_000, maxOutputBytes: 1024, ...(volatileOutput === undefined ? {} : { volatileOutput }), }, undefined, ); if (result.ok) throw new Error("Expected a capture refusal"); expect(result.error).toMatchObject({ _tag: "AnalysisResourceConstraintError", retryable, capturedOutput: { stdout: "x".repeat(1024), truncated: true }, }); expect(result.error).toHaveProperty("fixedAllowance", { name: expect.any(String), kind, limit: 1024, unit: "bytes", }); }, ); it("recognizes an empty successful probe as existence", async () => { await expect(probe(exits(0))).resolves.toEqual({ ok: true, value: { matches: true, capturedOutput: { exit_code: 0, stdout: "", stderr: "", stdout_bytes: 0, stderr_bytes: 0, signal: null, truncated: false, }, }, }); }); it.each(["stdout", "stderr"] as const)( "retains unexpected successful %s as unknown", async (stream) => { await expect( probe(exits(0, { [stream]: "unexpected" })), ).resolves.toMatchObject({ ok: false, error: { _tag: "AnalysisProtocolError", capturedOutput: { [stream]: "unexpected", exit_code: 0 }, }, }); }, ); it("hands back stdout bytes that are not UTF-8 exactly", async () => { const result = await runAdbCapture( "capture_adb_screen", { device: "device" }, scripted("process.stdout.write(Buffer.from([0x89, 0xff, 0x00]))"), ["exec-out", "screencap", "-p"], { timeoutMs: 10_000, maxOutputBytes: 3 }, undefined, ); if (!result.ok) throw result.error; expect([...result.value.stdout]).toEqual([0x89, 0xff, 0x00]); }); it.each([null, "caller stopped", new Error("caller stopped")] as const)( "uses the command owner's exact %s cancellation reason", async (reason) => { const controller = new AbortController(); const seen = { stdout: "", stderr: "" }; const result = await probe( scripted( "process.stdout.write('partial'); process.stderr.write('diagnostic'); setInterval(() => {}, 1000)", (stream, text) => { seen[stream] += text; if (seen.stdout === "partial" && seen.stderr === "diagnostic") controller.abort(reason); }, ), controller.signal, ); expect(result).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" }, }); if (result.ok) throw new Error("Expected owned cancellation"); expect(result.error.cause).toBe(reason); expect(result.error.capturedOutput).toMatchObject({ stderr: "diagnostic", stderr_bytes: 10, }); }, ); it("keeps a physical failure even when the later abort reason is that same error", async () => { const controller = new AbortController(); const failure = new Error("physical command failure"); const result = await runAdbCapture( "inspect_adb_device", { device: "device" }, { ...selection, launcher: async () => { controller.abort(failure); throw failure; }, }, [], { timeoutMs: 10_000, maxOutputBytes: 1024 }, controller.signal, ); expect(result).toMatchObject({ ok: false, error: { _tag: "AnalysisProtocolError", cause: failure }, }); }); const STARTUP_NOTICES = [ "* daemon not running; starting now at tcp:5037\n* daemon started successfully\n", "* daemon not running. starting it now on port 5037 *\r\n* daemon started successfully *\r\n", ]; it.each(STARTUP_NOTICES)( "recognizes completed true and false probes with successful startup: %j", async (stderr) => { await expect(probe(exits(0, { stderr }))).resolves.toMatchObject({ ok: true, value: { matches: true, capturedOutput: { stdout: "", stderr, exit_code: 0, stderr_bytes: Buffer.byteLength(stderr), }, }, }); await expect(probe(exits(1, { stderr }))).resolves.toMatchObject({ ok: true, value: { matches: false, capturedOutput: { stdout: "", stderr, exit_code: 1, stderr_bytes: Buffer.byteLength(stderr), }, }, }); }, ); it.each([ "* daemon not running; starting now at tcp:5037\n", "* daemon failed to start\n", "* daemon started successfully\n* daemon not running; starting now at tcp:5037\n", "* daemon started successfully\nunexpected\n", "\n", " ", ])("refuses an incomplete or unknown startup output: %j", async (stderr) => { await expect(probe(exits(0, { stderr }))).resolves.toMatchObject({ ok: false, error: { capturedOutput: { stderr, exit_code: 0 } }, }); await expect(probe(exits(1, { stderr }))).resolves.toMatchObject({ ok: false, error: { capturedOutput: { stderr, exit_code: 1 } }, }); }); it("reports an adb that never started without claiming an exit code", async () => { const result = await runAdbCapture( "list_adb_devices", { device: "device" }, refused(spawnFailure("ENOTDIR", "/host/adb")), ["devices"], { timeoutMs: 10_000, maxOutputBytes: 1024 }, undefined, ); if (result.ok) throw new Error("Expected a launch failure"); expect(result.error).toMatchObject({ _tag: "AnalysisProtocolError", message: "adb could not be started (ENOTDIR) for list_adb_devices", }); expect(result.error.capturedOutput).toBeUndefined(); }); it.each([ ["EAGAIN", "capacity", true, { boundary: "host-capacity" }], // Device commands carry request operands, so the request may shrink too. [ "E2BIG", "transport", false, { boundary: "provider-launch", oversized_launch_input: "request_and_environment", }, ], ] as const)( "reports host launch constraint %s through the shared launch owner rather than as an adb protocol failure", async (code, resource, retryable, facts) => { const result = await runAdbCapture( "list_adb_devices", { device: "device" }, refused(spawnFailure(code, "/host/adb")), ["devices"], { timeoutMs: 10_000, maxOutputBytes: 1024 }, undefined, ); if (result.ok) throw new Error("Expected a launch constraint"); expect(result.error).toMatchObject({ _tag: "AnalysisResourceConstraintError", resource, retryable, reportedLimits: { spawn_error: code }, }); expect(projectAnalysisError(result.error)).toMatchObject({ details: { diagnostics: { system_code: code, command: "/host/adb", ...facts }, }, }); }, ); it("keeps a completed adb refusal primary when post-exit cleanup fails or is cancelled", async () => { const localResources = new ArtifactResourceScope(); const controller = new AbortController(); const cancelledResult = await runAdbCapture( "install_adb_package", { device: "emulator-5554" }, { ...selection, resources: localResources, launcher: async (input) => { const launched = await spawnOwnedProviderProcess({ ...input, command: process.execPath, arguments: [ "-e", "process.stderr.write('Failure [INSTALL_FAILED_INVALID_APK]\\n'); process.exitCode = 1;", ], }); return { ...launched, cleanup: async () => { controller.abort("late abort during sweep"); return { cleaned: true, signaled: false }; }, }; }, }, [], { timeoutMs: 10_000, maxOutputBytes: 1024 }, controller.signal, ); if (cancelledResult.ok) throw new Error("Expected refusal"); expect(primaryAnalysisError(cancelledResult.error)).toMatchObject({ _tag: "AnalysisUnsupportedTargetError", path: "emulator-5554", reason: "INSTALL_FAILED_INVALID_APK", }); expect(cancelledResult.error.secondaryFailures).toMatchObject([ { _tag: "AnalysisCancelledError", cause: "late abort during sweep" }, ]); let attempts = 0; const cleanupResult = await runAdbCapture( "install_adb_package", { device: "emulator-5554" }, { ...selection, resources: localResources, launcher: async (input) => { const launched = await spawnOwnedProviderProcess({ ...input, command: process.execPath, arguments: [ "-e", "process.stderr.write('Failure [INSTALL_FAILED_INVALID_APK]\\n'); process.exitCode = 1;", ], }); return { ...launched, cleanup: async () => { attempts += 1; return attempts === 1 ? { cleaned: false, reason: "sweep temporarily blocked" } : { cleaned: true, signaled: false }; }, }; }, }, [], { timeoutMs: 10_000, maxOutputBytes: 1024 }, undefined, ); if (cleanupResult.ok) throw new Error("Expected refusal with cleanup error"); expect(primaryAnalysisError(cleanupResult.error)).toMatchObject({ _tag: "AnalysisUnsupportedTargetError", path: "emulator-5554", reason: "INSTALL_FAILED_INVALID_APK", }); expect(projectAnalysisError(cleanupResult.error)).toMatchObject({ code: "cleanup_incomplete", details: { execution_failure: "unsupported_target" }, }); await localResources.close(); expect(attempts).toBe(2); }); - src/adb/AdbCommand.ts (14170 bytes)
import { AnalysisProtocolError, AnalysisResourceConstraintError, AnalysisTimeoutError, AnalysisUnsupportedTargetError, cancelledBy, } from "../domain/analysisErrorCore.js"; import { primaryAnalysisError, type AnalysisError, } from "../domain/analysisErrorBase.js"; import { ellipsisExcerpt } from "../domain/excerpt.js"; import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js"; import { err, ok, type Result } from "../domain/result.js"; import { errorMessage } from "../kernel/errorMessage.js"; import { adbRunFailureError, runAdbProcess, type AdbCommandHost, type AdbExitedRun, type AdbRunFailure, } from "./AdbProcess.js"; import { classifyLaunchFailure } from "../process/classifyProviderOutcome.js"; import { packageChangeFailureReason } from "./AdbShellOutput.js"; import { isSuccessfulDaemonStartNotice, isDaemonStartingNotice, hasOnlySuccessfulAdbStartupNotices, } from "./AdbDeviceOutput.js"; import { ADB_BINARY_ENV } from "./AdbConfiguration.js"; const STDERR_EXCERPT_CHARACTERS = 512; // Match the known host operand in adb's local-file diagnostics. The suffix is // part of the format: opening/reading identify local failures explicitly. const LOCAL_FILE_DIAGNOSTICS = [ ["cannot create", ":"], ["cannot create file/directory", ":"], ["cannot stat", ":"], ["cannot open", ":"], ["cannot write", ":"], ["failed to stat local file", ":"], ["failed to read all of", ":"], ["failed to access", ":"], ["failed to stat", ":"], ["failed to open", ":"], ["opening", " locally failed:"], ["reading", " locally failed:"], ] as const; /** adb's own nonzero exit, kept for consumers that read its verdict. */ class AdbProtocolError extends AnalysisProtocolError { constructor( message: string, readonly run: AdbExitedRun, ) { super(message, { capturedOutput: run.capturedOutput }); } } /** The completed run behind a nonzero adb exit reported here. */ export const adbExitedRunOf = ( error: AnalysisError, ): AdbExitedRun | undefined => { const primary = primaryAnalysisError(error); return primary instanceof AdbProtocolError ? primary.run : undefined; }; /** adb joins shell operands into a remote POSIX command; quote at that boundary. */ const quoteShellOperand = (value: string): string => /^[A-Za-z0-9_./:=@+,-]+$/u.test(value) ? value : "'" + value.replaceAll("'", "'\\''") + "'"; export const adbArguments = ( serial: string | undefined, arguments_: readonly string[], ): readonly string[] => { const operands = arguments_[0] === "shell" ? ["shell", ...arguments_.slice(1).map(quoteShellOperand)] : [...arguments_]; return serial === undefined ? operands : ["-s", serial, ...operands]; }; export interface AdbRunLimits { readonly timeoutMs: number; readonly maxOutputBytes: number; /** * Live device observations can shrink between calls. Mutation commands omit * this so a truncated result stays non-retryable. */ readonly volatileOutput?: boolean; } /** Keep the selected device separate from the file addressed by the command. */ export interface AdbCommandTarget { readonly device: string; /** Caller-addressed file, such as a remote path or the original APK input. */ readonly path?: string; /** Exact host operand adb consumes, including an owned input snapshot. */ readonly localPath?: string; } /** Run one bounded adb invocation and keep its exact failure shape. */ export const runAdbCapture = async ( operation: string, target: AdbCommandTarget, host: AdbCommandHost, arguments_: readonly string[], limits: AdbRunLimits, signal: AbortSignal | undefined, classifyExit: (run: AdbExitedRun) => AnalysisError | undefined = (run) => run.exitCode === 0 ? undefined : adbExitFailure(operation, target, run), ): Promise<Result<{ stdout: Buffer; stderr: string }, AnalysisError>> => { if (signal?.aborted === true) return err(cancelledBy(operation, signal)); const started = await host.startServer?.(); if (started !== undefined && !started.ok) return started; const outcome = await runAdbProcess(host, arguments_, limits, signal); if (!outcome.ok) return err( adbRunFailureError(operation, host, outcome.failure, (failure) => failure.exited === undefined ? adbRunFailure(operation, host, limits, failure) : classifyExit(failure.exited), ), ); const { run } = outcome; const exitFailure = classifyExit(run); if (exitFailure === undefined) return ok({ stdout: run.stdout, stderr: run.stderr }); return err(exitFailure); }; /** adb did not exit on its own: it ran out of time or capture, or never started. */ const adbRunFailure = ( operation: string, host: AdbCommandHost, limits: AdbRunLimits, failure: AdbRunFailure, ): AnalysisError => { const detail = { cause: failure.cause, ...(failure.capturedOutput === undefined ? {} : { capturedOutput: failure.capturedOutput }), }; if (failure.command?.reason === "output-limit") { const name = `The adb output capture allowance of ${String(limits.maxOutputBytes)} bytes (this release has no runtime override)`; const facts = { limit: limits.maxOutputBytes, unit: "bytes" }; const allowance = limits.volatileOutput === true ? { fixedAllowance: { name, kind: "live" as const, ...facts }, retryable: true as const, } : fixedAllowanceOptions(name, "capture", facts); return new AnalysisResourceConstraintError( operation, "memory", `adb output exceeded the ${String(limits.maxOutputBytes)}-byte capture budget`, { max_output_bytes: limits.maxOutputBytes }, { ...detail, ...allowance }, ); } if (failure.command?.reason === "timeout") return new AnalysisTimeoutError(operation, limits.timeoutMs, { ...detail, userMessage: `adb ${operation} reached its ${String(limits.timeoutMs)} ms deadline (deadlineExpired). This release has no runtime override.`, remediationAction: `This ${String(limits.timeoutMs)} ms adb deadline has no runtime override. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`, }); // The host, not adb, refused this launch: it lacked capacity, or the // request's arguments and the environment exceed the launch limit. const { launch } = failure; if (launch?.kind === "host-exhausted" || launch?.kind === "argument-list") return classifyLaunchFailure(launch, { providerId: "adb", operation, command: host.binary, selection: ADB_BINARY_ENV, details: detail, }); return new AnalysisProtocolError( launch !== undefined ? `adb could not be started (${String(launch.code ?? "no system code")}) for ${operation}` : `adb failed for ${operation}: ${errorMessage(failure.cause)}`, detail, ); }; /** Read adb's verdict from a run that exited nonzero. */ export const adbExitFailure = ( operation: string, target: AdbCommandTarget, run: AdbExitedRun, ): AnalysisError => { const detail = { capturedOutput: run.capturedOutput }; const stderr = run.stderr.trim(); const excerpt = ellipsisExcerpt(stderr, STDERR_EXCERPT_CHARACTERS); // Device-state words inside a reported file name are not device verdicts. // Only leading notices need line parsing. Do not expand a capture-sized // stderr into an array whose entries can exceed the byte capture budget. let diagnosticStart = 0; while (diagnosticStart < stderr.length) { const newline = stderr.indexOf("\n", diagnosticStart); const line = stderr .slice(diagnosticStart, newline === -1 ? stderr.length : newline) .trimEnd(); if (!isSuccessfulDaemonStartNotice(line) && !isDaemonStartingNotice(line)) break; diagnosticStart = newline === -1 ? stderr.length : newline + 1; } const diagnostic = stderr .slice(diagnosticStart) .replace( /^(?:adb:\s*)?(?:error:\s*)?(?:(?:failed to get feature set|connect failed):\s*)?/iu, "", ); if ( /^(?:unauthorized\b|device(?: '[^'\n]*')? (?:unauthorized\b|offline\b|not found\b|still authorizing\b)|still authorizing\b|more than one device\b)/iu.test( diagnostic, ) ) return new AnalysisUnsupportedTargetError( operation, target.device, excerpt, detail, ); if ( /No such file or directory|Permission denied|read: Permission denied/iu.test( diagnostic, ) ) { const localPath = target.localPath; const path = localPath !== undefined && LOCAL_FILE_DIAGNOSTICS.some(([verb, suffix]) => [localPath, `'${localPath}'`, `"${localPath}"`].some((operand) => diagnostic.startsWith(`${verb} ${operand}${suffix}`), ), ) ? localPath : (target.path ?? target.device); return new AnalysisUnsupportedTargetError(operation, path, excerpt, detail); } const protocolError = new AdbProtocolError( excerpt === "" ? `adb exited with code ${String(run.exitCode)} for ${operation}` : excerpt, run, ); if ( operation === "install_adb_package" || operation === "uninstall_adb_package" ) { const reason = packageChangeFailureReason( `${run.capturedOutput.stdout}\n${run.stderr}`, ); if (reason !== null) return new AnalysisUnsupportedTargetError( operation, target.device, reason, { cause: protocolError }, ); } return protocolError; }; /** Decode textual adb protocols after the shared byte capture and error boundary. */ export const runAdb = async ( ...arguments_: Parameters<typeof runAdbCapture> ): Promise< Result<{ stdout: string; stderr: string; stdoutBytes: number }, AnalysisError> > => { const captured = await runAdbCapture(...arguments_); if (!captured.ok) return captured; return ok({ stdout: captured.value.stdout.toString("utf8"), stderr: captured.value.stderr, // Byte count of the captured output before UTF-8 decoding, so malformed // sequences replaced by U+FFFD still report their true captured size. stdoutBytes: captured.value.stdout.byteLength, }); }; /** * adb exits nonzero when the device refuses a package change, printing the * `Failure [...]` verdict to stderr (install) or stdout (uninstall). Read the * refusal from that failed run so it is not reported as unreadable output. */ export const packageChangeRefusal = ( operation: string, serial: string, error: AnalysisError, ): Result<never, AnalysisError> | undefined => { const run = adbExitedRunOf(error); if (run === undefined) return undefined; const reason = packageChangeFailureReason( `${run.capturedOutput.stdout}\n${run.stderr}`, ); return reason === null ? undefined : err( new AnalysisUnsupportedTargetError(operation, serial, reason, { cause: error, }), ); }; /** Parsed predicate and the complete output that supports it. */ export interface AdbPathProbe { readonly matches: boolean; readonly capturedOutput: { readonly stdout: string; readonly stderr: string; readonly stdout_bytes: number; readonly stderr_bytes: number; readonly exit_code: 0 | 1; readonly signal: null; readonly truncated: false; }; } const completedAdbPathProbe = ( matches: boolean, stderr: string, ): AdbPathProbe => ({ matches, capturedOutput: { stdout: "", stderr, stdout_bytes: 0, stderr_bytes: Buffer.byteLength(stderr), exit_code: matches ? 0 : 1, signal: null, truncated: false, }, }); const recognizedProbeStderr = (stderr: string): boolean => stderr === "" || hasOnlySuccessfulAdbStartupNotices(stderr); /** Only a complete false predicate, with no device diagnostics, establishes absence. */ export const probeAdbPathExistence = async ( operation: string, serial: string, path: string, host: AdbCommandHost, limits: AdbRunLimits, signal: AbortSignal | undefined, ): Promise<Result<AdbPathProbe, AnalysisError>> => { return probeAdbPath(operation, serial, path, host, limits, signal, "-e"); }; /** Completed predicate status is independent of recognized host startup notices. */ export const probeAdbPathDirectory = async ( operation: string, serial: string, path: string, host: AdbCommandHost, limits: AdbRunLimits, signal: AbortSignal | undefined, ): Promise<Result<AdbPathProbe, AnalysisError>> => probeAdbPath(operation, serial, path, host, limits, signal, "-d"); const probeAdbPath = async ( operation: string, serial: string, path: string, host: AdbCommandHost, limits: AdbRunLimits, signal: AbortSignal | undefined, predicate: "-d" | "-e", ): Promise<Result<AdbPathProbe, AnalysisError>> => { const fact = predicate === "-d" ? "destination_directory" : "destination_existence"; let exitCode = 0; const probed = await runAdbCapture( operation, { device: serial, path }, host, adbArguments(serial, ["shell", "test", predicate, path]), { ...limits, volatileOutput: true }, signal, (run) => { exitCode = run.exitCode; if ( (run.exitCode === 0 || run.exitCode === 1) && run.stdout.length === 0 && recognizedProbeStderr(run.stderr) ) return undefined; if (run.exitCode === 0) return new AnalysisProtocolError( `The ADB path ${predicate === "-d" ? "directory" : "existence"} probe returned unexpected output; destination status is unknown`, { diagnostics: { [fact]: "unknown" }, capturedOutput: run.capturedOutput, }, ); const failure = adbExitFailure(operation, { device: serial, path }, run); return !(failure instanceof AdbProtocolError) ? failure : new AnalysisProtocolError(failure.message, { cause: failure, diagnostics: { [fact]: "unknown" }, capturedOutput: run.capturedOutput, }); }, ); if (!probed.ok) return probed; return ok(completedAdbPathProbe(exitCode === 0, probed.value.stderr)); }; - src/adb/AdbConfiguration.test.ts (2608 bytes)
import { describe, expect, it } from "vitest"; import { ADB_BINARY_ENV, parseAdbVersionOutput, resolveAdbBinary, } from "./AdbConfiguration.js"; describe("resolveAdbBinary", () => { it("prefers an absolute REA_ADB_PATH", async () => { expect( await resolveAdbBinary({ [ADB_BINARY_ENV]: "/opt/tools/adb" }, "linux"), ).toEqual({ binary: "/opt/tools/adb", pathSource: "environment", environment: { [ADB_BINARY_ENV]: "/opt/tools/adb" }, }); }); it.skipIf(process.platform === "win32")( "falls back to POSIX PATH resolution without the environment key", async () => { expect(await resolveAdbBinary({}, "linux")).toEqual({ binary: "adb", pathSource: "path", environment: {}, }); expect( await resolveAdbBinary({ [ADB_BINARY_ENV]: " " }, "linux"), ).toEqual({ binary: "adb", pathSource: "path", environment: { [ADB_BINARY_ENV]: " " }, }); }, ); it("does not defer a missing Windows PATH selection to process creation", async () => { await expect( resolveAdbBinary({ Path: "", PathExt: ".EXE" }, "win32"), ).rejects.toMatchObject({ code: "binary_missing" }); }); it("rejects a relative environment path explicitly", async () => { await expect( resolveAdbBinary({ [ADB_BINARY_ENV]: "tools/adb" }, "linux"), ).rejects.toThrow(/must be an absolute path/u); // Rooted on the current drive, so it names a different file per drive. await expect( resolveAdbBinary({ [ADB_BINARY_ENV]: "\\tools\\adb.exe" }, "win32"), ).rejects.toThrow(/must be an absolute path/u); }); }); describe("parseAdbVersionOutput", () => { it("reads the build version and install path from real output", () => { expect( parseAdbVersionOutput( [ "Android Debug Bridge version 1.0.41", "Version 34.0.5-debian", "Installed as /usr/lib/android-sdk/platform-tools/adb", "", ].join("\n"), ), ).toEqual({ version: "34.0.5-debian", installedPath: "/usr/lib/android-sdk/platform-tools/adb", }); }); it("reports null identity fields when the named lines are absent", () => { expect(parseAdbVersionOutput("unexpected output")).toEqual({ version: null, installedPath: null, }); }); it("does not accept arbitrary successful output as an adb version", () => { expect( parseAdbVersionOutput( "Android Debug Bridge version tomorrow\nVersion unknown\n", ), ).toMatchObject({ version: null }); }); }); - src/adb/AdbConfiguration.ts (13064 bytes)
import { AnalysisProtocolError, AnalysisResourceConstraintError, AnalysisTimeoutError, cancelledBy, carriedReason, } from "../domain/analysisErrorCore.js"; import { isQualifiedCallerPath } from "../filesystem/callerPath.js"; import { findWindowsExecutable } from "../process/WindowsExecutable.js"; import { ProviderStartupDeadline } from "../process/ProviderDeadline.js"; import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; import type { ProviderAvailability } from "../ports/AnalysisProvider.js"; import type { ProviderRejectionCode } from "../domain/providerSelection.js"; import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js"; import type { JsonValue } from "../domain/jsonValue.js"; import type { LauncherFailure } from "../process/launchFailure.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { errorMessage } from "../kernel/errorMessage.js"; import { adbRunFailureError, runAdbProcess, type AdbCommandHost, type AdbRunFailure, } from "./AdbProcess.js"; import { classifyLaunchFailure } from "../process/classifyProviderOutcome.js"; /** Environment key selecting the caller's adb binary. */ export const ADB_BINARY_ENV = "REA_ADB_PATH"; const VERSION_TIMEOUT_MS = 10_000; const ADB_VERSION_REMEDIATION = `Set ${ADB_BINARY_ENV} to an Android SDK Platform-Tools adb binary whose \`adb version\` reports its version, or put one on PATH.`; /** Repair when the selected adb binary does not exist. */ const ADB_MISSING_REMEDIATION = `Set ${ADB_BINARY_ENV} to an absolute path to an existing adb binary.`; /** Repair when execution of the adb binary selected by the environment is denied. */ const ADB_NOT_EXECUTABLE_REMEDIATION = `Set ${ADB_BINARY_ENV} to an absolute path to the adb executable file, not a directory, and check execute permission on it and search permission on its parent directories.`; const VERSION_MAX_OUTPUT_BYTES = 64 * 1024; /** How the adb binary was selected for this provider instance. */ export interface AdbBinarySelection { readonly binary: string; readonly pathSource: "environment" | "path"; readonly environment: Readonly<Record<string, string | undefined>>; } /** * Resolve the caller-supplied adb binary. `REA_ADB_PATH` must be absolute so * the selection stays explicit. Windows resolves the default from the selected * PATH before launch; POSIX retains execFile PATH lookup. */ export const resolveAdbBinary = async ( environment: Readonly<Record<string, string | undefined>>, platform: NodeJS.Platform, signal?: AbortSignal, ): Promise<AdbBinarySelection> => { const selectedEnvironment = snapshotEnvironment(environment, platform); const configured = selectedEnvironment[ADB_BINARY_ENV]; if (configured === undefined || configured.trim() === "") return { binary: platform === "win32" ? await resolveWindowsAdb(selectedEnvironment, signal) : "adb", pathSource: "path", environment: selectedEnvironment, }; if (!isQualifiedCallerPath(configured, platform)) throw new AdbConfigurationFailure( "not_absolute", `${ADB_BINARY_ENV} must be an absolute path to the adb binary`, `Set ${ADB_BINARY_ENV} to an absolute adb executable path, or unset it to use adb from PATH.`, { configured_path: configured }, ); return { binary: configured, pathSource: "environment", environment: selectedEnvironment, }; }; const resolveWindowsAdb = async ( environment: Readonly<NodeJS.ProcessEnv>, signal?: AbortSignal, ): Promise<string> => { const deadline = new ProviderStartupDeadline(VERSION_TIMEOUT_MS, signal); try { const found = await findWindowsExecutable("adb", environment, { signal: deadline.signal, }); if (found.ok) return found.value; const failure = found.error; if (failure.kind === "interrupted") { if (deadline.interruption === "cancelled") throw cancelledBy("inspect_adb_client", carriedReason(signal?.reason)); throw new AnalysisTimeoutError("inspect_adb_client", VERSION_TIMEOUT_MS, { diagnostics: { phase: "windows_path_lookup" }, }); } throw new AdbConfigurationFailure( failure.kind === "missing" ? "binary_missing" : "binary_unresolved", "The adb binary could not be selected from the Windows PATH/PATHEXT", `Set ${ADB_BINARY_ENV} to an absolute adb executable, or add it to PATH/PATHEXT.`, { selected_binary: "adb", path_source: "path", ...(failure.kind === "invalid_extension" ? { invalid_extension: failure.extension } : {}), ...(failure.kind === "inspection" ? { candidate_path: failure.path, ...(failure.code === null ? {} : { filesystem_error: failure.code }), } : {}), }, failure.kind === "inspection" ? { cause: failure.cause } : undefined, ); } finally { deadline.dispose(); } }; export type AdbConfigurationFailureCode = | "not_absolute" | "binary_missing" | "binary_unresolved" | "binary_not_executable" | "version_unresolved"; /** Why the selected adb binary is unusable, with the owner's repair instruction. */ export class AdbConfigurationFailure extends Error { constructor( readonly code: AdbConfigurationFailureCode, message: string, readonly remediation: string, readonly diagnostics: Readonly<Record<string, JsonValue>> = {}, options?: ErrorOptions, ) { super(message, options); } } export interface AdbClientIdentity { readonly version: string | null; readonly installedPath: string | null; } /** * Parse `adb version` output. The first line carries the protocol version, * `Version ` the build version (no colon), and `Installed as` the binary path. */ export const parseAdbVersionOutput = (stdout: string): AdbClientIdentity => { const build = /^Version\s+(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\s*$/mu.exec( stdout, ); // The literal delimiter and line ending belong to the protocol; path // whitespace belongs to the reported executable identity. const installed = /^Installed as ([^\n]*)$/mu .exec(stdout)?.[1] ?.replace(/\r$/u, ""); return { version: build === null ? null : build[1]!.trim(), installedPath: installed === undefined || installed === "" ? null : installed, }; }; /** * Probe the selected adb binary without contacting devices. `adb version` * never starts the adb server, so this stays a pure client check. */ export const inspectAdbClient = async ( host: AdbCommandHost, signal?: AbortSignal, ): Promise<AdbClientIdentity> => { const outcome = await runAdbProcess( host, ["version"], { timeoutMs: VERSION_TIMEOUT_MS, maxOutputBytes: VERSION_MAX_OUTPUT_BYTES }, signal, ); if (!outcome.ok) { const failure = outcome.failure; // The process never started: the launcher's errno is not an exit status. const launch = failure.launch; if ( failure.command === undefined && launch !== undefined && launch.kind !== "host-exhausted" && launch.kind !== "argument-list" ) throw adbLaunchRefusal(host, launch, failure.cause); throw adbRunFailureError("inspect_adb_client", host, failure, () => failure.exited === undefined ? versionProbeFailure(host, failure) : undefined, ); } const { run } = outcome; const stdout = run.stdout.toString("utf8"); if (run.exitCode !== 0) throw new AdbConfigurationFailure( "version_unresolved", `The selected adb binary did not report a usable version: ${host.binary}`, ADB_VERSION_REMEDIATION, { selected_binary: host.binary, path_source: host.pathSource, exit_code: run.exitCode, stderr_excerpt: run.stderr.slice(0, 512), }, ); const identity = parseAdbVersionOutput(stdout); const hasRecognizedProtocolVersion = /^Android Debug Bridge version\s+\d+\.\d+\.\d+\s*$/mu.test(stdout); if (identity.version === null && !hasRecognizedProtocolVersion) throw new AdbConfigurationFailure( "version_unresolved", "The selected adb binary exited successfully but did not report a recognizable protocol or build version", ADB_VERSION_REMEDIATION, { selected_binary: host.binary, path_source: host.pathSource, version_probe: "unrecognized_output", stdout, stderr: run.stderr, }, ); return identity; }; /** The version probe did not exit on its own. */ const versionProbeFailure = ( host: AdbCommandHost, failure: AdbRunFailure, ): AnalysisError => { const facts = { selected_binary: host.binary, path_source: host.pathSource, }; const options = { cause: failure.cause, diagnostics: facts, ...(failure.capturedOutput === undefined ? {} : { capturedOutput: failure.capturedOutput }), }; if (failure.command?.reason === "output-limit") return new AnalysisResourceConstraintError( "inspect_adb_client", "memory", `adb version output exceeded the ${String(VERSION_MAX_OUTPUT_BYTES)}-byte capture budget`, { max_output_bytes: VERSION_MAX_OUTPUT_BYTES }, { ...options, ...fixedAllowanceOptions( `The adb version-output capture allowance of ${String(VERSION_MAX_OUTPUT_BYTES)} bytes (this release has no runtime override)`, "capture", { limit: VERSION_MAX_OUTPUT_BYTES, unit: "bytes" }, ), }, ); if (failure.command?.reason === "timeout") return new AnalysisTimeoutError("inspect_adb_client", VERSION_TIMEOUT_MS, { ...options, userMessage: `adb version probe reached its ${String(VERSION_TIMEOUT_MS)} ms deadline (deadlineExpired). This release has no runtime override.`, remediationAction: `This ${String(VERSION_TIMEOUT_MS)} ms adb version probe has no runtime override. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`, }); const launch = failure.launch; // The host, not the selected binary, refused this launch. if (launch?.kind === "host-exhausted" || launch?.kind === "argument-list") return classifyLaunchFailure(launch, { providerId: "adb", operation: "inspect_adb_client", command: host.binary, fixedArguments: true, selection: ADB_BINARY_ENV, details: { cause: failure.cause, diagnostics: facts }, }); return new AnalysisProtocolError( `adb version probe failed: ${errorMessage(failure.cause)}`, options, ); }; /** The selected adb binary could not be started: a repair to its selection. */ const adbLaunchRefusal = ( host: AdbCommandHost, launch: LauncherFailure, cause: unknown, ): AdbConfigurationFailure => { const code = launch.code ?? "no system code"; const fromEnvironment = host.pathSource === "environment"; const facts = { selected_binary: host.binary, path_source: host.pathSource, filesystem_error: code, }; // Nothing executable resolves at the selected path. if (launch.kind === "missing") return new AdbConfigurationFailure( "binary_missing", `The selected adb binary was not found: ${host.binary}`, ADB_MISSING_REMEDIATION, facts, { cause }, ); return new AdbConfigurationFailure( "binary_not_executable", code === "EACCES" || code === "EPERM" ? `Execution of the selected adb binary was denied (${code}): ${host.binary}` : `The selected adb binary could not be started (${code}): ${host.binary}`, code === "EACCES" ? fromEnvironment ? ADB_NOT_EXECUTABLE_REMEDIATION : `Make sure the adb found on PATH is a file with execute permission, not a directory, and that its parent directories have search permission, or set ${ADB_BINARY_ENV} to an absolute path to an executable adb binary.` : code === "EPERM" ? `The host refused to run this adb binary, for example because of a security policy or file flags; allow it to run, or set ${ADB_BINARY_ENV} to an absolute path to an adb binary the host permits.` : `Select an adb executable this host can start directly: set ${ADB_BINARY_ENV} to its absolute path, or make it the adb found on PATH.`, facts, { cause }, ); }; /** Availability in the shape shared by every provider. */ const rejectionCodeOf = ( code: AdbConfigurationFailureCode, ): ProviderRejectionCode => code === "binary_missing" ? "executable_missing" : code === "not_absolute" || code === "binary_not_executable" || code === "binary_unresolved" ? "not_configured" : "version_unresolved"; export const adbConfigurationAvailability = ( cause: AdbConfigurationFailure, ): ProviderAvailability => ({ status: "unavailable", code: rejectionCodeOf(cause.code), reason: cause.message, remediation: cause.remediation, diagnostics: { ...cause.diagnostics }, }); - src/adb/AdbDeviceOperations.ts (4283 bytes)
import { createAnalysisExecution, type AnalysisExecution, } from "../ports/AnalysisProvider.js"; import { AnalysisProtocolError } from "../domain/analysisErrorCore.js"; import { err, ok, type Result } from "../domain/result.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { adbArguments, runAdb, type AdbRunLimits } from "./AdbCommand.js"; import type { AdbCommandHost } from "./AdbProcess.js"; import { parseAdbDevicesOutput, parseGetpropOutput, } from "./AdbDeviceOutput.js"; import type { AdbRequest } from "../domain/adb/adbDeviceAnalysis.js"; import type { AdbClientResult, AdbProviderIdentity, } from "./AdbOperationResults.js"; const DEVICES_TIMEOUT_MS = 20_000; const DEVICES_MAX_OUTPUT_BYTES = 1024 * 1024; const SHELL_TIMEOUT_MS = 30_000; const GETPROP_MAX_OUTPUT_BYTES = 2 * 1024 * 1024; export interface AdbCommandContext { readonly operation: AdbRequest["operation"]; readonly request: AdbRequest; readonly selection: AdbCommandHost; readonly client: AdbClientResult; readonly provider: AdbProviderIdentity; readonly signal: AbortSignal | undefined; readonly shell: ( arguments_: readonly string[], limits: AdbRunLimits, ) => ReturnType<typeof runAdb>; } export const inspectAdbClientOperation = ( context: AdbCommandContext, ): Result<AnalysisExecution, AnalysisError> => ok( createAnalysisExecution( { client: context.client, contacted_adb_server: false }, context.provider, ), ); export const listAdbDevicesOperation = async ( context: AdbCommandContext, ): Promise<Result<AnalysisExecution, AnalysisError>> => { const started = await context.selection.startServer?.(); if (started !== undefined && !started.ok) return started; const ran = await runAdb( context.operation, { device: "adb-devices" }, context.selection, ["devices", "-l"], { timeoutMs: DEVICES_TIMEOUT_MS, maxOutputBytes: DEVICES_MAX_OUTPUT_BYTES, volatileOutput: true, }, context.signal, ); if (!ran.ok) return ran; // Keep exact transport identities internally; the shared client boundary // alone produces the legacy numeric projection. const { devices, unparsedLines, daemonStarted } = parseAdbDevicesOutput( ran.value.stdout, ran.value.stderr, ); if (unparsedLines.total > 0) return err( new AnalysisProtocolError( `adb devices reported an unrecognized line: ${unparsedLines.sample[0]!}`, ), ); return ok( createAnalysisExecution( { client: context.client, devices, may_have_started_adb_server: started?.value?.daemonStarted === true || daemonStarted, }, context.provider, { limitations: [ "Device kind is inferred from the emulator serial prefix and USB transport metadata, not from device attestation", "Kind stays unknown for TCP transports unless the serial is an emulator port", ], }, ), ); }; export const inspectAdbDeviceOperation = async ( context: AdbCommandContext, ): Promise<Result<AnalysisExecution, AnalysisError>> => { const { request } = context; if (request.operation !== "inspect_adb_device") return err( new AnalysisProtocolError( `adb device inspection does not accept ${request.operation}`, ), ); const serial = request.input.serial; const ran = await runAdb( context.operation, { device: serial }, context.selection, adbArguments(serial, ["shell", "getprop"]), { timeoutMs: SHELL_TIMEOUT_MS, maxOutputBytes: GETPROP_MAX_OUTPUT_BYTES, volatileOutput: true, }, context.signal, ); if (!ran.ok) return ran; const { properties, emulatorObserved } = parseGetpropOutput(ran.value.stdout); return ok( createAnalysisExecution( { client: context.client, serial, properties, property_count: properties.length, emulator_observed: emulatorObserved, }, context.provider, { limitations: [ "Properties are a fixed whitelist of build identity facts, not the full getprop dump", "emulator_observed is null when the build does not report ro.kernel.qemu", ], }, ), ); }; - src/adb/AdbDeviceOutput.test.ts (17708 bytes)
import { describe, expect, it } from "vitest"; import { parseAdbDevicesOutput, parseGetpropOutput, parsePackageListOutput, parsePmPathOutput, } from "./AdbDeviceOutput.js"; describe("parseAdbDevicesOutput", () => { it("parses emulator, USB, and network devices with their metadata", () => { const output = [ "List of devices attached", "emulator-5554 device product:sdk_gphone64_x86_64 model:sdk_gphone64_x86_64 device:emu64xa transport_id:1", "07ef9c2a device usb:1-1 product:raven model:Pixel_6_Pro device:raven transport_id:2", "192.168.1.42:5555 device product:mock model:mock transport_id:3", "", ].join("\n"); const { devices, unparsedLines, daemonStarted } = parseAdbDevicesOutput(output); expect(unparsedLines).toEqual({ sample: [], total: 0 }); expect(daemonStarted).toBe(false); expect(devices).toEqual([ { serial: "emulator-5554", state: "device", transport: "tcp", product: "sdk_gphone64_x86_64", model: "sdk_gphone64_x86_64", device: "emu64xa", transport_identity: { status: "reported", decimal: "1", source_token: "1", source_line: "emulator-5554 device product:sdk_gphone64_x86_64 model:sdk_gphone64_x86_64 device:emu64xa transport_id:1", }, kind: "emulator", kind_basis: "emulator_serial_prefix", }, { serial: "07ef9c2a", state: "device", transport: "usb", product: "raven", model: "Pixel_6_Pro", device: "raven", transport_identity: { status: "reported", decimal: "2", source_token: "2", source_line: "07ef9c2a device usb:1-1 product:raven model:Pixel_6_Pro device:raven transport_id:2", }, kind: "physical", kind_basis: "usb_transport", }, { serial: "192.168.1.42:5555", state: "device", transport: "tcp", product: "mock", model: "mock", device: null, transport_identity: { status: "reported", decimal: "3", source_token: "3", source_line: "192.168.1.42:5555 device product:mock model:mock transport_id:3", }, kind: "unknown", kind_basis: "none", }, ]); }); it("classifies adb mDNS wireless serials as TCP without treating them as USB", () => { const output = [ "List of devices attached", "adb-8c4f2a1b4e5d6f70-AbCdEf._adb-tls-connect._tcp device product:cheetah model:Pixel_7_Pro device:cheetah transport_id:4", "phone._adb._tcp device transport_id:5", "not-a-service._tcp device transport_id:6", "adb-wired._adb-tls-connect._tcp device usb:1-1 product:raven model:Pixel_6 device:raven transport_id:7", "", ].join("\n"); const { devices, unparsedLines } = parseAdbDevicesOutput(output); expect(unparsedLines).toEqual({ sample: [], total: 0 }); expect( devices.map(({ serial, transport, kind, kind_basis }) => ({ serial, transport, kind, kind_basis, })), ).toEqual([ { serial: "adb-8c4f2a1b4e5d6f70-AbCdEf._adb-tls-connect._tcp", transport: "tcp", kind: "unknown", kind_basis: "none", }, { serial: "phone._adb._tcp", transport: "tcp", kind: "unknown", kind_basis: "none", }, { serial: "not-a-service._tcp", transport: "unknown", kind: "unknown", kind_basis: "none", }, { serial: "adb-wired._adb-tls-connect._tcp", transport: "usb", kind: "physical", kind_basis: "usb_transport", }, ]); }); }); describe("ADB daemon startup notices", () => { it("recognizes daemon startup notices instead of failing the listing", () => { const output = [ "* daemon not running; starting now at tcp:5037", "* daemon started successfully", "List of devices attached", "emulator-5554 device transport_id:1", "", ].join("\n"); const { devices, daemonStarted } = parseAdbDevicesOutput(output); expect(daemonStarted).toBe(true); expect(devices).toHaveLength(1); }); it("recognizes daemon startup notices emitted on stderr", () => { const stdout = [ "List of devices attached", "emulator-5554 device transport_id:1", "", ].join("\n"); const stderr = [ "* daemon not running; starting now at tcp:5037", "* daemon started successfully", "", ].join("\n"); const { devices, daemonStarted, unparsedLines } = parseAdbDevicesOutput( stdout, stderr, ); expect(daemonStarted).toBe(true); expect(unparsedLines).toEqual({ sample: [], total: 0 }); expect(devices).toHaveLength(1); }); it("recognizes the legacy daemon notice with its trailing marker and CRLF", () => { const { daemonStarted, unparsedLines } = parseAdbDevicesOutput( "List of devices attached\r\n", "* daemon started successfully *\r\n", ); expect(daemonStarted).toBe(true); expect(unparsedLines).toEqual({ sample: [], total: 0 }); }); it("does not treat a daemon startup error containing the success phrase as success", () => { const { daemonStarted, unparsedLines } = parseAdbDevicesOutput( "List of devices attached\r\n", "* daemon not started successfully\r\n", ); expect(daemonStarted).toBe(false); expect(unparsedLines).toEqual({ sample: [], total: 0 }); }); it("ignores non-startup lines and device strings on stderr", () => { const stdout = [ "List of devices attached", "emulator-5554 device transport_id:1", "", ].join("\n"); const stderr = [ "adb: warning: some transport warning", "emulator-5556 device transport_id:2", "", ].join("\n"); const { devices, daemonStarted, unparsedLines } = parseAdbDevicesOutput( stdout, stderr, ); expect(daemonStarted).toBe(false); expect(unparsedLines).toEqual({ sample: [], total: 0 }); expect(devices).toHaveLength(1); expect(devices[0]?.serial).toBe("emulator-5554"); }); }); describe("ADB device states", () => { it("keeps non-device states such as unauthorized and offline", () => { const output = [ "List of devices attached", "emulator-5556 offline transport_id:2", "HT84L0240512 unauthorized usb:1-2 transport_id:3", "", ].join("\n"); const { devices } = parseAdbDevicesOutput(output); expect(devices.map((device) => [device.serial, device.state])).toEqual([ ["emulator-5556", "offline"], ["HT84L0240512", "unauthorized"], ]); }); it("accepts complete multiword states and rejects state prefixes", () => { const output = [ "serial-no-permission no permissions usb:1-1", "serial-bad-device deviceXYZ ", "serial-bad-offline offline-ish", "serial-bad-auth unauthorizedXYZ", ].join("\n"); const { devices, unparsedLines } = parseAdbDevicesOutput(output); expect(devices.map(({ serial, state }) => [serial, state])).toEqual([ ["serial-no-permission", "no permissions"], ]); expect(unparsedLines).toEqual({ sample: [ "serial-bad-device deviceXYZ ", "serial-bad-offline offline-ish", "serial-bad-auth unauthorizedXYZ", ], total: 3, }); }); it.each([ [ "without a reason", "no permissions; see [http://developer.android.com/tools/device.html]", ], [ "with a reason", "no permissions (user alice is not in the plugdev group); see [http://developer.android.com/tools/device.html]", ], ])("parses adb's no-permissions help text %s", (_name, stateText) => { const { devices, unparsedLines } = parseAdbDevicesOutput( [ "List of devices attached", `07ef9c2a ${stateText} usb:1-1 transport_id:4`, "emulator-5554 device product:sdk model:sdk device:emu transport_id:1", "", ].join("\n"), ); expect(unparsedLines).toEqual({ sample: [], total: 0 }); expect(devices.map(({ serial, state }) => [serial, state])).toEqual([ ["07ef9c2a", "no permissions"], ["emulator-5554", "device"], ]); expect(devices[0]).toMatchObject({ transport: "usb", product: null, model: null, device: null, transport_identity: { status: "reported", decimal: "4", source_token: "4", source_line: `07ef9c2a ${stateText} usb:1-1 transport_id:4`, }, kind: "physical", }); }); it("rejects a semicolon after any state other than no permissions", () => { const { devices, unparsedLines } = parseAdbDevicesOutput( "serial-bad-device device; see [url] transport_id:1\n", ); expect(devices).toEqual([]); expect(unparsedLines.total).toBe(1); }); it("returns unrecognized lines instead of dropping them", () => { const output = [ "List of devices attached", "this is not a device line", "", ].join("\n"); const { unparsedLines } = parseAdbDevicesOutput(output); expect(unparsedLines).toEqual({ sample: ["this is not a device line"], total: 1, }); }); it("reports a non-numeric transport_id as unknown", () => { const output = [ "List of devices attached", "emulator-5554 device transport_id:not-a-number", "", ].join("\n"); const { devices } = parseAdbDevicesOutput(output); expect(devices[0]?.transport_identity).toEqual({ status: "invalid", source_token: "not-a-number", source_line: "emulator-5554 device transport_id:not-a-number", reason: "invalid_decimal", }); }); }); describe("parseGetpropOutput", () => { it("projects the whitelisted build identity from a real dump", () => { const dump = [ "[ro.build.version.release]: [14]", "[ro.build.version.sdk]: [34]", "[ro.build.version.security_patch]: [2024-06-05]", "[ro.build.id]: [AP21.240617.014]", "[ro.build.fingerprint]: [google/sdk_gphone64_x86_64/emu64xa:14/AP21.240617.014/12094027:userdebug/dev-keys]", "[ro.product.brand]: [google]", "[ro.product.device]: [emu64xa]", "[ro.product.manufacturer]: [Google]", "[ro.product.model]: [sdk_gphone64_x86_64]", "[ro.product.cpu.abilist]: [x86_64,x86,arm64-v8a,armeabi-v7a,armeabi]", "[ro.kernel.qemu]: [1]", "[ro.debuggable]: [1]", "[sys.unlisted.property]: [dropped]", "", ].join("\n"); const { properties, emulatorObserved } = parseGetpropOutput(dump); expect(emulatorObserved).toBe(true); expect(properties).not.toContainEqual({ name: "sys.unlisted.property", value: "dropped", }); expect(properties).toEqual([ { name: "ro.build.version.release", value: "14" }, { name: "ro.build.version.sdk", value: "34" }, { name: "ro.build.version.security_patch", value: "2024-06-05" }, { name: "ro.build.id", value: "AP21.240617.014" }, { name: "ro.build.fingerprint", value: "google/sdk_gphone64_x86_64/emu64xa:14/AP21.240617.014/12094027:userdebug/dev-keys", }, { name: "ro.debuggable", value: "1" }, { name: "ro.kernel.qemu", value: "1" }, { name: "ro.product.brand", value: "google" }, { name: "ro.product.device", value: "emu64xa" }, { name: "ro.product.manufacturer", value: "Google" }, { name: "ro.product.model", value: "sdk_gphone64_x86_64" }, { name: "ro.product.cpu.abilist", value: "x86_64,x86,arm64-v8a,armeabi-v7a,armeabi", }, ]); }); it("reports an explicit non-emulator build without inventing a value", () => { const dump = [ "[ro.build.version.release]: [13]", "[ro.kernel.qemu]: [0]", "", ].join("\n"); const { emulatorObserved } = parseGetpropOutput(dump); expect(emulatorObserved).toBe(false); }); it("reports the emulator indicator unknown when the build omits it", () => { const { emulatorObserved } = parseGetpropOutput( "[ro.build.version.sdk]: [33]\n", ); expect(emulatorObserved).toBeNull(); }); }); describe("parsePackageListOutput", () => { it("parses package lines with their base APK device paths", () => { const output = [ "package:/data/app/~~xy==/com.example.npzyCvVb1I-YzKIsGFvVYw==/base.apk=com.example", "package:/system/app/WebView/WebView.apk=com.android.webview", "", ].join("\n"); const { packages, unparsedLines } = parsePackageListOutput(output); expect(unparsedLines).toEqual({ sample: [], total: 0 }); expect(packages).toEqual([ { package_name: "com.example", base_apk_device_path: "/data/app/~~xy==/com.example.npzyCvVb1I-YzKIsGFvVYw==/base.apk", }, { package_name: "com.android.webview", base_apk_device_path: "/system/app/WebView/WebView.apk", }, ]); }); it("preserves the first ten raw unrecognized lines and counts every one", () => { const rows = [ " garbage line ", ...Array.from({ length: 10 }, (_, index) => `row ${String(index + 1)}`), ]; const { packages, unparsedLines } = parsePackageListOutput( ["package:/data/app/x/base.apk=com.ok", ...rows].join("\n"), ); expect(packages).toHaveLength(1); expect(unparsedLines).toEqual({ sample: rows.slice(0, 10), total: 11 }); }); }); describe("parsePmPathOutput", () => { it("classifies base and split APKs from their file names", () => { const output = [ "package:/data/app/~~a==/com.example.b==/base.apk", "package:/data/app/~~a==/com.example.b==/split_config.arm64_v8a.apk", "package:/data/app/~~a==/com.example.b==/split_config.en.apk", "", ].join("\n"); const { paths, unparsedLines } = parsePmPathOutput(output, "linux"); expect(unparsedLines).toEqual({ sample: [], total: 0 }); expect(paths).toEqual([ { device_path: "/data/app/~~a==/com.example.b==/base.apk", file_name: "base.apk", role: "base", }, { device_path: "/data/app/~~a==/com.example.b==/split_config.arm64_v8a.apk", file_name: "split_config.arm64_v8a.apk", role: "split", }, { device_path: "/data/app/~~a==/com.example.b==/split_config.en.apk", file_name: "split_config.en.apk", role: "split", }, ]); }); it("reports an unknown role for names that follow neither convention", () => { const { paths } = parsePmPathOutput( "package:/system/app/X/Y.apk\n", "linux", ); expect(paths[0]).toEqual({ device_path: "/ - src/adb/AdbDeviceOutput.ts (10352 bytes)
/** * Parsers for the exact adb and Package Manager output formats REA consumes. * * Each parser preserves what the tool actually printed: unparseable lines are * sampled and counted rather than silently dropped, and derived * classifications carry their evidence basis. */ import { adbHostFileName, type AdbHostFileNameReason, } from "./AdbHostFileName.js"; import { collectUnparsedLines, type AdbUnparsedLines, } from "./AdbUnparsedLines.js"; import { ADB_DEVICE_STATES, type AdbDeviceObservation, } from "../domain/adb/adbDeviceAnalysis.js"; import { parseAdbTransportIdentity } from "../domain/adb/adbTransportIdentity.js"; const DEVICE_LINE = /^(\S+)\s+(.*)$/u; /** * adb prints a wireless-debugging transport's serial as the mDNS instance * `<instance>._adb._tcp` or `<instance>._adb-tls-connect._tcp`. That serial * has neither a colon nor a `usb:` field. */ const isAdbMdnsTcpSerial = (serial: string): boolean => serial.endsWith("._adb._tcp") || serial.endsWith("._adb-tls-connect._tcp"); const normalizeAdbOutputLine = (rawLine: string): string => rawLine.trimEnd(); export const isSuccessfulDaemonStartNotice = (line: string): boolean => line === "* daemon started successfully" || line === "* daemon started successfully *"; /** Host-side startup line, shared by failure and successful probe parsing. */ export const isDaemonStartingNotice = (line: string): boolean => /^\* daemon not running(?:; starting now at [^\r\n]*|\. starting it now on port \d+ \*)$/u.test( line, ); /** No diagnostics beyond a completed, recognized startup sequence. */ export const hasOnlySuccessfulAdbStartupNotices = (output: string): boolean => { let started = false; for (let offset = 0; offset < output.length;) { const newline = output.indexOf("\n", offset); const line = normalizeAdbOutputLine( output.slice(offset, newline === -1 ? output.length : newline), ); if (isSuccessfulDaemonStartNotice(line)) started = true; else if (isDaemonStartingNotice(line)) started = false; else return false; offset = newline === -1 ? output.length : newline + 1; } return started; }; const metadataValue = (remainder: string, key: string): string | null => { const match = new RegExp(`(?:^|\\s)${key}:(\\S+)`, "u").exec(remainder); return match === null ? null : match[1]!; }; /** * Parse `adb devices -l` device lines. The banner, blank lines, and the * daemon startup notices adb prints on first use are recognized separately; * every other unrecognized line is sampled and counted for honest reporting. */ export const parseAdbDevicesOutput = ( stdout: string, stderr = "", ): { devices: readonly AdbDeviceObservation[]; unparsedLines: AdbUnparsedLines; daemonStarted: boolean; } => { const devices: AdbDeviceObservation[] = []; const unparsed = collectUnparsedLines(); let daemonStarted = false; for (const rawLine of stdout.split(/\r?\n/u)) { const line = normalizeAdbOutputLine(rawLine); if (isSuccessfulDaemonStartNotice(line)) { daemonStarted = true; continue; } if (line === "" || line.startsWith("List of devices attached")) continue; if (line.startsWith("* daemon")) continue; const match = DEVICE_LINE.exec(line); const state = ADB_DEVICE_STATES.find((candidate) => { const remainder = match?.[2]; if (remainder === undefined || !remainder.startsWith(candidate)) return false; const next = remainder[candidate.length]; // adb prints no-permissions as `no permissions[ (reason)]; see [URL]` and // omits the reason on a host where it finds no udev problem to name, // such as one without a plugdev group, so `;` can follow it directly. return ( next === undefined || /\s/u.test(next) || (candidate === "no permissions" && next === ";") ); }); if (match === null || state === undefined) { if (rawLine.trim() !== "") unparsed.add(rawLine); continue; } const serial = match[1]!; const remainder = match[2]!.slice(state.length); const usb = metadataValue(remainder, "usb"); // AOSP appends the authoritative field last; earlier metadata may contain // the same spelling. Keep the exact source token before decimal admission. const transportToken = /(?:^|\s)transport_id:(\S*)$/u.exec(remainder)?.[1] ?? null; const transportIdentity = parseAdbTransportIdentity( transportToken, rawLine, ); const isEmulator = /^emulator-\d+$/u.test(serial); const kind = isEmulator ? ("emulator" as const) : usb !== null ? ("physical" as const) : ("unknown" as const); devices.push({ serial, state, transport: usb !== null ? "usb" : isEmulator || serial.includes(":") || isAdbMdnsTcpSerial(serial) ? "tcp" : "unknown", product: metadataValue(remainder, "product"), model: metadataValue(remainder, "model"), device: metadataValue(remainder, "device"), transport_identity: transportIdentity, kind, kind_basis: kind === "emulator" ? "emulator_serial_prefix" : kind === "physical" ? "usb_transport" : "none", }); } if (!daemonStarted && stderr !== "") { for (const rawLine of stderr.split(/\r?\n/u)) { const line = normalizeAdbOutputLine(rawLine); if (isSuccessfulDaemonStartNotice(line)) { daemonStarted = true; break; } } } return { devices, unparsedLines: unparsed.facts(), daemonStarted }; }; /** * Properties projected from a `getprop` dump. The whitelist keeps device * inspection to build identity facts; a full dump is out of scope. */ const DEVICE_PROPERTY_WHITELIST = [ "ro.build.version.release", "ro.build.version.sdk", "ro.build.version.security_patch", "ro.build.id", "ro.build.fingerprint", "ro.build.characteristics", "ro.debuggable", "ro.kernel.qemu", "ro.product.brand", "ro.product.device", "ro.product.manufacturer", "ro.product.model", "ro.product.cpu.abilist", ] as const; export interface AdbDeviceProperty { readonly name: string; readonly value: string; } /** Parse a full `getprop` dump into `[name]: [value]` pairs. */ export const parseGetpropOutput = ( stdout: string, ): { properties: readonly AdbDeviceProperty[]; emulatorObserved: boolean | null; } => { const values = new Map<string, string>(); for (const rawLine of stdout.split(/\r?\n/u)) { const match = /^\[([^\]]+)\]:\s*\[(.*)\]$/u.exec(rawLine.trim()); if (match === null) continue; values.set(match[1]!, match[2]!); } const properties = DEVICE_PROPERTY_WHITELIST.flatMap((name) => { const value = values.get(name); return value === undefined ? [] : [{ name, value } satisfies AdbDeviceProperty]; }); const qemu = values.get("ro.kernel.qemu"); return { properties, emulatorObserved: qemu === undefined ? null : qemu === "1", }; }; /** One installed package exactly as `pm list packages -f` reports it. */ export interface AdbPackageEntry { readonly package_name: string; readonly base_apk_device_path: string; } const PACKAGE_LINE = /^package:(.+)=([^\s=]+)$/u; /** Parse `pm list packages -f` lines, sampling and counting unrecognized lines. */ export const parsePackageListOutput = ( stdout: string, ): { packages: readonly AdbPackageEntry[]; unparsedLines: AdbUnparsedLines; } => { const packages: AdbPackageEntry[] = []; const unparsed = collectUnparsedLines(); for (const rawLine of stdout.split(/\r?\n/u)) { const line = rawLine.trim(); if (line === "") continue; const match = PACKAGE_LINE.exec(line); if (match === null) { unparsed.add(rawLine); continue; } packages.push({ package_name: match[2]!, base_apk_device_path: match[1]!, }); } return { packages, unparsedLines: unparsed.facts() }; }; /** Quote raw device paths for prose without allowing bidi or invisible text. */ export const displayDevicePath = (devicePath: string): string => { let excerpt = ""; let count = 0; for (const character of devicePath) { if (count === 160) break; excerpt += character; count += 1; } const quoted = JSON.stringify(excerpt).replace( /[\p{C}\p{Z}\p{Default_Ignorable_Code_Point}\u2800]/gu, (character) => character === " " ? character : `\\u{${character.codePointAt(0)!.toString(16).toUpperCase()}}`, ); return excerpt.length === devicePath.length ? quoted : `${quoted} (excerpt)`; }; /** One APK of an installed package exactly as `pm path` reports it. */ export interface AdbPackagePathEntry { readonly device_path: string; readonly file_name: string; readonly role: "base" | "split" | "unknown"; } /** * Parse `pm path PACKAGE` lines. The base/split role is derived from the file * name (`base.apk`, `split_*.apk`), which is the only signal the output * carries; any other name reports an unknown role. */ export const parsePmPathOutput = ( stdout: string, platform: NodeJS.Platform, ): { paths: readonly AdbPackagePathEntry[]; rejectedPaths: readonly { device_path: string; reason: AdbHostFileNameReason; }[]; unparsedLines: AdbUnparsedLines; } => { const paths: AdbPackagePathEntry[] = []; const rejectedPaths: { device_path: string; reason: AdbHostFileNameReason; }[] = []; const unparsed = collectUnparsedLines(); for (const rawLine of stdout.split(/\r?\n/u)) { if (rawLine === "") continue; const match = /^package:(.*)$/u.exec(rawLine); if (match === null) { unparsed.add(rawLine); continue; } const devicePath = match[1]!; const validated = adbHostFileName(devicePath, platform); if (!validated.ok) { rejectedPaths.push({ device_path: devicePath, reason: validated.reason, }); continue; } const fileName = validated.fileName; paths.push({ device_path: devicePath, file_name: fileName, role: fileName === "base.apk" ? "base" : fileName.startsWith("split_") && fileName.endsWith(".apk") ? "split" : "unknown", }); } return { paths, rejectedPaths, unparsedLines: unparsed.facts() }; }; - src/adb/AdbDirectoryListing.ts (3419 bytes)
import { isUtf8 } from "node:buffer"; import { collectUnparsedLines, type AdbUnparsedLines, } from "./AdbUnparsedLines.js"; interface AdbDirectoryEntry { readonly name: string; readonly kind: "directory" | "file" | "symlink" | "other"; readonly permissions: string | null; readonly owner: string | null; readonly group: string | null; readonly bytes: number | null; readonly date: string | null; readonly link_target: string | null; } /** * List direct children with Android 8 Toybox's batched `find -exec` and * `stat -c` support. Names and link targets are NUL-framed; neither is ever * inserted into a line-oriented metadata record or command substitution. */ export const ADB_DIRECTORY_BATCH_SCRIPT = String.raw`metadata=$(stat -c '%A|%U|%G|%s|%y' "$@") || exit printf '%s\n' "$metadata" | { while IFS= read -r metadata; do [ "$#" -gt 0 ] || exit 1 path=$1 shift printf '%s\000%s\000' "$metadata" "${"${path##*/}"}" case "$metadata" in l*) readlink -n "$path" || exit 1 ;; esac printf '\000' done [ "$#" -eq 0 ] }`; const METADATA = /^([bcdlps-][rwxstST-]{9})\|([^|\n]+)\|([^|\n]+)\|(\d+)\|([^|\n]+)$/u; const parseEntry = ( metadata: string, name: string, linkTarget: string, ): AdbDirectoryEntry | null => { const match = METADATA.exec(metadata); if (match === null || name === "" || name.includes("/")) return null; const permissions = match[1]!; const bytes = Number(match[4]!); if (!Number.isSafeInteger(bytes)) return null; const isSymlink = permissions.startsWith("l"); if (isSymlink ? linkTarget === "" : linkTarget !== "") return null; return { name, kind: permissions.startsWith("d") ? "directory" : isSymlink ? "symlink" : permissions.startsWith("-") ? "file" : "other", permissions, owner: match[2]!, group: match[3]!, bytes, date: match[5]!, link_target: isSymlink ? linkTarget : null, }; }; /** Parse metadata/name/target NUL triples from `ADB_DIRECTORY_BATCH_SCRIPT`. */ export const parseAdbDirectoryListing = ( stdout: Buffer, ): { entries: readonly AdbDirectoryEntry[]; unparsedLines: AdbUnparsedLines; } => { const entries: AdbDirectoryEntry[] = []; const unparsed = collectUnparsedLines(); let offset = 0; while (offset < stdout.length) { const metadataEnd = stdout.indexOf(0, offset); const nameEnd = metadataEnd < 0 ? -1 : stdout.indexOf(0, metadataEnd + 1); const targetEnd = nameEnd < 0 ? -1 : stdout.indexOf(0, nameEnd + 1); if (targetEnd < 0) { unparsed.add(describeUnparsedRecord(stdout.subarray(offset))); break; } const rawRecord = stdout.subarray(offset, targetEnd + 1); if (!isUtf8(rawRecord)) { unparsed.add(describeUnparsedRecord(rawRecord)); } else { const entry = parseEntry( stdout.toString("utf8", offset, metadataEnd), stdout.toString("utf8", metadataEnd + 1, nameEnd), stdout.toString("utf8", nameEnd + 1, targetEnd), ); if (entry === null) unparsed.add(rawRecord.toString("utf8")); else entries.push(entry); } offset = targetEnd + 1; } return { entries, unparsedLines: unparsed.facts() }; }; const describeUnparsedRecord = (record: Buffer): string => isUtf8(record) ? record.toString("utf8") : `Invalid UTF-8 directory record (hex): ${record.toString("hex")}`; - src/adb/AdbFilesystemAdmission.ts (1462 bytes)
import { stat } from "node:fs/promises"; import { AnalysisInputError } from "../domain/analysisErrorCore.js"; export const adbFilesystemErrorCode = (cause: unknown): string | undefined => cause instanceof Error && "code" in cause && typeof cause.code === "string" ? cause.code : undefined; /** Admit the caller's file once, retaining the selection and the host's reason. */ export const adbInputFileError = async ( operation: string, field: "local_path" | "apk_path", selectedPath: string, absolutePath: string, ): Promise<AnalysisInputError | undefined> => { let info; try { info = await stat(absolutePath); } catch (cause) { const code = adbFilesystemErrorCode(cause); const message = code === "ENOENT" || code === "ENOTDIR" ? "The selected file does not exist or a parent is not a directory." : "The selected file could not be inspected."; return new AnalysisInputError(operation, { cause }, [ { path: [field], reason: "invalid_value", message, observed: { path: selectedPath, ...(code === undefined ? {} : { code }), }, }, ]); } if (!info.isFile()) return new AnalysisInputError(operation, undefined, [ { path: [field], reason: "invalid_value", message: "The selected path is not a regular file.", observed: { path: selectedPath }, }, ]); return undefined; }; - src/adb/AdbHostFileName.test.ts (2546 bytes)
import { describe, expect, it } from "vitest"; import { adbHostFileName } from "./AdbHostFileName.js"; describe("adbHostFileName", () => { it.each([ ["/data/local/tmp/notes.txt", "notes.txt"], ["/data/data/com.example/databases/app.db", "app.db"], ["/sdcard/My Notes.txt", "My Notes.txt"], ["/system/etc/hosts", "hosts"], [ "/data/local/tmp/split_config.arm64_v8a.apk", "split_config.arm64_v8a.apk", ], ["/data/local/tmp/résumé.xml", "résumé.xml"], ["/data/local/tmp/a-b_c.d", "a-b_c.d"], ["/data/local/tmp/a\\b", "a\\b"], ["/data/local/tmp/report:2024", "report:2024"], ["/data/local/tmp/a*b.txt", "a*b.txt"], ["/data/local/tmp/re\u007fport", "re\u007fport"], ])("accepts the POSIX device path %s", (devicePath, fileName) => { expect(adbHostFileName(devicePath, "linux")).toEqual({ ok: true, fileName, }); }); it.each([ ["/", "empty_file_name"], ["data/local/tmp/file", "not_absolute_path"], ["/data/local/tmp/", "empty_file_name"], ["/data/local/tmp/..", "dot_segment"], ["/data/local/tmp/.", "dot_segment"], ["/data\0/local/tmp/file", "unsupported_character"], ["/data/local/tmp/a\0b", "unsupported_character"], ] as const)("refuses %s as %s", (devicePath, reason) => { expect(adbHostFileName(devicePath, "linux")).toEqual({ ok: false, reason }); }); it.each([ ["/data/local/tmp/a\\b", "unsupported_character"], ["/data/local/tmp/ta\tb", "unsupported_character"], ["/data/local/tmp/CON", "reserved_name"], ["/data/local/tmp/nul.txt", "reserved_name"], ["/data/local/tmp/com1", "reserved_name"], ["/data/local/tmp/LPT9", "reserved_name"], ["/data/local/tmp/COM¹.txt", "reserved_name"], ["/data/local/tmp/lpt³", "reserved_name"], ["/data/local/tmp/report:2024", "unsupported_character"], ["/data/local/tmp/report.", "trailing_dot_or_space"], ["/data/local/tmp/report ", "trailing_dot_or_space"], ["/data/local/tmp/a*b.txt", "unsupported_character"], ["/data/local/tmp/a?b.txt", "unsupported_character"], ] as const)("rejects %s on Windows as %s", (devicePath, reason) => { expect(adbHostFileName(devicePath, "win32")).toEqual({ ok: false, reason }); }); it("does not impose non-Windows control restrictions on Windows filenames", () => { expect(adbHostFileName("/data/local/tmp/name\u007f.txt", "win32").ok).toBe( true, ); expect(adbHostFileName("/data/local/tmp/name\u0085.txt", "win32").ok).toBe( true, ); }); }); - src/adb/AdbHostFileName.ts (1897 bytes)
/** Why a device-reported path cannot be used as a host file name. */ export type AdbHostFileNameReason = | "empty_file_name" | "not_absolute_path" | "dot_segment" | "unsupported_character" | "reserved_name" | "trailing_dot_or_space"; export type AdbHostFileNameResult = | { readonly ok: true; readonly fileName: string } | { readonly ok: false; readonly reason: AdbHostFileNameReason }; const WINDOWS_RESERVED_BASENAME = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/iu; /** * Derive the final component of a device POSIX path without normalizing the * source. A trailing slash has no filename and must not silently become the * preceding component as `basename` would make it. */ export const adbHostFileName = ( devicePath: string, platform: NodeJS.Platform, ): AdbHostFileNameResult => { if (devicePath === "" || devicePath.endsWith("/")) return { ok: false, reason: "empty_file_name" }; if (devicePath.includes("\0")) return { ok: false, reason: "unsupported_character" }; if (!devicePath.startsWith("/")) return { ok: false, reason: "not_absolute_path" }; const fileName = devicePath.slice(devicePath.lastIndexOf("/") + 1); if (fileName === "." || fileName === "..") return { ok: false, reason: "dot_segment" }; if (platform === "win32") { if (/[\\:*?"<>|]/u.test(fileName) || hasWindowsControl(fileName)) return { ok: false, reason: "unsupported_character" }; if (WINDOWS_RESERVED_BASENAME.test(fileName)) return { ok: false, reason: "reserved_name" }; if (/[. ]$/u.test(fileName)) return { ok: false, reason: "trailing_dot_or_space" }; } return { ok: true, fileName }; }; const hasWindowsControl = (fileName: string): boolean => { for (const character of fileName) { const code = character.codePointAt(0)!; if (code > 0 && code < 0x20) return true; } return false; }; - src/adb/AdbInputSnapshot.ts (5721 bytes)
import { createHash } from "node:crypto"; import { open, stat } from "node:fs/promises"; import { basename, join } from "node:path"; import type { ArtifactResourceScope } from "../resources/index.js"; import { AnalysisArtifactChangedError, AnalysisOutputError, cancelledBy, carriedReason, } from "../domain/analysisErrorCore.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { openRegularFile, RegularFileAdmissionFailure, sameRegularFileState, } from "../filesystem/RegularFile.js"; import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; import type { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js"; export interface AdbInputSnapshot { readonly path: string; readonly bytes: number; readonly sha256: string; } /** Snapshot failure with the handles that remain owned for a later retry. */ export class AdbInputSnapshotFailure extends Error { constructor( readonly operation: string, readonly sourcePath: string, readonly primaryCause: unknown, readonly cleanupResources: readonly string[], readonly cleanupCause: unknown, ) { super(`ADB input snapshot failed for ${sourcePath}`, { cause: primaryCause ?? cleanupCause, }); this.name = "AdbInputSnapshotFailure"; } } /** Copy one caller file into a private root, hashing the bytes adb will consume. */ export const snapshotAdbInput = async ( sourcePath: string, root: Pick<PrivateRuntimeRoot, "path">, resources: ArtifactResourceScope, operation: string, signal?: AbortSignal, ): Promise<AdbInputSnapshot> => { let source: OwnedFileHandle | undefined; let destination: OwnedFileHandle | undefined; const cleanupResources: string[] = []; const cleanupCauses: unknown[] = []; let snapshot: AdbInputSnapshot | undefined; let primaryCause: unknown; try { const { handle, initial } = await openRegularFile(sourcePath, { symlinks: "follow", signal, }); source = new OwnedFileHandle(handle); const destinationPath = join(root.path, basename(sourcePath)); destination = new OwnedFileHandle(await open(destinationPath, "wx", 0o600)); if (!Number.isSafeInteger(initial.size) || initial.size < 0) throw new RangeError( `Regular file size cannot be represented safely: ${sourcePath}`, ); const hash = createHash("sha256"); const chunk = Buffer.allocUnsafe(64 * 1024); let position = 0; while (position < initial.size) { signal?.throwIfAborted(); const read = await source.handle.read( chunk, 0, Math.min(chunk.length, initial.size - position), position, ); signal?.throwIfAborted(); if (read.bytesRead === 0) throw new AnalysisArtifactChangedError( operation, sourcePath, "the file ended before its admitted size was copied", ); const bytes = chunk.subarray(0, read.bytesRead); let written = 0; while (written < bytes.length) { signal?.throwIfAborted(); const result = await destination.handle.write( bytes, written, bytes.length - written, position + written, ); if (result.bytesWritten === 0) throw new Error("Private ADB input snapshot stopped accepting bytes"); written += result.bytesWritten; } hash.update(bytes); position += read.bytesRead; } signal?.throwIfAborted(); const [opened, named] = await Promise.all([ source.handle.stat(), stat(sourcePath), ]); signal?.throwIfAborted(); if ( !sameRegularFileState(initial, opened) || !sameRegularFileState(initial, named) ) throw new AnalysisArtifactChangedError( operation, sourcePath, "the file changed while its private snapshot was copied", ); await destination.handle.sync(); // Keep the private snapshot non-writable while preserving executable intent // for adb push (which transmits the staged file's mode). await destination.handle.chmod(0o400 | (initial.mode & 0o111)); snapshot = { path: destinationPath, bytes: position, sha256: hash.digest("hex"), }; } catch (cause: unknown) { if (cause instanceof RegularFileAdmissionFailure) { source = cause.owner; primaryCause = cause.cause; } else if (cause instanceof AnalysisError) { primaryCause = cause; } else { primaryCause = signal?.aborted === true ? cancelledBy(operation, carriedReason(cause)) : cause; } } for (const [owner, resource] of [ [source, `${sourcePath} (ADB snapshot source handle)`], [ destination, `${join(root.path, basename(sourcePath))} (ADB snapshot handle)`, ], ] as const) { if (owner === undefined) continue; const result = await resources.release({ kind: "file-handle", resource, handle: owner, }); if (result.kind === "failed") { cleanupResources.push(resource); cleanupCauses.push(result.cause); } } if (cleanupCauses.length > 0) throw new AdbInputSnapshotFailure( operation, sourcePath, primaryCause, cleanupResources, new AggregateError(cleanupCauses, "ADB snapshot handles remain open"), ); if (primaryCause instanceof AnalysisError) throw primaryCause; if (primaryCause !== undefined) throw new AnalysisOutputError( operation, `The caller input could not be staged for adb: ${sourcePath}`, { cause: primaryCause }, ); if (snapshot === undefined) throw new Error("ADB input snapshot ended without a result"); return snapshot; }; - src/adb/AdbNumericIssues.ts (727 bytes)
import { UNPARSED_LINE_SAMPLE_LIMIT } from "./AdbUnparsedLines.js"; /** Retain the first diagnostic facts and exact count without copying command output. */ export const collectNumericIssues = <Issue>() => { const sample: Issue[] = []; let total = 0; return { add: (issue: Issue) => { total += 1; if (sample.length < UNPARSED_LINE_SAMPLE_LIMIT) sample.push(issue); }, append: (issues: { readonly sample: readonly Issue[]; readonly total: number; }) => { total += issues.total; for (const issue of issues.sample) { if (sample.length === UNPARSED_LINE_SAMPLE_LIMIT) break; sample.push(issue); } }, facts: () => ({ sample, total }), }; }; - src/adb/AdbOperationResults.ts (1548 bytes)
import { createAnalysisExecution } from "../ports/AnalysisProvider.js"; import type { AdbUnparsedLines } from "./AdbUnparsedLines.js"; import type { AdbBinarySelection, AdbClientIdentity, } from "./AdbConfiguration.js"; export const clientIdentityResult = ( selection: AdbBinarySelection, identity: AdbClientIdentity, ) => ({ binary_path: selection.binary, path_source: selection.pathSource, version: identity.version, installed_path: identity.installedPath, }); export type AdbClientResult = ReturnType<typeof clientIdentityResult>; export type AdbProviderIdentity = { id: string; name: string; version: string | null; }; /** * Build a parsed-listing execution whose `unparsed_lines`, coverage, and * truncation limitation all derive from the parser's unrecognized-line facts, * so the limitation can never describe a field the result does not carry. */ export const parsedListingExecution = ( result: Readonly<Record<string, unknown>>, unparsed: AdbUnparsedLines, provider: AdbProviderIdentity, limitations: readonly string[] = [], ) => createAnalysisExecution( { ...result, unparsed_lines: unparsed.sample, coverage: unparsed.total > 0 ? "partial" : "complete", }, provider, { limitations: [ ...limitations, ...(unparsed.total > unparsed.sample.length ? [ `unparsed_lines reports the first ${String(unparsed.sample.length)} of ${String(unparsed.total)} unrecognized lines`, ] : []), ], }, ); - stryker.config.mjs (6373 bytes)
import { mutationRanges } from "./scripts/lib/reverse-tools-mutation-targets.mjs"; const config = { $schema: "./node_modules/@stryker-mutator/core/schema/stryker-schema.json", testRunner: "vitest", plugins: [ "@stryker-mutator/typescript-checker", "@stryker-mutator/vitest-runner", ], vitest: { configFile: "vitest.reverse-tools.config.ts", related: true, }, checkers: ["typescript"], tsconfigFile: "tsconfig.reverse-tools-mutation.json", typescriptChecker: { prioritizePerformanceOverAccuracy: true, }, coverageAnalysis: "perTest", thresholds: { break: null }, ignorePatterns: ["/.cache/rea-command-locks/**", "/coverage/**"], concurrency: 2, timeoutMS: 30000, reporters: ["clear-text", "progress", "html", "json"], jsonReporter: { fileName: "reports/mutation/reverse-tools.json" }, htmlReporter: { fileName: "reports/mutation/reverse-tools.html" }, }; export default { ...config, mutate: [ ...mutationRanges("src/application/reverse/ReverseEngineeringService.ts", [ { kind: "method", owner: "ReverseEngineeringService", name: "inspectWithObjdump", }, { kind: "method", owner: "ReverseEngineeringService", name: "executeRizinCommand", }, { kind: "method", owner: "ReverseEngineeringService", name: "#observe", }, { kind: "method", owner: "ReverseEngineeringService", name: "retryCleanup", }, { kind: "guard", owner: "ReverseEngineeringService", method: "#observeProvider", condition: "signal?.aborted", direct: true, }, { kind: "guard", owner: "ReverseEngineeringService", method: "#observeProvider", condition: "!cleanup.ok", }, { kind: "declaration", owner: "ReverseEngineeringService", method: "#observeProvider", name: "absolutePath", }, { kind: "declaration", owner: "ReverseEngineeringService", method: "#observeProvider", name: "cleanup", }, { kind: "try", owner: "ReverseEngineeringService", method: "#observeProvider", assignment: "digest", }, { kind: "try", owner: "ReverseEngineeringService", method: "#observeProvider", callee: "this.#run", }, { kind: "expression", text: "snapshot.signal !== null && snapshot.signal !== undefined", }, ]), ...mutationRanges("src/process/ExecFileOutput.ts", [ { kind: "declaration", name: "execFileOutputFailure", }, ]), ...mutationRanges("src/server/providerEnvironment.ts", [ { kind: "declaration", name: "captureProviderEnvironment", }, ]), ...mutationRanges("src/server/externalMutationToolHandler.ts", [ { kind: "declaration", name: "createExternalMutationToolHandler", }, ]), ...mutationRanges("src/server/serviceToolBindings.ts", [ { kind: "declaration", name: "prepareRizinCommand", }, ]), ...mutationRanges("src/gdb/GdbSessionManager.ts", [ { kind: "constructor", owner: "GdbCommandTimeoutError", }, { kind: "constructor", owner: "GdbCommandProcessExitError", }, { kind: "constructor", owner: "GdbSessionManager", }, { kind: "declaration", owner: "GdbSessionManager", method: "#startProtocol", name: "session", }, { kind: "declaration", owner: "GdbSessionManager", method: "#startProtocol", name: "stdoutSettled", }, { kind: "call", owner: "GdbSessionManager", method: "#startProtocol", callee: "launched.process.stdout?.on", event: "data", }, { kind: "call", owner: "GdbSessionManager", method: "#startProtocol", callee: "launched.process.stdin?.on", event: "error", }, { kind: "call", owner: "GdbSessionManager", method: "#startProtocol", callee: "launched.process.stdin?.once", event: "close", }, { kind: "call", owner: "GdbSessionManager", method: "#startProtocol", callee: "launched.process.once", event: "exit", }, { kind: "guard", owner: "GdbSessionManager", method: "#startProtocol", condition: "launched.process.stdout === null", }, { kind: "method", owner: "GdbSessionManager", name: "close", }, ]), ...mutationRanges("src/process/ownedDebuggerSession.ts", [ { kind: "declaration", name: "waitForInferiorDetach", }, ]), ...mutationRanges("src/rizin/RizinDebugSessionManager.ts", [ { kind: "guard", owner: "RizinDebugSessionManager", method: "execute", condition: "captured.outputTruncated", }, { kind: "declaration", owner: "RizinDebugSessionManager", method: "execute", name: "result", withinBlockWithBinding: "captured", }, { kind: "declaration", owner: "RizinDebugSessionManager", method: "execute", name: "evidence", withinBlockWithBinding: "captured", }, { kind: "declaration", owner: "RizinDebugSessionManager", method: "#receive", name: "nextOffset", }, ]), ...mutationRanges("src/domain/analysisResourceLimits.ts", [ { kind: "declaration", name: "DEFAULT_DEBUGGER_MAX_SESSIONS", }, ]), ...mutationRanges("src/cli/reverseEngineeringCommands.ts", [ { kind: "command-handler", command: "debugWithGdb", }, { kind: "command-handler", command: "debugWithRizin", }, ]), ...mutationRanges("src/cutter/CutterBridgeClient.ts", [ { kind: "expression", text: "status.data.current_file === undefined", }, { kind: "expression", text: "response.current_file === undefined", }, ]), ], }; - stryker.semantics.config.mjs (1579 bytes)
import { mutationRanges } from "./scripts/lib/reverse-tools-mutation-targets.mjs"; const config = { $schema: "./node_modules/@stryker-mutator/core/schema/stryker-schema.json", testRunner: "command", commandRunner: { command: "npx vitest run --config vitest.reverse-tools-semantics.config.ts", }, plugins: ["@stryker-mutator/typescript-checker"], checkers: ["typescript"], tsconfigFile: "tsconfig.reverse-tools-mutation.json", typescriptChecker: { prioritizePerformanceOverAccuracy: true, }, coverageAnalysis: "off", thresholds: { break: null }, ignorePatterns: ["/.cache/rea-command-locks/**", "/coverage/**"], concurrency: 2, timeoutMS: 30000, reporters: ["clear-text", "progress", "html", "json"], jsonReporter: { fileName: "reports/mutation/reverse-tools-semantics.json" }, htmlReporter: { fileName: "reports/mutation/reverse-tools-semantics.html" }, }; export default { ...config, mutate: [ ...mutationRanges("src/cutter/CutterBridgeClient.ts", [ { kind: "expression", text: "status.data.current_file === undefined", }, { kind: "expression", text: "response.current_file === undefined", }, ]), ...mutationRanges("src/rizin/RizinDebugSessionManager.ts", [ { kind: "expression", text: "remaining <= 0", }, { kind: "declaration", name: "snapshot", withinBlockWithBinding: "output", }, { kind: "declaration", name: "createRizinCommandTimeoutEvidence", }, ]), ], }; - THIRD_PARTY_NOTICES.md (27552 bytes)
# Third-party notices REA-authored code is licensed under [MIT](LICENSE). Third-party material retains its own copyright, license, attribution, and NOTICE requirements. REA's MIT license grants no rights to proprietary analysis tools. Project and product names identify integrations; they do not imply affiliation or endorsement. This inventory covers the locked npm dependency graph, code or assets derived from upstream projects, and separately obtained engines used by REA. A listed integration is not a statement that its executable is bundled. Upstream components and caller-selected versions may have additional terms; retain the notices supplied with the software you actually obtain or redistribute. ## Distributed dependencies, derived code, and assets | Material | Use and licensing records | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | npm dependencies | [Complete inventory](licenses/npm-dependencies.txt) of every entry in `package-lock.json`, including transitive, optional platform, development, and website dependencies. [Runtime notices](licenses/npm-runtime-notices.txt) preserve the copyright, license, and NOTICE documents from integrity-verified release archives, plus the MIT notice for Rolldown's generated runtime helpers. Development dependencies are inventoried but are not all distributed in REA's npm package. | | pefile ordinal tables | Import-hash ordinal names are derived from [pefile 2024.8.26](https://github.com/erocarrera/pefile/tree/4b3b1e2e568a88d4f1897d694d684f23d9e270c4), copyright 2004–2024 Ero Carrera. Preserve the [MIT license](licenses/pefile-2024.8.26-LICENSE.txt). The Python package is not a runtime dependency. | | UF2 family names | UF2 family IDs and short names are copied from [microsoft/uf2 `utils/uf2families.json`](https://github.com/microsoft/uf2/blob/cf3bd7f9c274b949528f8cd6a19eef2502a687d2/utils/uf2families.json), copyright Microsoft Corporation. Preserve the [MIT license](licenses/microsoft-uf2-MIT.txt). | | NativeAOT parser | REA's derived parser uses the MIT-licensed [ghidra-nativeaot](https://github.com/Washi1337/ghidra-nativeaot/tree/effeb734fc570c32650f88b159608979dc7b423e) work of Washi and the NativeAOT layout definitions in [dotnet/runtime](https://github.com/dotnet/runtime/tree/a3b2d40328be0be3f8dd43f0e5cc925b8827b044). Preserve [Washi's MIT notice](licenses/nativeaot-parser-MIT.txt) and the [.NET Foundation MIT notice](licenses/dotnet-runtime-MIT.txt). | | EVM analysis | `[email protected]`, MIT, copyright 2023 Maxim Andreev. The published npm archive omits its license document; REA retains the [original upstream license](third_party/evmole/LICENSE) and [provenance](third_party/evmole/README.md). It is also included in the runtime notices. | | Windows native addon | The release addon is compiled with MinGW-w64 and statically links GCC runtime libraries. Preserve the [MinGW-w64 runtime notices](licenses/MinGW-w64-runtime.txt), [GPLv3 text](licenses/GPL-3.0.txt), and [GCC Runtime Library Exception 3.1](licenses/GCC-Runtime-Library-Exception-3.1.txt). The exception governs eligible compiled combinations; it does not relicense the runtime itself under MIT. The Node-API build headers are from Node 22.19.0; its [original license and component notices](licenses/Node-22.19.0-LICENSE.txt) are retained. Node itself is supplied by the user. Snapshot provenance and release-toolchain review requirements are in [licenses/README.md](licenses/README.md). | | Dinosaur website example | Selected excerpts from [wayou/t-rex-runner](https://github.com/wayou/t-rex-runner/tree/5455bfa408ec6b707c7300ff194b7390733a766d), derived from Chromium's dinosaur game. The website retains the [original BSD-3-Clause notices](website/public/assets/licenses/dinosaur.txt), including Chromium authors and wayou. This asset is not part of the npm runtime. | The UEFI x86 BCJ decoder is adapted from Igor Pavlov's public-domain [Bra86.c](https://github.com/tianocore/edk2/blob/556dcfb466e9f05affeaff881d738807f8156d3c/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/Bra86.c), as used by EDK II's LZMAF86 handler. Two locked runtime releases, [`[email protected]`](https://github.com/TheSavior/clean-git-ref/tree/bf3c8afc8032bcdc6a53634c18b601dc6df478fb) (declared Apache-2.0) and [`[email protected]`](https://github.com/kt3k/minimisted/tree/95fdfb8d6efb9546c1117854fe3a58105f6332ce) (declared MIT), omit a full license/copyright document in their published archives and inspected upstream release sources. Their runtime notice entries preserve the declared license and author metadata and include a clearly labeled standard license text. These are documented upstream notice gaps, not recovered copyright notices or a claim that attribution has been fully verified. The optional `[email protected]` npm archive and tagged Node binding source also omit a standalone license/copyright document. Its declared `LGPL-2.0 WITH WxWindows-exception-3.1` license is recorded with unchanged [Frida licensing text](licenses/frida-17.23.2-COPYING.txt) and the [GNU Library GPL v2](licenses/LGPL-2.0.txt). These are licensing supplements, not recovered Node binding or prebuild-component copyright notices. ## Open-source engine credits and licenses We thank the maintainers and contributors of the projects below. Their decompilers, binary-analysis engines, debuggers, parsers, and capture tools provide capabilities used through REA's integrations. Each row identifies the upstream project, its own license, and its role in REA. In particular, JADX provides the Android decompiler, while jadx-headless-mcp provides the separate headless integration used by REA; both projects deserve credit. These acknowledgments are voluntary thanks. Required upstream copyright and NOTICE texts remain in their original form and are not replaced by this summary. Credits do not imply endorsement or change any license. REA's adapters do not grant, replace, or waive these licenses. The upstream executables and their dependency graphs are supplied separately. Git submodules pin inspection sources; they are not included in the npm package. | Project | License and source | REA relationship | | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Ghidra | [Apache-2.0](https://github.com/NationalSecurityAgency/ghidra/blob/Ghidra_12.2_build/LICENSE), with the government-work and component qualifications in its [NOTICE](https://github.com/NationalSecurityAgency/ghidra/blob/Ghidra_12.2_build/NOTICE) | Bring your own Ghidra; see [supported versions](docs/getting-started/installation.md#ghidra). Copies of the 12.2 [LICENSE](licenses/ghidra-12.2-LICENSE.txt), [NOTICE](licenses/ghidra-12.2-NOTICE.txt), and [DISCLAIMER](licenses/ghidra-12.2-DISCLAIMER.txt) are retained for reference. | | ghidra-nativeaot | [MIT](https://github.com/Washi1337/ghidra-nativeaot/blob/effeb734fc570c32650f88b159608979dc7b423e/LICENSE.md) | Pinned inspection source; derived parser attribution above. | | JADX | [Apache-2.0](https://github.com/skylot/jadx/blob/v1.5.6/LICENSE) | The audited jadx-headless-mcp source uses JADX 1.5.6 for Android decompilation; the engine JAR is separately supplied. | | jadx-headless-mcp | [Apache-2.0](https://github.com/1013503897/jadx-headless-mcp/blob/5844800a486d2248fa949b74c9896285f5b54de2/LICENSE) | v0.7.1; pinned submodule and user-supplied JAR. | | Kuna | [Apache-2.0](https://github.com/Noelo-Lab/kuna/blob/v1.1000/LICENSE), with its [NOTICE](https://github.com/Noelo-Lab/kuna/blob/v1.1000/NOTICE) | Bring your own `kuna`; REA verified 1.1000 and never downloads, installs or bundles it. REA invokes it as a separate process. | | Apktool | [Apache-2.0](https://github.com/iBotPeaches/Apktool/blob/master/LICENSE.md) | User-supplied Android resource decoder. | | Binwalk | [MIT](https://github.com/ReFirmLabs/binwalk/blob/4fdab3d464d97b68e0af9088df3f9e2e1545b21c/LICENSE) | v3.1.0; pinned submodule and user-supplied firmware engine. | | Unblob | [MIT](https://github.com/onekey-sec/unblob/blob/1fcc7a0a584a70a96c31f5a276c20944d199a089/LICENSE) | 26.6.4; pinned submodule and user-supplied firmware engine.
- tsconfig.build.json (252 bytes)
{ "extends": "./tsconfig.json", "compilerOptions": { "rootDir": "src", "types": ["node"] }, "include": ["src/**/*.ts"], "exclude": [ "src/**/*.fixture.ts", "src/**/*.test.ts", "tests", "dist", "node_modules" ] } - tsconfig.frida-verification.json (205 bytes)
{ "extends": "./tsconfig.json", "compilerOptions": { "noEmit": true }, "files": [ "src/frida/frida-bindings.d.ts", "scripts/verify/fridaBindingsCompatibility.ts" ], "include": [] } - tsconfig.json (827 bytes)
{ "compilerOptions": { "allowJs": true, "allowUnreachableCode": false, "allowUnusedLabels": false, "checkJs": false, "exactOptionalPropertyTypes": true, "forceConsistentCasingInFileNames": true, "lib": ["ES2023"], "module": "NodeNext", "moduleResolution": "NodeNext", "noFallthroughCasesInSwitch": true, "noImplicitOverride": true, "noImplicitReturns": true, "noUncheckedIndexedAccess": true, "outDir": "dist", "paths": { "#dist/*": ["./src/*"] }, "rootDir": ".", "skipLibCheck": true, "strict": true, "target": "ES2023", "types": ["node"], "verbatimModuleSyntax": true }, "include": [ "src/**/*.ts", "tests/**/*.ts", "vitest.config.ts", "docs/.vitepress/config.ts" ], "exclude": ["dist", "node_modules"] } - tsconfig.reverse-tools-mutation.json (2577 bytes)
{ "extends": "./tsconfig.json", "include": [ "src/frida/frida-bindings.d.ts", "src/application/reverse/ReverseEngineeringService.ts", "src/cli/reverseEngineeringCommands.ts", "src/cutter/CutterBridgeClient.ts", "src/cutter/CutterBridgeService.ts", "src/gdb/GdbSessionManager.ts", "src/objdump/ObjdumpCommand.ts", "src/process/ownedDebuggerSession.ts", "src/process/ExecFileOutput.ts", "src/server/externalMutationToolHandler.ts", "src/server/serviceToolBindings.ts", "src/server/providerEnvironment.ts", "src/rizin/RizinCommand.ts", "src/rizin/RizinDebugSessionManager.ts", "tests/boundary/providers/GdbSessionManagerCoverage.test.ts", "tests/boundary/mcp/rizinPendingOutput.test.ts", "tests/boundary/providers/RizinInferiorTty.test.ts", "tests/boundary/providers/RizinDecoderInputs.test.ts", "tests/boundary/providers/RizinTestInferiorTty.ts", "tests/boundary/providers/CutterBridgeClient.test.ts", "tests/boundary/providers/CutterBridgeNullIdentity.test.ts", "tests/boundary/providers/CutterBridgeService.test.ts", "tests/boundary/process/ownedDebuggerSession.test.ts", "tests/boundary/mcp/cutterMcp.test.ts", "tests/boundary/mcp/cutterCancellationMcp.test.ts", "tests/boundary/mcp/reverseEngineeringPartialMcp.test.ts", "tests/boundary/mcp/reverseEngineeringEnvironmentMcp.test.ts", "tests/boundary/cli/gdbStartupCleanupCli.test.ts", "tests/composition/reverseEngineering.test.ts", "tests/composition/reverseEngineeringAdmission.test.ts", "tests/composition/reverseEngineeringEdgeCases.test.ts", "tests/composition/reverseEngineeringCancellation.test.ts", "src/process/ExecFileOutput.test.ts", "tests/boundary/providers/GdbSessionManagers.test.ts", "tests/boundary/providers/RizinDebugSessionManagers.test.ts", "tests/boundary/providers/GdbCommandQueue.test.ts", "tests/boundary/providers/GdbSessionReviewRegressions.test.ts", "tests/boundary/providers/RizinDebugSessionReviewRegressions.test.ts", "tests/boundary/providers/RizinDebugSessionCoverage.part1.test.ts", "tests/boundary/providers/RizinDebugSessionCoverage.part2.test.ts", "tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts", "tests/boundary/providers/RizinDebugSessionCoverage.part4.test.ts", "tests/boundary/providers/RizinDebugSessionCoverage.part5.test.ts", "tests/boundary/mcp/gdbCancellationMcp.test.ts", "tests/boundary/mcp/rizinDebuggerCancellationMcp.test.ts" ], "exclude": ["dist", "node_modules"] } - tsconfig.scripts.json (1202 bytes)
{ "extends": "./tsconfig.json", "compilerOptions": { "allowJs": true, "checkJs": true, "noEmit": true, "paths": { "#dist/*": ["./src/*"] } }, "files": [ "scripts/fixtures/managed/function-dossier.mjs", "scripts/fixtures/managed/pe.mjs", "scripts/lib/canonical-temporary-directory.mjs", "scripts/lib/catalog-cli.mjs", "scripts/lib/mcp-verifier-results.mjs", "scripts/lib/real-ghidra-snapshot-lifecycle.mjs", "scripts/lib/verifier-artifact-scope.mjs", "scripts/lib/verifier-cleanup.mjs", "scripts/lib/verifier-fixture.mjs", "scripts/lib/verifier-run.mjs", "scripts/lib/verifier-source-loader.mjs", "scripts/verify-package-evidence.mjs", "scripts/verify/javascript/digests.mjs", "scripts/verify/javascript/output.mjs", "scripts/verify/managed/completion-report.mjs", "scripts/verify/managed/config.mjs", "scripts/verify/managed/conformance.mjs", "scripts/verify/managed/manifest-parser.mjs", "scripts/verify/managed/manifest.mjs", "scripts/verify/managed/oracles.mjs", "scripts/verify/managed/support.mjs", "scripts/verify/typed-script-declarations-guard.mjs" ], "include": [] } - turbo.json (7880 bytes)
{ "$schema": "https://turborepo.dev/schema.json", "cacheMaxAge": "7d", "cacheMaxSize": "500MB", "globalDependencies": [".nvmrc", ".npmrc"], "globalPassThroughEnv": [ "GOMAXPROCS", "GOMEMLIMIT", "UV_THREADPOOL_SIZE", "REA_TYPESCRIPT_COMPILER" ], "tasks": { "compile": { "dependsOn": ["metadata:check"], "inputs": [ "package.json", "package-lock.json", "scripts/run-turbo.mjs", "scripts/run-typescript.mjs", "scripts/check-dependency-install.mjs", "scripts/clean-build-output.mjs", "scripts/bundle-runtime.mjs", "scripts/record-catalog-digests.mjs", "scripts/record-mcp-catalog.mjs", "scripts/record-cli-commands.mjs", "scripts/generate-package-metadata.mjs", "src/**/*.{cts,mts,ts,tsx}", "src/**/package.json", "!src/**/*.test.ts", "!src/**/*.fixture.ts", "tsconfig.json", "tsconfig.build.json" ], "outputs": ["dist/**"], "env": ["REA_TYPESCRIPT_COMPILER"] }, "typecheck": { "inputs": [ "package.json", "package-lock.json", "scripts/run-turbo.mjs", "scripts/run-typescript.mjs", "src/**/*.{cts,mts,ts,tsx}", "src/**/package.json", "tests/**/*.{cts,mts,ts,tsx}", "tests/**/package.json", "tsconfig.json", "tsconfig.build.json", "tsconfig.scripts.json", "vitest.config.ts", "scripts/**/*.d.{cts,mts,ts}", "scripts/**/*.mjs", "scripts/**/package.json", ".github/actions/**/*.{cts,mts,ts,tsx}", ".github/**/package.json", "docs/**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}", "docs/**/package.json", "!docs/.vitepress/cache/**", "!docs/.vitepress/dist/**" ], "outputs": [], "env": ["REA_TYPESCRIPT_COMPILER"] }, "metadata:check": { "inputs": [ "package.json", "package-lock.json", "scripts/generate-package-metadata.mjs", "scripts/lib/generated-file.mjs", "scripts/lib/verifier-source-loader.mjs", "src/domain/skillManifest.ts", "src/domain/result.ts", ".agents/skills/reverse-engineer-anything/SKILL.md", "src/generatedPackageMetadata.ts" ] }, "lint": { "outputs": [".cache/static-checks/oxlint.json"], "inputs": [ ".gitignore", ".oxlintrc.json", "package.json", "package-lock.json", "scripts/lib/module-layers.baseline.json", "scripts/**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}", "src/**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}", "tests/**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}", "docs/**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}", "docs/reference/rea-limit-inventory.md", ".github/actions/**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}", "website/**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}", "src/**/*.{json,md,py,yaml,yml}", "tests/**/*.{json,md,py,yaml,yml}", "scripts/**/*.{json,md,py,yaml,yml}", ".agents/**/*.{js,json,md,mjs,py,ts,tsx,yaml,yml}", "!docs/.vitepress/cache/**", "!docs/.vitepress/dist/**", "!website/_site/**", "*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}" ] }, "format:check": {}, "knip": { "dependsOn": ["compile"], "inputs": [ ".gitignore", "knip.json", "package.json", "package-lock.json", "scripts/**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}", "src/**/*.ts", "tests/**/*.ts", ".github/actions/**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}", ".github/**/package.json", ".github/workflows/*.{yml,yaml}", ".github/**/action.{yml,yaml}", "tsconfig.json", "tsconfig.build.json", "docs/.vitepress/config.ts", "*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}" ] }, "jscpd": { "inputs": [ ".gitignore", ".jscpd.json", "package.json", "package-lock.json", "scripts/ci/static-check-report.mjs", "src/**", "tests/**" ], "outputs": [".cache/static-checks/jscpd/jscpd-report.json"] }, "scan:todos": { "inputs": [ "bridge/**/*.{java,py}", "scripts/**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}", "src/**/*.ts", "tests/**/*.ts" ] }, "test:run": { "cache": false, "dependsOn": [ "artifacts:product-catalog", "artifacts:managed-evidence", "artifacts:skills" ] }, "docs:check:built": { "dependsOn": [ "artifacts:product-catalog", "artifacts:managed-evidence", "artifacts:skills" ], "inputs": [ "package.json", "package-lock.json", "scripts/generate-*.mjs", "scripts/check-doc-facts.mjs", "scripts/lib/*.mjs", "scripts/verify/managed/*.mjs", "scripts/fixtures/managed/*.mjs", "scripts/verify/apple/*.mjs", "scripts/fixtures/apple/*.mjs", "src/generated*.ts", "src/contracts/**/*.ts", "licenses/**", "docs/**", "!docs/public/product-catalog.json", "!docs/verification/managed-conformance-*.json", ".agents/skills/**", "README*.md", "AGENTS.md", "CONTRIBUTING.md", "website/public/**/*.{md,html}", { "mode": "dependencyOutputs", "globs": [ "skills/**", "docs/public/product-catalog.json", "docs/verification/managed-conformance-manifest.json", "docs/verification/managed-conformance-ledger.json" ] } ] }, "artifacts:skills": { "dependsOn": ["compile"], "inputs": [ "package.json", "package-lock.json", "scripts/generate-skill-metadata.mjs", "scripts/lib/generated-file.mjs", "scripts/lib/verifier-source-loader.mjs", ".agents/skills/reverse-engineer-anything/**" ], "outputs": ["skills/**"] }, "artifacts:product-catalog": { "dependsOn": ["compile"], "inputs": [ "package.json", "package-lock.json", "scripts/generate-product-catalog.mjs", "scripts/lib/**/*.mjs", ".oxfmtrc.json" ], "outputs": ["docs/public/product-catalog.json"] }, "artifacts:managed-evidence": { "dependsOn": ["artifacts:skills"], "inputs": [ "package.json", "package-lock.json", "scripts/generate-completion-ledger.mjs", "scripts/lib/generated-file.mjs", "scripts/verify/managed/**", "scripts/fixtures/managed/**" ], "outputs": [ "docs/verification/managed-conformance-manifest.json", "docs/verification/managed-conformance-ledger.json" ] }, "artifacts:error-schema": { "dependsOn": ["compile"], "inputs": [ "package.json", "package-lock.json", "scripts/generate-error-schema.mjs", "scripts/lib/generated-file.mjs", "scripts/lib/format-generated-file.mjs", ".oxfmtrc.json" ], "outputs": [ "docs/error-contract.schema.json", "docs/user-visible-errors.csv" ] }, "evidence:check:built": { "dependsOn": ["artifacts:managed-evidence"], "inputs": [ "package.json", "package-lock.json", "scripts/generate-completion-ledger.mjs", "scripts/lib/generated-file.mjs", "scripts/verify/managed/**", "scripts/fixtures/managed/**", { "mode": "dependencyOutputs", "globs": [ "docs/verification/managed-conformance-manifest.json", "docs/verification/managed-conformance-ledger.json" ] } ] } } } - vitest.config.ts (8536 bytes)
import { realpathSync } from "node:fs"; import { availableParallelism, tmpdir } from "node:os"; import { join } from "node:path"; import { defineConfig } from "vitest/config"; import { parseCLI } from "vitest/node"; import { BUILT_TEST_PROJECTS, SOURCE_TEST_PROJECTS, } from "./scripts/lib/test-projects.mjs"; import { CiTestSequencer } from "./tests/ciTestSequencer.js"; import { COVERAGE_DEADLINE_SCALE, HOSTED_RUNNER_DEADLINE_SCALE, LONG_RUNNING_DEADLINE_MS, remainingTestDeadline, TEST_DEADLINE_MS as BASE_TEST_DEADLINE_MS, } from "./tests/support/testDeadlines.js"; // Playwright's registry does not derive a cache directory for Termux's // `android` platform. Match the production CLI fallback before workers import // browser modules. if ( process.platform === "android" && process.env.PLAYWRIGHT_BROWSERS_PATH === undefined ) { const cacheRoot = process.env.XDG_CACHE_HOME ?? join(process.env.HOME ?? ".", ".cache"); process.env.PLAYWRIGHT_BROWSERS_PATH = join(cacheRoot, "ms-playwright"); } const CANONICAL_TEMPORARY_DIRECTORY = realpathSync(tmpdir()); // Use Vitest's option parser so explicit false and spaced shard values retain // their meaning. Unknown worker/embedding arguments are not Vitest options. const { options: testOptions } = parseCLI( ["vitest", ...process.argv.slice(2)], { allowUnknownOptions: true }, ); const COVERAGE_ENABLED = testOptions.coverage?.enabled === true; const COVERAGE_SHARD = testOptions.shard !== undefined; // Bound concurrency by the runner rather than command locks. A hosted CI job // owns its whole four-core runner, so it may use every core; other hosts stay // at two workers because developers and agents share them with other checks. const DEDICATED_CI_RUNNER = process.env.GITHUB_ACTIONS === "true"; const MAX_TEST_WORKERS = Math.min( DEDICATED_CI_RUNNER ? 4 : 2, availableParallelism(), ); // A test deadline only turns a hang into a named failure; it is not a // performance assertion. Projects own it so tests do not hard-code host speed. // Built projects launch compiled CLI, MCP, and provider processes while other // lanes share the runner, and coverage instrumentation slows every lane. Hosted // CI runs a worker per core, so CPU-bound cases there share every core with // other workers and their subprocesses. const DEADLINE_SCALE = (COVERAGE_ENABLED ? COVERAGE_DEADLINE_SCALE : 1) * (DEDICATED_CI_RUNNER ? HOSTED_RUNNER_DEADLINE_SCALE : 1); const TEST_DEADLINE_MS = { source: BASE_TEST_DEADLINE_MS.source * DEADLINE_SCALE, built: BASE_TEST_DEADLINE_MS.built * DEADLINE_SCALE, } as const; // Vitest's one-second `expect.poll` default is a host-speed guess. A poll the // project owns waits as long as its test may run, less a reporting reserve, so // a condition that never holds still fails with the poll's own diagnostics. const pollPolicy = (deadlineMs: number) => { const timeout = remainingTestDeadline(deadlineMs, 0); return timeout === undefined ? {} : { timeout }; }; const TEST_PROJECTS = [...SOURCE_TEST_PROJECTS, ...BUILT_TEST_PROJECTS]; // Source projects that share a module graph still run in forked workers. // Thread workers share one process, so the source lane's workers once grew // one 3.8 GiB process; Linux CI then refused to fork test subprocesses from it // (`spawnSync ... ENOMEM`). A forked worker keeps its own heap and main-thread // stack, so the largest process stays near one worker's size. const PROJECT_POLICIES = { domain: { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS, // Domain and contract modules are pure and own no process-global state, so // per-file module isolation adds startup cost without protecting a seam. }, services: { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS, // Service tests use recording ports and own no process-global state. Share // their module graph so file startup does not dominate the lane. }, adapters: { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS }, composition: { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS, // Composition tests use provider-neutral sessions and test-scoped cleanup; // sharing their immutable module graph avoids per-file startup work. }, boundary: { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS }, "cli-boundary": { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS, // CLI tests create fresh command instances or subprocesses and own their // cleanup. Reuse the immutable graph; module mocks belong in process-global. // The shared source/contract graph also needs transient schema/help space. // Ordinary CI exhausted 384 MiB after earlier files warmed that graph. // Use the measured 512 MiB budget with the same bounded concurrency. execArgv: ["--max-old-space-size=512"], }, "process-boundary": { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS, // Process-tree observations share host sampling resources; keep this small // lane serial while the independent projects run together. fileParallelism: false, sequence: { groupOrder: 1 }, }, "mcp-boundary": { pool: "threads" as const, maxWorkers: MAX_TEST_WORKERS, // Each file creates and closes an explicit in-memory MCP session. Reuse the // immutable server graph so module startup does not outweigh transport work. }, acceptance: { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS }, "process-global": { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS }, conformance: { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS, // Contract cases use recording providers and own no process-global state. }, evaluation: { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS, // Evaluator tests inspect deterministic inputs without mutating shared state. }, }; const ZERO_COVERAGE_THRESHOLDS = { statements: 0, branches: 0, functions: 0, lines: 0, "src/domain/**": { statements: 0, branches: 0, functions: 0, lines: 0, }, "src/contracts/**": { statements: 0, branches: 0, functions: 0, lines: 0, }, }; const projects = TEST_PROJECTS.map((project) => { const policy = PROJECT_POLICIES[project.name as keyof typeof PROJECT_POLICIES]; if (!policy) throw new Error(`Missing test runner policy for ${project.name}`); return { extends: true as const, test: { name: project.name, include: [...project.include], ...(project.exclude ? { exclude: [...project.exclude] } : {}), isolate: project.isolate !== false, testTimeout: TEST_DEADLINE_MS[project.group], hookTimeout: TEST_DEADLINE_MS[project.group], expect: { poll: pollPolicy(TEST_DEADLINE_MS[project.group]) }, ...policy, }, }; }); export default defineConfig({ test: { env: { TMPDIR: CANONICAL_TEMPORARY_DIRECTORY, }, maxWorkers: MAX_TEST_WORKERS, projects, ...(process.env.REA_CI_TEST_HISTORY ? { sequence: { sequencer: CiTestSequencer } } : {}), retry: 0, reporters: ["default"], runner: "./tests/processOwnershipRunner.ts", testTimeout: TEST_DEADLINE_MS.source, hookTimeout: TEST_DEADLINE_MS.source, expect: { poll: pollPolicy(TEST_DEADLINE_MS.source) }, // Deadline probes compare what Vitest applies with the configured policy. provide: { testDeadlineScale: DEADLINE_SCALE }, tags: [ { name: "long-running", description: "A bounded workload that needs more than its project's deadline", timeout: LONG_RUNNING_DEADLINE_MS * DEADLINE_SCALE, }, ], coverage: { enabled: false, provider: "v8", reportsDirectory: join( tmpdir(), `rea-vitest-coverage-${String(process.pid)}`, ), include: ["src/**"], thresholds: COVERAGE_SHARD ? ZERO_COVERAGE_THRESHOLDS : { statements: 65, branches: 60, functions: 60, lines: 68, "src/domain/**": { statements: 80, branches: 75, functions: 75, lines: 80, }, "src/contracts/**": { statements: 85, branches: 80, functions: 80, lines: 85, }, }, reporter: ["text", "text-summary"], }, }, }); declare module "vitest" { export interface ProvidedContext { readonly testDeadlineScale: number; } } - vitest.reverse-tools-semantics.config.ts (434 bytes)
import { defineConfig } from "vitest/config"; export default defineConfig({ test: { include: [ "tests/boundary/providers/CutterBridgeClient.test.ts", "tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts", "tests/boundary/mcp/rizinPendingOutput.test.ts", ], pool: "forks", maxWorkers: 2, retry: 0, testTimeout: 60_000, runner: "./tests/processOwnershipRunner.ts", }, }); - vitest.reverse-tools.config.ts (3345 bytes)
import { defineConfig } from "vitest/config"; const REVERSE_TOOL_MODULES = [ "src/application/reverse/ReverseEngineeringService.ts", "src/application/binary/BinarySession.ts", "src/cutter/CutterBridgeClient.ts", "src/cutter/CutterBridgeService.ts", "src/gdb/GdbSessionManager.ts", "src/objdump/ObjdumpCommand.ts", "src/process/ownedDebuggerSession.ts", "src/process/ExecFileOutput.ts", "src/server/externalMutationToolHandler.ts", "src/server/serviceToolBindings.ts", "src/server/externalMutationAdmission.ts", "src/server/providerEnvironment.ts", "src/rizin/RizinCommand.ts", "src/rizin/RizinDebugSessionManager.ts", ]; export default defineConfig({ test: { include: [ "tests/composition/analysis-sessions/binarySession.test.ts", "tests/boundary/filesystem/directAnalysisSnapshotReplay.test.ts", "tests/boundary/providers/GdbSessionManagers.test.ts", "tests/boundary/providers/RizinDebugSessionManagers.test.ts", "tests/boundary/providers/RizinInferiorTty.test.ts", "tests/boundary/providers/RizinDecoderInputs.test.ts", "tests/boundary/providers/GdbSessionManagerCoverage.test.ts", "tests/boundary/providers/GdbCommandQueue.test.ts", "tests/boundary/providers/GdbSessionReviewRegressions.test.ts", "tests/boundary/providers/RizinDebugSessionReviewRegressions.test.ts", "tests/boundary/providers/RizinDebugSessionCoverage.part1.test.ts", "tests/boundary/providers/RizinDebugSessionCoverage.part2.test.ts", "tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts", "tests/boundary/providers/RizinDebugSessionCoverage.part4.test.ts", "tests/boundary/providers/RizinDebugSessionCoverage.part5.test.ts", "tests/boundary/providers/CutterBridgeClient.test.ts", "tests/boundary/providers/CutterBridgeCapacity.test.ts", "tests/boundary/providers/cutterBridgeProducer.test.ts", "tests/boundary/providers/CutterBridgeNullIdentity.test.ts", "tests/boundary/providers/CutterBridgeService.test.ts", "tests/boundary/process/ownedDebuggerSession.test.ts", "tests/boundary/mcp/gdbCancellationMcp.test.ts", "tests/boundary/mcp/rizinDebuggerCancellationMcp.test.ts", "tests/boundary/mcp/rizinPendingOutput.test.ts", "tests/boundary/mcp/cutterMcp.test.ts", "tests/boundary/mcp/cutterCancellationMcp.test.ts", "tests/boundary/mcp/reverseEngineeringEnvironmentMcp.test.ts", "tests/boundary/mcp/reverseEngineeringPartialMcp.test.ts", "tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts", "tests/boundary/cli/gdbStartupCleanupCli.test.ts", "tests/composition/reverseEngineering.test.ts", "tests/composition/reverseEngineeringAdmission.test.ts", "tests/composition/reverseEngineeringEdgeCases.test.ts", "tests/boundary/cli/reverseEngineeringCommands.test.ts", "tests/composition/reverseEngineeringCancellation.test.ts", "src/process/ExecFileOutput.test.ts", ], pool: "forks", maxWorkers: 2, retry: 0, testTimeout: 60_000, runner: "./tests/processOwnershipRunner.ts", coverage: { enabled: false, provider: "v8", reportsDirectory: "coverage/reverse-tools", include: REVERSE_TOOL_MODULES, reporter: ["text", "text-summary", "json"], }, }, }); - website/AGENTS.md (3958 bytes)
# Website maintenance > A good website is like a good paper: easy to follow, clear and concise, with a clean, refined presentation. > > — N0zoM1z0 Read [README.md](README.md) and [style-guide.md](style-guide.md) before changing website content, layout or figures. Use [figures.md](figures.md) and `evidence/` for asset notes and the source of case-study claims. - Author source pages in English. Use direct headings and concrete instructions in every language. Each paragraph should explain a new fact or action. - Follow [locales/README.md](locales/README.md) for translations. Edit standard PO catalogs, run `translations extract` after changing source text, and review translated setup prompts, terminology and case-study reasoning for readability. Keep code, commands, URLs, paths and Evidence unchanged. Use inline `code` or `translate="no"` for executable literals inside a translated sentence. Preserve named placeholders, source references and reviewer comments. Generated language HTML belongs in ignored `_site/`; do not author duplicate translated pages. - Keep the language inventory aligned with README editions. Review long headings, figures and right-to-left layouts. A missing or fuzzy translation produces a labeled, nonindexable English fallback; do not present stale text as current. - Reuse the shared styles, prompts, figures and code-step components. Keep a case study focused on one question, with further examples in native details. - Edit shared header, footer and sharing markup in `templates/`; run `python3 scripts/website.py sync` and commit the rendered regions with their templates. Keep page bodies outside the marked regions. Author each title and description once; derive sharing fields and canonicals from them. Use `new-page` for a reading-page scaffold, then add its index link. Keep a draft's visible label and `noindex` until the content is ready. - Show what REA returns and how the agent uses it. Preserve source attribution, target identity and verification scope. - Blog articles teach methods, decisions and workflows through concrete cases. Lead with the takeaway. Essays can develop a personal argument through experience; figures are optional and should add an explanation the prose needs. Use engine details only when they explain a decision. Label working outlines and mark them `noindex`. - Keep personal paths, account data, credentials and raw captures outside the public assets. Use generic inputs and label shortened display paths. - Follow the same clear writing standard in search titles and descriptions. Give each content page its own absolute `https://rea.tools/` canonical and matching sharing metadata; keep navigation relative. The sitemap is generated from HTML automatically. Mark example applications `noindex` in the head and keep them crawlable. Maintain the SVG sharing source, not the generated PNG. - Check both local root and `/rea/` paths, mobile layouts, expanded details, copying and downloads. Check light and dark themes, including a manual choice opposite to the system preference. Run `python3 scripts/website.py check`, using the Python environment described in the README. It rejects drift rather than silently rewriting shared HTML. Use `website.py links` for an optional network audit; distinguish missing targets from access denials and unverified fragments. - Check setup and support statements against the current installation/provider guides and released package. Preserve historical case-study checkpoints and versions unless a new investigation supplies replacement evidence. - Keep `website-pages.yml` as the sole, manual production publisher for Cloudflare and Pages. Default to `both`: both hosts receive the same verified artifact and pass the published-commit check. Use `pages` only when explicitly requested while Cloudflare credentials are being configured. Follow the website README.