Skip to content

fix(discord): /codex detach and rebind revert after a Gateway restart - #178333

Closed
Satoshi-Kusumoto wants to merge 1 commit into
openclaw:mainfrom
Satoshi-Kusumoto:fix/discord-binding-owner-runtime
Closed

Satoshi-Kusumoto wants to merge 1 commit into
openclaw:mainfrom
Satoshi-Kusumoto:fix/discord-binding-owner-runtime

Conversation

@Satoshi-Kusumoto

Copy link
Copy Markdown
Contributor

Closes #178330
Related: #175379
Alternative to #177691

What Problem This Solves

Fixes: in Discord, /codex detach and re-running /codex bind reply with success but are not saved, so the earlier binding is back after a Gateway restart.

User Impact

User impact: detaching or re-binding a Discord conversation with /codex now survives a Gateway restart, and one such command no longer leaves Discord's binding storage memory-only for the rest of the Gateway process.

  • No config or migration change. The exports of Discord's public runtime-api keep their signatures.
  • A binding that an earlier detach left in the store still loads at startup. Detaching it again on this build removes it (the focused detach test covers this path), and /session unbind also removes it, as on main.
  • If a plugin reload's provider stop times out, writes from the old Discord lifecycle can change stored bindings through the new runtime. This and the other reload-window limits are listed at the end of the next section.

Why This Change Was Made

Discord opened its binding store with the runtime of whichever plugin instance was running at write time. /codex commands run in the Codex plugin instance, where Discord's runtime slot is empty, so the write failed. commitBindingRecord caught the failure, kept the change in memory, turned persistence off for the whole process, and the command reported success. #178330 has the reproduction.

The thread-binding manager now keeps the runtime of the Discord instance that created it. Its load, bind, unbind, touch, deprecated synchronous touch, and save-interrupted reporter use that runtime. This is the runtime ownership of the Telegram repair merged in #175379 (2a30b52). Discord needs two more pieces:

  • The session-wide idle, max-age, and unbind helpers are module-level exports with no manager closure. They now look up the account's manager and use the runtime it keeps, through a WeakMap in Discord's existing shared binding state. On main, the same calls from another plugin instance did not reach the store either: the runtime lookup failed and switched Discord to memory-only for the rest of the process. Without a manager, or with a manager that has no runtime, the helpers fall back to the call-time lookup, as on main.
  • When a provider's stop times out during a reload, the replacement provider gets the old, still running manager back from createThreadBindingManager. That manager now adopts the replacement provider's runtime when the provider has one. A caller without a Discord runtime, such as the Codex instance, does not replace it.

No core production code or public SDK contract changes; the tests extend one existing core test file.

This is an alternative to #177691, which fixes the same bug; thanks to its author for the careful work there. The original #175379 description already noted that Discord opens its binding store the same way, and I started on Discord after a maintainer took that PR over on 2026-10-18. Reproducing the bug and proving the fix on a real Discord bot took a few more days, so this PR arrives after #177691; apologies for the overlap. For the session-wide helpers, this PR follows #177691, whose first commit already covered them through the manager's retained runtime. This PR keeps the repair inside Discord's binding owner: it does not change core implementation or the public SDK contract, its runtime ownership has the same shape as the Telegram repair merged in #175379 (2a30b52), and it has real Discord runs before and after the fix. #177691 goes further: it fences runtime-owned plugin-state stores after their owning runtime retires, and makes refused async binding changes (other than best-effort activity touches) reject without publishing the change or disabling persistence. This PR leaves both cases as accepted limits below. Both rely on core plugin-state changes in #177691 (refusing retired runtimes when stores open and on synchronous writes, with a typed refusal error) that change behavior for every plugin using runtime-owned stores, and the async case also changes how Discord binding commands report failures; these are maintainer decisions beyond this Discord-local fix. I am happy to follow whichever direction maintainers prefer; the live reproduction in #178330 applies to either PR.

