Bluetooth Controller Reverse Engineering
What this skill does
It turns a raw, unnamed Bluetooth Controller binary loaded in Ghidra into one where HCI Commands, HCI Events, LMP packets, and LLCP packets are all named according to the Bluetooth Core Specification, their arguments and locals are typed as proper packet structs, and per-connection global state is modeled as arrays of structs. The end state is decompilation that reads close to the spec.
The work is organized as a five-phase DAG. Phases that share no dependencies are dispatched as parallel batches; phases that build on earlier renames run strictly in order.
Prerequisites
Run bash scripts/preflight.sh before the first analysis. The Codex launcher requires Ghidra 12 with JDK 21+, the XenoKovah pyghidra-mcp fork, uvx, Node.js/npx, jq, Python, and the Codex CLI. Provision the fork with bash scripts/setup_forks.sh, or explicitly allow the launcher to do so with --setup-forks. Optionally set BTRE_VSC_CORPUS to a local clone of BT_Security_VSC_DB for public vendor-command/event names.
When you are invoked (START HERE)
Per-category mode (optional — CATEGORY session variable). If CATEGORY is set to one of the keys in config/category_slices.json (hci_ctrl_cmd, hci_host_cmd, hci_ctrl_evt, llcp_send, llcp_recv, lmp_send, lmp_recv), run only that category's slice instead of the full phase DAG: resolve the project/server exactly as below, then read prompts/RUN_SLICE.md and follow it for the given CATEGORY. RUN_SLICE loads the slice from config/category_slices.json, applies the binary-type gate (e.g. an lmp_* slice is a no-op on a BLE-only chip), ensures the in_scope.md coverage target exists, and runs the slice's ordered prompts (discovery → structs → S6 → S10) under its /goal. This is the reversion-safe per-category mode — one linear session per category, no Agent subagents — and it measurably de-dilutes recovery on the later categories (LLCP/LMP) that a single full-DAG session tends to starve (validated: mean strict recovery 0.68 → 0.82 across five controllers vs the all-phases run, gains concentrated in the dilution-starved categories, zero regressions). When CATEGORY is not set, run the full DAG as described here.
Resolve the project and the pyghidra-mcp connection in this order — do not assume a server is running, and do not assume a running one serves the right project.
Step 1 — Get the project. The user must provide a Ghidra project: a .gpr, or a .zip containing one. If no project was given, ask the user for one and stop until they provide it. Never proceed without a project.
Step 1b — P-phase-done fast-path detection. Look at the project name. If it contains p_phase_done (a *_p_phase_done.zip/.gpr produced by the bt-re-controller-p-phase-binary-creation skill), the preparatory P-phase (P2..P7) has already been run and saved into the project, so this run must SKIP Batches 0a/0b/1 (the prep) and start at H1 — re-running the P-phase would waste tokens re-deriving renames that are already present. (The deferred F2 at Batch 11 still runs — it is a finalize pass, not baked into a p_phase_done baseline.) scripts/run.sh detects this automatically (it sets @@PPHASE_DONE@@=yes and exports BTRE_PPHASE_DONE=yes), and prompts/ORCHESTRATE.md Step 1.5 acts on it. Cache presence is a separate startup invariant: the orchestrator verifies or regenerates it from the live project before H1. A plain *_clean_disasm (or any non-p_phase_done) project runs the full DAG including the P-phase.
Step 2 — Is a pyghidra-mcp server already running? Check both:
- Attached to your current session — load its tools (
ToolSearchquerypyghidra) and calllist_programs. - Any server on this host — not just port 8000.
bash scripts/mcp_lifecycle.sh list_serversprints every running pyghidra-mcp as<port>\t<project>, andfind_server_for <your.gpr>prints the port of one already serving that exact resolved project path (empty if none). Same-named project copies in parallel workspaces never match.run.shrefuses to adopt even an exact match automatically because another session may be mutating it.
Step 3 — If a server IS running, VERIFY it serves the given project before using it. Call list_programs and confirm the loaded program/project actually corresponds to the project the user gave (match the binary/project name against the .gpr; an empty program list means the project did not open — treat as not-serving-it).
- Match → do not share it implicitly. Ask the user before using a server that may belong to another Claude/Codex session. Only an explicit
--use-existing http://127.0.0.1:PORT/mcpopts into sharing; otherwise use a separate project copy and port. - Mismatch (it serves a different project, or none) → do NOT run against the wrong server. Tell the user what's actually loaded, and start a fresh server for the given project on a different
--port(or have them point you at the correct one).
Step 4 — If NO server serves the given project, start one for it. Determine the session variables (--chip, --bt-support, --stack, --spec; ask the user or infer — DUAL_MODE / BELOW_HCI are common defaults), then run the launcher (path relative to this skill's base directory):
bashbash scripts/run.sh --project <PATH.gpr|PATH.zip> \ --chip "<Chip Name>" --bt-support DUAL_MODE --stack BELOW_HCI --spec <ver>
run.sh refuses to start if the port is already in use (it checks first), launches pyghidra-mcp for the project (headless by default; --gui to watch it live), and spawns a headless inner codex exec that runs the whole DAG. In headless mode the launcher also stops the pyghidra-mcp server automatically once the analysis completes; --gui leaves it running for inspection. You do not run the phases yourself in self-launch mode — the spawned inner does, because only a freshly-started session can attach the just-launched server. Report the monitoring commands the launcher prints; tail <decomps>/.bt_re_logs/timeline.jsonl if the user wants to watch.
When invoking run.sh through a managed Codex/Claude shell tool, add --wait so the tool does not reap detached descendants when the launcher returns.
Verify the local runtime first with bash scripts/preflight.sh. See "Launching with a self-managed pyghidra-mcp server (scripts/run.sh)" below and references/codex_launcher.md for the full flag list.
Session variables
Five values must be bound before any phase prompt runs. The first two are always required; the rest have defaults. They are referenced by name in the preamble and every H/B/S/E phase prompt, so they need to resolve to concrete values by the time the prompt is sent to an agent:
| Token | Meaning | Example |
|---|---|---|
{{CHIP_NAME}} | The chip or model being analyzed — free-text, can include spaces. Appears once, in the system preamble. | Realtek RTL8761BU |
{{DECOMPS_PATH}} | Absolute path to the local decompilation-cache folder. For a single-binary project, this is a flat folder of cache files. For a multi-binary project, this is a root folder containing one subdirectory per binary (named with the binary filename), each with its own decomps/ child. The preamble's cache-layout rule tells Codex how to detect which layout applies and where to write. Must exist and be writable. | Single: /Users/user/my_fw_re/decomps — Multi: /Users/user/multi_fw/ (holds per-binary subdirectories) |
{{BT_SUPPORT}} | Which Bluetooth protocols the Controller supports. One of DUAL_MODE (default), BLE_ONLY, CLASSIC_ONLY. Determines which prompts apply and which LMP/LL prose gets stripped. | BLE_ONLY |
{{STACK_MODE}} | Which side(s) of the HCI boundary the binary image contains. One of BELOW_HCI (default) or FULL_STACK. Determines (a) whether the host-side cluster exists in the binary at all (issuer wrappers + helpers + cmd-routing plumbing) — present in FULL_STACK, absent in BELOW_HCI. In BELOW_HCI binaries the cmd-routing plumbing is the only HCI-cmd-related code present, and it stays bare (hci_cmd_dispatch, etc.) because there's nothing for the host infix to disambiguate against. Also (b) gates the H2 per-opcode issuer-wrapper discovery pass — only runs in FULL_STACK. The ctrl infix on the HCI-event-flow side applies in both stack modes (event creation exists in every BT controller binary). | FULL_STACK |
{{BT_SPEC_VERSION}} | The Core Spec version the chip is believed to support (human guess from datasheets). Bounds search scope + /goal exit conditions (via scripts/downselect.py → {{DECOMPS_PATH}}/.bt_re_scope/in_scope.md) — NOT naming (opcodes found in dispatcher/fptr tables are always renamed from the full tables). Refined at runtime from the over-the-air VersNr in LL_VERSION_IND/LMP_VERSION_RES (see references/bt_spec_versions.md). Default NEWEST (= ALL, full superset, no down-select / no OTA override). | 5.1 (or 0x0B, NEWEST) |
What BT_SUPPORT does
Bluetooth Controllers split into three camps: dual-mode chips (BR/EDR + BLE — what most modern general-purpose chips are), BLE-only chips (e.g. simple peripherals, many IoT chips), and classic-only chips (legacy HID dongles, some voice/audio-specific silicon). LMP (Link Manager Protocol) exists only in BR/EDR; LLCP (Link Layer Control Protocol, referred to in code as LL) exists only in BLE. Running LMP-centric prompts against a BLE-only firmware produces no-op noise; running BLE-advertising prompts against a classic-only firmware does the same.
Setting BT_SUPPORT at bind time has two effects:
-
Whole prompts are removed from the resolved tree when they don't apply. In BLE_ONLY the output loses the LMP-side prompts B1_LMP / B2_LMP / B3_LMP / B7_LMP / S2_LMP, plus B4_SCO (SCO/eSCO discovery) and S4_LMP (LMP globals). In CLASSIC_ONLY it loses the LL-side prompts B1_LL / B2_LL / B3_LL / B7_LL / S2_LL, plus B5_ADV (BLE advertising) and S5_LL (LL globals). The filtered manifest reflects this — its
batcheslist only references prompts that actually ship in the resolved tree, so an orchestrator consuming the manifest can dispatch without special-casing. -
Prose inside the remaining prompts is ablated where it references the unsupported protocol. For example, S6's line "every
hci_,lmp_, orll_-prefixed function..." becomes "everyhci_orll_-prefixed function..." in BLE_ONLY — the LMP clause is removed but the recursive-propagation logic itself still runs across all the kept prefixes. -
Protocol-specific reference files are included or excluded wholesale;
hci_commands_to_events.csvis row- and event-filtered. The mapping CSVs are split by protocol —host_to_air_hci_to_lmp.csvandair_to_host_lmp_to_hci.csvonly ship in DUAL_MODE and CLASSIC_ONLY;host_to_air_hci_to_ll.csvandair_to_host_ll_to_hci.csvonly ship in DUAL_MODE and BLE_ONLY. The combinedhci_commands_to_events.csvalways ships, with filtering applied only inCLASSIC_ONLYmode:- Row-level filter: drop any row where OGF is
0x08(LE Controller — strictly LE-only per spec) or the command name starts withhci_le_. - Event-level filter: on surviving rows, split the events column (semicolon-separated) and drop any individual event whose name starts with
hci_le_. Many BR/EDR-applicable commands list LE events as possible outcomes — for exampleHCI_Disconnect(OGF 0x01, OCF 0x06) listshci_le_cis_establishedbecause the command is available in all three modes, and any LE-capable chip (DUAL_MODE or BLE_ONLY) can disconnect an LE CIS via this command. The source CSV row's listing ofhci_le_cis_establishedis spec-correct as a union of what's reachable across chip types. On a strictly BR/EDR-only chip those LE events can't physically fire, so they get pruned out of the events column (the row itself is preserved becauseHCI_DisconnectIS callable on a BR/EDR-only chip).
In
BLE_ONLYandDUAL_MODEthe CSV passes through unchanged at both levels: BLE-only chips still implement protocol-shared commands from OGF 0x01 (e.g.HCI_Disconnectat OCF 0x06,HCI_Read_Remote_Version_Informationat OCF 0x1D), OGF 0x02, OGF 0x03 (e.g.HCI_Reset), OGF 0x04 (informational), OGF 0x05 (e.g.HCI_Read_RSSI), and OGF 0x06 (testing), and BLE-only chips can emit non-LE events too (e.g.HCI_Command_Complete,HCI_Command_Status). Dropping OGFs or non-LE events in BLE_ONLY would falsely strip real spec rows. - Row-level filter: drop any row where OGF is
Two derived booleans are available inside prompts for conditional body content — SUPPORTS_LMP (true when the mode is DUAL_MODE or CLASSIC_ONLY) and SUPPORTS_LL (true when DUAL_MODE or BLE_ONLY) — each usable as mustache-style positive section (#SUPPORTS_LMP) or inverted section (^SUPPORTS_LMP). Two derived strings are also substituted: FN_PREFIX_LIST resolves to "hci_, lmp_, or ll_" in DUAL_MODE, "hci_ or ll_" in BLE_ONLY, "hci_ or lmp_" in CLASSIC_ONLY; LINK_PROTOCOL_LIST resolves to "LMP and LL", "LL", or "LMP" respectively.
What STACK_MODE does
STACK_MODE describes which side(s) of the HCI boundary live in the binary image being analyzed. This is independent of BT_SUPPORT (which protocols are supported) — a BLE_ONLY chip can be either a BELOW_HCI-stack image (external HCI on UART to a host PC) or a FULL_STACK SoC image (host stack and controller stack co-located on one chip, application API → internal HCI queue → controller-side handler).
Two values:
BELOW_HCI(default): the binary is a pure controller. HCI commands enter via a wire-byte-receive path (UART/USB/SPI parser). Only the controller side of the HCI boundary lives in this binary. There is exactly one function cluster per HCI command opcode — the controller-side handler that parses the inbound cmd packet, performs the procedure, and creates the immediate response event. Most third-party chip firmware (Realtek, Broadcom, CSR, Cypress) falls in this camp.FULL_STACK: the binary contains both an on-chip application/host-stack layer AND the controller. HCI is internal — no external wire. Two function clusters exist per opcode, on the two sides of the HCI boundary. Typical examples: Silabs EFR32 BLE SoC application images, Nordic nRF SoCs running combined SoftDevice+app, ESP32 BT firmware with co-located stack.
Naming rule — HCI-traffic-flow-based, not physical-side or stack-mode-based
The ctrl/host selector on an HCI-related function is an infix placed after hci_
(hci_ctrl_cmd_*, hci_host_cmd_*), determined by which direction of HCI traffic the function
participates in, NOT by which physical side of the boundary or which STACK_MODE the binary is in. (Full forms,
opcode rendering, and the __ boundary live in references/naming_conventions.md — this is the summary.)
-
hostinfix → any function that participates in the HCI command flow (host → controller direction). This includes:- On-chip issuer wrappers (FULL_STACK only): build a wire-format HCI Command packet, fill opcode+params, enqueue for dispatch. Examples:
hci_host_cmd_<OGF>_<OCF>__<Cmd_Name>, plus shared helpershci_host_cmd_pkt_alloc_and_enqueue,hci_host_cmd_queue_signal_processor. - Controller-side cmd-routing/queue plumbing (BOTH stack modes): pull cmds from queue, dispatch by opcode to handlers. Examples:
hci_host_cmd_dispatch,hci_host_cmd_dispatch_by_opcode,hci_host_get_current_cmd_pkt(which collapse to barehci_cmd_dispatch, etc. in BELOW_HCI).
Even though the dispatcher/queue plumbing is physically on the controller side, it processes inbound HCI commands and is part of the command-flow role — hence the
hostinfix. Thehostinfix is about HCI-traffic direction, not chip-side location. - On-chip issuer wrappers (FULL_STACK only): build a wire-format HCI Command packet, fill opcode+params, enqueue for dispatch. Examples:
-
ctrlinfix → any function that participates in the HCI event flow (controller → host direction). This includes:- HCI command handlers that synchronously create their response events (Command_Complete for read-style cmds, Command_Status for async-trigger cmds):
hci_ctrl_cmd_<OGF>_<OCF>__<Cmd_Name>. They consume an inbound HCI cmd AND construct the wire-format response event — the event-creating role wins for naming. - Event construction primitives:
hci_ctrl_evt_0E__HCI_Command_Complete__header_build,hci_ctrl_evt_0F__HCI_Command_Status__header_build,hci_ctrl_event_buf_alloc,hci_ctrl_send_command_complete. - Event delivery primitives:
hci_ctrl_event_buf_push,hci_ctrl_send_event,hci_ctrl_evt_push_to_host_tx_queue,hci_ctrl_dispatch_one_pending_event.
The
ctrlinfix applies in both stack modes because every BT controller binary creates HCI events. - HCI command handlers that synchronously create their response events (Command_Complete for read-style cmds, Command_Status for async-trigger cmds):
The ctrl infix is deliberately generic across both LL (BLE Link Layer) and LMP (BR/EDR Link Manager) sub-layers — important for combo chips where a shared HCI command (e.g. HCI_Reset, HCI_Disconnect) touches both sub-layers. Optional sub-layer-specific refinements: ll_hci_cmd_* (BLE Link Layer confirmed) or lmp_hci_cmd_* (BR/EDR Link Manager confirmed), applied manually after evidence-gathering. The default hci_ctrl_* is always correct.
Setting STACK_MODE at bind time has these effects:
-
{{HOST_PREFIX}}is stack-mode-dependent;{{CTRL_PREFIX}}is not.{{HOST_PREFIX}}resolves to"host_"in FULL_STACK and""(empty) in BELOW_HCI, placed as the infixhci_{{HOST_PREFIX}}…. Reason: in BELOW_HCI the binary contains no host-side code at all — there's nothing for thehostinfix to disambiguate against — so even the cmd-routing/queue plumbing stays bare (hci_cmd_dispatch,hci_cmd_dispatch_by_opcode,hci_get_current_cmd_pkt). In FULL_STACK, the host-side issuer cluster coexists with controller-side handlers, and thehostinfix marks anything in the HCI command flow (per-opcode issuer wrappers + issuer-side helpers + cmd-routing plumbing).{{CTRL_PREFIX}}resolves to"ctrl_"in BOTH stack modes, placed as the infixhci_{{CTRL_PREFIX}}…. Reason: controller-side event-creating functions exist in every BT controller binary, and thectrlinfix marks them as event-creators (distinct from other controller-side code like LL state machines, radio drivers, etc.) regardless of whether there's also host-side code in the binary.
-
Drives the
IS_FULL_STACK/IS_BELOW_HCIboolean sections. Phase prompts can include fullstack-only or controller-only prose via{{#IS_FULL_STACK}}…{{/IS_FULL_STACK}}and inverted forms. Critically, the H2 phase's per-opcode issuer-wrapper discovery pass is gated byIS_FULL_STACK— the per-opcode issuer wrappers (hci_host_cmd_<OGF>_<OCF>__<Cmd_Name>— the on-chip API equivalent of a host driver building each specific HCI cmd) only exist in FULL_STACK binaries. In BELOW_HCI binaries those per-opcode wrappers don't exist (the on-chip APIs that would build them live off-chip), so the skill must NOT search for them. -
Validates resumability markers (see preamble's marker schema). A marker written under
STACK_MODE=BELOW_HCIis invalid for aSTACK_MODE=FULL_STACKresume and vice versa — both the per-opcode issuer cluster and thehostinfix on cmd-routing plumbing differ between the two modes.
There are two ways to bind the session variables. Pick one:
Mode 1 — One-shot templating (recommended for parallel orchestration)
Run scripts/template.py once to produce a resolved copy of the skill tree with both values substituted literally. Dispatch against the resolved copy.
bashpython3 scripts/template.py \ --chip "Realtek RTL8761BU" \ --decomps "/Users/user/my_fw_re/decomps" \ --bt-support DUAL_MODE \ --stack BELOW_HCI \ --out ./bt_re_skill_resolved
Best when you're about to spin up multiple parallel agent sessions against the same target — bind once, reuse everywhere. The script also validates that no {{...}} placeholders remain in the output, catching typos before any agent sees them. --bt-support is one of DUAL_MODE (default) / BLE_ONLY / CLASSIC_ONLY, and --stack is BELOW_HCI (default) / FULL_STACK, so you only need to supply them when they differ from the defaults (e.g. --bt-support BLE_ONLY --stack FULL_STACK for a Silabs EFR32 BLE SoC).
Mode 2 — Conversational binding (recommended for single-session manual work)
Start the agent session with prompts/INIT.md as the first user turn. Codex will ask for both values, bind them in-context for the session, run a quick existence check on the path, and then proceed. Each new session has to re-bind because conversations have no cross-session state.
Launching with a self-managed pyghidra-mcp server (scripts/run.sh) — recommended
You do not need pyghidra-mcp already running. scripts/run.sh is a two-tier launcher (modeled on bt-re-controller-improvement-orchestrator): it starts a pyghidra-mcp server for your project, binds the session variables (via template.py), and spawns one inner codex exec that runs the whole DAG against that server (dispatching phases as subagents internally). The launcher itself never connects to MCP — only the spawned inner does, at its own startup, which is the only point Codex CLI can attach an MCP server. This is why launch-and-use in a single already-running session is impossible; the inner-session split is the way around it.
bashscripts/run.sh --project user_rtl8761b_clean_disasm.gpr \ --chip "Realtek RTL8761B" --bt-support DUAL_MODE --stack BELOW_HCI --spec 5.1
- Input: a
.gpr, or a.zipcontaining one (extracted automatically). - Workspace-local temporary state:
--tmp-dir DIRexportsTMPDIR=DIR, keeping ZIP extraction and descendant temporary files there. - Headless by default — runs with no Ghidra GUI (safe for servers / cron / any host without a display). Add
--guito open the Ghidra GUI and watch the project live (desktop only). - Own server by default on
--port(8000). If the exact project is already served, the launcher refuses rather than interfering with that session. To point the run at a server you intentionally manage/share, pass--use-existing http://127.0.0.1:PORT/mcp; localhost targets are path-verified. Non-local URLs additionally require--allow-unverified-existingafter independent verification. - Server lifecycle: in headless mode (default) the launcher stops the pyghidra-mcp server automatically once the analysis completes (a detached reaper waits for the inner to exit, then stops it). With
--guithe server is left running so you can keep inspecting; stop it with themcp_lifecycle.sh stop <pidfile>command the launcher prints. A--use-existingserver is never stopped by the launcher. - Locating pyghidra-mcp:
--pyghidra-src DIR(or envPYGHIDRA_MCP_SRC) points at a local checkout of the required XenoKovah fork. There is no personal-path default; provision it withscripts/setup_forks.shor opt in withrun.sh --setup-forks. - Network exposure: an owned server is launched with an explicit
--host 127.0.0.1, overriding environment/default drift sorun_inline_scriptis never exposed directly to the LAN. - Java/Ghidra preflight: when launching its own server, the launcher validates
JAVA_HOMEandGHIDRA_INSTALL_DIR; when unset, it conditionally detects platform/Homebrew JDK 21 and conventional Ghidra installs. Explicit env values win and invalid values fail beforeuvxstarts. - Inner model/config: autonomous runs default to
gpt-5.6-solatultra; phase subagents inherit both from the inner.--modeland--effortoverride the pair, with known combinations validated against the local Codex model cache and rejected rather than silently downgraded. The inner ignores~/.codex/config.tomlby default so an unsupported personal setting cannot break automation;--inherit-user-configopts back in while explicit launcher model/effort settings retain precedence. - Attached lifecycle: detached launch remains the default. Pass
--waitin managed command environments that terminate detached descendants when the command returns; it keepsrun.shattached, propagates the inner status, and synchronously stops an owned headless server. - Cache bootstrap: before marker validation, the inner proves cache provenance/count against live program identity. Missing, stale, legacy, or interrupted content is archived and rebuilt from the already-open project with
scripts/export_decomp_cache_inline.py; catastrophic decompiler failure cannot finalize a cache. It never starts a second Ghidra JVM against the locked project. - Monitor / offline / no-log: watch with
tail -F <decomps>/.bt_re_logs/timeline.jsonl;BTRE_OFFLINEandBTRE_NO_LOGare inherited by the inner and all subagents. Use--dry-runto resolve and print the inner configuration without spawning either pyghidra-mcp or Codex.
The inner reads prompts/ORCHESTRATE.md (the filled orchestration prompt) and drives the batches from manifest.json. See also references/codex_launcher.md.
Common pre-flight (both modes)
- pyghidra-mcp must be reachable with the target program loaded. With
scripts/run.sh(above) this is handled for you. If instead you run inside an existing Codex CLI session, confirm pyghidra-mcp is connected and the program is the active program first — phase prompts assume both. - Read
references/naming_conventions.mdonce if you're not already familiar with the conventions — every phase prompt relies on them. - Use
references/system_prompt_preamble.md(resolved or with conversational bindings) as the system prompt for every agent session. Phase prompts are terse by design and assume the role, tool context, and naming conventions laid out in the preamble.
Offline mode (BTRE_OFFLINE environment variable)
This skill is fully self-contained: every opcode/event/PDU name, spec mapping, and pattern it needs ships under references/, and all decompilation is read from the local cache and the pyghidra-mcp server. It never requires the web.
For deterministic benchmarking you may want to guarantee a run touches no network at all. Check the BTRE_OFFLINE environment variable at the start of every invocation:
- If
BTRE_OFFLINEis set to any non-empty value (e.g.BTRE_OFFLINE=1): operate fully offline for the entire run. Do not callWebSearchorWebFetch, do not fetch URLs, and do not reach the network by any other means (nocurl/wgetin Bash, no browser MCP tools). Rely solely onreferences/, the decomp cache, and pyghidra-mcp. If a phase would normally consult the web, skip that step and proceed with local evidence only, noting the skip. Because the analysis work is performed by per-phase subagents that each get their own tool access, you (the orchestrator) MUST propagate this constraint into every dispatched phase prompt — add an explicit "offline only: never use WebSearch/WebFetch or any network access" line to each subagent prompt wheneverBTRE_OFFLINEis set. - If
BTRE_OFFLINEis unset or empty (the default): normal behavior — web tools may be used where a phase calls for them.
This is an opt-in, env-var-gated instruction: it activates only on a machine where the operator exports BTRE_OFFLINE, so distributing this skill does not impose offline mode on anyone else (their runs keep full web access unless they set the variable themselves). It is an instruction to the agent, not a hard sandbox; pair it with a settings.json permission/hook if you need enforcement rather than convention.
Phase DAG
┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ │ P2: │ │ P3: │ │ P4: │ │ P5: │ │ P6: │ │set_ │ │undef4│ │log_ │ │memcpy│ │bulk │ │mem_ │ │→fptr │ │print │ │memset│ │ptr │ │at_* │ │+cpu │ │infer │ │alloc │ │type │ └──┬───┘ └──┬───┘ └──┬───┘ └──┬───┘ └──┬───┘ │ │ │ │ │ └─────────┴────┬────┴─────────┘ │ ┌─────────▼────────┐ │ │ P7: Consolidated │ │ │ refresh of │ │ │ P2/P3/P4/P5 │ │ │ staleness │ │ └─────────┬────────┘ │ │ │ └───────┬────────────────┘ ┌───────────────────┘ │ ┌───────────────▼──────────────────────────────────┐ │ H1: Discover + rename the OGF dispatcher tree │ │ (top-level hci_cmd_dispatch_by_opcode + per-OGF) │ └───────────────┬──────────────────────────────────┘ │ ┌───────────────▼─────────────┐ │ H2: Rename HCI cmd handlers│ └───────────────┬─────────────┘ │ ┌───────────────▼──────────────────────────────────┐ │ H5: Discover cmd handlers via a DATA table │ │ (table-driven chips; no-op if H1/H2's code │ │ dispatcher already covers them) │ └───────────────┬──────────────────────────────────┘ │ ┌──────────┼────────────┬─────────────┐ │ │ │ │ ┌────▼────┐ ┌───▼────┐ ┌─────▼─────┐ ┌─────▼─────┐ │H3: Type │ │H4:Evt │ │B1_LMP: │ │B1_LL: │ │HCI args │ │handlers│ │LMP s/r │ │LLCP s/r │ └────┬────┘ └───┬────┘ └─────┬─────┘ └─────┬─────┘ │ │ │ │ │ ┌────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐ │ │V2_HCI: │ │B2_LMP→ │ │B2_LL→ │ │ │HCI cross-│ │B3_LMP │ │B3_LL │ │ │check │ │+B4_SCO +B7│ │+B5_ADV +B7│ │ └────┬─────┘ └─────┬─────┘ └─────┬─────┘ │ │ ┌─────▼─────┐ ┌─────▼─────┐ │ │ │V3_LMP: │ │V4_LL: │ │ │ │LMP cross- │ │LLCP cross-│ │ │ │check │ │check │ │ │ └─────┬─────┘ └─────┬─────┘ └──────────┴─────────────┴─────────────┘ │ (V2_HCI→S1_HCI/S6, V3_LMP→S2_LMP/S4_LMP/S6, V4_LL→S2_LL/S5_LL/S6) │ ┌─────────▼─────────┐ │ Phase S: Structs │ │ (S1–S9) │ └─────────┬─────────┘ │ ┌─────────▼─────────┐ │ D1: Masked locals │ └─────────┬─────────┘ │ ┌─────────▼─────────┐ │ E2: Struct unknown│ │ field refinement │ └─────────┬─────────┘ │ ┌─────────▼─────────┐ │ F2 (Batch 11, last│ │ — formerly P1): │ │ hardcode_return_ │ │ tmp_* stub rename│ └───────────────────┘
The P-prefix prompts are preparatory — they run before Phase H's Bluetooth-specific work. Two of them (P2/P3) find and rename low-level utility functions (set_mem_at_a0_to_a1, undefined4 → function pointer) with pure pattern matching that has nothing to do with Bluetooth (a third such structural pass, the constant-return-stub renamer that applies hardcode_return_tmp_*, is F2 (formerly P1), which no longer runs in the P-phase — it is deferred to run LAST in the terminal Batch 11); P3 additionally carries a tiny CPU-intrinsic-function sub-pass (≤5-instruction functions that read/write a system register, toggle interrupts, or issue a barrier — named per the program's processor, no Bluetooth knowledge needed). P4 walks the string table, finds the common logging sink, renames it log_print, then reads every log-call site's string arguments and infers names for the surrounding functions from phrases like "acl_tx_complete() failed". P6 types word-aligned address-shaped slots in two tiers: a precise tier applies pointer to function/string pointer tables and exception/interrupt vector tables (contiguous runs whose values ≥75% resolve to function entries or string starts), and a loose tier applies undefined * to every remaining slot whose value falls inside an INITIALIZED memory block — a purely additive prep pass that never overwrites existing types and always loses to later, more specific S-phase typing. (An isolated experiment showed this typing keys only on what a value points to — known from auto-analysis — so it needs no renames; the matching <prefix>_funcs labeling is deferred to F1, which runs after the Bluetooth phases supply the names.) P5 (the context-free half of the old D2) identifies the memcpy/memset primitives from their behavioral signatures — another structural pass that needs no Bluetooth context. (The malloc/free half stayed late as the D-phase prompt D2, because allocator/free detection needs the A01 spec-significance guard — see below.) None of the five (P2/P3/P4/P5/P6) depends on any Bluetooth analysis having been done yet, so they are all mutually parallel-safe — but they are not dispatched all at once. P-phase parallelism is capped at 3 (two waves, Batches 0a and 0b): dispatching too many concurrently overwhelms pyghidra-mcp's single decompiler thread (observed in earlier runs: several sessions failed and had to be re-dispatched serially). The cap is a decompiler-throughput limit, not a dependency constraint.
Why P7 exists. P2/P3/P4/P5 all produce overlapping staleness — a single caller may call a P2-renamed stub, read a P3-retyped fptr, be itself renamed by P4 based on a log string, AND call a P5-renamed memcpy/memset helper. If each P-phase refreshed its own staleness cone, that caller's decomp would be fetched up to four times for a net of one final state. Instead, P2/P3/P4/P5 each write a JSON staleness manifest listing which functions they made stale (without refreshing the cache), and P7 reads all four manifests, unions them by (binary, address), deduplicates, and performs a single refresh pass. In practice this runs the total decomp-fetch count down by 2–4× on firmware with dense cross-references.
P4 conflict resolution. P4's semantic renames (from log-string evidence) always win over F2's / P2's structural renames (hardcode_return_0_nN, set_mem_at_a0_to_a1_nN) when both touch the same function. A log string saying "acl_tx_complete() failed" produces a strictly better name than hardcode_return_0_n7, so P4 overwrites. The conflict is rare in practice — tiny stub functions almost never have log strings pointing to them — but the prompt body tells Codex to resolve in P4's favor when it happens.
The D-prefix prompts are derived-cleanup — they depend on prior analysis. D1 (masked-locals) is most effective after S6 has given locals meaningful names (masking conn_hand & 0xff only produces a good rename if the source has conn_hand as its name already). D2 (malloc/free) is the guarded, late half of the old combined memcpy/memset/malloc/free pass: its memcpy/memset detection turned out not to need post-struct context and moved early to P5, but the allocator/free detection stays here. Allocator/free signatures readily latch onto a spec-specific pool allocator (sco_slot_alloc, *_bm_alloc, an OSA buffer pool, nrf_balloc), so D2 needs the A01 spec-significance guard — which only has dispatcher names, protocol-prefixed callers, and tagged dispatch tables to test against after the H/B phases. Running it late makes the guard live; in the P phase the guard would be inert. Most controller images have no generic libc malloc/free at all, so D2 is frequently a no-op.
P-phase-done fast-path (pre-baked prep baselines)
The P-phase (Batches 0a/0b/1 → P2..P7) is preparatory and non-Bluetooth-specific, so its output is identical no matter what chip or mode the binary is — which makes it wasteful to re-run on every experiment against the same firmware. The companion bt-re-controller-p-phase-binary-creation skill runs the P-phase once and bakes the renames into a reusable *_p_phase_done project (user_<chip>_clean_disasm.zip → user_<chip>_p_phase_done.zip). (F2, the deferred constant-return-stub finalize pass, is not part of the P-phase and is not baked — see below.)
When the input project's name contains p_phase_done, this skill skips Batches 0a/0b/1 (the P2..P7 prep) and starts at H1 — but still runs the deferred F2 (Batch 11) at the end, because F2 is a finalize pass and is not baked into a p_phase_done baseline:
scripts/run.shdetects the name, substitutes@@PPHASE_DONE@@=yesinto the inner prompt, and exportsBTRE_PPHASE_DONE=yes.prompts/ORCHESTRATE.mdStep 0 verifies or regenerates a P-consistent cache from the live project; Step 1.5 then skips the three P-phase batches. H1's normal dependency on P7 is therefore satisfied.- Nothing else changes — H1 onward runs exactly as it would after a live P-phase.
To (re)generate the baselines — e.g. after the P* prompts here change — run bt-re-controller-p-phase-binary-creation against the *_clean_disasm projects; it single-sources P2..P7 from this skill (not F2), so it always bakes the current prep prompts.
Parallel-safe batches
Dispatch each batch as a concurrent set (one agent session per prompt); wait for the whole batch to finish before advancing to the next.
| Batch | Prompts | Notes |
|---|---|---|
| Batch 0a | P2, P3, P5 | 3-wide parallel — P-phase wave 1 of 2, at the cap. P-phase parallelism is capped at 3 because dispatching too many at once overwhelms pyghidra-mcp's single decompiler thread. The five P-phase prep passes (P2–P6) are all mutually parallel-safe — the cap is a throughput limit, not a dependency one. This wave: P2 (heavy) renames pointer-write stubs; P3 retypes undefined4→fptr data locations and runs the tiny CPU-intrinsic-function sub-pass; P5 identifies memcpy/memset candidates (the malloc/free half is the late-phase D2). Keeps the two heaviest phases (P2, P4) in separate waves. |
| Batch 0b | P4, P6 | 2-wide parallel — P-phase wave 2 of 2, runs after Batch 0a. P4 (heavy) finds the logging sink and uses log-string evidence to rename functions; P6 applies pointer types to word-aligned address-shaped slots in two tiers — pointer on function/string pointer tables and vector tables (precise), undefined * on the remaining isolated data pointers (loose). Keeps the two heaviest phases (P2, P4) in separate waves. P2–P5 write staleness manifests instead of refreshing the cache; P7 consolidates. (The constant-return-stub renamer that was here as P1 is now F2, deferred to the terminal Batch 11.) |
| Batch 1 | P7 | Serial. Runs after Batches 0a+0b. Unions the four P-phase staleness manifests (P2–P5), dedups by (binary, address), runs one consolidated decomp-cache refresh. H1 depends on this — don't skip. |
| Batch 2 | H1 | Serial. Discovers the top-level OGF dispatcher from scratch (the old P0 discovery pass, folded in), renames it hci_cmd_dispatch_by_opcode (hci_host_cmd_dispatch_by_opcode in FULL_STACK), then renames the per-OGF sub-dispatchers (hci_cmd_dispatcher_ogf_<OGF>_<abbrev>). |
| Batch 3 | H2 | Serial. Must complete before V1/H3/H4/B1_LMP/B1_LL because they rely on the handler names. |
| Batch 3a | H5 | Serial, after H2 and before V1. Recovers HCI command handlers that live in a data dispatch table (an {handler-ptr, opcode} array searched at runtime, with handlers invoked by indirect call) — the table-driven idiom used by chips like EM9304/WL1835/TI-CC2640, whose handlers are orphans with no static call edges and so are invisible to H1/H2's code-dispatcher walk. Runs before V1 so the version/feature/Supported_Commands read handlers it names are available to the down-select. A no-op on chips that dispatch HCI commands purely in code (H1/H2 already covered them). |
| Batch 3b | V1 | Serial. Resolves the authoritative spec version (human {{BT_SPEC_VERSION}} refined by the over-the-air VersNr from LL_VERSION_IND / LMP_VERSION_RES) and down-selects the search scope before any version-sensitive phase. Runs here — not inside B1_LMP/B1_LL — so H4/B1_LMP/B1_LL/B2_LMP/B2_LL/B3_LMP/B3_LL/V2_HCI/V3_LMP/V4_LL never search against a stale down-select (no need to cancel/restart a parallel phase). No-op override when BT_SPEC_VERSION=NEWEST/ALL. H3 may run concurrently (version-insensitive). |
| Batch 4 | H3, H4, B1_LMP, B1_LL | DUAL_MODE 4-wide parallel, after V1 (single-mode: 3-wide — only one B1 variant survives applies_when filtering). HCI arg typing, event-handler naming, and the two independent link-layer packet phases all fork from H2; H4/B1_LMP/B1_LL also depend on V1 so the down-select is final. B1_LMP and B1_LL are separate protocol chains (distinct opcode spaces, TX paths, dispatch tables) and run concurrently. |
| Batch 5 | B2_LMP, B2_LL, B4_SCO, B5_ADV, B6, B7_LMP, B7_LL | Per-protocol discovery wave 1 (DUAL_MODE 7-wide; single-mode ~4–5 after filtering). The B2 closures run here; the matching fptr-table walks B3_LMP/B3_LL follow in Batch 5b because B3_X depends on B2_X — so each protocol channel runs B2→B3 sequentially while the LMP and LL channels run in parallel. B6 identifies spec-defined AES/ECC crypto primitives (Bluetooth Core Spec / NIST FIPS 186-4) and depends on both B1 variants. B7_LMP / B7_LL (split from the old combined B7) identify spec-defined controller-internal link-layer algorithms — BR/EDR frequency-hopping selection (Vol 2 Part B §2.6) and BLE Channel Selection Algorithms #1/#2 (Vol 6 Part B §4.5.8) respectively — applying the lmp_* / ll_* prefix family (those prefixes already imply controller-side). Decompiler-ceiling caveat: if 7-wide overwhelms the single decompiler thread, wave-split by protocol (LMP: B2_LMP, B4_SCO, B7_LMP / LL: B2_LL, B5_ADV, B7_LL / shared: B6). |
| Batch 5b | B3_LMP, B3_LL | Per-protocol discovery wave 2: the fptr-table walks, run after their channel's B2 closure. B3_LMP depends on B2_LMP and B3_LL on B2_LL, so each B3 sees the full set of handlers its B2 already named via the call graph and only resolves the table slots B2 still missed. The two channels stay mutually parallel. |
| Batch 6 | V2_HCI | HCI coverage cross-check (formerly E1) after H4 closes out HCI. Its checked namespace (hci_cmd_*/hci_evt_*) is frozen once H4 finishes, so it needs nothing from the B channels and runs in parallel with Batch 5/5b. Any handler it newly names feeds S1_HCI/S6 via explicit dependency edges (not batch ordering). |
| Batch 6b | V3_LMP, V4_LL | LMP / LLCP coverage cross-checks — the spec-side backstop to the B2/B3 structural discovery. Unlike V2_HCI these run after Batch 5b: V3_LMP depends on B3_LMP and V4_LL on B3_LL, so each protocol's gap-check runs only once its B1→B2→B3 channel has converged. Mutually parallel (disjoint LMP vs LLCP namespaces); single-mode filtering drops the non-applicable one. Each feeds its struct phases via explicit edges (V3_LMP→S2_LMP/S4_LMP/S6, V4_LL→S2_LL/S5_LL/S6). |
| Batch 7 | S1_HCI, S2_LMP, S2_LL, S3_HCI, S4_LMP, S5_LL, S8_SCO, S9_ADV | DUAL_MODE 8-wide parallel struct creation (single-mode filters out the non-applicable S2 variant, S4_LMP or S5_LL, and S8_SCO or S9_ADV). Each targets a different scope (HCI cmd/evt bodies, LMP packet args, LLCP packet args, HCI globals, LMP globals, LL globals, SCO/eSCO structs, advertisement structs). Depends on the Batch 6/6b coverage passes (S1_HCI←V2_HCI, S2_LMP/S4_LMP←V3_LMP, S2_LL/S5_LL←V4_LL) so any handler those passes minted gets struct typing. S8_SCO/S9_ADV (SCO/eSCO + advertisement struct creation) moved here from the old Batch 8 so S6's recursive propagation includes their structs — S8_SCO is BR/EDR (CLASSIC), S9_ADV is BLE. |
| Batch 8 | S6, S7 | Serial after Batch 7. S6 propagates types through callees — now including the SCO/eSCO and advertisement structs created by S8_SCO/S9_ADV in Batch 7; S7 handles per-connection arrays. The SCO/adv struct creation moved up to Batch 7 (it only depends on B4_SCO/B5_ADV, not on S6), leaving just propagation + array consolidation here. |
| Batch 9 | D1 | Serial. Masked-local renaming. Deliberately run late: it propagates names from already-named source variables, so it is far more effective once prior phases have given variables and callees meaningful names. (The old D2's memcpy/memset half moved to the P phase as P5; its malloc/free half stays as D2 in Batch 9b.) |
| Batch 9b | D2 | Serial, after D1. Guarded malloc/free identification — the late half of the old combined pass. Runs here so the A01 spec-significance guard is fully live (H/B dispatcher names + protocol-prefixed callers + tagged dispatch tables all exist) and won't mislabel a spec-specific pool allocator as generic malloc/free. D1/D2 are parallel-safe but split into separate serial batches to keep load off the single decompiler thread. Often a no-op (no generic libc malloc/free in controller firmware). |
| Batch 10 | E2, E3, E4, F1 | Finishing pass — all parallel-safe with each other. E2 re-examines struct fields still named pad_/field_. E3 authors labels and comments. E4 does xref-cluster naming for unnamed funcs whose 3+ callers share a common prefix. F1 labels function-pointer arrays (<common_prefix>_funcs) and types switch jump tables (ushort) — the two name-dependent finishing steps. The terminal F2 pass still follows in Batch 11. |
| Batch 11 | F2 | Terminal pass — runs dead last, after every H/B/S/D/E/F phase. F2 (formerly P1) renames trivial constant-return stub functions to hardcode_return_tmp_*. It is deferred to the end (rather than run in the P-phase) so its provisional stub names never shadow an in-scope handler that an earlier search would otherwise have renamed to a canonical spec name. F2 refreshes its own staleness cone (it is not part of P7's consolidated refresh). |
Why P2/P3/P4/P5/P6 launch in the P-phase waves (Batches 0a/0b) but D1/D2 don't: the P-phases operate on signals that don't need Bluetooth context — structural patterns for P2/P3, string-table evidence for P4, behavioral memcpy/memset signatures for P5, and value-falls-in-mapped-memory checks for P6. D1/D2 do the opposite: D1's masked-local rename propagates names from an already-named source variable, and D2's malloc/free guard keys off H/B dispatcher names + protocol-prefixed callers — both want prior phases done first. Running them early would produce fewer/worse renames (D1) or an inert guard that risks mislabeling spec-specific pool allocators as generic malloc/free (D2).
File layout
bt-re-controller/ ├── SKILL.md ← you are here ├── manifest.json ← machine-readable phase DAG ├── scripts/ │ ├── run.sh ← isolated launcher + owned-server lifecycle │ ├── mcp_lifecycle.sh ← all-port discovery and PID-scoped server control │ ├── preflight.sh ← read-only prerequisite checker │ ├── setup_forks.sh ← provisions the required pyghidra-mcp fork │ ├── template.py ← one-shot session-variable binder │ ├── program_identity_inline.py ← headless-safe program metadata/fingerprint via run_inline_script │ ├── export_decomp_cache_inline.py ← live-project cache bootstrap via run_inline_script │ └── downselect.py ← emits the BT_SPEC_VERSION in-scope search list (bounds search//goal, not naming) ├── references/ │ ├── system_prompt_preamble.md ← role + naming conventions (SET AS SYSTEM PROMPT) │ ├── codex_launcher.md ← Codex prerequisites, flags, and monitoring │ ├── naming_conventions.md ← consolidated naming rules (normalized, BT Core Spec 6.3) │ ├── bt_spec_versions.md ← VersNr byte ↔ Core Spec version; down-select ordering + OTA extraction │ ├── ll_features.md ← LE FeatureSet bit → gated LLCP PDUs (feature down-select; DUAL/BLE) │ ├── lmp_features.md ← LMP feature mask → gated LMP PDUs (feature down-select; DUAL/CLASSIC) │ ├── supported_commands.md ← Supported_Commands bit → HCI command (HCI-command down-select) │ ├── hci_commands_to_events.csv ← BT Core Spec 6.3, OGF-filtered by mode │ ├── hci_events.md ← HCI event + LE-Meta code → spec name (BT Core Spec 6.3) │ ├── hci_commands_deprecated.md ← removed HCI commands (legacy-firmware RE) │ ├── procedures.md ← canonical procedure tokens for proc_<name> (6.3, human-reviewed) │ ├── link_layer_packet_patterns.md ← vendor-invariant LMP/LL packet send/recv enumeration patterns (shared by B1_LMP/B1_LL/B2_LMP/B2_LL) │ ├── lmp_opcodes.md ← LMP single + extended (0x7F) opcode → PDU name (DUAL_MODE or CLASSIC_ONLY only) │ ├── llcp_opcodes.md ← LLCP opcode → PDU name (DUAL_MODE or BLE_ONLY only) │ ├── host_to_air_hci_to_lmp.csv ← HCI cmd → outgoing LMP packet (DUAL_MODE or CLASSIC_ONLY only) │ ├── host_to_air_hci_to_ll.csv ← HCI cmd → outgoing LL packet (DUAL_MODE or BLE_ONLY only) │ ├── air_to_host_lmp_to_hci.csv ← incoming LMP packet → HCI event (DUAL_MODE or CLASSIC_ONLY only) │ └── air_to_host_ll_to_hci.csv ← incoming LL packet → HCI event (DUAL_MODE or BLE_ONLY only) └── prompts/ ├── INIT.md ← session-variable binder (Mode 2 only) ├── P2_rename_set_mem_stubs.md ├── P3_retype_undefined4_fptrs.md ├── P4_log_string_inference.md ├── P5_find_memcpy_memset.md ├── P6_bulk_apply_pointer_type.md ├── P7_consolidate_p_phase_refresh.md ├── H1_rename_ogf_dispatchers.md ├── H2_rename_hci_command_handlers.md ├── V1_extract_ota_spec_version.md ├── V2_HCI_crosscheck_missing_hci.md ├── V3_LMP_crosscheck_missing_lmp.md ├── V4_LL_crosscheck_missing_llcp.md ├── H3_type_hci_command_args.md ├── H4_rename_hci_event_handlers.md ├── B1_LMP_rename_lmp_packet_functions.md ├── B1_LL_rename_llcp_packet_functions.md ├── B2_LMP_discover_missing_lmp_handlers.md ├── B2_LL_discover_missing_llcp_handlers.md ├── B3_LMP_discover_missing_lmp_fptr_table.md ├── B3_LL_discover_missing_llcp_fptr_table.md ├── B4_SCO_identify_sco_esco_handlers.md ├── B5_ADV_identify_ble_advertisement.md ├── B6_identify_spec_crypto_primitives.md ├── B7_LMP_identify_lmp_frequency_hopping.md ├── B7_LL_identify_ble_channel_selection.md ├── S1_HCI_structs_hci_cmd_evt_bodies.md ├── S2_LMP_structs_lmp_packet_args.md ├── S2_LL_structs_llcp_packet_args.md ├── S3_HCI_structs_hci_globals.md ├── S4_LMP_structs_lmp_globals.md ├── S5_LL_structs_ll_globals.md ├── S6_recursive_arg_propagation.md ├── S7_per_connection_arrays.md ├── S8_SCO_esco_structs.md ├── S9_ADV_advertisement_structs.md ├── D1_rename_masked_locals.md ├── D2_find_malloc_free.md ├── E2_rename_struct_unknown_fields.md ├── E3_author_labels_and_comments.md ├── E4_xref_cluster_naming.md ├── F1_apply_basic_data_types.md └── F2_rename_hardcode_return_stubs.md ← terminal Batch 11 (formerly P1)
How to dispatch a prompt
Each prompt file has a YAML frontmatter block declaring its id, phase, depends_on, parallel_safe_with, and — for mode-specific prompts — applies_when fields. (applies_when mirrors the manifest entry; the manifest is the authoritative source scripts/template.py reads for mode filtering, but every mode-specific prompt declares it in its own frontmatter too, so the file is self-describing.) The body is the prompt text itself, referencing CSVs by relative path (e.g. references/hci_commands_to_events.csv). To run a prompt:
- Start a new agent session (or reuse one that has already seen the system preamble).
- Paste the prompt body.
- Let the agent work until it prints its completion signal ("list of renamed functions" or equivalent per-phase signal).
- Mark the prompt done in your tracker.
Standing rule applied to every phase
After any rename, struct application, or retype, update the local decompilation cache at
{{DECOMPS_PATH}}to match the new Ghidra view. Also update affected callers. Atomically keep exactly one live.cper binary/address and archive superseded old-name files so staleFUN_*and current names cannot both match searches. This rule is in every H/B/S phase prompt — it is the single biggest cause of drift if skipped.
Progress logging
A full run spans many phases over an hour or more, so every phase writes an append-only progress log you can watch live. This is on by default and opt-out (cheap — a few tiny file appends per phase, unlike OBJECTIVE_SNAPSHOTS, which does a full symbol enumeration and stays off by default).
-
Opt-out: set
BTRE_NO_LOGto any non-empty value to disable all progress logging for the run. Thebtre_log.pyhelper self-guards on it, so no prompt or phase behavior changes — logging simply becomes a no-op. (Completion markers are unaffected; resume still works.) -
Where:
{{DECOMPS_PATH}}/.bt_re_logs/— a sharedtimeline.jsonl(all phases, chronological) plus one<PROMPT_ID>.logper phase. -
How phases log: each phase agent calls
scripts/btre_log.pyatstart, at each milestone (progress), and atend/error. The mechanism and exact invocation are defined once inreferences/system_prompt_preamble.md("Progress logging"), so every dispatched phase inherits it — you don't repeat it per prompt. -
Orchestrator logging: when dispatching, the orchestrator should also log batch boundaries to the same timeline — e.g.
python3 scripts/btre_log.py --logs-dir "{{DECOMPS_PATH}}/.bt_re_logs" --phase ORCH --event progress --msg "Batch 4 dispatched: H3,H4,B1_LMP,B1_LL"— so the timeline interleaves batch-level and phase-level events. -
Watch a run:
tail -F {{DECOMPS_PATH}}/.bt_re_logs/timeline.jsonl(everything) ortail -F {{DECOMPS_PATH}}/.bt_re_logs/<PROMPT_ID>.log(one phase). Because writes are atomic single lines, tailing is safe even while many phases run concurrently. -
Relation to markers: markers (
.bt_re_markers/) record completion for resume; the log records live progress within a phase. They are complementary — the log is telemetry (safe to delete), the markers are the resume contract.
Re-running a phase safely
All prompts are idempotent — re-running a rename that has already been applied is a no-op. If a phase ran against a stale decompilation cache, re-run that phase and then the cache-update step at the end.
Resumability across sessions
Every phase prompt writes a JSON completion marker to {{DECOMPS_PATH}}/.bt_re_markers/<PROMPT_ID>.json as its final action. A marker attests that work was applied to the specific live Ghidra project it was created against AND that the work was flushed to disk via save_program — it is not portable evidence that the work exists today. A marker is invalid (and MUST be ignored) if any of the following are true:
- The Ghidra project has been replaced since the marker was written (re-import, fresh decompile, orchestrator re-clone of the binary). This is the primary failure mode: the on-disk decomp cache and the marker set survive a re-clone, but the live project does not.
bt_supportdiffers from the value recorded in the marker.- Either full identity map differs from
scripts/program_identity_inline.py, is empty, or omits a current project binary.binary_fingerprintsbinds bytes;program_state_idsbinds the exact saved Ghidra project/domain objects so identical-byte re-imports do not validate old markers. - The decomp cache files referenced by the marker are missing or have been hand-edited in ways that contradict the project state.
Save-before-mark protocol (CRITICAL)
pyghidra-mcp tool calls (rename, set_data_type, set_function_prototype, set_comment, etc.) mutate Ghidra's in-memory program state. Until that state is flushed to the on-disk .gpr, the work is volatile — a process kill, OOM, host reboot, or a fresh pyghidra-mcp launch (which the orchestrator does for forbidden-adoption reasons; see orchestrator SKILL.md §10.6) will lose every change since the last save. A marker that attests "phase H2 ran" while H2's renames live only in volatile memory is a marker that lies on resume.
Every phase prompt MUST, in order, before writing its marker:
- Update the local decompilation cache at
{{DECOMPS_PATH}}(the standing rule already restated in every H/B/S prompt body). - Call
save_programon every binary modified during this prompt. For typical single-binary projects that's one call; for layout (b) multi-binary projects, one per affected binary. Ifsave_programreturns an error for any binary, do NOT write the marker — surface the error and stop the phase. An unsaved change is not durable, and a marker without durability is worse than no marker (it suppresses re-running on resume while the work doesn't actually exist). - Capture full, nonempty
binary_fingerprintsandprogram_state_idsmaps for every Step-0 program (including no-op binaries), or recompute them for each exactlist_programsname withscripts/program_identity_inline.pythroughrun_inline_script. - THEN write the marker with both complete maps.
The strict ordering — save → fingerprint → mark — guarantees that whenever a marker exists on disk, the corresponding work is also durable on disk and identifiable to a specific binary version. A kill between save and mark-write is recoverable (work is durable; the phase will be re-run; re-runs are idempotent per the standing rule). A kill between mark-write and save would leave a marker that lies; the strict ordering prevents this case.
The full authoritative write protocol is in references/system_prompt_preamble.md ("Resumability via completion markers"). The preamble takes precedence over individual prompt bodies; legacy markers missing either identity map are archived stale and re-run.
Marker schema
json{ "prompt_id": "<phase id, e.g. H1>", "bt_support": "BLE_ONLY | DUAL_MODE | CLASSIC_ONLY", "stack_mode": "BELOW_HCI | FULL_STACK", "bt_spec_version": "<active scope version>", "completed_at": "<ISO-8601 UTC>", "binary_fingerprints": { "<binary_filename>": "<initialized-memory sha256 from program_identity_inline.py>" }, "program_state_ids": { "<binary_filename>": "<program_state_id from program_identity_inline.py>" }, "summary": "<one-sentence description of what was done>" }
The schema can be extended with optional fields for richer integrity probes (see "Future enhancement" below) — unknown fields are tolerated by the read protocol.
Read protocol (run at session start)
After binding session variables but before running any phase prompt:
ls {{DECOMPS_PATH}}/.bt_re_markers/(create if missing, treat as empty). Validate only exact manifest prompt IDs as completion files; preserve*_staleness.jsonand other auxiliaries. If P7 is incomplete, P2–P5 completions require their matching staleness inputs or must rerun.- Call
list_programs, then runscripts/program_identity_inline.pyfor each exact program name and capture both full identity maps. - For each marker, validate it:
bt_supportmust equal the session's{{BT_SUPPORT}}.stack_modemust equal the session's{{STACK_MODE}}.- Both identity maps must be nonempty, match the current project key set exactly, and match every current value.
- For search-bounded phases,
bt_spec_versionmust equal the active scope version. - Legacy markers missing either identity map are stale; an idempotent re-run is safer than an unprovable skip.
- Any failure: move the marker to
.bt_re_markers.stale-<UTC-timestamp>/(never delete — it's forensic evidence) and treat the phase as not-yet-done.
- Decide what to do:
- Interactive session with a human in the loop: ask whether to resume from validated markers, re-run specific prompts, or start over.
- Autonomous session (launched by the orchestrator with
AUTONOMOUS=true, or any session forbidden from asking the user): default to full resume — skip prompts whose markers passed validation in step 3, run every other prompt in DAG order. Log the resume plan prominently before starting work.
Resume modes
- Full resume (default when ≥1 marker passes validation): apply validated markers; re-run everything else.
- Selective re-run: archive specific markers and re-run those phases.
- Start over: archive the entire
.bt_re_markers/directory.
In every mode, "archive" means move to .bt_re_markers.stale-<UTC-timestamp>/, never delete. The stale directory is forensic evidence for the orchestrator and human operators.
Future enhancement: marker integrity probes
The schema and read protocol above are the minimum needed to make sub-step resume work correctly when save_program is honored on the write side. A more thorough integrity probe — sampling N markers, checking each against evidence_symbols (a list of {address, name_substring} tuples that the phase recorded as proof-of-work), plus universal post-condition fast-path probes (e.g. "if H2 is marked complete, search_symbols("hci_cmd_") must return ≥1 hit") — is a stronger guarantee against silent-success failures (markers exist, project is at clean baseline). It catches drift cases that a fingerprint check alone can miss, e.g. someone hand-editing the project between sessions while the fingerprint stays the same.
This richer probe is not required for save-program-based resumability to work, but is recommended for runs where multiple humans or tools may be modifying the same project. To adopt it, extend the marker schema with evidence_symbols and per_section_status, and add the probe steps to the read protocol. The overhead is bounded (≤8 read-only MCP calls) and the cost is negligible relative to a full session re-run.


