Skip to content

fix(mcp): name the close_binary retry for retained cleanup - #8329

Merged
kaoru0822-kitauji merged 4 commits into
mainfrom
fix/8211-kuna-close-retry-remediation
Oct 31, 2026
Merged

kaoru0822-kitauji merged 4 commits into
mainfrom
fix/8211-kuna-close-retry-remediation

Conversation

@kaoru0822-kitauji

@kaoru0822-kitauji kaoru0822-kitauji commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

What broke: close_binary returned cleanup_incomplete with retryable: false, no recovery, and only "Review the reported local resources before opening another target." The session kept the failed owners, and the next close_binary on the same connection retried them, but the error never said so (observed with Kuna's unproven export stop).
Fix: The MCP close tool passes its retry operation to the session. The session binds a typed AnalysisCleanupRetry to a failed close only when it retired the target and still holds that cleanup. The projection then adds recovery.kind=retry_cleanup and a retry instruction that does not promise success.
Risk: Low, but the contract changes: the error schema gains one recovery kind, and remediation text grows only on those errors. One-shot CLI, open_binary, analysis tools and failed snapshot saves are unchanged.

Summary

Fixes #8211.

A failed close_binary retires the target and keeps every owner whose cleanup failed. The next close_binary on the same connection retries them; the Kuna guide already documented this. The error did not name that recovery, so an agent could drop the connection that owns the only retry.

After a failed close_binary, the error now carries recovery: {"kind": "retry_cleanup", "operation": "close_binary"} and adds this to the owner's remediation:

This connection retains that cleanup. Keep it open; after the reported condition settles or is resolved, call close_binary without snapshot_path and check its result. That call retries the retained cleanup without rerunning the failed analysis, clears session records like any close_binary, and can report cleanup_incomplete again.

The hint disappears once that cleanup resolves. retryable still describes the failed operation and stays false.

Problem and expected behavior

  • Trigger (from the issue): a Kuna export whose process stop cannot be proven, then close_binary.
  • Invariant: the cleanup error should name the recovery the owner actually supports. That recovery is the same-connection close_binary retry of the retained cleanup. It must stay distinct from rerunning the analysis, must not promise success, and must not suggest terminating processes. Owners that cannot offer the retry must not advertise it.

Change and scope

The fact is owned by the component that retains the cleanup, and it is never derived from message text.

  • Domain (analysisErrorBase.ts, analysisErrorRecovery.ts):

    • AnalysisError.bindCleanupRetry() records a frozen { operation: "close_binary" }.
    • cleanupRetry returns that value only while cleanupIncomplete is live.
    • retry_cleanup joins the recovery union and its zod schema.
  • Projection (analysisErrorProjection.ts): a small, localized change outside errorRecovery. A live bound retry takes precedence over the class-derived hint and appends the instruction to the owner's remediation.

  • Composition (analysisErrorCleanup.ts): analysisErrorWithCleanupFailure copies the cleanup owner's remediation without any retry offer. A composed error therefore shows the retry text once, and only when its own owner binds it.

  • Session (BinarySession.ts, BinarySessionPort.ts): close and closeWithSnapshot accept an optional cleanupRetry. The session binds it only when all three hold:

    • the target retirement (#closeActive) failed with incomplete cleanup;
    • the caller named a retry;
    • the session still retains a client, bundle, file or provider-candidate owner for its next close.

    cleanup_pending uses the same predicate, #retainsCloseCleanup, plus the external-mutation owner, which close_binary does not retry. A failed export or save returns before retirement and gets no offer.

  • MCP adapter (registerCloseLifecycleTool.ts):

    • passes CLOSE_RETRY to the session;
    • binds it to process-capture cleanup failures, which its own scope keeps for the next close;
    • binds it to a session-plus-process composition only when the session part already carried the offer.

Provider audit (source-read only, no real-provider runs). A second close() retries the remaining cleanup and never reports ok before confirmation in all of the following:

  • Kuna, Ghidra, Hopper, IDA;
  • the composite, lazy and deferred clients;
  • the artifact, bundle, native and managed clients;
  • the session file scope, the provider registry's owned resources, and the process-capture scope.

IDA retries cannot reconnect a dead transport, so they keep failing. The retry text already allows for that by saying it can report cleanup_incomplete again. The Hopper document text and the Kuna published-staging text already mention close_binary, so they now repeat that advice once.

Not included:

  • open_binary: it gets no hint. Its cleanup failures can leave a previous target active, and recommending close_binary there would clear its records.
  • One-shot CLI commands: no hint, because the process exits after its single close.
  • Analysis-tool failures: no hint.
  • Mixed composition: a close whose session failure is not itself a cleanup failure, combined with a process-capture failure, stays conservative and shows no hint.

Contribution scope: an ordinary fix within existing boundaries; no maintainer scope decision is needed.

Contract and boundary impact

  • Semantic owner and earliest changed stage:
    • BinarySession owns the retained close cleanup, and the MCP close tool owns the process-capture scope and the retry operation.
    • The domain error carries the fact, and the shared projection renders it for CLI and MCP alike; only the MCP close tool binds it.
    • The superseded inline cleanup_pending expression was replaced by the shared predicate.
  • Contribution scope fit and linked maintainer decision: fix within the existing lifecycle contract; not applicable.
  • CLI and MCP/tool-catalog contract:
    • The error schema gains the additive recovery.kind=retry_cleanup variant; docs/error-contract.schema.json was regenerated.
    • close_binary's cleanup_incomplete remediation text grows.
    • No tool input or output schema changes.
  • Provider, bridge, target-format, or platform compatibility: none. Provider clients are unchanged.
  • Evidence, artifact, provenance, or reconstruction contract:
    • unchanged: resources, cleanup reason, diagnostics, saved-snapshot receipts and live resolution are kept;
    • the hint follows the error's live cleanup state.
  • Target selection, authority, upstream behavior, and cleanup details:
    • cleanup ordering and retry are unchanged;
    • no new process signalling or termination advice.
  • Generated metadata, package, or installation impact: error schema only.

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated:
    • tests/boundary/mcp/kunaCloseRetryMcp.test.ts (new) runs a real public MCP workflow with the production KunaProvider, a fake Kuna and a launcher whose decompile-project stop stays unproven:
      • open_binary → procedure_pseudo_code → close_binary reports cleanup_incomplete, retryable: false, recovery retry_cleanup/close_binary, and a remediation equal to the owning formatters' output (analysisErrorRemediationAction on the delivered error plus cleanupRetryRemediation), so prose is never frozen;
      • binary_session shows open: false, cleanup_pending: true;
      • open_binary is blocked with no hint;
      • a repeated close keeps the offer;
      • after the stop is proven, close_binary succeeds, cleanup_pending becomes false, staging is empty, and the target bytes are unchanged.
    • processCleanupRetryMcp.test.ts:
      • a retained process-capture root now asserts the hint;
      • a non-cleanup session failure composed with process cleanup asserts no hint.
    • binarySessionCleanupRetry.test.ts:
      • a one-shot close() without cleanupRetry gets no hint, the offered close gets it, and it disappears after release;
      • a failed snapshot save gets no hint while a session file owner is still retained (this fails if save failures were offered), and the target stays open;
      • a completed save followed by failed retirement gets the hint and keeps saved_snapshot.
    • providerCleanupError.test.ts:
      • bound vs. unbound projection, plus schema parse;
      • resolution removes the hint;
      • composition does not inherit a peer's offer, and binding it once yields one instruction.
    • idaRetainedCleanupCli.test.ts: the built one-shot CLI output contains no retry_cleanup.
  • Base reproduction: the same Kuna MCP test run against the base source (my src/ changes removed) failed only on the missing recovery. Its first close returned {"code":"cleanup_incomplete","retryable":false,"remediation":{"action":"Provider cleanup could not be fully confirmed. Review the reported local resources before opening another target."},"recovery":null}, which matches the issue.
  • User-visible MCP output: see the quoted remediation and recovery object above.
  • Lifecycle regressions covered:
    • cleanup retry, with failure, repeated failure and recovery;
    • owners that recover after an error was returned (the hint disappears on resolution);
    • cleanup that fails after primary success (saved snapshot) or after a primary failure (composed session plus process).
  • Remaining proof gaps:
    • No real Kuna, Ghidra, Hopper or IDA run, so the provider retry audit is source-read only.
    • The issue's macOS environment-withheld ownership case is simulated by the unproven-stop launcher seam.
    • Cancellation during final cleanup is not exercised. close_binary takes no cancellation signal, and this change does not touch cleanup ordering.
    • Concurrent close_binary calls are not tested.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

All commands ran with Node 24.22.1 on macOS arm64.

  • node scripts/run-exact-tests.mjs run tests/boundary/mcp/kunaCloseRetryMcp.test.ts

    • against the base source: failed on the missing recovery (reproduction above);
    • with this change: passed.
  • npm run test:focused -- with idaRetainedCleanupCli, kunaCloseRetryMcp, processCleanupRetryMcp, selectedSnapshotCleanupMcp, cleanupPrimaryProjection, sessionFixtureCleanup, createServerCleanup, finishAnalysisCommand, kunaProvider, kunaPublicationCleanup, hopperLaunchFailureCli and captureCleanup — 12 files, 66 tests passed.

  • npm run test:local -- src/domain/providerCleanupError.test.ts tests/composition/analysis-sessions/binarySessionCleanupRetry.test.ts — passed (7 + 12 tests).

  • npm run test:changed -- --base origin/main — 12545 passed, 23 skipped, 1 failed.

    • The failure was src/inspector/JavaScriptRuntimeScope.cancellation.test.ts ("stops Inspector target authorization after the current stat settles"), in code this PR does not touch.
    • It also failed in 3 of 3 isolated reruns with this change, and in 1 of 1 isolated run on the unmodified base source on this host, so it is pre-existing and unrelated.
  • npm run check:fast — passed.

  • npm run format:check — passed.

  • Review follow-up (533e76a): guidance assertions now come from the owning formatters, and the controls behaved as intended:

    • rewording both owners' text passes;
    • dropping the retry suffix fails 3 tests;
    • copying the projected remediation into a composition fails 1 test.

    test:focused on the 5 touched or added test files passed (25 tests); check:fast, format:check and docs:check passed.

  • npm run docs:error-schema — regenerated docs/error-contract.schema.json.

  • npm run docs:check — passed; it includes generate-error-schema --check and package metadata checks.

  • After merging origin/main (a989c0e), these were rerun:

    • npm run check:fast — passed;
    • npm run format:check — passed;
    • npm run docs:check — passed;
    • npm run test:focused -- with kunaCloseRetryMcp, processCleanupRetryMcp, selectedSnapshotCleanupMcp, idaRetainedCleanupCli, binarySessionCleanupRetry, providerCleanupError, analysisErrorProjection, analysisErrorCleanup, cleanupPrimaryProjection and kunaProvider — 10 files, 151 tests passed.

Compatibility, safety, and release

  • Breaking changes or migration steps: none. recovery is optional, and the new kind is additive. Strict clients that enumerate recovery.kind should accept retry_cleanup.
  • Real Hopper/Ghidra, browser, or OS coverage: unavailable. Kuna was exercised only through a fake Kuna with the production provider, and only on macOS. The test is skipped on Windows, like the other Kuna boundary tests.
  • Package or release metadata impact: none beyond the generated error schema.
  • Security, privacy, process, or containment review:
    • no new process control;
    • the text does not suggest terminating processes;
    • no new paths or values are exposed.

Author readiness

Human owner: @kaoru0822-kitauji

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

🤖 Generated with Claude Code

kaoru0822-kitauji and others added 2 commits October 31, 2026 15:16
A close_binary that retired its target but could not confirm cleanup
returned cleanup_incomplete with retryable: false and only the generic
"Review the reported local resources" remediation, although the session
keeps every failed owner and the next close_binary on the same connection
retries them. Agents could abandon the connection that owns the only retry.

The MCP close tool now passes its retry operation to the session. The
session binds that typed AnalysisCleanupRetry to a failed retirement only
while it retains the cleanup for its next close; the close tool binds it to
process-capture failures its own scope retains and to compositions whose
session part was offered. Projection then reports
recovery.kind=retry_cleanup and appends a conditional instruction: keep the
connection, let the condition settle or resolve it, call close_binary
without snapshot_path and check the result. The hint disappears once that
cleanup resolves. retryable keeps describing the failed operation.

One-shot CLI closes, open_binary, analysis tools and failed snapshot saves
(which keep the target open) offer no retry. Cleanup composition copies the
owner's remediation without a retry offer, so the text appears once.

Fixes #8211

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kaoru0822-kitauji kaoru0822-kitauji added bug Something isn't working track:bugs Small-bug loop track PRs labels Oct 31, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-31T16:08:09.880122Z 4fca1f6 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: apex

[Low impact] This PR appears safe to merge; no actionable new issues were found.

Summary

Adds retry_cleanup recovery metadata to failed MCP close_binary calls when their cleanup remains owned for another close on the same connection.

  • Failed closes now name the retry held by the same connection.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A["MCP close_binary"] --> B{"Snapshot requested?"}
  B -->|Yes| C{"Save succeeded?"}
  C -->|No| D["Return save error without retry offer"]
  C -->|Yes| E["Retire target and close owned resources"]
  B -->|No| E
  E --> F{"Cleanup failed and remains retained?"}
  F -->|Yes| G["Bind retry_cleanup and append guidance"]
  F -->|No| H["Return normal close result"]
  G --> I["Next same-connection close retries cleanup"]
Loading

Reviews (3) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

kaoru0822-kitauji and others added 2 commits October 31, 2026 15:31
The new close_binary retry assertions froze ProviderCleanupError's
explanatory sentence, so a harmless wording edit would break them. The MCP
test now compares delivered remediation with analysisErrorRemediationAction
applied to the delivered typed error plus cleanupRetryRemediation. The
domain tests use the same formatters, check that unbound and released errors
carry no retry text, and check that a bound composition adds the offer once.
Recovery fields, cleanup state and retry behavior keep separate assertions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kaoru0822-kitauji
kaoru0822-kitauji merged commit 8a6ddec into main Oct 31, 2026
52 checks passed
@kaoru0822-kitauji
kaoru0822-kitauji deleted the fix/8211-kuna-close-retry-remediation branch October 31, 2026 18:12
@morluto

morluto commented Oct 31, 2026

Copy link
Copy Markdown
Owner

Independent real-Kuna cleanup-retry check after merge

On REA main d54a4661da20382ad8456564a08569fdd24131c5, macOS arm64, Node 24.22.1 and SDK 2.3.1, I repeated #8211's controlled lifecycle with real Kuna 1.986. A caller-owned wrapper signaled when decompile-project started, waited 30 seconds, then forwarded to Kuna. After that signal I canceled the only MCP assembly waiter and kept the connection open.

  • The first close_binary returned cleanup_incomplete, retryable: false, recovery: {kind: "retry_cleanup", operation: "close_binary"} and the conditional same-connection retry instructions. Its underlying ownership reason was platform_binary_environment_withheld for two live candidates.
  • binary_session showed open: false, cleanup_pending: true. An early open_binary of a different supported target returned cleanup_incomplete with no retry offer; a second early close_binary remained incomplete and retained the retry offer.
  • After the controlled delay, the next close_binary succeeded; status showed cleanup_pending: false, the isolated staging and project directories were empty, and opening the other target and resolving a real procedure succeeded. Final close succeeded.

Both owned target hashes were unchanged and neither target was executed. Successful MCP replies used fetched compact tool definitions; I separately validated the two close errors and the blocked-open error against docs/error-contract.schema.json (draft 2020-12). Error replies are not validated by the SDK's success-output schema. This is one artificially delayed macOS run, not a natural-rate, cancellation-during-finalization, other-owner, or other-platform claim.

One separate status-discoverability observation: while cleanup was pending, the procedure_assembly availability group still said target_required and directed the caller to open_binary, which was then blocked by the retained cleanup. The close error itself correctly named the recovery. Any status improvement needs the actual cleanup owner's retry capability; cleanup_pending alone can also represent owners that close_binary cannot retry.

coyoteXujie pushed a commit to coyoteXujie/rea that referenced this pull request Nov 2, 2026
)

* fix(mcp): name the close_binary retry for retained cleanup

A close_binary that retired its target but could not confirm cleanup
returned cleanup_incomplete with retryable: false and only the generic
"Review the reported local resources" remediation, although the session
keeps every failed owner and the next close_binary on the same connection
retries them. Agents could abandon the connection that owns the only retry.

The MCP close tool now passes its retry operation to the session. The
session binds that typed AnalysisCleanupRetry to a failed retirement only
while it retains the cleanup for its next close; the close tool binds it to
process-capture failures its own scope retains and to compositions whose
session part was offered. Projection then reports
recovery.kind=retry_cleanup and appends a conditional instruction: keep the
connection, let the condition settle or resolve it, call close_binary
without snapshot_path and check the result. The hint disappears once that
cleanup resolves. retryable keeps describing the failed operation.

One-shot CLI closes, open_binary, analysis tools and failed snapshot saves
(which keep the target open) offer no retry. Cleanup composition copies the
owner's remediation without a retry offer, so the text appears once.

Fixes morluto#8211

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test: derive close retry guidance from its owning formatters

The new close_binary retry assertions froze ProviderCleanupError's
explanatory sentence, so a harmless wording edit would break them. The MCP
test now compares delivered remediation with analysisErrorRemediationAction
applied to the delivered typed error plus cleanupRetryRemediation. The
domain tests use the same formatters, check that unbound and released errors
carry no retry text, and check that a bound composition adds the offer once.
Recovery fields, cleanup state and retry behavior keep separate assertions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
@morluto morluto added the area: mcp MCP server, transport, and tool registration label Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: mcp MCP server, transport, and tool registration bug Something isn't working track:bugs Small-bug loop track PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Kuna cleanup error omits the available close retry

2 participants