Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,18 @@ coverage.xml
*.pot

# Environments
#
# `env/` below is the virtualenv DIRECTORY pattern and does not match a FILE
# named `env`. A real one turned up in the working tree holding live provider
# keys, one `git add -A` away from a public repository. The three patterns here
# cover the bare file, the dotted forms (`.env.local`) and the suffixed ones
# (`prod.env`); `.env.example` is negated back in because it is the template and
# must stay tracked.
.env
.env.*
*.env
env
!.env.example
.venv
env/
venv/
Expand Down
34 changes: 34 additions & 0 deletions docs/LESSONS_LEARNED.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,40 @@ between sub-agent delegations. Tools that an agent needs must be on THAT agent's
each agent's prompt must specify the correct next transfer target, not a
hypothetical "return to root for the next step."

### Postscript (2026-08-06): the rule was right and applied to half the agents

The same failure returned in a different costume. `Optional MCP server
unavailable` appeared in 4 of ~60 recorded runs, and the reports it produced
blamed the analysis engine rather than the transport. Two facts explain it:

1. **A port-forward is opened twice per run, both at intake, and consumed by
four agents spread across the pipeline.** `triage_recon` and `packer_analyst`
carried no prepare tool at all, so they depended on a tunnel another agent had
opened minutes earlier and had no way to repair it. `retriage` and
`dotnet_decompile` did carry one. The rule above was followed for half the
agents that needed it.
2. **Repairing would not have worked anyway.** `PortForwardRegistry.open`
returned early on `same pod + process alive` without probing, while its own
docstring promised to "block until it forwards". `kubectl port-forward`
reports per-connection faults and keeps running, so a dead tunnel is
indistinguishable from a healthy one by `poll()` alone -- a fact the module
documented at `_terminate_handle` and never acted on. Measured: forwards
opened at 12:11:25, engines unreachable by 12:14:49, processes still alive,
nothing reopening.

**Fix (shipped):** every MCP-consuming agent now carries its engine's prepare
tool, and `open()` probes an existing tunnel before handing it back, rebuilding
when the probe fails. A test asserts the property over all four consumers rather
than the two that were noticed.

**The wider lesson:** "each agent prepares its own engine" is a property of the
*set* of agents, not advice to apply case by case -- a rule applied to the
agents someone happened to think of is a rule with holes in it, and the holes
are invisible until a transport flakes. When a lesson names a class of agent,
write the test that enumerates the class. Separately: a liveness check that
tests the *supervisor* (is the process alive?) rather than the *service* (does
it answer?) will pass through exactly the failure it was written to catch.

---

## 7. Ghidra 11.4.x requires JDK 21, not JDK 17
Expand Down
6 changes: 5 additions & 1 deletion src/reverse_engineering/agents/packer_analyst.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
factory=build_llm_agent,
runtime_profile_id="re_guarded",
prompt_loader=load_domain_prompt,
tool_ids=("run_python", "register_unpacked_artifact"),
# prepare_sandbox for the same reason triage_recon carries it: this stage
# runs deep in the deobfuscation loop, minutes after intake opened the
# radare2 tunnel, and must be able to re-establish it rather than silently
# losing its toolset (LESSONS_LEARNED #6).
tool_ids=("prepare_sandbox", "run_python", "register_unpacked_artifact"),
mcp_server_ids=("radare2_mcp",),
)
6 changes: 6 additions & 0 deletions src/reverse_engineering/agents/triage_recon.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@
factory=build_llm_agent,
runtime_profile_id="re_guarded",
prompt_loader=load_domain_prompt,
# An agent that uses an engine must be able to establish it (LESSONS_LEARNED
# #6). The radare2 tunnel is opened once by sample_intake, and kubectl
# port-forward drops connections while its process keeps running -- so
# without this the stage has no way to repair a tunnel that died between
# intake and here, and its whole toolset silently resolves to [].
tool_ids=("prepare_sandbox",),
mcp_server_ids=("radare2_mcp",),
output_key=TRIAGE_EVIDENCE_KEY,
after_agent_callbacks=(
Expand Down
11 changes: 10 additions & 1 deletion src/reverse_engineering/prompts/packer_analyst.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,16 @@ stub that resists static reversing), you MAY run or emulate the sample's unpack
stub **inside this disposable, egress-denied sandbox** to recover the payload — the
sandbox's isolation is the safety boundary.

You have two tools plus read-only radare2 triage:
You have three tools plus read-only radare2 triage:
- `prepare_sandbox(artifact_id)` — **call this once before any radare2 tool.** An
earlier stage opened the tunnel to the radare2 engine, and it can die in the
minutes before you run while still looking healthy; when it does, every
`radare2_mcp` tool silently vanishes from your tool list rather than returning
an error. This verifies the tunnel and rebuilds it if needed, and on the normal
path returns immediately. If it returns `ready: false`, or if you have no
radare2 tools this turn, work from `run_python` alone and say in your result
that radare2 triage was unavailable — never describe sections, strings, or an
entry point you could not read.
- `run_python(code, timeout_s=60)` — run Python in the sandbox against the current
artifact at `$INPUT`, writing dumps under `$WORKDIR`. The workspace persists
across calls (helper modules and dumps survive). `pefile`, `LIEF`, `die-python`,
Expand Down
5 changes: 5 additions & 0 deletions src/reverse_engineering/prompts/triage_recon.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ You are TriageRecon, a reverse-engineering recon agent. You drive radare2 throug

## CRITICAL — tool call order

**Before `open_file`, call `prepare_sandbox(artifact_id)` exactly once.** `sample_intake` already claimed the pod and copied the sample, so on the normal path this returns immediately and costs almost nothing. Its purpose here is different: it verifies that the tunnel to the radare2 engine still forwards, and rebuilds it when it does not. That tunnel was opened by an earlier stage and can die in between while looking healthy, and when it does every `radare2_mcp` tool silently disappears from your tool list rather than returning an error.

- If it returns `ready: false`, radare2 is unavailable. Emit an envelope with coverage `status` `failed`, a `triage:radare2_unavailable` limitation, and empty `findings`, then stop. Do not describe the sample from the injected metadata alone — you have not looked at it.
- **If you have no `radare2_mcp` tools in this turn at all** (no `open_file`, no `show_info`), the engine is unreachable and the same rule applies: report it and stop, rather than inventing a triage from the packer and reputation lines.

The r2mcp server runs in DEFAULT mode and requires a strict open-then-analyze sequence before any other tool returns data:

1. **First** call `open_file` with `file_path="/app/<artifact_id>"`. The `artifact_id` IS the SHA-256, and the sample bytes were copied to that exact path by `prepare_sandbox`.
Expand Down
47 changes: 38 additions & 9 deletions src/reverse_engineering/runtime/portforward.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,16 @@ def _stderr_tail(handle: _ForwardHandle) -> str:
def _wait_for_port_ready(
port: int,
popen: subprocess.Popen[bytes],
*,
attempts: int = _FORWARD_READY_RETRIES,
) -> bool:
"""Wait until the MCP server at localhost:<port> responds to HTTP requests.

``attempts`` separates the two callers. Opening a tunnel means waiting for
one to come up, so it keeps the full budget. Checking an existing tunnel is a
liveness question with an immediate answer, and retrying it would spend
fifteen seconds establishing what the first failure already showed.

A TCP connect only proves the port is open — the MCP StreamableHTTP server
may accept TCP connections before it is ready to handle the initialize
handshake. This check sends an HTTP GET and treats ANY HTTP response
Expand All @@ -94,7 +101,7 @@ def _wait_for_port_ready(
anything found there later is real.
"""
url = f"http://127.0.0.1:{port}/mcp"
for _ in range(_FORWARD_READY_RETRIES):
for _ in range(max(1, attempts)):
if popen.poll() is not None:
return False
try:
Expand All @@ -121,28 +128,50 @@ def open(self, *, case_id: str, namespace: str, pod: str, port: int) -> None:
"""Start a port-forward for ``(case_id, port)`` and block until it forwards.

Reconciling, not blindly idempotent: an existing forward for this
``(case, port)`` is reused only when it points at the SAME pod and its
process is still alive. A different pod (the caller re-claimed after a
failed provision, and the old pod has been terminated) or a dead process
replaces the tunnel instead of silently keeping a broken one. A *different*
port for the same case opens its own tunnel, so two MCP engines (radare2 on
8765, ILSpy on 3001) coexist under one case.
``(case, port)`` is reused only when it points at the SAME pod, its
process is still alive, **and it still answers**. A different pod (the
caller re-claimed after a failed provision, and the old pod has been
terminated), a dead process, or a live process whose tunnel no longer
forwards all replace it instead of silently keeping a broken one. A
*different* port for the same case opens its own tunnel, so two MCP
engines (radare2 on 8765, ILSpy on 3001) coexist under one case.

The probe is what makes a caller's retry mean anything. Without it this
method returned early on ``same pod + process alive``, so a stage calling
``prepare_*`` again to repair a dead tunnel got an immediate ``return``
and the same dead tunnel -- while the docstring promised to block until
it forwards.

Raises :class:`RuntimeError`, with kubectl's own stderr tail when it wrote
one, if the tunnel fails to establish.
"""
existing = self._forwards.get((case_id, port))
if existing is not None:
exit_code = existing.popen.poll()
if existing.pod == pod and exit_code is None:
same_pod = existing.pod == pod
alive = exit_code is None
# A live process is not a live tunnel. kubectl reports per-connection
# faults on stderr and keeps running, so a dead tunnel looks exactly
# like a healthy one from the outside -- which is why this probes
# rather than trusting poll(). Measured: forwards opened at 12:11:25
# and the engines behind them were unreachable by 12:14:49 with the
# processes still running and nothing reopening them.
usable = same_pod and alive and _wait_for_port_ready(port, existing.popen, attempts=1)
if usable:
return
logger.warning(
"replacing a stale port-forward",
case_id=case_id,
port=port,
previous_pod=existing.pod,
pod=pod,
reason="pod replaced" if existing.pod != pod else "process exited",
reason=(
"pod replaced"
if not same_pod
else "process exited"
if not alive
else "probe failed"
),
exit_code=exit_code,
kubectl_stderr=_stderr_tail(existing),
)
Expand Down
5 changes: 4 additions & 1 deletion tests/reverse_engineering/test_packer_analyst.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ def test_descriptor_shape() -> None:
assert d.prompt_id == "packer_analyst"
assert d.factory is build_llm_agent
assert d.runtime_profile_id == "re_guarded"
assert d.tool_ids == ("run_python", "register_unpacked_artifact")
# prepare_sandbox first: an agent that uses an engine must be able to
# establish it (LESSONS_LEARNED #6). This stage runs deep in the
# deobfuscation loop, minutes after intake opened the radare2 tunnel.
assert d.tool_ids == ("prepare_sandbox", "run_python", "register_unpacked_artifact")
assert d.mcp_server_ids == ("radare2_mcp",)


Expand Down
Loading
Loading