Accepted limits (plugin reload windows only; named here rather than coded around):

  • Old lifecycle after runtime replacement. After a replacement provider adopts a still-running manager, writes that the old lifecycle starts, including thread-delete cleanup and idle/max-age sweeps, change stored bindings through the replacement runtime. Both lifecycles belong to the Discord plugin. The retired-runtime test below shows only that a retired runtime cannot complete the tested async refresh. The old lifecycle also stops the shared manager later, as on main.
  • Retired runtime, synchronous writes. Between registry retirement and manager stop, the deprecated synchronous compatibility writes (touch, session-wide idle/max-age, unbind) still write through the retained runtime, because the core synchronous store does not check retirement. This is the same shape as the synchronous compatibility writes of the Telegram repair merged in fix(telegram): /codex detach and rebind fail with 'Telegram runtime not initialized' #175379 (2a30b52). No bundled code calls these deprecated writes; only external SDK callers can.
  • Retired runtime, async writes. In the same window, an async write that the store refuses still turns persistence off and keeps the change in memory, as on main. Every later Discord binding write in the process, including the replacement owner's, is then memory-only until restart, so a reload that hits this window can show the symptom of [Bug]: Discord: /codex detach and rebind are not saved, so the binding returns after a Gateway restart #178330. The window includes the time after the new registry is published and before the replacement provider creates or adopts the manager: session-wide helpers then use the still-running old manager's runtime, where main would look the runtime up at call time. If no live manager exists, they fall back to the call-time lookup, as on main.
  • Public export. createThreadBindingManager is exported. A caller that gets an existing manager back while holding a different Discord runtime also replaces that manager's runtime. In bundled code only the Discord provider calls it with a Discord runtime.
  • Older shared-state shape. A process that still holds Discord's shared binding state in an older shape lacks the new field and throws a TypeError until restart, as refactor(channels): consolidate private transport paths #173128 decided for such shape changes.
  • No core fence. Making core's runtime-owned synchronous plugin-state stores refuse retired runtimes would change core and public SDK behavior for plugins that use those stores. That is a maintainer decision, separate from this Discord-local fix. refactor(plugin-sdk): remove synchronous APIs deprecated by stable v2026.10.2 #169868 (draft) proposes removing the deprecated SessionBindingService.touch.
Design notes
  • The WeakMap is keyed by manager, next to the existing accountOperationTails map in the same shared state. Unlike the default runtime slot, which resolves from the calling plugin instance, the stored value does not follow the caller.
  • Writers receive a resolver that reads the manager's runtime holder at write time, so a runtime adopted on reuse also reaches the manager's own writers and the session-wide helpers.
  • The manager takes its runtime with getOptionalDiscordRuntime(), because existing tests create managers without one. Such a manager cannot open the store, so Discord stays memory-only, as it did before when the first load found no runtime.

Evidence

On a real Discord bot and the same d8e54ec checkout, /codex detach left the binding stored before the fix (1 row, and the binding was back after a restart) and removed it with this PR (0 rows, no binding after a restart, and no persistence unavailable line).

Real Discord, before and after. Both runs used the same d8e54ec checkout and a dedicated test bot in a paired DM, with the commands sent as plain-text messages from a Discord client (commands.native: false). The Codex plugin was enabled and the Gateway had no model credentials; no ordinary message was sent, so there was no model turn. The Gateway was built with pnpm build and started with node openclaw.mjs --dev gateway --bind loopback --tailscale off --verbose, which loads Discord from dist/. Stored rows were counted read-only with the Gateway stopped (plugin_id = 'discord', namespace = 'thread-bindings'). The pre-fix run used unpatched d8e54ec; the post-fix run used this PR's diff on the same checkout.

  • Pre-fix run (2026-10-20; transcript and log lines in [Bug]: Discord: /codex detach and rebind are not saved, so the binding returns after a Gateway restart #178330):
    • First /codex bind, Allow once: 1 row.
    • /codex bind --cwd <dir>, /codex detach, /codex binding: all success replies, but still 1 row. The console logged discord thread binding persistence unavailable; keeping bindings in memory once, 1 ms before the re-bind's plugin binding auto-refresh line.
    • After a restart, /codex binding showed the binding again, with Workspace: <worktree> from the first bind; the re-bind's <dir> was lost. /session unbind then removed it (0 rows).
  • Post-fix run (2026-10-20; build pinning and transcript below):
    • 0 rows at the start. /codex bind --cwd <dir>, Allow once, then /session idle 2h: 1 row, with idleTimeoutMs=7200000.
    • The same /codex bind --cwd <dir>, /codex detach, /codex binding: 0 rows.
    • After a restart, /codex binding, /session unbind, /codex binding replied No Codex conversation binding is attached., then ℹ️ This conversation is not currently bound., then No Codex conversation binding is attached. 0 rows at the end. persistence unavailable lines over the whole run (4 Gateway starts; the first was stopped to approve the DM pairing): 0.
  • The three commands under test were identical. The runs differ in the patch and around the first bind: the pre-fix run's first bind had no --cwd (left out by mistake), and the post-fix run added /session idle 2h. That command reaches the changed session-wide async helper (source reading). The run shows that the helper still stores on a real Gateway; the focused tests below cover the cross-instance calls.

Focused tests. src/plugins/conversation-binding.cross-instance.test.ts gets a new describe("Discord thread bindings across plugin instances"): 5 it blocks, one of them an it.each over 3 writers, so 7 executed cases. Each case uses the real plugin registry lifecycle, the real plugin-state store, and Discord's real thread-binding manager started inside a Discord plugin instance, as channel startup does. Writes come from a Codex plugin instance, through requestPluginConversationBinding / detachPluginConversationBinding or Discord's public session-wide exports; in the reuse case they come from a replacement Discord instance. Every case except the retired-runtime control reads the stored row and then checks that a later write from Discord's own instance is still stored, which catches the process-wide switch to memory-only.

  • A write from another plugin instance is stored through Discord's owner. Refresh, detach, and the three session-wide writers (async idle, deprecated sync idle, deprecated sync unbind) fail on d8e54ec and pass with this change. A sixth case has a replacement provider, running in a replacement Discord instance, reuse a live manager (the reload-timeout path). It passes on d8e54ec, which looks the runtime up at call time, and fails if only the manager keeps the runtime; it guards against that regression.
  • A retired runtime does not write the stored binding. A refresh is paused at the store write, Discord's registry is retired, and the stored row must stay unchanged. This is an existing core protection (the plugin-state store's runtime check), kept as a control. On d8e54ec the case fails before it reaches the paused store write, because the request settles first, so it is not red/green proof for this change.
  • With this change: 10 passed (the 3 existing Telegram cases and the 7 Discord cases). The two deprecated synchronous writer cases call deprecated APIs on purpose, so DEP_PLUGIN_SDK deprecation warnings are expected.

Test cost (pnpm test <file> --maxWorkers=1, Linux x86_64, Node 24.21.0, Vitest on Node):

  • src/plugins/conversation-binding.cross-instance.test.ts: wall 19.17 s, Vitest Duration 16.59 s. Each Discord case takes 446–602 ms (about 3.4 s for the 7), and the 3 existing Telegram cases about 1.9 s. This is above the 5 s target and under 30 s: each case builds a real registry, a real SQLite-backed plugin-state store, and Discord's real manager, because the bug is which plugin instance opens that store, and a fake adapter would not open it. The per-case cost matches the Telegram cases already in this file.
  • extensions/discord/src/monitor/thread-bindings.state.test.ts (two existing calls now pass the runtime resolver; no cases added): wall 13.82 s, Vitest Duration 11.33 s.
  • CI seconds will be added once CI reports.

Checks (same environment, tree d8e54ec plus this diff):

  • git diff --check, format check, core and Discord lint, core and extension type checks, and the existing Discord thread-binding tests: pass.
  • pnpm test:extension discord: passed (252 files, 2496 tests).
  • pnpm check:changed: exited 1. The lanes covering this diff pass (core-test and extension type checks, lint on the changed files, import cycles). Three checks fail identically on a clean d8e54ec: the max-lines suppression ratchet (files under ui/), the core tsgo test-root budget per shard (724 and 725 against 720), and the dead-export scan (untouched google-meet and gateway talk files).
  • autoreview against d8e54ec: scoped-clean, no actionable findings.
  • Not run: pnpm test:contracts:channels, since no shared plugin or channel interface changed.

Not covered:

  • The discord-e2e skill's QA Lab lane with leased QA bots. These runs used a dedicated test bot, with the commands sent as plain-text messages from a Discord client; native slash commands hit a separate failure in plugin-bound threads (fix(discord): native slash commands fail in a plugin-bound thread #177850).
  • Live runs used a DM only: no server channel, child-thread placement, Always allow, initialized native Codex thread, subagent thread spawn, or model turn.
  • The deprecated synchronous helpers, the retirement window, and the reload-timeout reuse are covered by the tests above only; real reload timing and third-party SDK callers were not tested.
  • No upgrade run: the stored record shape, namespace, and config are unchanged.
  • Matrix is not changed here; see fix(matrix): spawns from Gateway chat.send turns break thread bindings until restart #177372.
Focused tests on d8e54ec, a manager-only variant, and this change

The middle column is a variant of this fix, not submitted, in which only the manager keeps the runtime: the session-wide helpers still look it up at call time, and a reused manager keeps its old runtime. It shows that each of the last four Discord cases fails without the part of this change it covers. Same environment and test file in all three runs; only the production files differ.

Case (Discord thread bindings across plugin instances > …) d8e54ec Manager only (not submitted) This change
lets the owning plugin root refresh a Discord binding across plugin instances fail pass pass
lets the owning plugin root detach a Discord binding across plugin instances fail pass pass
keeps a retired Discord runtime from writing the persistent binding fail (control, see above) pass pass
lets the owning Discord plugin persist the async session idle update across plugin instances fail fail pass
lets the owning Discord plugin persist the deprecated sync session idle update across plugin instances fail fail pass
lets the owning Discord plugin persist the deprecated sync session unbind across plugin instances fail fail pass
replaces the owner runtime when a new Discord provider reuses a live manager pass fail pass

The 3 existing Telegram cases pass in all three runs. Failures on d8e54ec:

× lets the owning plugin root refresh a Discord binding across plugin instances
  AssertionError: Discord refresh should update the persisted binding: expected { accountId: 'default', …(11) } to match object { metadata: { …(2) } }
× lets the owning plugin root detach a Discord binding across plugin instances
  AssertionError: Discord detach should delete the persisted binding: expected { accountId: 'default', …(11) } to be undefined
× keeps a retired Discord runtime from writing the persistent binding
  Error: Discord binding request settled before reaching the registry-owned queued write
× lets the owning Discord plugin persist the async session idle update across plugin instances
  AssertionError: expected { accountId: 'default', …(11) } to strictly equal ObjectContaining{…}
× lets the owning Discord plugin persist the deprecated sync session idle update across plugin instances
  AssertionError: expected { accountId: 'default', …(11) } to strictly equal ObjectContaining{…}
× lets the owning Discord plugin persist the deprecated sync session unbind across plugin instances
  AssertionError: expected { accountId: 'default', …(11) } to strictly equal undefined

The manager-only variant fails the three session-wide cases with the same assertions, and the reuse case with:

× replaces the owner runtime when a new Discord provider reuses a live manager
  AssertionError: expected undefined to match object { Object (metadata) }
Post-fix run: build pinning and transcript (redacted)

The pre-fix working tree had an empty diff against d8e54ec. For the post-fix run, the freshly built Discord chunks contain this change's identifiers (ownersByManager ×4 and resolveThreadBindingsOwnerRuntime ×6, all in files built after this run's build started; 0 of each before the build), each of the 4 Gateway starts logged [plugins] loading discord from <worktree>/dist/extensions/discord/index.js, and the working-tree diff (sha256 b7bddf1b49d00fe979febf11ef28da00b4abc80978d15fa81feff31f83b82757) is byte-identical to git diff --binary d8e54ec 74d9a81348e6. The working tree matched this diff right after the build and again after the last Gateway stop.

<user>: /codex bind --cwd <dir>
        (pressed Allow once)
<bot>:  Allowed Codex to bind this conversation once. Codex app-server thread a new thread in <dir>
<user>: /session idle 2h
<bot>:  ✅ Idle timeout set to 2h for 1 binding (next auto-unbind at 2026-10-20T11:04:18.424Z).
        [Gateway stopped: 1 row, idleTimeoutMs=7200000; started again]
<user>: /codex bind --cwd <dir>
<bot>:  Bound this conversation to a new thread in <dir>. The next message will initialize it.
<user>: /codex detach
<bot>:  Detached this conversation from Codex.
<bot>:  ⚙️ This conversation is no longer bound to that session.
<user>: /codex binding
<bot>:  No Codex conversation binding is attached.
        [Gateway stopped: 0 rows; started again]
<user>: /codex binding
<bot>:  No Codex conversation binding is attached.
<user>: /session unbind
<bot>:  ℹ️ This conversation is not currently bound.
<user>: /codex binding
<bot>:  No Codex conversation binding is attached.
        [Gateway stopped: 0 rows]

Maintainer edits are enabled ("Allow edits and access to secrets by maintainers"); this fork has no Actions secrets configured.

Discord opened its thread-binding store with the runtime of whichever
plugin instance was running at write time. `/codex` commands run in the
Codex plugin instance, where Discord's runtime slot is empty, so the
write failed. The failure was caught, the change stayed in memory,
persistence was turned off for the whole process, and the command still
reported success, so the earlier binding came back after a Gateway
restart.

Keep the runtime of the Discord instance that created the thread-binding
manager and use it for the manager's own loads and writes. The
module-level session-wide idle, max-age, and unbind writes look up the
account's manager and read the same owner holder through
`ownersByManager`, falling back to the call-time lookup when there is
none. When a provider reuses a live manager after a timed-out stop, a
non-empty runtime from the new provider replaces the old one. No core
production code or public SDK contract changes.
@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord size: L labels Oct 20, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 20, 2026
@clawsweeper

clawsweeper Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR makes Discord binding persistence use the thread-binding manager’s retained runtime across plugin calls.

Example: Send /codex detach in a bound Discord DM, then restart the Gateway.

  • Before: The command reports success, but the stored binding survives and returns after restart.
  • After: The supplied live run deletes the stored binding, and it remains absent after restart.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful live-backed repair with passing checks, blocked by concrete runtime-lifetime and persistence regressions; namespace, keys, serialized records, and schema remain unchanged.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) Security review found an item that needs attention.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Discord says a conversation was detached or rebound, but the earlier binding returns after a Gateway restart.
Reason: Durable binding changes are an existing contract, and the live report demonstrates silent state loss without requiring a new feature or setting.

Merge readiness

⛔ Blocked before merge - 6 items remain

Keep this PR open: it repairs a demonstrated Discord persistence bug, but the retained runtime introduces actionable retirement and reload defects.

Priority: P1
Reviewed head: 74d9a81348e6c611fec48afe0d0c06940a7178f2

