Skip to content

fix(reverse): reconcile cleanup ownership and mutation diagnostics - #2799

Merged
morluto merged 169 commits into
mainfrom
codex/review-fixes-pr-2005
Oct 13, 2026
Merged

morluto merged 169 commits into
mainfrom
codex/review-fixes-pr-2005

Conversation

@morluto

@morluto morluto commented Oct 13, 2026 •

Copy link
Copy Markdown
Owner

Fixes external-mutation cleanup failures that could permanently block analysis reopening or release analysis while a debugger writer remained. GDB/Rizin close recovery now belongs to the retained session owner; parent exit requires confirmed cleanup, with partial Evidence preserved. Rizin startup uses shared mutation admission and checks lifecycle state before publishing readiness. GDB also rechecks cancellation after its readiness yield. Both debugger status contracts expose observed decoding loss; Rizin command Evidence retains original and resolved launch paths as provenance, with current-target identity still unknown. The Ghidra admission guard reads the selected provider binding. Unrestricted commands now retire the active analysis instead of reopening it automatically: their protocol reply cannot prove background writers ended. Call open_binary explicitly after effects settle. Cleanup after failed detach can recover from captured PID/start-time identities and complete inferior inventories, with unknown, live, unreadable, or unsupported identities still retaining the owner. Rizin startup errors retain completed protocol frames and trailing partial diagnostics. Failed GDB startup Evidence propagates decoding loss in both raw and normalized results. Rizin command loss metadata follows only its collected frames, while session status stays cumulative. The queued-snapshot MCP workflow rejects saves after retirement, exports retained Evidence, and explicitly reopens before saving; it is now included in the reverse-tools lane and CI scope.

Cutter authenticates both peers before sending commands and authenticates responses. Timed-out commands retain bounded receipts by request ID until acknowledgement. Fresh clients recover terminal receipts before dispatch, while authenticated completion tokens preserve the original caller's cleanup proof after another caller acknowledges its receipt. The v2 handshake rejects older peers before command delivery. Discovery is bounded to 256 descriptor candidates and eight concurrent reads/probes; encoded command expansion is checked before transport dispatch. Response bytes are counted incrementally and collected into bounded pages, with one concatenation per completed frame. Concurrent cleanup callers share one receipt-recovery attempt. Poisoned-session rejections report not_started through the shared contract and MCP without creating a nonexistent cleanup owner. TypeScript-to-Python producer tests exercise the actual bridge protocol; they do not establish real Cutter/Qt behavior.

Objdump architecture queries are pathless and return subjectless Evidence; the CLI exposes list-objdump-architectures. The focused lane includes the owning BinarySession, snapshot, CLI, and Python producer suites. Coverage and mutation reports remain, but this PR no longer adds a perfect-score requirement. Existing repository-wide coverage thresholds remain unchanged. Stale mutation selectors, transient sandbox lock copying, translated documentation links, shared CI fixtures, and dependency notices are repaired. GDB sessions reject non-Linux hosts before launch because safe live-inferior descriptor verification is implemented only on Linux. CLI cleanup recovery preserves the producer's original completed Evidence; cancellation, timeout and unknown completion stay errors. Windows executable lookup resolves configured relative paths and quoted/relative PATH entries with Windows path semantics while preserving caller selections.

Continues #2005, originally authored by @dandgabr (Daniel Gonçalves Araujo), preserving the original commits and author attribution without squashing.

Validation: repository static checks (typecheck, lint, formatting, unused code, metadata, module boundaries, architecture guards), docs/license checks, focused reverse-tools tests with coverage, supplemental boundary tests, Python producer tests, and both Stryker dry runs. Full mutation scores and real GDB, Rizin, Cutter, and Windows native qualification remain unverified.

The final merged reverse-tools run passed 540 tests across 36 suites, with 23 platform skips, including CLI/MCP and Python producer boundaries. Six Windows path-semantics tests also passed using an injected filesystem. Repository static/docs checks and both mutation-runner dry runs passed; full mutation scores were not run. The two new real /proc Rizin identity cases were skipped on this macOS host and await Linux CI verification.

A parser-only benchmark used the actual AST-selected production frame methods to complete a 16 MiB frame in 256 chunks. Cold wall/CPU time was 154.5/352.1 ms before and 3.5/3.7 ms after; warm medians were 163.2/372.4 and 3.8/10.4 ms. Peak benchmark-process RSS, including transpilation and four runs, was 1,203,472 versus 253,952 KiB. Provider/transport, full process-family memory and model-token costs were not measured; no end-to-end speedup is claimed.