Before merge

  • Add real behavior proof - Authority-chain proof required: the supplied built-Gateway Discord DM transcript proves ordinary detach persistence and restart readback, and integration tests exercise active cross-instance writes and one retired async refresh; they do not establish rejection before synchronous effects or before old lifecycle effects after runtime reassignment. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Keep replacement runtime authority separate from old lifecycle work (P1) - When provider shutdown times out, the replacement reuses the still-running manager and overwrites its runtime holder. Every existing manager closure now resolves the replacement runtime, including an old sweeper or thread-delete cleanup. assertManagerCurrent still passes because the manager object is unchanged, and the store checks the replacement registry rather than the retired origin. Consequently old lifecycle work can delete durable bindings through fresh authority where its original async runtime would refuse the write. Replace or retire the old lifecycle owner, or retain operation-origin authority through the final write instead of lending every old closure the new runtime.
  • Check retained runtime authority before synchronous binding writes (P1) - After Discord’s registry retires but before its manager stops, another plugin can call the supported synchronous session idle or unbind exports. These paths now obtain Discord’s retained runtime even though that caller has no Discord runtime slot. openSyncKeyedStore and its legacy mutators do not check assertRuntimeCurrent, so the call updates or deletes durable Discord rows through a retired owner. The added retirement test covers only an async refresh and cannot catch this path. Validate the retained owner before synchronous effects and do not convert authority refusal into a successful memory mutation.
  • Preserve persistence when a retained helper runtime is retired (P2) - Between publication of the replacement registry and adoption of its runtime by the existing manager, a session-wide update running in the new Discord instance now selects the old manager’s retired runtime. Previously this helper used the caller’s current Discord runtime. The V2 store refuses the old runtime, but this call supplies no authority assertion, so commitBindingRecord treats the refusal as storage failure, sets persistenceAvailable=false, publishes the memory update, and reports success. Later manager adoption never resets that flag, leaving subsequent binding changes memory-only until restart. Reject the refused mutation without publishing it or disabling persistence, and cover a later replacement-owner write.
  • Resolve security concern: Replacement authority reaches retired lifecycle callbacks - The existing async store fence validates whichever runtime the mutable holder currently supplies; after reassignment it no longer rejects effects originating in the retired lifecycle.
  • Resolve security concern: Retired runtime remains usable by compatibility writers - The synchronous store has no runtime-lifetime assertion, so retaining its runtime makes cross-instance compatibility effects possible after the owning registry retires.

Findings

  • [P1] Keep replacement runtime authority separate from old lifecycle work — extensions/discord/src/monitor/thread-bindings.manager.ts:128-130
  • [P1] Check retained runtime authority before synchronous binding writes — extensions/discord/src/monitor/thread-bindings.lifecycle.ts:204
  • [P2] Preserve persistence when a retained helper runtime is retired — extensions/discord/src/monitor/thread-bindings.session-shared.ts:78
  • [medium] Replacement authority reaches retired lifecycle callbacks — extensions/discord/src/monitor/thread-bindings.manager.ts:130
  • [medium] Retired runtime remains usable by compatibility writers — extensions/discord/src/monitor/thread-bindings.lifecycle.ts:204

Tests

  • Missing end-to-end proof: Extend the existing production-owner proof to show retired synchronous callers and old lifecycle work cannot change durable rows after replacement, and a refused helper write leaves replacement persistence working.
Agent review details

How this fits together

Discord’s thread-binding manager translates conversation-binding operations from plugins and session commands into in-memory routing records and durable plugin-state writes.

flowchart TD
  A[Codex and session commands] --> B[Conversation binding service]
  B --> C[Discord binding manager]
  D[Session lifecycle helpers] --> C
  C --> E[Retained Discord runtime]
  E --> F[Plugin state store]
  F --> G[SQLite binding records]
Loading

Technical review

Best possible solution:

Retain Discord-owned persistence while fencing retired writers, separating replacement lifecycle authority, and preserving persistence after refused writes.

Do we have a high-confidence way to reproduce the issue?

The linked report supplies a real Discord reproduction, and current-main source explains it: Codex’s instance lacks Discord’s runtime slot, and the resulting storage failure is swallowed; this review executed no target code.

Is this the best way to solve the issue?

Capturing the channel owner’s runtime addresses the root cause and follows the merged Telegram repair, but mutable reassignment and unchecked compatibility writes do not preserve runtime lifetime authority.

Full review comments:

  • [P1] Keep replacement runtime authority separate from old lifecycle work — extensions/discord/src/monitor/thread-bindings.manager.ts:128-130
    When provider shutdown times out, the replacement reuses the still-running manager and overwrites its runtime holder. Every existing manager closure now resolves the replacement runtime, including an old sweeper or thread-delete cleanup. assertManagerCurrent still passes because the manager object is unchanged, and the store checks the replacement registry rather than the retired origin. Consequently old lifecycle work can delete durable bindings through fresh authority where its original async runtime would refuse the write. Replace or retire the old lifecycle owner, or retain operation-origin authority through the final write instead of lending every old closure the new runtime.
    Confidence: 0.98
  • [P1] Check retained runtime authority before synchronous binding writes — extensions/discord/src/monitor/thread-bindings.lifecycle.ts:204
    After Discord’s registry retires but before its manager stops, another plugin can call the supported synchronous session idle or unbind exports. These paths now obtain Discord’s retained runtime even though that caller has no Discord runtime slot. openSyncKeyedStore and its legacy mutators do not check assertRuntimeCurrent, so the call updates or deletes durable Discord rows through a retired owner. The added retirement test covers only an async refresh and cannot catch this path. Validate the retained owner before synchronous effects and do not convert authority refusal into a successful memory mutation.
    Confidence: 0.97
  • [P2] Preserve persistence when a retained helper runtime is retired — extensions/discord/src/monitor/thread-bindings.session-shared.ts:78
    Between publication of the replacement registry and adoption of its runtime by the existing manager, a session-wide update running in the new Discord instance now selects the old manager’s retired runtime. Previously this helper used the caller’s current Discord runtime. The V2 store refuses the old runtime, but this call supplies no authority assertion, so commitBindingRecord treats the refusal as storage failure, sets persistenceAvailable=false, publishes the memory update, and reports success. Later manager adoption never resets that flag, leaving subsequent binding changes memory-only until restart. Reject the refused mutation without publishing it or disabling persistence, and cover a later replacement-owner write.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 1ff58cefbe8d.

Provenance checked

Testing

Proof path: shipped entry point.

Security

Needs attention: Runtime retention and reassignment bypass the originating lifecycle’s authority for reachable binding writes.

Evidence

Security concerns:

  • [medium] Replacement authority reaches retired lifecycle callbacks — extensions/discord/src/monitor/thread-bindings.manager.ts:130
    The existing async store fence validates whichever runtime the mutable holder currently supplies; after reassignment it no longer rejects effects originating in the retired lifecycle.
    Confidence: 0.98
  • [medium] Retired runtime remains usable by compatibility writers — extensions/discord/src/monitor/thread-bindings.lifecycle.ts:204
    The synchronous store has no runtime-lifetime assertion, so retaining its runtime makes cross-instance compatibility effects possible after the owning registry retires.
    Confidence: 0.97

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit b310493 adds extensions/discord/src/monitor/thread-bindings.manager.ts:508 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b310493c0928; files: extensions/discord/src/monitor/thread-bindings.manager.ts)
  • BTofu: Raw commit 2a30b52 adds src/plugins/conversation-binding.cross-instance.test.ts:231 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2a30b52a603e; files: src/plugins/conversation-binding.cross-instance.test.ts)

PR surface

Source +58, Tests +424. Total +482 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 89 31 +58
Tests 2 433 9 +424
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 522 40 +482

Review metrics

Metric Value Why it matters
Production versus test growth Production +87/-31; tests and test support +435/-9 The production changes thread runtime ownership through existing writers; the integration cases cover distinct refresh, detach, compatibility, retirement, and replacement paths.

Labels

Label changes:

  • add P1: Real Discord commands report success while losing binding changes and restoring stale routing after restart.
  • add merge-risk: 🚨 session-state: A retired-runtime refusal can disable later durable binding writes, causing successful session changes to disappear after restart.
  • add merge-risk: 🚨 security-boundary: Retained and reassigned runtimes allow binding effects beyond the originating plugin lifecycle’s authority.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P1: Real Discord commands report success while losing binding changes and restoring stale routing after restart.
  • merge-risk: 🚨 security-boundary: Retained and reassigned runtimes allow binding effects beyond the originating plugin lifecycle’s authority.
  • merge-risk: 🚨 session-state: A retired-runtime refusal can disable later durable binding writes, causing successful session changes to disappear after restart.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 20, 2026, 6:34 AM ET / 10:34 UTC.

@Satoshi-Kusumoto

Copy link
Copy Markdown
Contributor Author

After further review, a complete fix would overlap with the core-side approach in #177691, so I am closing this PR in favor of it and have left a few notes from this work there. The real Discord reproduction is in #178330. Thanks for the review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: discord Channel integration: discord merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Discord: /codex detach and rebind are not saved, so the binding returns after a Gateway restart

1 participant