The aggregate contribution still includes pending integration scope tracked by #1959, #1960, and #1961. These fixes do not replace the required scope decisions or approve integration/deployment.

A separate frame-collector benchmark compared the former Cutter accumulation algorithm with the actual AST-selected replacement collector for a complete 16 MiB wire frame in 256 chunks. Cold wall/CPU was 475.2/503.5 ms before versus 2.2/2.4 ms after; warm medians were 446.7/463.9 versus 2.8/7.8 ms. Peak benchmark-process RSS, including transpilation and four runs, was 411,536 versus 187,824 KiB. Authentication, JSON parsing, transport, provider process-family costs and model tokens were not measured; this is not an end-to-end speedup claim.

…cycle' into feat/reverse-tools-coverage-gate
…nto feat/reverse-tools-coverage-gate

# Conflicts:
#	src/server/createServer.ts
… into feat/reverse-tools-coverage-gate

# Conflicts:
#	scripts/lib/catalog-builders.mjs
#	scripts/lib/catalog-core.mjs
#	src/cli/reverseEngineeringCommands.ts
#	src/cliCommandNames.ts
#	src/contracts/toolContracts.ts
#	src/contracts/toolEffects.ts
#	src/server/createServer.ts
# Conflicts:
#	docs/reverse-engineering-tools.md
# Conflicts:
#	src/application/reverse/ReverseEngineeringService.ts
#	tests/composition/reverseEngineering.test.ts

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9570aec126

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/cli/reverseEngineeringCommands.ts Resolved
Comment thread src/cutter/CutterBridgeClient.ts Resolved
Comment thread src/process/ownedDebuggerSession.ts Resolved
Comment thread src/application/binary/BinarySession.ts Resolved
Stopping a debugger no longer reports success when inherited output
streams stay open, so BinarySession cannot reopen a binary a child is
still changing. Concurrent Cutter cleanup retries share one receipt
acknowledgement instead of treating a consumed receipt as failure.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9a38942050

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/rizin/RizinDebugSessionManager.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a46a91f53a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/gdb/GdbSessionManager.ts Resolved
Comment thread src/rizin/RizinDebugSessionManager.ts Resolved
Comment thread src/application/binary/BinarySession.ts Resolved
@morluto
morluto merged commit 4aa51bf into main Oct 13, 2026
9 of 10 checks passed
@morluto
morluto deleted the codex/review-fixes-pr-2005 branch October 13, 2026 20:47

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: da4d7d8477

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1874 to +1878
pending.reject(
new AnalysisCancelledError("gdb_console", {
cause,
partialObservation: evidence,
}),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Retain cleanup ownership when cancellation shutdown rejects

When an active GDB command is cancelled and #stopDebuggerOnly rejects, this branch returns an AnalysisCancelledError without cleanup metadata. The outer execute path therefore does not add the failure to session.cleanupFailures, and shared mutation admission sees no retained owner even though the GDB process may still be active, allowing a later external mutation to proceed. Preserve the session resource as incomplete cleanup here, as the timeout rejection branch does.

AGENTS.md reference: AGENTS.md:L19-L21

Useful? React with 👍 / 👎.

Comment on lines +1056 to +1059
: Buffer.concat(
session.frameChunks,
session.bufferedFrameBytes,
).toString("utf8");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Report UTF-8 loss in failed Rizin startup output

When the initial Rizin frame contains invalid UTF-8 and startup subsequently fails, this builder returns replacement-character text from session.history or the partial frame but does not expose session.invalidUtf8Observed. Since the failed session is then deleted, callers have no status endpoint from which to discover the decoding loss and the returned startup diagnostics appear faithful. Include a decoding-loss diagnostic or partial Evidence in the startup error.

AGENTS.md reference: AGENTS.md:L13-L13

Useful? React with 👍 / 👎.

Comment on lines +1088 to +1091
const historyFrame =
frameBytes > MAX_RECENT_FRAME_BYTES || frame.truncated
? `${frame.text.slice(0, MAX_RECENT_FRAME_BYTES)}[recent frame truncated]`
: frame.text;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enforce the recent-frame limit in UTF-8 bytes

For a frame larger than MAX_RECENT_FRAME_BYTES, frame.text.slice(0, MAX_RECENT_FRAME_BYTES) limits UTF-16 code units rather than bytes. A frame of three-byte BMP characters therefore retains about 192 KiB instead of 64 KiB, and 64 history entries can inflate status serialization and agent context to roughly 12 MiB. Use the existing UTF-8-aware truncation helper so the intended byte bound applies to all text.

AGENTS.md reference: AGENTS.md:L49-L50

Useful? React with 👍 / 👎.

Comment on lines +53 to +55
.refine(
(value) => !/[\r\n]/u.test(value),
"A single command line is required",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject NUL in persistent Rizin commands

An MCP caller can submit a command containing \u0000 because this validator rejects only CR and LF; the manager then writes that value into Rizin's line-oriented command stream. Rizin's native command parser may terminate or reject the string at the NUL, so Evidence can report the full caller value even though only a prefix was interpreted. The one-shot Rizin schema already rejects NUL; apply the same boundary rule here and in the CLI validator.

AGENTS.md reference: AGENTS.md:L29-L29

Useful? React with 👍 / 👎.

@dandgabr

Copy link
Copy Markdown
Contributor

@morluto I could not open a PR against this branch from my fork (no permission), so here is a patch for the four threads that are still open on da4d7d847.

Commit: dandgabr@1d1dd752b (branch dandgabr:distill/pr-2799, one commit on top of da4d7d847; git fetch https://github.com/dandgabr/rea distill/pr-2799 && git cherry-pick 1d1dd752b).

  • GdbSessionManager.ts:1878
    • Root cause: a cancelled command whose owned shutdown is incomplete, or whose shutdown attempt rejects, built an error that was never tracked on the session.
    • Structural fix: that failure is added to session.cleanupFailures, so a later close resolves it.
    • Validation: new regression test in GdbSessionReviewRegressions; fails without the fix.
  • RizinDebugSessionManager.ts:1059
    • Root cause: failed-startup capturedOutput had no invalid-UTF-8 signal.
    • Structural fix: capturedOutput.output_invalid_utf8 (new optional field on AnalysisCapturedOutput), covering the buffered partial frame.
    • Validation: new test in RizinDebugSessionReviewRegressions.
  • RizinDebugSessionManager.ts:1091
    • Root cause: the recent-frame cap sliced by UTF-16 units.
    • Structural fix: truncation uses truncateUtf8 with the byte limit.
    • Validation: new test with 9000 two-byte characters.
  • rizinDebugToolContracts.ts:55
    • Root cause: NUL, the frame delimiter, was accepted in command text.
    • Structural fix: rizin_debug_command input rejects \0.
    • Validation: new schema test.

Overall validation: tsc --noEmit, oxlint and oxfmt are clean. The vitest.reverse-tools.config.ts run had 563 passing and 2 failing in ownedDebuggerSession.test.ts (unknown descendant holds output pipes open, PTY after the REA probe exits); both also fail on da4d7d847 without this commit. Not run: Stryker, check:pr, real providers, Windows/macOS.

Remaining cleanup: none identified for these four threads.

🤖 Generated with Claude Code

dandgabr added a commit to dandgabr/rea that referenced this pull request Oct 14, 2026
Reconcile the debugger lifecycle with the cleanup-ownership work merged in
morluto#2799:

- Keep main's rule that an exited debugger with open output writers stays
  incomplete; drop the deferred-disposal path this branch added.
- Keep main's inferior identity verification alongside this branch's
  required independent input sink and shared in-flight stop.
- GDB and Rizin report `inputSink` from /proc readback. Rizin now routes the
  inferior's stdin to the selected TTY so it can be verified.
- Merge the Windows backpressure handling with prompt cleanup polling.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
dandgabr added a commit to dandgabr/rea that referenced this pull request Oct 14, 2026
dandgabr added a commit to dandgabr/rea that referenced this pull request Oct 14, 2026
The reviewed GDB lifecycle, cleanup-ownership and mutation-admission work
landed on main through morluto#2799. Take main's implementation for the shared
sources and fixtures, and keep only what this branch still adds:

- one-shot `debug-with-gdb` classification now also rejects `shell`, `!`
  and a trailing `&`, which can leave a child outliving the debugger;
- the one-shot classifier regression test.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: bridge Hopper bridge (Python) related changes area: cli CLI adapter and one-shot commands area: domain Domain logic, errors, and pure functions bug Something isn't working i18n Translations and localization workflow P2: medium Medium priority issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants