{
 "nextId": 151,
 "findings": [
  {
   "id": "OC-0001",
   "title": "Wrapped room keys have no freshness binding, so old offers replay forever",
   "file": "Client/tauri-client/src/lib/livekitE2EE.ts",
   "line": 772,
   "severity": "high",
   "why": "The ephemeral ECDH keypair is generated only in setupKeyExchange (:151) and reannounceForReconnect (:316); neither rotation site (:898, :996) regenerates it, so deriveWrappingKey returns identical output all session. HKDF salt/info are constants, wrapRoomKey passes no additionalData, and the wire payload carries no epoch. handleOfferInner installs whatever decrypts.",
   "repro": "Malicious server captures a voice_e2ee_offer, then replays it after a rotation. The recipient unwraps it successfully and installs the superseded key. Replayed to every peer, the room re-converges on a key a departed participant still holds, defeating membership forward secrecy. Aggravator at :783-789: accepting an offer sets _isKeyHolder=false and kills the rotation timer.",
   "evidence": "e2eeCrypto.ts:30-34 constant HKDF params; :259-286 deriveWrappingKey; livekitE2EE.ts:763 epoch guard is intra-call only; :772-773 unconditional install",
   "status": "declined",
   "found": "2026-08-09",
   "hunt": "voice-e2ee-2026-08-09",
   "lens": "crypto-primitives",
   "fix": null,
   "rationale": "Requires a protocol-level freshness field (epoch in voice_e2ee_offer via protocol-change across schema/server/client) plus a design decision on the scheme; a client-only patch cannot detect replay without a wire epoch. Architectural, not a single-file fix."
  },
  {
   "id": "OC-0002",
   "title": "A dead E2EE worker is invisible; the Secured badge cannot detect it",
   "file": "Client/tauri-client/src/components/VoiceWidget.ts",
   "line": 196,
   "severity": "high",
   "why": "The badge is derived purely from voiceStatus === 'connected', never from the SDK's live encryption state. livekit-client emits EncryptionEvent.EncryptionError from E2eeManager.onWorkerError, and src/ subscribes to none of it (zero grep hits for EncryptionEvent, ParticipantEncryptionStatusChanged, EncryptionError, isE2EEEnabled).",
   "repro": "The e2ee worker constructs successfully then fails asynchronously (CSP on a lazily-loaded chunk, WASM load failure, WebView2 quirk). keyProvider.setKey still resolves because it is local WebCrypto plus an EventEmitter.emit that never round-trips through the worker. Join completes, status goes connected, badge shows Secured.",
   "evidence": "VoiceWidget.ts:196 display toggle; livekitSession.ts:376-427 createRoom; E2eeManager.ts:242-245 emits EncryptionError",
   "status": "fixed",
   "found": "2026-08-09",
   "hunt": "voice-e2ee-2026-08-09",
   "lens": "degradation-observability",
   "fix": {
    "commit": "8579cb5d",
    "test": "Client/tauri-client/tests/unit/voice-widget.test.ts",
    "revertProof": "pass",
    "branchCommit": "a0358f41"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0003",
   "title": "Unverified peers get no safety number, removing TOFU's only out-of-band escape hatch",
   "file": "Client/tauri-client/src/lib/livekitE2EE.ts",
   "line": 477,
   "severity": "high",
   "why": "The !publishedIdentity branch accepts a peer as 'unverified' with safetyNumber: null. TOFU's designed compensation for first-contact risk is out-of-band safety-number comparison, and for exactly those peers the client renders no number to compare.",
   "repro": "A malicious server suppresses identity_public_key for one victim pairing in ready/member_join/user_update, then substitutes the ephemeral key. The peer shows a grey shield indistinguishable from a genuine legacy client, and the user has no fingerprint to verify out of band.",
   "evidence": "livekitE2EE.ts:473-481; the pinned-peer strip is already blocked at :458, so this branch is reachable only for never-pinned peers",
   "status": "declined",
   "found": "2026-08-09",
   "hunt": "voice-e2ee-2026-08-09",
   "lens": "tofu-trust-chain",
   "fix": null,
   "rationale": "A fallback safety number from the ephemeral key conflicts with the test-pinned contract that safetyNumber is null for legacy/unverified peers (livekit-session.test.ts), and substituting a weaker per-session fingerprint for the identity-based safety number is a product/security design decision, not a file-scoped fix."
  },
  {
   "id": "OC-0004",
   "title": "Key-holder promotion silently no-ops when the client's own voice_state has not arrived",
   "file": "Client/tauri-client/src/lib/livekitE2EE.ts",
   "line": 864,
   "severity": "medium",
   "why": "handleParticipantLeft early-returns when voiceUsers.get(channelId) is missing or empty. That roster is populated only by voice_state broadcasts, including the client's own. The server sends voice_token directly at voice_join.go:312 but enqueues the joiner's own voice_state on the hub broadcast queue at :337, with a GetChannelVoiceStates query in between.",
   "repro": "Client Y joins a channel where X is holder. Y starts setupKeyExchange on the token. X leaves inside the window before Y's own voice_state is delivered; X's voice_leave arrives first, removeVoiceUser empties the channel entry (voice.store.ts:245-246 deletes it), handleParticipantLeft returns at :864 and never promotes. The server has elected Y holder; Y never learns. setupKeyExchange times out at 15s and Y is ejected with e2ee_timeout.",
   "evidence": "livekitE2EE.ts:859-864; Server/ws/voice_join.go:312 vs :337",
   "status": "fixed",
   "found": "2026-08-09",
   "hunt": "voice-e2ee-2026-08-09",
   "lens": "keyholder-election",
   "fix": {
    "commit": "8579cb5d",
    "test": "Client/tauri-client/tests/unit/livekit-e2ee.test.ts",
    "revertProof": "pass",
    "branchCommit": "9e375c93"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0005",
   "title": "Rotation offers exceed the server rate limit in large channels, permanently starving the same peers",
   "file": "Client/tauri-client/src/lib/livekitE2EE.ts",
   "line": 817,
   "severity": "medium",
   "why": "voiceE2EEOfferRateLimit is 64 per (sender, channel) per second, but voice_max_users defaults to 0 (unlimited) and admins may set up to maxVoiceLimit 99. distributeRoomKey loops over every peer with no pacing, awaiting only a fast WebCrypto wrap, so all sends land in one window. ws.send is fire-and-forget; onSendFailure covers local transport failures only, never a server ErrCodeRateLimited.",
   "repro": "80-person voice channel, key holder rotates, 79 offers fire inside one second, the server drops everything past 64. _peerPublicKeys iterates in stable insertion order, so the same tail peers are starved on every subsequent rotation and stay on the old key.",
   "evidence": "Server/ws/voice_e2ee.go:23, :213-216; migrations/004_voice_optimization.sql:6; Server/admin/handlers_channels.go:148",
   "status": "fixed",
   "found": "2026-08-09",
   "hunt": "voice-e2ee-2026-08-09",
   "lens": "rotation-forward-secrecy",
   "fix": {
    "commit": "8579cb5d",
    "test": "Client/tauri-client/tests/unit/livekit-e2ee.test.ts",
    "revertProof": "pass",
    "branchCommit": "9e375c93"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0006",
   "title": "Both rotation paths call keyProvider.setKey with no session-generation guard",
   "file": "Client/tauri-client/src/lib/livekitE2EE.ts",
   "line": 900,
   "severity": "medium",
   "why": "handleParticipantLeft (:900) and rotateKeyPeriodically (:998) never capture or re-check _sessionGeneration around their setKey await. Every other destructive write in the file does; setupKeyExchange does it three times (:156, :174, :209). clearState bumps _sessionGeneration but does not touch keyProvider, which is one instance shared across Room objects.",
   "repro": "A rotation's setKey is in flight when the user leaves and rejoins. The new session installs its own key; the stale setKey resolves afterwards and leaves the live encryptor holding an abandoned key. Narrow: needs two setKey promises to resolve out of order, and distributeRoomKey's ownership check already blocks the network half.",
   "evidence": "livekitE2EE.ts:900, :998, :990 entry-only guard, :1038-1051 clearState",
   "status": "fixed",
   "found": "2026-08-09",
   "hunt": "voice-e2ee-2026-08-09",
   "lens": "rotation-forward-secrecy",
   "fix": {
    "commit": "8579cb5d",
    "test": "Client/tauri-client/tests/unit/livekit-e2ee.test.ts",
    "revertProof": "pass",
    "branchCommit": "9e375c93"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0007",
   "title": "Reconnect reaches the Secured state without confirming the room key is current",
   "file": "Client/tauri-client/src/lib/livekitE2EE.ts",
   "line": 329,
   "severity": "medium",
   "why": "reannounceForReconnect re-applies the pre-disconnect room key and fires a single voice_e2ee_announce with no wait, no timeout, and no retry. The join path blocks on a confirmed key with a 10s attempt plus a 5s retry and aborts if it never arrives.",
   "repro": "Network blip; the key rotates during the outage; the re-announce is lost or races the holder's own reconnect. The client sits on a dead key while the widget shows Secured, with no recovery bound short of the 5-minute rotation timer.",
   "evidence": "livekitE2EE.ts:309-342; livekitSession.ts:535 awaited before :549/556 set connected",
   "status": "fixed",
   "found": "2026-08-09",
   "hunt": "voice-e2ee-2026-08-09",
   "lens": "degradation-observability",
   "fix": {
    "commit": "8579cb5d",
    "test": "Client/tauri-client/tests/unit/livekit-e2ee.test.ts",
    "revertProof": "pass",
    "branchCommit": "9e375c93"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0008",
   "title": "restoreLocalVoiceState has no internal supersession guard",
   "file": "Client/tauri-client/src/lib/livekitSession.ts",
   "line": 834,
   "severity": "medium",
   "why": "await room.localParticipant.setMicrophoneEnabled can block for seconds on the mic-permission prompt. applyMicMuteState re-reads this._room fresh, so it acts on whichever room is live at resume time. connectAndSetup's checkpoint 3 (:1110) runs after the call returns and cannot prevent writes that happen mid-call.",
   "repro": "Join channel A; the permission prompt stalls; the user switches to channel B; A's continuation resumes and unpublishes B's live mic using A's captured muted value.",
   "evidence": "livekitSession.ts:834 await, unguarded writes at :845, :866-868, :871",
   "status": "fixed",
   "found": "2026-08-09",
   "hunt": "voice-e2ee-2026-08-09",
   "lens": "reconnect-stale-continuations",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Client/tauri-client/tests/unit/livekit-session.test.ts",
    "revertProof": "pass",
    "branchCommit": "db7d518b"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0009",
   "title": "attemptAutoReconnect's tail has no supersession checkpoints after connected",
   "file": "Client/tauri-client/src/lib/livekitSession.ts",
   "line": 564,
   "severity": "low",
   "why": "reconnectSuperseded is used exhaustively before newRoom.connect and never called again after the success setState. The tail runs unguarded, and startTokenRefreshTimer clobbers a single shared timer field that a newer session may have armed.",
   "repro": "Reconnect for channel 5 succeeds and sets connected. During restoreLocalVoiceState or switchActiveDevice the user joins channel 9. The stale tail resumes and runs setupAudioPipeline, reapplyMuteGain, and startTokenRefreshTimer against channel 9's session.",
   "evidence": "livekitSession.ts:564-589, no reconnectSuperseded call after :548",
   "status": "fixed",
   "found": "2026-08-09",
   "hunt": "voice-e2ee-2026-08-09",
   "lens": "reconnect-stale-continuations",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Client/tauri-client/tests/unit/livekit-session.test.ts",
    "revertProof": "pass",
    "branchCommit": "db7d518b"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0010",
   "title": "handleOfferInner and handleAnnounceInner re-check generation before their final await, not after",
   "file": "Client/tauri-client/src/lib/livekitE2EE.ts",
   "line": 784,
   "severity": "low",
   "why": "handleOfferInner's guard at :763 precedes the setKey await; the writes at :784 and :793 follow it. A teardown-and-rejoin-as-holder landing inside that await means :784 reads the new session's _isKeyHolder and stands it down. handleAnnounceInner has the same shape at :643 versus the write at :668.",
   "repro": "Non-holder in channel A receives a valid offer, passes :763, and during setKey the user leaves and rejoins channel B as holder. The stale continuation sets _isKeyHolder=false for channel B and kills its rotation timer.",
   "evidence": "livekitE2EE.ts:763 guard, :773 await, :784/:793 writes; :643 guard, :655-665 awaits, :668 write. The dangerous announce variant is blocked server-side by sendToUserIfInVoiceChannel's atomic same-channel check.",
   "status": "fixed",
   "found": "2026-08-09",
   "hunt": "voice-e2ee-2026-08-09",
   "lens": "reconnect-stale-continuations",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/livekit-e2ee.test.ts",
    "revertProof": "pass",
    "branchCommit": "15d3c9c2"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0011",
   "title": "A replayed announce overwrites a peer's live ephemeral key",
   "file": "Client/tauri-client/src/lib/livekitE2EE.ts",
   "line": 651,
   "severity": "low",
   "why": "The signed announce message is domain || userId || ephemeralPubRaw with no channel, epoch, or nonce, so an old validly-signed announce replays cleanly. handleAnnounceInner sees a changed key and overwrites the live one, logging 'peer public key changed (reconnect?)'.",
   "repro": "A malicious server re-emits a recorded announce carrying a retired ephemeral key. Subsequent offers are wrapped to a key nobody holds, silently denying that peer audio. Low because a malicious server can deny service more directly by not relaying.",
   "evidence": "livekitE2EE.ts:651-670; e2eeCrypto.ts:41-45, :101-117 buildAnnounceMessage",
   "status": "fixed",
   "found": "2026-08-09",
   "hunt": "voice-e2ee-2026-08-09",
   "lens": "tofu-trust-chain",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/livekit-e2ee.test.ts",
    "revertProof": "pass",
    "branchCommit": "15d3c9c2"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0012",
   "title": "CleanupVoiceForChannel never clears voiceKeyHolders",
   "file": "Server/ws/hub_sweep.go",
   "line": 290,
   "severity": "low",
   "why": "Every other removal path re-elects (finishVoiceLeave, the LiveKit webhook, registerNow, rollbackVoiceJoin, sweepStaleVoiceStates). Channel delete and archive do not, leaving h.voiceKeyHolders[channelID] populated.",
   "repro": "Delete a channel that had an elected holder. The map entry is never reachable and never freed — an unbounded per-deleted-channel leak for the process lifetime. On archive the next join's own updateKeyHolder overwrites it before any client can act, so there is no live desync.",
   "evidence": "Server/ws/hub_sweep.go:290-346; contrast Server/ws/voice_leave.go:102",
   "status": "blocked",
   "found": "2026-08-09",
   "hunt": "voice-e2ee-2026-08-09",
   "lens": "keyholder-election",
   "fix": null,
   "rationale": "cross-cluster edit: shares Server/db/voice_queries.go with Server/db/queries/sqlite/voice.sql - needs a human (agent edits saved in .superpowers/debris-2026-08-14.patch)",
   "blockedDate": "2026-08-14"
  },
  {
   "id": "OC-0013",
   "title": "REST DM events never bump the visibility watermark — *ws.Hub does not implement dmVisibilityMarker",
   "file": "Server/api/dm_handler.go",
   "line": 45,
   "severity": "high",
   "why": "markDMVisibilityChanged reaches the watermark bump through a type assertion to dmVisibilityMarker, but *ws.Hub has no MarkVisibilityChanged method anywhere in the repo (grep: only api/dm_handler.go and a test double define it), so the assertion always misses. The WS-side emitter of the same unsequenced, targeted dm_channel_open does bump it unconditionally (Server/ws/emit.go:41-48), so the two sibling paths disagree: hub.visibilityChangeSeq tracks WS-originated DM opens but never REST-originated ones, and mustFullResync therefore lets a client warm-resume across a REST DM change it can never be re-sent.",
   "repro": "Alice calls POST /api/v1/dms/group with Bob among recipient_ids while Bob's socket is momentarily down (or Bob's socket drops during the call). broadcastDMOpen (dm_handler.go:265) calls markDMVisibilityChanged — a no-op — then SendToUser(bob) returns false. Bob reconnects with last_seq>0; h.mustFullResync(lastSeq) is false because visibilityChangeSeq never moved, so handleReconnect serves a seq replay and sends auth_ok, NOT ready. dispatcher.ts's setDmChannels therefore never runs, so Bob's dmStore has no entry for the group. Chat messages in that channel do replay (computeAllowedChannels includes it via dm_open_state) but updateDmLastMessage/updateDmLastMessagePreview early-return on a channelId not in dmStore and incrementUnread no-ops, so the group DM is invisible in Bob's sidebar with no badge and no way to open it until a full logout/login. The same no-op affects handleCloseDM (dm_handler.go:218), PATCH rename, and the group-leave refresh. Note api/dm_handler_watermark_voice_test.go:57 asserts markCalls>=1 using a double that DOES implement the interface, so the suite is green while production is inert.",
   "evidence": "type dmVisibilityMarker interface { MarkVisibilityChanged() }\n\nfunc markDMVisibilityChanged(broadcaster DMBroadcaster) {\n\tif vm, ok := broadcaster.(dmVisibilityMarker); ok {\n\t\tvm.MarkVisibilityChanged()\n\t}\n}\n\n// contrast, same file:\nvar _ dmVoiceEvictor = (*ws.Hub)(nil)   // sibling capability IS compile-time asserted; dmVisibilityMarker is not",
   "suggestedFix": "Add `func (h *Hub) MarkVisibilityChanged() { h.bumpVisibilityWatermark() }` in Server/ws (e.g. hub.go next to bumpVisibilityWatermark), and add `var _ dmVisibilityMarker = (*ws.Hub)(nil)` in Server/api/dm_handler.go mirroring the existing dmVoiceEvictor compile-time assertion at line 63 so a future rename cannot silently re-break it.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "state-desync",
   "finder": "opus",
   "round": 2,
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/ws/hub_visibility_watermark_test.go",
    "revertProof": "pass",
    "branchCommit": "108bbe42",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0014",
   "title": "Client refreshes the LiveKit token every 23 hours while the server mints it with a 5-minute TTL, so auto-reconnect fails for any voice session older than 5 minutes",
   "file": "Client/tauri-client/src/lib/livekitSession.ts",
   "line": 714,
   "severity": "high",
   "why": "Two sources of truth for the same credential disagree by three orders of magnitude. `Server/ws/livekit.go` sets `tokenTTL = 5 * time.Minute` and documents \"The client requests a refresh via voice_token_refresh before expiry\"; the client's only periodic refresh is `TOKEN_REFRESH_MS = 23h`. Nothing else re-requests a token: `requestTokenRefresh()` is called only from that timer and once right after a successful reconnect, and it early-returns when `this._room === null` (which is the case throughout \"reconnecting\"). `handleDisconnected` hands `deps.getLatestToken()` straight to `attemptAutoReconnect`, which passes it to `newRoom.connect(resolvedUrl, token)`.",
   "repro": "Join voice, stay connected for >5 minutes, then drop the SFU connection (Wi-Fi blip, laptop sleep, SFU restart). `handleDisconnected` (roomEventHandlers.ts:161-197) starts `attemptAutoReconnect` with the join-time token, which expired at T+5min. Both attempts fail JWT validation at LiveKit, the loop exhausts, and line 640 runs `this.leaveVoice(true); leaveVoiceChannel(); onErrorCallback(\"Voice connection lost — failed to reconnect\")`. The user is ejected from the call for a blip that the reconnect path exists to absorb. The stale comment at livekitSession.ts:780-786 (\"Sessions longer than the 4h TTL…\", \"The 23h refresh timer ensures a fresh token is always ready *before* the original expires\") describes a TTL the server no longer uses. Note tests/unit/livekit-session.test.ts:2817 hardcodes the 23h advance, so it locks the constant but asserts nothing about the interop contract.",
   "evidence": "Client/tauri-client/src/lib/livekitSession.ts:714\n  private static readonly TOKEN_REFRESH_MS = 23 * 60 * 60 * 1000;\n\nServer/ws/livekit.go:28\n  // Short-lived (5 min) to limit replay window (BUG-127). The client requests\n  // a refresh via voice_token_refresh before expiry.\n  const tokenTTL = 5 * time.Minute",
   "suggestedFix": "Lower LiveKitSession.TOKEN_REFRESH_MS below the server TTL — e.g. 4 * 60 * 1000 (refresh 1 min before the 5-min expiry) — and update the stale KNOWN LIMITATION comment (livekitSession.ts:777-786) plus the three test constants that advance the timer by 23h. Optionally also have handleDisconnected request a refresh before starting attemptAutoReconnect, but the timer change alone restores the invariant the server comment documents.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "flow-voice",
   "finder": "opus",
   "round": 3,
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Client/tauri-client/tests/unit/livekit-session.test.ts",
    "revertProof": "pass",
    "branchCommit": "df221814"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0015",
   "title": "A failed voice channel-switch leaves the client live in a voice call (mic hot, audio flowing) with the voice UI completely hidden and no way to leave",
   "file": "Client/tauri-client/src/lib/dispatcher.ts",
   "line": 812,
   "severity": "high",
   "why": "The VOICE_LEAVE handler unconditionally calls the store's leaveVoiceChannel() whenever the event is about the local user (`if (isSelf) leaveVoiceChannel();`), even though the sibling effect three lines above — actually tearing down the LiveKit session — is correctly gated on `shouldTeardownSession` (payload.channel_id matching the store's *current* channel). During a channel switch the store's currentChannelId has already been optimistically set to the NEW channel by VoiceCallbacks.onVoiceJoin before the server responds, so the self voice_leave broadcast for the OLD channel (which the server always sends first, per voice_join.go's `h.handleVoiceLeave(ctx, c)` call before minting a token for the new channel) makes shouldTeardownSession false — but leaveVoiceChannel() still runs and blanks voiceStore.currentChannelId to null. In the normal success path this is harmless because a voice_state broadcast for the new channel (VOICE_STATE handler, dispatcher.ts:745, `joinVoiceChannel(payload.channel_id)`) arrives shortly after and restores currentChannelId. But when the switch fails server-side — e.g. voice_join.go:158-179's `LeaveVoiceChannelIfMatch` retry for the old channel's DB row fails, so GetVoiceState still returns the old row and the join is aborted — the server never sends a voice_token or a voice_state for either channel; it only sends a generic ErrCodeInternal error ('voice channel switch failed — please try again'), which dispatcher.ts's S.ERROR handler does not specially handle for this code (it falls through to the generic setTransientError toast at dispatcher.ts:1002, with no voiceStore write). So voiceStore.currentChannelId is permanently stuck at null with nothing left to restore it. Meanwhile voice_leave.go's finishVoiceLeave() unconditionally calls `h.livekit.RemoveParticipant(ctx, oldChID, c.userID, oldJoinToken)` (voice_leave.go:108-114) regardless of whether the DB delete succeeded, forcibly kicking the client's still-live LiveKit Room object (the client never ran connectAndSetup()/leaveVoice() for this failed switch, since it never got a voice_token) out of the SFU. That kick fires roomEventHandlers.ts's handleDisconnected with a non-CLIENT_INITIATED reason; its auto-reconnect branch (roomEventHandlers.ts:172-198) decides whether to reconnect using `deps.getCurrentChannelId()`, which is LiveKitSession's own internal `_currentChannelId` getter (livekitSession.ts:207-211, derived from `_state`) — completely independent of voiceStore.currentChannelId. Since `_state` was never touched by the failed switch, `_currentChannelId` still points at the old channel with a valid cached token/URL, so attemptAutoReconnect silently reconnects the client back into the old channel's LiveKit room, republishes the microphone (restoreLocalVoiceState), and sets voiceStatus to 'connected' (livekitSession.ts:548-556) — all without ever calling joinVoiceChannel() to resync voiceStore.currentChannelId.",
   "repro": "User is in voice channel A (fully joined, mic live). They click to switch to channel B (VoiceCallbacks.onVoiceJoin optimistically sets voiceStore.currentChannelId=B and sends voice_join). Server-side, handleVoiceJoin leaves channel A first; the DB's LeaveVoiceChannelIfMatch delete for the A row transiently fails (busy DB, timeout, etc.) but RemoveParticipant(A) and the voice_leave(A) broadcast still fire unconditionally. The client's VOICE_LEAVE(A) handler blanks voiceStore.currentChannelId to null (dispatcher.ts:812) since shouldTeardownSession is false (currentChannelId was already B) so it never calls session.leaveVoice(). Server then finds the stale A row still present, aborts the switch, restores its own hub state to channel A, and returns only a generic error — no voice_token/voice_state ever reaches the client, so nothing ever sets currentChannelId back to A or B. The client's still-live Room for channel A, kicked by RemoveParticipant, fires handleDisconnected, which — driven by LiveKitSession's own internal channel state, not the store — auto-reconnects back into channel A's LiveKit room and republishes the microphone. End state: voiceStore.currentChannelId is null (VoiceWidget.render() at VoiceWidget.ts:220 hides the entire widget when null, and ChannelSidebar.ts:335's `isJoined` is also false for row A) while the user is actually connected to channel A's SFU with a live, transmitting microphone and an intact E2EE session — invisible to the user, who has no on-screen mute/leave/status affordance until they happen to click channel A's row again (which itself would only start a *new* join attempt, tearing down the phantom session as a side effect of `connectAndSetup`'s `if (this._room !== null) this.leaveVoice(false)`).",
   "suggestedFix": "Gate the teardown on the SESSION's live channel rather than only the store's: in the VOICE_LEAVE handler, tear down when isSelf and the LiveKit session's current channel id equals payload.channel_id (expose it from livekitSession alongside leaveVoice). The stale-leave protection test still holds (after a completed rejoin the session's channel is the new one), and every failed-switch variant then converges to a clean idle state instead of a hidden live session. Server-side hardening (send a voice_state resync in the voice_join abort branch) can follow, but the client guard alone removes the hot-mic state.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "flow-voice",
   "finder": "sonnet",
   "round": 3,
   "confidence": "medium",
   "fix": {
    "commit": "8579cb5d",
    "test": "Client/tauri-client/tests/unit/dispatcher.test.ts",
    "revertProof": "pass",
    "branchCommit": "1a47c85a"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0016",
   "title": "Re-opening a channel visited earlier in the session renders a permanently stale message window — loadMessages short-circuits on isChannelLoaded and nothing invalidates on switch",
   "file": "Client/tauri-client/src/pages/main-page/MessageController.ts",
   "line": 76,
   "severity": "high",
   "why": "`loadMessages` returns immediately when the channel is already in `loadedChannels`, and `loadedChannels` is only ever cleared by `invalidateLoadedMessageWindows()` (dispatcher's second-`ready` full-resync path) and `clearChannelMessages()` — which has no caller anywhere in `src/`. Combined with the focus-scoped fan-out above, every message posted in a channel while the user was viewing a different one is absent from the store, never delivered live, and never refetched. The stale window is what MessageList renders on the way back, with no gap indicator and no way for the user to force a refresh short of restarting the app.",
   "repro": "Open channel A (50 messages fetched, `loadedChannels` = {A}). Switch to channel B — the server unsubscribes the socket from `channel:A`. Ten messages are posted in A; none reach this client. Switch back to A: `MainPage`'s activeChannelId subscriber calls `mountChannel(A)` → `loadMessages(A)` → `isChannelLoaded(A)` is true → early return. MessageList renders the 50-message snapshot from the first visit; the 10 new messages are missing with no \"has more below\" affordance, and stay missing for the rest of the session (scroll-up only calls `loadOlderMessages`, which prepends).",
   "evidence": "Client/tauri-client/src/pages/main-page/MessageController.ts:76-79  `if (isChannelLoaded(channelId)) { log.debug(\"Messages already loaded\", { channelId }); return; }`\nClient/tauri-client/src/pages/main-page/ChannelController.ts:245  `void msgCtrl.loadMessages(channelId, signal);` — the only load on mount; `mountChannel` does not clear the window\nClient/tauri-client/src/stores/messages.store.ts:746 `clearChannelMessages` — `grep -rn \"clearChannelMessages\" src/` matches only its own definition\nClient/tauri-client/src/lib/dispatcher.ts:311  `invalidateLoadedMessageWindows();` — reached only when `hasReceivedReadyBefore` (a full-ready resync)",
   "suggestedFix": "In ChannelController.mountChannel, when previousChannelId !== null, drop that channel from loadedChannels (export a store helper mirroring reattachToPresent's Set-delete, without requiring the detached flag) so the next visit refetches the live tail; setMessages' existing merge already preserves pending/failed rows and newer live rows, so the refetch cannot clobber in-flight state.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "flow-message",
   "finder": "opus",
   "round": 3,
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "ff17920",
    "test": "Client/tauri-client/tests/unit/channel-controller.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0017",
   "title": "Virtual scroll window never follows the scroll position — rows outside the initial ±20-item overscan render as blank space",
   "file": "Client/tauri-client/src/components/MessageList.ts",
   "line": 536,
   "severity": "high",
   "why": "renderWindow() only rebuilds DOM when `renderedStart < 0`, and the only two callers that set that sentinel are renderAll() and scrollToMessage(). Every scroll-driven call therefore lands in the `else` branch, which is a pure no-op — it does not even update the spacers its own comment on line 496-497 claims it updates. The rendered window is frozen wherever the last data-change rebuild left it, so scrolling into the top/bottom spacer shows an empty region with no rows, and nothing ever fills it.",
   "repro": "Open a channel whose full history is loaded (hasMoreMessages(channelId) === false) and that holds ~300 messages. mount() → renderAll() positions the window at the tail (~41 items ≈ 2.5k px). Scroll up past that: handleScroll → requestAnimationFrame → renderWindow() → renderedStart is 0-or-greater → else branch → nothing rendered. The area above the frozen window is the top spacer (offsetBefore(renderedStart) px of empty div) and stays blank indefinitely, because the scroll-top fetch is gated on hasMoreMessages and no store update fires. The only escape is an unrelated store event (new message, role revision bump) that triggers renderAll and re-centres the window on the current scrollTop. tests/unit/message-list.test.ts:244 (\"scrollToMessage renders a target that was outside the rendered window\") documents the same frozen-window behaviour rather than locking it as intended.",
   "evidence": "if (renderedStart < 0) { … full rebuild … } else {\n  // Scroll-driven: no-op. The ResizeObserver handles measurement and\n  // spacer updates when element sizes change.\n}\n// called from: handleScroll → scrollRafId = requestAnimationFrame(() => { scrollRafId = 0; renderWindow(); })",
   "suggestedFix": "In renderWindow's else branch, detect that the freshly computed [start,end) range is not contained in [renderedStart,renderedEnd) and take the rebuild path in that case (the existing >30-rebuilds-per-2s renderWindowCount breaker already guards the image-height oscillation loop the no-op was written to avoid); keep the no-op only when the target range is already fully rendered.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "opus",
   "round": 5,
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "7e22fe7",
    "test": "Client/tauri-client/tests/unit/message-list.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0018",
   "title": "voice_join into a 1:1 DM has no block gate — a blocked user can enter the blocker's DM voice room and publish audio to them",
   "file": "Server/ws/voice_join.go",
   "line": 64,
   "severity": "high",
   "why": "Every other 1:1-DM interaction sink routes through service.requireDMNotBlocked (send, edit, delete, react, pin, typing, and call_ring — see service/message_perms.go:92-118, whose own doc comment claims it is \"called from every DM interaction sink\"). The voice path's only gate is hasChannelAccess, which by construction never consults blocks, and grep shows the entire ws/ package contains no IsEitherBlocked / requireDMNotBlocked call. Blocking never touches dm_participants (service/block.go:48 calls only st.BlockUser), so IsDMParticipant still returns true and the blocked user passes straight through.",
   "repro": "Bob blocks Alice (PUT /api/v1/blocks/{alice}). Alice sends {\"type\":\"voice_join\",\"payload\":{\"channel_id\":<their 1:1 DM channel id>}} over WS. hasChannelAccess passes: the default Member role holds CONNECT_VOICE 0x200 (migrations/007_member_video_permissions.sql sets Member = 0x1E63) and IsDMParticipant(alice, dm) is still true because BlockUser does not remove participant rows. handleVoiceJoin then persists a voice_states row, mints a LiveKit token with RoomJoin + CanPublishSources [\"microphone\", \"camera\", \"screen_share\"] for room channel-<dmID> (ws/livekit.go:110-121), and broadcastVoiceEvent resolves the DM audience to its participants (ws/hub_broadcast.go:149-166), so Bob's client receives Alice's voice_state and renders her as present in that DM's call (Client dispatcher.ts:740 -> updateVoiceState). Alice can repeat this within the 5/s voice_join limit to spam Bob's UI with voice_state/voice_leave, and if Bob is in that room her microphone audio reaches him. The identical channel's call_ring is correctly refused with FORBIDDEN — the block is enforced on the doorbell but not on the door.",
   "evidence": "ws/voice_join.go:64 — `if !h.requireChannelAccess(ctx, c, channelID, permissions.ConnectVoice, \"CONNECT_VOICE\") {` is the only authorization on the join; ws/deps.go:190-193 — \"Blocking is deliberately not consulted here: it is the message paths' rule (service.requireDMNotBlocked), it is two-party only, and a blocked user is still a participant, so it is orthogonal to the non-participant hole this closes.\"; the same gate is reused for re-minting at ws/voice_join.go:418 (`hasChannelAccess(... permissions.ConnectVoice)` in handleVoiceTokenRefreshV2). Contrast service/dm.go:368 (`requireDMNotBlocked` inside RingTargets), added for A-2026-08-03 and locked by ws/dm_group_call_test.go:344 TestCallRing_BlockedOneToOneForbidden.",
   "suggestedFix": "Expose service.requireDMNotBlocked (e.g. a DMService method) and call it in handleVoiceJoin right after the ch.Type == \"dm\" branch (voice_join.go:82-85), refusing with FORBIDDEN; group DMs are already exempt inside requireDMNotBlocked. Reuse the same call in handleVoiceTokenRefreshV2 next to its hasChannelAccess gate (voice_join.go:418) so a mid-session block also evicts on refresh.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-ws",
   "finder": "opus",
   "round": 6,
   "confidence": "medium",
   "fix": {
    "commit": "8579cb5d",
    "test": "Server/ws/voice_dm_access_test.go",
    "revertProof": "pass (manual: voice_join.go reverted alone, DMBlocked tests red, green at HEAD)",
    "branchCommit": "423f9cbc"
   },
   "declinedDate": "2026-08-14",
   "notes": "Reopened 2026-08-14: advisory-path routing dropped per user decision; fix lands in normal PR with sanitized messaging.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0019",
   "title": "Disconnect teardown decides `replaced` before a multi-second voice cleanup, then stamps the already-reconnected user offline",
   "file": "Server/ws/serve_pumps.go",
   "line": 186,
   "severity": "medium",
   "why": "readPump's defer samples `replaced := hub.unregisterNow(c)` at line 148 and then reuses that stale boolean at line 186 to gate `MarkUserDisconnected` (196) and the global offline presence broadcast (203). Between those two points it runs `hub.handleVoiceLeave(cleanupCtx, c)` (157), which does a DB delete, a per-connected-user permission scan in `channelReadAudience`, and a `livekit.RemoveParticipant` HTTP call bounded only by `lkTimeout = 5s` (Server/ws/livekit.go:151). A reconnect that registers during that window is invisible to the stale flag, so the dead socket's teardown marks the live session offline. `hub_sweep_test.go:87` documents that `replaced` exists precisely so \"a reconnect's teardown does not mark the live connection's user offline\" — the guard is simply evaluated too early to hold.",
   "repro": "User U is connected as client A and is in voice channel V; LiveKit is unreachable/slow. (1) A's socket drops. readPump's defer snapshots voiceChID=V and calls unregisterNow(A), which finds A in h.clients, deletes it, and returns replaced=false. (2) The defer enters handleVoiceLeave, which blocks up to 5s in RemoveParticipant. (3) U's client reconnects: authenticateConn succeeds, handleReconnect (or handleFreshConnect) calls registerNow(B) so h.clients[U]=B, then applyConnectStatus writes users.status='online' and announceConnectPresence broadcasts presence{U, online}. (4) A's defer resumes with the stale replaced=false: MarkUserDisconnected(U) flips users.status back to 'offline' (db/dbgen/users.sql.go:185) and BroadcastToAll(presence{U, offline}) reaches every peer. Result: U is live on socket B but renders offline on every already-connected client, and a client that connects later reads users.status='offline' from ListMembers (presentableMembers only downgrades non-connected users, never upgrades). Nothing re-announces until U changes status or reconnects again.",
   "evidence": "148: replaced := hub.unregisterNow(c)\n156:\t\t\tif voiceChID != 0 && !replaced {\n157:\t\t\t\thub.handleVoiceLeave(cleanupCtx, c)   // DB + audience scan + 5s LiveKit call\n186:\t\t\tif !replaced {\n196:\t\t\t\t_ = hub.db.MarkUserDisconnected(cleanupCtx, c.userID)\n203:\t\t\t\thub.BroadcastToAll(buildPresenceMsg(c.userID, db.StatusOffline, nil))",
   "suggestedFix": "In readPump's defer (and unregisterFailedHandshake), re-evaluate liveness at decision time instead of reusing the pre-cleanup snapshot: gate the MarkUserDisconnected + offline broadcast on `!replaced && hub.GetClient(c.userID) == nil` (any entry present after unregisterNow removed c is necessarily a newer connection), evaluated immediately before line 196 — after handleVoiceLeave returns.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "ws-hub",
   "finder": "opus",
   "round": 1,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Server/ws/serve_pumps_reconnect_race_test.go",
    "revertProof": "pass",
    "branchCommit": "250a7819"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0020",
   "title": "Stale `_isKeyHolder` survives a voice-channel switch made while the SFU is reconnecting, so the client joins the new channel as a phantom key holder",
   "file": "Client/tauri-client/src/lib/livekitE2EE.ts",
   "line": 188,
   "severity": "medium",
   "why": "`setupKeyExchange` ORs the server-authoritative `is_key_holder` with whatever `_isKeyHolder` already holds. Its stated justification is that `clearState()` always runs between sessions (so a non-false residue can only be an in-window `handleParticipantLeft` promotion). That invariant is broken by `connectAndSetup`, which only tears E2EE state down via `if (this._room !== null) this.leaveVoice(false);` (livekitSession.ts:933) — and `_room` (livekitSession.ts:202) is null in the `reconnecting` state. A join issued while the LiveKit auto-reconnect loop is running therefore reaches `setupKeyExchange` with `_isKeyHolder` still true from the previous channel, and the server's `false` is discarded.",
   "repro": "1. User (uid 5) is alone/lowest in voice channel A, so the server sent `is_key_holder=true`; `_isKeyHolder === true`, rotation timer armed.\n2. The LiveKit SFU connection drops (network blip). `handleDisconnected` -> `setRoom(null)` -> `setReconnectAc(ac)` puts `_state` in `reconnecting` (livekitSession.ts:319-334). The WS socket is unaffected, so the sidebar's `onVoiceJoin` guard (`socketLive()`, VoiceCallbacks.ts:173) still passes.\n3. During the reconnect loop (MAX_RECONNECT_ATTEMPTS=2, RECONNECT_DELAY_MS=3000, plus URL resolution/connect time) the user clicks voice channel B, which already has a lower-uid participant. Server: `computeIsKeyHolder(B, 5)` -> false, sends `voice_token` with `is_key_holder=false`.\n4. `handleVoiceToken` -> state is `reconnecting`, so neither the `connected` fast path nor the `_connecting` queue applies -> `connectAndSetup(...)`. `this._room` is null, so `leaveVoice(false)` is skipped and `_e2ee.clearState()` never runs.\n5. `setupKeyExchange(false, B)` executes `this._isKeyHolder = false || true` -> true. The client bumps the epoch, generates its OWN room key, applies it to the shared `keyProvider`, arms a 5-minute rotation timer, sends only an announce, and returns true immediately — skipping the entire non-key-holder wait/timeout path.\n6. `connectAndSetup` proceeds to `room.connect()` and `setVoiceStatus(\"connected\")`. The client now publishes SFrame-encrypted audio under a key nobody in B holds and cannot decrypt any peer, while the UI reports the call connected/secured. Every `voice_e2ee_offer` it sends is rejected server-side with `NOT_KEY_HOLDER` (Server/ws/voice_e2ee.go:198). Recovery depends entirely on B's real key holder answering the announce with an offer (handleOfferInner's stand-down at livekitE2EE.ts:783); if that offer never arrives — holder is TOFU-blocked on us, rate-limited (voice_e2ee.go:214-223), or mid-join — the client stays silently deaf and mute forever, because the 10s+5s `e2ee_timeout` safety net that would have ejected a real non-holder was never entered. Meanwhile the phantom rotation timer regenerates a fresh useless room key every 5 minutes.",
   "evidence": "livekitE2EE.ts:188  `this._isKeyHolder = isKeyHolder || this._isKeyHolder;`\nlivekitE2EE.ts:190-203  `if (this._isKeyHolder) { this._e2eeEpoch++; this._roomKey = generateRoomKey(); await this.keyProvider.setKey(...); this.startKeyRotationTimer(); }`\nlivekitE2EE.ts:230-232  `if (this._isKeyHolder) { ...send announce... } else { /* wait up to 10s+5s for an offer, else return false */ }`\nlivekitSession.ts:933  `if (this._room !== null) this.leaveVoice(false);`\nlivekitSession.ts:202-204  `private get _room(): Room | null { return this._state.type === \"connected\" ? this._state.room : null; }`\nlivekitSession.ts:329-357  `teardownForReconnect` — tears down the audio pipeline/tracks, never calls `_e2ee.clearState()`\nlivekitSession.ts:1370-1379  `leaveVoice()` is the sole caller of `this._e2ee.clearState()`",
   "suggestedFix": "In connectAndSetup, treat superseding an in-flight reconnect the same as superseding a live room: change livekitSession.ts:933 to `if (this._room !== null || this._state.type === \"reconnecting\") this.leaveVoice(false);`. leaveVoice(false) aborts the stale reconnect AbortController and runs _e2ee.clearState(), bumping _sessionGeneration so line 188's OR can only preserve promotions that land during THIS setupKeyExchange call (the B3-2 behavior), never residue from a prior session.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "voice-e2ee",
   "finder": "opus",
   "round": 1,
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Client/tauri-client/tests/unit/livekit-session.test.ts",
    "revertProof": "pass",
    "branchCommit": "9e375c93"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0021",
   "title": "Login builds a rate-limiter key from the unvalidated username, so an unauthenticated caller pins ~1 MiB of heap per request for 6 hours",
   "file": "Server/api/auth_handler.go",
   "line": 353,
   "severity": "medium",
   "why": "handleLogin never length-checks req.Username (its sibling handleRegister calls auth.ValidateUsername, max 32 runes, before touching anything). The raw string becomes a RateLimiter map key, and RateLimiter.Allow inserts that key into the shard map before the limit test, while RateLimiter.Cleanup only evicts an entry once every recorded timestamp is older than rateLimiterCleanupMaxWindow — 6 hours. An attacker-chosen, body-sized key is therefore retained for 6 hours per attempt on an endpoint that requires no credentials.",
   "repro": "POST /api/v1/auth/login with body {\"username\":\"<1 MiB of 'a'>\",\"password\":\"x\"}. The user does not exist, so GetUserByUsername returns (nil,nil), execution reaches line 366-367, and \"login_user_fail:\" + the 1 MiB string is stored in RateLimiter.shards[h].windows. The response is 401, but the key stays resident until a Cleanup pass finds its timestamp older than 6 hours. The route's own IP limiter permits loginRateLimitPerMinute = 5 such requests per minute per source, i.e. ~5 MiB/min retained, ~1.8 GiB resident at steady state from a single IP (more from several). Sending 10 identical oversized usernames additionally trips the per-username lockout, which persists the same ~1 MiB key into the lockouts table via RateLimiter.Lockout -> UpsertLockout, and that row is reloaded into memory by NewPersistentRateLimiter on every restart. The identical input to POST /api/v1/auth/register is rejected at api/auth_handler.go:192 before any allocation.",
   "evidence": "api/auth_handler.go:323  unameKey := strings.ToLower(req.Username)\napi/auth_handler.go:324  userLockKey := \"login_user_lock:\" + unameKey\napi/auth_handler.go:353  userFailKey := \"login_user_fail:\" + unameKey\napi/auth_handler.go:366  if !limiter.Allow(failKey, loginFailureThreshold+1, loginFailureWindow) ||\napi/auth_handler.go:367     !limiter.Allow(userFailKey, loginUserFailureThreshold+1, loginUserFailureWindow) {\n\nauth/ratelimit.go:134  e, ok := s.windows[key]\nauth/ratelimit.go:136      e = &entry{}\nauth/ratelimit.go:137      s.windows[key] = e   // inserted even when the call is then refused\n\nauth/ratelimit.go:249  cutoff := time.Now().Add(-maxWindow)          // maxWindow == 6h in production\nauth/ratelimit.go:255  for key, e := range s.windows { ... if ts.After(cutoff) { allStale = false } }\nauth/ratelimit.go:263      if allStale { delete(s.windows, key) }        // entry survives ~6h after its last use\n\napi/constants.go:133  rateLimiterCleanupMaxWindow = 6 * time.Hour\napi/router.go:52      r.Use(MaxBodySizeUnless(defaultMaxBodySize, ...))   // defaultMaxBodySize = 1 MiB, /auth/login not exempt",
   "suggestedFix": "In handleLogin, reject or clamp an over-long username before building unameKey — e.g. after the empty check add `if len(req.Username) > maxUsernameKeyLen { return 400 }` (or truncate the value used to key the limiter), so an unbounded body-sized string can never become a retained map/DB key. maxUsernameLength (32 runes) is the natural bound.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "api-authz",
   "finder": "opus",
   "round": 1,
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Server/api/auth_handler_test.go",
    "revertProof": "pass",
    "branchCommit": "47eeb930"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0022",
   "title": "The archived-channel read-only gate exists only on SendMessage; edit, reaction, pin and purge still mutate an archived channel",
   "file": "Server/service/message_crud.go",
   "line": 268,
   "severity": "medium",
   "why": "SendMessage refuses an archived channel (message_crud.go:54) because \"any caller that still held the id ... could keep posting into an archive indefinitely\". EditMessage routes its non-DM gate through checkSendPermission, which carries no archived check, and the same is true of handleReaction, SetMessagePinned and PurgeMessages. So the archive is still writable: an author can inject arbitrary new text into an archived channel and it is fanned out as chat_edited to every reader with READ_MESSAGES, and a MANAGE_MESSAGES holder can still pin or bulk-delete there.",
   "repro": "Admin PATCHes /admin/api/channels/{id} with archived=true. Alice, who previously posted message M in that channel and still holds its id, sends the WS chat_edit command for M with new content: EditMessage passes checkSendPermission (her base READ|SEND bits are untouched by archiving) and commits the new text, broadcasting chat_edited to every client that can read the channel — while the identical chat_send is refused with ErrForbidden \"channel is archived\" (locked by service/archived_channel_readonly_test.go). The same holds over REST: POST /api/v1/channels/{id}/pins/{messageId} (api/channel_handler.go:73) and POST /api/v1/channels/{id}/messages/purge (api/channel_handler.go:70) both succeed against the archived channel.",
   "evidence": "message_crud.go:54   if !isDM && ch.Archived { return ...ErrForbidden: channel is archived }   // send only\nmessage_crud.go:268  } else if permErr := s.checkSendPermission(ctx, userID, msg.ChannelID, chanType); permErr != nil {\n                     // comment: \"an edit injects new text into the channel and is fanned out to every\n                     //  reader, so it must clear the same gate as a send\" — but checkSendPermission\n                     //  (message_perms.go:69-90) never consults ch.Archived\nmessage_query.go:215 } else if !s.perms.HasChannelPerm(ctx, userID, channelID, ReadMessages|ManageMessages)  // SetMessagePinned, no archived check\nmessage_purge.go:55  same, PurgeMessages\nmessage_reactions.go:116 same, handleReaction\nadmin/handlers_channels.go:260 \"Archiving hides a voice channel the same way deleting it does — nobody can see it or reach it afterward\"",
   "suggestedFix": "Add the archived read-only check to the shared write policy so all mutation paths inherit it: put `if ch.Type != \"dm\" && ch.Archived { return ErrForbidden }` inside checkSendPermission (covers EditMessage and CanPost), and add the same guard to SetMessagePinned, PurgeMessages and handleReaction (which bypass checkSendPermission), ideally via one requireWritableChannel(ch) helper called from every write sink.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "api-authz",
   "finder": "opus",
   "round": 1,
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Server/service/archived_channel_readonly_test.go",
    "revertProof": "pass",
    "branchCommit": "8ad4f59d"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0023",
   "title": "ListMembers hides users whose temporary ban has lapsed, while every other path treats them as active",
   "file": "Server/db/queries/sqlite/users.sql",
   "line": 58,
   "severity": "medium",
   "why": "ListMembers filters on the raw `u.banned = 0` column, but nothing ever clears `banned` when `ban_expires` passes — expiry is evaluated lazily by `auth.IsEffectivelyBanned` (auth/helpers.go:73) and by `db.notBannedClause` (db/mention_queries.go:40). A user whose temp ban has lapsed can therefore authenticate (ws/serve_auth.go:85), post, and be resolved as an @mention/@everyone target, yet is absent from the `members[]` roster the ready payload is built from (ws/serve_ready.go:153 -> db/auth_queries.go:545). The two sources of truth disagree — exactly the hazard the notBannedClause comment was written to close, applied to mentions but not to the roster.",
   "repro": "Ban user B with a 1-hour expiry (ModerationService.BanUser -> db.BanUser writes banned=1, ban_expires=now+1h). Wait for the expiry to pass. B logs in: api/middleware.go:131 and ws/serve_auth.go:85 both call auth.IsEffectivelyBanned, which returns false, so the connection is accepted. B sends a message and is a valid @mention target (GetUserIDsByUsernames uses notBannedClause). But every connected client's `ready` payload — B's own included — omits B from members[], because ListMembers still sees banned=1. Result: B's messages render with no member entry (no avatar, no role colour), B is missing from the member sidebar and from mention autocomplete, and B cannot be opened from the roster. TestListMembers_ExcludesBanned (db/auth_queries_test.go:755) only covers a permanent ban (expires=nil), so this case is not test-locked.",
   "evidence": "users.sql:53-59\n-- name: ListMembers :many\nSELECT u.id, u.username, u.avatar, u.status, LOWER(r.name), u.identity_public_key,\n       u.display_name, u.custom_status\nFROM users u\nJOIN roles r ON u.role_id = r.id\nWHERE u.banned = 0\nORDER BY u.username ASC;\n\n-- vs db/mention_queries.go:40 (the same question, answered differently)\nconst notBannedClause = `(banned = 0 OR (ban_expires IS NOT NULL AND replace(ban_expires, ' ', 'T') <= strftime('%Y-%m-%dT%H:%M:%SZ', 'now')))`",
   "suggestedFix": "Via the db-change skill, change ListMembers' WHERE clause in Server/db/queries/sqlite/users.sql to the same lapsed-ban test as db.notBannedClause: WHERE (u.banned = 0 OR (u.ban_expires IS NOT NULL AND replace(u.ban_expires, ' ', 'T') <= strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))), then regenerate Server/db/dbgen/.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "db-storage",
   "finder": "opus",
   "round": 1,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Server/db/auth_queries_test.go",
    "revertProof": "pass",
    "branchCommit": "45dd39f7"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0024",
   "title": "channel_focus re-subscribes after a concurrent visibility revoke, leaving a demoted user permanently subscribed to a channel they can no longer READ",
   "file": "Server/ws/handlers.go",
   "line": 170,
   "severity": "medium",
   "why": "The READ_MESSAGES check for channel_focus happens inside the handler (service/channel.go:245), but the pub/sub Subscribe that acts on it happens later, in the applier, with two SQLite round-trips in between. Nothing re-validates at Subscribe time, and the revoke sweeps (Hub.RefreshChannelVisibility / Hub.revokeUnreadableChannels) only ever Unsubscribe what the socket holds at the instant they run — so a Subscribe landing after the sweep is never undone.",
   "repro": "User U is a member of role R, currently focused on channel 5. U's client sends channel_focus{channel_id:7} (7 is readable at that moment). On U's readPump goroutine, HandleChannelFocus passes the READ check at service/channel.go:245 and then blocks in GetLatestMessageID/UpdateReadState. Concurrently an admin POSTs a channel_overrides change denying R READ_MESSAGES on channel 7: admin/handlers_channel_perms.go:164 calls permInvalidator.InvalidateAll(), then :167 calls hub.RefreshChannelVisibility(ch7), which sends U a channel_delete, runs pubsub.Unsubscribe(c, ChannelTopic(7)) (a no-op — U is not subscribed yet, focus is still 5) and clears c.channelID if it equals 7 (it does not). The admin request finishes. U's handler now returns SetChannelID=7, and handlers.go:170 runs pubsub.Subscribe(c, ChannelTopic(7)) plus sets c.channelID=7. U is now subscribed to channel 7's topic with no READ permission and nothing left to revoke it: every subsequent chat_message / chat_edited / chat_deleted / reaction_update published to channel 7 is delivered to U for the remaining lifetime of the socket. The same window exists for revokeUnreadableChannels on a role reassignment (hub_broadcast.go:534-562).",
   "evidence": "handlers.go applier:\n\tif result.SetChannelID != nil {\n\t\toldChID := c.getChannelID()\n\t\tc.mu.Lock(); c.channelID = *result.SetChannelID; c.mu.Unlock()\n\t\tnewChID := *result.SetChannelID\n\t\tif oldChID != newChID {\n\t\t\tif oldChID > 0 { c.hub.pubsub.Unsubscribe(c, ChannelTopic(oldChID)) }\n\t\t\tif newChID > 0 { c.hub.pubsub.Subscribe(c, ChannelTopic(newChID)) }   // <- line 170, no re-check\n\t\t}\n\t}\n\nservice/channel.go HandleChannelFocus (the only gate):\n\t} else if !s.perms.HasChannelPerm(ctx, userID, channelID, permissions.ReadMessages) {   // line 245\n\t\treturn nil, fmt.Errorf(\"%w: access denied\", ErrForbidden)\n\t}\n\tlatestID, err := s.st.GetLatestMessageID(ctx, channelID)   // DB round trip 1\n\tif err == nil { _ = s.st.UpdateReadState(ctx, userID, channelID, latestID) }   // DB round trip 2\n\nhub_broadcast.go RefreshChannelVisibility (the revoke, line 350-356):\n\t\tc.sendMsg(buildChannelDelete(ch.ID))\n\t\th.pubsub.Unsubscribe(c, ChannelTopic(ch.ID))\n\t\tc.mu.Lock(); if c.channelID == ch.ID { c.channelID = 0 }; c.mu.Unlock()",
   "suggestedFix": "In the handlers.go applier, after pubsub.Subscribe(c, ChannelTopic(newChID)), re-validate access with a live check (hasChannelAccess, as used by requireChannelAccess) and on failure Unsubscribe + clear c.channelID. Subscribe-then-recheck closes the window in both orders: a revoke committing before the recheck is seen by the recheck; a revoke committing after finds the subscription present and its sweep removes it.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "concurrency",
   "finder": "opus",
   "round": 2,
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/ws/handler_focus_revoke_race_test.go",
    "revertProof": "pass",
    "followUp": "3026ddf2",
    "branchCommit": "cc82417f",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0025",
   "title": "enableCamera has no supersession re-check after publishTrack, so a concurrent disableCamera leaves the server and every peer believing the camera is on",
   "file": "Client/tauri-client/src/lib/screenShare.ts",
   "line": 243,
   "severity": "medium",
   "why": "The generation guard is checked only after device acquisition (line 235), not after the awaited publishTrack. A disableCamera that runs during the publish round-trip bumps the generation, unpublishes/stops the track and sends voice_camera{enabled:false}; the superseded enableCamera then resumes and sends voice_camera{enabled:true}, so the last frame the server sees says the camera is on while the local store says off and no track exists.",
   "repro": "In a live voice channel the user clicks the camera toggle on. enableCamera acquires the device, sets state.manualCameraTrack and awaits room.localParticipant.publishTrack (an SFU negotiation round trip, tens to hundreds of ms). Before it resolves the user clicks the toggle off (or the dispatcher's VIDEO_LIMIT/error handler calls disableCamera — dispatcher.ts:992/1018). disableCamera bumps state.generation, stopManualCameraTrack clears state.manualCameraTrack and stops the MediaStreamTrack, setLocalCamera(false) runs and voice_camera{enabled:false} is sent. publishTrack then resolves; enableCamera continues past line 243 with no generation check and sends voice_camera{enabled:true} at line 251. Server-side ordering is false then true, so the DB row and the voice_state broadcast say camera=true: every peer renders a camera tile for a participant whose track was stopped, while the local voiceStore has localCamera=false, so the user's next toggle click sends enabled:true again and there is no single click that turns it off.",
   "evidence": "    if ((state.generation ?? 0) !== generation) {          // 235 - only guard\n      videoTrack.stop();\n      return;\n    }\n    state.manualCameraTrack = videoTrack;                   // 242\n    await room.localParticipant.publishTrack(videoTrack, {  // 243 - awaited, no guard after\n      ...\n    });\n    const sendId = ws.send({ type: \"voice_camera\", payload: { enabled: true } });  // 251\n\nexport async function disableCamera(state, deps) {\n  bumpGeneration(state);                                    // 276\n  stopManualCameraTrack(state, room);                       // unpublishes + stops the in-flight track\n  ...\n  finally { setLocalCamera(false); ws.send({ type: \"voice_camera\", payload: { enabled: false } }); }",
   "suggestedFix": "After the awaited publishTrack (and before the ws.send at 251), re-check (state.generation ?? 0) !== generation; on supersession, unpublish and stop videoTrack, clear state.manualCameraTrack if it still points at it, and return without sending voice_camera(true).",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "concurrency",
   "finder": "opus",
   "round": 2,
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "0db0433",
    "test": "Client/tauri-client/tests/unit/screen-share-tracks.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0026",
   "title": "enableScreenshare has no supersession re-check across its publish loop, so a concurrent stop still announces the share as on",
   "file": "Client/tauri-client/src/lib/screenShare.ts",
   "line": 345,
   "severity": "medium",
   "why": "Same missing post-await guard as enableCamera, but worse: the loop publishes tracks from the local `screenTracks` array while disableScreenshare has already emptied state.manualScreenTracks, so the remaining publishes are made against tracks the disable path can no longer reach, and the final ws.send announces enabled:true after the disable already announced enabled:false.",
   "repro": "The user picks a window in the OS share picker; every quality preset requests audio alongside video, so enableScreenshare enters the loop at line 345 with two tracks and awaits the first publishTrack. The user then hits the app's Stop Sharing button (or the OS 'Stop sharing' bar fires the 'ended' listener registered at line 358 for a previous share). disableScreenshare bumps the generation, stopManualScreenTracks sets state.manualScreenTracks = [] and stops/unpublishes both tracks, setLocalScreenshare(false) runs, and voice_screenshare{enabled:false} is sent. The loop resumes and publishes the second track — held only by the local `screenTracks` closure variable, which state.manualScreenTracks no longer references, so no later disable can unpublish it — and line 370 sends voice_screenshare{enabled:true}. The server's last observed state is enabled:true, peers keep a screenshare tile for the participant, and the local store says screenshare off.",
   "evidence": "    if ((state.generation ?? 0) !== generation) {   // 334 - only guard\n      for (const t of screenTracks) t.stop();\n      return;\n    }\n    state.manualScreenTracks = screenTracks;         // 341\n    for (const track of screenTracks) {\n      await room.localParticipant.publishTrack(track, {   // 345 - awaited per track, no guard\n        ...\n      });\n    }\n    const sendId = ws.send({ type: \"voice_screenshare\", payload: { enabled: true } });  // 370\n\nexport async function disableScreenshare(state, deps) {\n  bumpGeneration(state);                             // 399\n  stopManualScreenTracks(state, room);               // sets state.manualScreenTracks = [] and stops them\n  ...\n  finally { setLocalScreenshare(false); ws.send({ type: \"voice_screenshare\", payload: { enabled: false } }); }",
   "suggestedFix": "Re-check (state.generation ?? 0) !== generation after each awaited publishTrack in the loop (and before the ws.send at 370); on supersession, unpublish/stop every track in the local screenTracks array, clear state.manualScreenTracks if it still references them, and return without sending voice_screenshare(true).",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "concurrency",
   "finder": "opus",
   "round": 2,
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "62792c7",
    "test": "Client/tauri-client/tests/unit/screen-share-tracks.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0027",
   "title": "HTTP listen failure returns from run() without hub.GracefulStop(), orphaning the companion livekit-server process and leaving the maintenance goroutine's stop channel unclosed",
   "file": "Server/main.go",
   "line": 383,
   "severity": "medium",
   "why": "hub.GracefulStop() — the only caller of LiveKitProcess.Stop() — is a plain statement at line 401, not a defer, and the serve-error branch returns at line 383 before reaching it. LiveKitProcess.Stop() is what cancels the context passed to exec.CommandContext, so skipping it leaves the spawned livekit-server child alive; Go does not kill children when the parent exits, so it is reparented and keeps holding :7880 and the 50000-60000 UDP range. `close(stopMaintenance)` (line 407) is likewise skipped, so the 15-minute maintenance goroutine survives the whole deferred teardown, including `database.Close()` at line 133.",
   "repro": "Configure voice.livekit_binary (or voice.auto_download_livekit: true) and start the server while another process holds the configured server.port. api.NewRouter spawns livekit-server via LiveKitProcess.Start. The listen loop retries 20 times, then pushes the bind error onto serveErr; run() returns at line 383, main() calls os.Exit(1) — hub.GracefulStop() never runs, so LiveKitProcess.Stop() never cancels its context and the livekit-server child outlives the OwnCord process. Restarting OwnCord then fails LiveKit startup with :7880 already in use. The same return also strands the maintenance goroutine, which can be mid-DeleteExpiredSessions(bgCtx) when the deferred database.Close() executes.",
   "evidence": "select { case err := <-serveErr: if err != nil { return fmt.Errorf(\"server error: %w\", err) } ... }  // line 380-387\n...\nhub.GracefulStop()            // line 401 — never reached on the serveErr path\nif err := srv.Shutdown(shutdownCtx); err != nil { return ... }\nclose(stopMaintenance)        // line 407 — also never reached\n\n// router.go:164-169 already started the companion process by this point:\nproc := ws.NewLiveKitProcess(&cfg.Voice, &cfg.TLS, cfg.Server.DataDir)\nif startErr := proc.Start(); startErr != nil { ... } else { hub.SetLiveKitProcess(proc) }",
   "suggestedFix": "Add `defer hub.GracefulStop()` immediately after `router, hub, routerCleanup := api.NewRouter(...)` (main.go:198). gracefulOnce makes it idempotent with the explicit call at line 401 on the normal path, and it guarantees LiveKitProcess.Stop() runs on every early return.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "lifecycle",
   "finder": "opus",
   "round": 2,
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/main_test.go",
    "revertProof": "pass",
    "branchCommit": "d74e9861",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0028",
   "title": "buildReady drops the user's own live voice room when it is not READ-visible, wiping the client's call roster on a full resync",
   "file": "Server/ws/serve_ready.go",
   "line": 276,
   "severity": "medium",
   "why": "buildReady filters every voice_state through visibleSet = READ-visible non-DM channels ∪ the user's *open* DM channels. Voice membership is gated on CONNECT_VOICE alone (voice_join.go:64) and DM visibility comes from dm_open_state, so the room the user is currently in can be absent from visibleSet — the exact hole handleReconnect patches on the replay tier via liveVoiceEventsSince (serve.go:341-343, whose comment names 'a DM voice call after the DM was closed' as the stock case). The full-ready tier has no equivalent supplement, so the ready payload asserts the user is in no voice channel while the server's voice_states row, the hub's c.voiceChID and the LiveKit session all say otherwise.",
   "repro": "Alice and Bob are in a 1:1 DM voice call. Alice closes the DM from the sidebar (DELETE /api/v1/dms/{id}); CloseDM's non-group branch only deletes her dm_open_state row and leaves result.Left false, so no voice eviction runs — she stays in the call. Alice's socket then drops and her resume takes the full-ready path (mustFullResync, or a buffer/cold-tier miss). buildReady's dmChannels comes from GetUserDMChannels (dm_open_state), so the DM id is not in visibleSet and BOTH voice_state rows are filtered out; payload.voice_states is empty. Client-side setVoiceStates (Client/tauri-client/src/stores/voice.store.ts:185) then does `voiceUsers: channelMap` — a full replacement with an empty map — while `currentChannelId: autoJoinChannel ?? prev.currentChannelId` keeps her in the channel, and selfState is undefined so localServerMuted/localServerDeafened are reset to false. Result: a live, audible call rendering zero participants (including herself), setLocalSpeaking permanently a no-op (it early-returns when voiceUsers.get(channelId) is undefined), and any moderator server-mute gate silently lifted in the UI. Nothing repopulates her own row until she toggles mute herself. The same happens for any voice channel where an override grants CONNECT_VOICE but denies READ_MESSAGES.",
   "evidence": "visibleSet := make(map[int64]struct{}, len(visibleChannels)+len(dmChannels))\nfor i := range visibleChannels { visibleSet[visibleChannels[i].ID] = struct{}{} }\nfor i := range dmChannels    { visibleSet[dmChannels[i].ChannelID] = struct{}{} }\nvoiceStates := make([]db.VoiceState, 0, len(allVoiceStates))\nfor i := range allVoiceStates {\n\tif _, ok := visibleSet[allVoiceStates[i].ChannelID]; ok {\n\t\tvoiceStates = append(voiceStates, allVoiceStates[i])\n\t}\n}",
   "suggestedFix": "In buildReady, before filtering, seed visibleSet with the channel of the user's own voice row: scan allVoiceStates for a row with UserID == userID and add its ChannelID to visibleSet (the user's own live room can never leak — they are in it). This mirrors liveVoiceEventsSince's rationale on the replay tier.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "state-desync",
   "finder": "opus",
   "round": 2,
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/ws/serve_ready_own_voice_test.go",
    "revertProof": "pass",
    "branchCommit": "5c4b338d",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0029",
   "title": "buildReady swallows three DB errors and ships an authoritative-looking empty snapshot; the client wipes its DM list, member list and unread badges",
   "file": "Server/ws/serve_ready.go",
   "line": 242,
   "severity": "medium",
   "why": "Inside one function, `ListChannels`/`ListRoles`/`GetChannelOverridesFor` failures abort the handshake (`return nil, err`), but `ListMembers` (l.153), `GetChannelUnreadCounts` (l.188) and `GetUserDMChannels` (l.242) failures are downgraded to `slog.Warn` plus an empty value, and the `ready` frame is then built and sent as if it succeeded. `ready` is the protocol's full-state snapshot, so the client cannot distinguish \"the query failed\" from \"you genuinely have none\" — the error is mapped to success on the wire.",
   "repro": "A server restart makes every client reconnect at once and take the full-ready path; under that load one `GetUserDMChannels` read returns SQLITE_BUSY (or hits the request ctx deadline). The server logs a warning and sends `ready` with `dm_channels: []`. Client/tauri-client/src/lib/dispatcher.ts:331-335 documents the exact opposite contract — \"the server always sends the field, so an empty array is an authoritative 'no open DMs' ... and must clear ghosts from dmStore\" — so `setDmChannels([])` wipes the user's whole DM list, and the reconcile loop at dispatcher.ts:347-366 then deletes every dm-typed mirror row from channelsStore. If the user was viewing a DM, `stillPresent` at dispatcher.ts:285-292 is false, so `setActiveChannel(null)` tears down the open conversation. Every DM is unreachable for the rest of the session: a `ready` is only re-sent on a fresh connect or a full resync, and successful seq-replay reconnects never send one. The same interleaving on `ListMembers` empties the member sidebar (removing the \"Message\" affordance that is the only way back to a DM), and on `GetChannelUnreadCounts` zeroes every channel's unread_count/mention_count/last_message_id.",
   "evidence": "members, err := database.ListMembers(ctx)\nif err != nil {\n\tslog.Warn(\"buildReady ListMembers\", \"err\", err)\n\tmembers = []db.MemberSummary{}\n}\n...\nunreadMap, err := database.GetChannelUnreadCounts(ctx, userID)\nif err != nil {\n\tslog.Warn(\"buildReady GetChannelUnreadCounts\", \"err\", err)\n\tunreadMap = map[int64]db.ChannelUnread{}\n}\n...\ndmChannels, err := database.GetUserDMChannels(ctx, userID)\nif err != nil {\n\tslog.Warn(\"buildReady GetUserDMChannels\", \"err\", err)\n\tdmChannels = []db.DMChannelInfo{}\n}\n\n// contrast, same function, lines 144-151:\nchannels, err := database.ListChannels(ctx)\nif err != nil { return nil, fmt.Errorf(\"buildReady ListChannels: %w\", err) }",
   "suggestedFix": "In buildReady, treat the three per-user loads like ListChannels: on error from ListMembers, GetChannelUnreadCounts, or GetUserDMChannels, return nil, fmt.Errorf(...) so the handshake fails and the client's reconnect logic retries, instead of shipping empty values the protocol defines as authoritative.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "error-paths",
   "finder": "opus",
   "round": 2,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Server/ws/serve_ready_error_propagation_test.go",
    "revertProof": "pass",
    "branchCommit": "6c0a7caa"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0030",
   "title": "prependMessages trims the tail at the 500-row cap, silently destroying the user's pending/failed optimistic rows",
   "file": "Client/tauri-client/src/stores/messages.store.ts",
   "line": 602,
   "severity": "medium",
   "why": "Optimistic rows (status \"pending\"/\"failed\") are appended at the END of a channel's array by addOptimisticMessage, and prependMessages trims with `combined.slice(0, MAX_MESSAGES_PER_CHANNEL)` — i.e. it drops the tail. Every other writer that replaces a channel window (setMessages L415-424, setAroundMessages L492, invalidateLoadedMessageWindows L545) deliberately carries non-\"sent\" rows across, with the comment \"they are the only copy of the user's composed text\". prependMessages is the one path that does not, so an unsent/failed message and its Retry draft are deleted with no server copy to restore them (the comment at L597-599 claims the dropped tail is \"restored via the detached-window machinery\", which is only true for rows the server actually has).",
   "repro": "1. Open a channel with plenty of history. MAX_MESSAGES_PER_CHANNEL = 500, PAGE_SIZE = 50.\n2. Send a message while the socket is down (or let a send fail): addOptimisticMessage appends a row with id 0 and status \"pending\"/\"failed\" at the end of messagesByChannel[ch]; the composer text now exists ONLY in that row (Retry/Delete render off it).\n3. Scroll up repeatedly. Each loadOlderMessages -> prependMessages adds up to 50 older rows at the head. After ~10 pages the array reaches 500.\n4. On the next scroll-up, combined.length = 550 > 500, so wasTrimmed is true and combined = combined.slice(0, 500) keeps the first 500 (oldest) rows and discards the last 50 — which include the optimistic row.\n5. The failed message and its text are gone from the store forever; pendingSends still holds the correlationId, and nothing re-renders a Retry affordance. Contrast step 4 with setMessages, which slices merged.slice(merged.length - MAX) and therefore preserves the same rows.",
   "evidence": "let combined = [...converted, ...existing];\n// ...\nconst wasTrimmed = combined.length > MAX_MESSAGES_PER_CHANNEL;\nif (wasTrimmed) {\n  combined = combined.slice(0, MAX_MESSAGES_PER_CHANNEL);\n}",
   "suggestedFix": "In prependMessages' trim branch, carry non-'sent' rows out of the dropped tail: `if (wasTrimmed) { const kept = combined.slice(0, MAX_MESSAGES_PER_CHANNEL); const carried = combined.slice(MAX_MESSAGES_PER_CHANNEL).filter((m) => m.status !== \"sent\"); combined = carried.length > 0 ? [...kept, ...carried] : kept; }` — mirroring the carry every other window-replacing writer already performs.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "ordering-boundary",
   "finder": "opus",
   "round": 2,
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "e8bf022",
    "test": "Client/tauri-client/tests/unit/messages-store-detached.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0031",
   "title": "Channel drag-reorder assumes distinct positions; tied positions make the drop a silent no-op or land the channel in the wrong slot",
   "file": "Client/tauri-client/src/components/channel-sidebar/drag-reorder.ts",
   "line": 151,
   "severity": "medium",
   "why": "The mouseup handler reassigns \"the group's own existing position slots\" by sorting the category's position values ascending and zipping them onto the new id order. That is only correct when the positions are distinct. `channels.position` has no uniqueness constraint (Server/db/queries/sqlite/channels.sql has no unique index, AdminUpdateChannel/CreateChannel store whatever is given, and the admin panel's Create Channel modal ships `value=\"0\"` for the Position field — Server/admin/static/index.html:925). When every channel in a category shares position 0, slots is [0,0,0,...] and `ch.position !== newPosition` is false for every row, so `reorders` stays empty, `drag.onReorder` is never called, no PATCH is sent, and updateChannelPosition is never applied — the drag silently does nothing and the row snaps back. With partial ties the zip assigns the wrong slot to the wrong channel, so the dragged channel lands somewhere other than where it was dropped.",
   "repro": "1. In the admin panel, create three text channels in category \"Text Channels\" without editing the Position field: general, random, dev. All three are stored with position = 0 (Server/admin/handlers_channels.go:117 -> AdminCreateChannel with req.Position = 0).\n2. In the desktop client, signed in as a MANAGE_CHANNELS holder, getChannelsByCategory sorts them by position (all 0, so stable Map-insertion order): [general, random, dev].\n3. Drag `dev` and drop it on the top half of `general`.\n4. reorderedIds = [dev, general, random]; slots = [0,0,0].\n5. Loop: i=0 -> dev, newPosition 0, dev.position is already 0 -> skipped. i=1 -> general, 0 == 0 -> skipped. i=2 -> random, 0 == 0 -> skipped.\n6. reorders.length === 0, so `drag.onReorder(reorders)` at L166-168 never fires. No adminUpdateChannel PATCH is issued and the store is never updated; the sidebar re-renders in the original order. The drag is unrecoverably a no-op for as long as the tie exists.\nPartial-tie variant: positions [general=0, random=0, dev=5]; dragging dev to the front yields dev->0 (changed, sent), general->0 (skipped), random->5 (changed, sent), leaving general and dev both at 0 — the resulting order depends on Map iteration order rather than the drop.",
   "evidence": "const slots = drag.channels.map((c) => c.position).sort((a, b) => a - b);\nconst reorders: ChannelReorderData[] = [];\nfor (let i = 0; i < reorderedIds.length; i++) {\n  const id = reorderedIds[i];\n  const newPosition = slots[i];\n  ...\n  const ch = drag.channels.find((c) => c.id === id);\n  if (ch !== undefined && ch.position !== newPosition) {\n    reorders.push({ channelId: id, newPosition });\n    updateChannelPosition(id, newPosition);\n  }\n}\nif (reorders.length > 0) {\n  drag.onReorder(reorders);\n}",
   "suggestedFix": "After sorting, make the slot list strictly increasing before zipping: `for (let i = 1; i < slots.length; i++) { if (slots[i]! <= slots[i - 1]!) slots[i] = slots[i - 1]! + 1; }` — tied groups then get distinct positions, the reorder fires, and subsequent renders order deterministically, while categories with already-distinct slots keep their exact existing range (the behavior the offset test at drag-reorder.test.ts:360 locks).",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "ordering-boundary",
   "finder": "opus",
   "round": 2,
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "df82fca",
    "test": "Client/tauri-client/tests/unit/drag-reorder.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0032",
   "title": "Client's `lastSeq` watermark is never reset by a full-ready resync, so it desyncs permanently from the server's seq counter (and then silently skips events)",
   "file": "Client/tauri-client/src/lib/ws.ts",
   "line": 307,
   "severity": "medium",
   "why": "`lastSeq` is monotone-increasing (`if (seq > lastSeq) lastSeq = seq`) and is only ever zeroed by `disconnect()` (logout). The server answers an unusable `last_seq` by sending a full `ready` and stamps `replay_source: \"none\"` into auth_ok, but the client ignores that field and keeps the stale watermark forever. Once the server's counter is *below* the client's watermark (any restart where `MAX(events.seq)` is 0 — `event_persistence.enabled=false`, an events table emptied by the 24h pruner, a restored DB), the two counters never re-converge, and while the server's counter climbs back through the stale value the client asks for a range the server happily answers as a complete resume.",
   "repro": "Server with `event_persistence.enabled=false` (or an events table emptied by the pruner). Client is connected long enough to reach lastSeq=5000, then the server restarts, so `h.seq` starts at 0. (a) Immediate effect: every subsequent reconnect takes the full-ready tier (ringbuffer.go:66 `afterSeq > newestSeq`), and dispatcher.ts:301-327 fires `invalidateLoadedMessageWindows()` + a full `getMessages` refetch each time, forever. (b) Data loss: the client stays connected while the server's counter climbs to 4990 (received live, lastSeq stays pinned at 5000 because 4990 < 5000). The socket drops; during the reconnect backoff the server broadcasts up to seq 5090. The client reconnects with `last_seq=5000`; the 1000-entry ring buffer holds 4091..5090, so `afterSeq(5000) > oldestSeq(4091)` and `afterSeq <= newestSeq(5090)` both pass and the server replays only 5001..5090 with `replay_source: \"buffer\"`. Events 4991..5000 — real chat_message/chat_deleted/channel_update frames the client missed while offline — are never delivered, no `ready` arrives, and no history refetch is triggered.",
   "evidence": "ws.ts:256-260 `const seq = ...; if (seq > lastSeq) { lastSeq = seq; }`  — the only write outside disconnect().\nws.ts:307-320 auth_ok branch: `replayDedup = null; setState(\"connected\"); reconnectAttempt = 0; startHeartbeat();` — `payload.replay_source` (Server/ws/serve_ready.go:49, `\"none\"` for fresh/full resync) is never read and lastSeq is never reset.\nws.ts:427 `last_seq: lastSeq` is sent unconditionally on every auth frame.\nws.ts:598 `lastSeq = 0;` inside `disconnect()` only.\nServer side: Server/ws/ringbuffer.go:66 `if afterSeq > rb.newestSeqLocked() { return nil }` forces full ready while the server is behind, and Server/main.go:208-213 only seeds `h.seq` when `cfg.EventPersistence.Enabled` and `maxSeq > 0`.",
   "suggestedFix": "In ws.ts's auth_ok branch (line ~307), reset the watermark when the server declares a full resync: `if ((msg.payload as { replay_source?: string }).replay_source === \"none\") lastSeq = 0;` before setState(\"connected\"). The next sequenced frame then adopts the server's current epoch via the existing seq > lastSeq update.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "flow-reconnect",
   "finder": "opus",
   "round": 3,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Client/tauri-client/tests/unit/ws-reconnect.test.ts",
    "revertProof": "pass",
    "branchCommit": "bdbbed65"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0033",
   "title": "A DM send survives a transient GetDMParticipantIDs failure by silently dropping live fan-out to everyone, including the sender",
   "file": "Server/service/message_crud.go",
   "line": 174,
   "severity": "medium",
   "why": "SendMessage already committed the message row via CreateMessageWithMentions before this block runs. If s.st.GetDMParticipantIDs then errors (transient DB hiccup, lock contention), the function logs and does `return result, nil` with result.ParticipantIDs left nil and result.IsDM=true. handleChatSendV2 (Server/ws/handlers_chat.go:101-105) unconditionally builds MessageSentDMEvent{participantIDs: result.ParticipantIDs} from that nil slice. EmitEvents routes it as a SequencedDMEvent to Hub.sendSequencedToUsers(channelID, nilUserIDs, payload) (Server/ws/hub_broadcast.go:607-619), which still allocates a seq and pushes into the replay ring buffer/EventPersister, but its `for _, userID := range userIDs` loop is a no-op over the empty slice, so h.SendToUser is never called for anyone -- not even the sender. SendMessage returns err=nil, so chat_send_ok still goes to the sender (their optimistic row reconciles fine), but the other DM participant(s) get no chat_message frame, no unread/mention bump, no last-message preview update, and no notification. They only learn about the message on their own NEXT reconnect, because only a fresh 'ready' recomputes unread_count from the DB independent of WS delivery -- a recipient who stays continuously connected never sees the message land at all.",
   "repro": "Users A and B share a DM channel, both connected. A sends a message at the moment s.st.GetDMParticipantIDs(ctx, channelID) returns a transient error for this one call (Server/service/message_crud.go:174-178). CreateMessageWithMentions already succeeded, so the row is in the DB. SendMessage returns (result, nil) with ParticipantIDs=nil; handleChatSendV2 emits MessageSentDMEvent{participantIDs: nil}; sendSequencedToUsers allocates seq N, stores it in the replay buffer, and iterates zero recipients. A's client gets chat_send_ok and shows the message locally; B's client (still connected, no reconnect) never receives seq N live, never bumps its DM badge, and never shows the message -- until B happens to disconnect and reconnect, which is the only path that recomputes unread_count from the DB.",
   "suggestedFix": "Query the participants with a cancellation-proof context — participantIDs, pErr := s.st.GetDMParticipantIDs(context.WithoutCancel(ctx), p.ChannelID) — matching the pattern SendMessage already uses for its other post-commit side effects (compensating deletes, applyMentionCounts, audit writes), which eliminates the deterministic sender-disconnect trigger; for the residual genuine-DB-error case, have handleChatSendV2 fall back to emitting MessageSentChannelEvent when result.IsDM && result.ParticipantIDs is empty, so ChannelTopic delivery still reaches any participant currently viewing the DM.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "flow-message",
   "finder": "sonnet",
   "round": 3,
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/service/message_crud_test.go",
    "revertProof": "pass",
    "followUp": "9cdef406",
    "branchCommit": "081bb169",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0034",
   "title": "Aborted voice-channel switch restores the server's voice state but never undoes the voice_leave it already broadcast — the user is stuck in a phantom voice session nobody (including themselves) can see",
   "file": "Server/ws/voice_join.go",
   "line": 174,
   "severity": "medium",
   "why": "When the pre-switch leave fails to delete the voice_states row, handleVoiceJoin aborts and restores the client's voice state, VoiceTopic subscription and key-holder entry. But finishVoiceLeave has already broadcast voice_leave to an audience that explicitly includes the leaver themselves (voice_leave.go:96-99), and nothing re-broadcasts a voice_state afterwards. Server, DB and the SFU keep the user in the channel while every client — the user's own included — has removed them.",
   "repro": "1. User U is in voice channel A; voice_states holds (U, A, joined_at=T) and U's client holds token T.\n2. U sends voice_join{channel_id: B}.\n3. handleVoiceJoin (voice_join.go:151) runs handleVoiceLeave. Inside finishVoiceLeave, leaveVoiceChannelWithRetry fails to remove the row — either the synchronous DELETE errors (SQLITE_BUSY under concurrent writes; the background retries have not landed yet) or the client's join token is empty, in which case voice_leave.go:129 skips the DELETE entirely and returns nil.\n4. finishVoiceLeave still broadcasts voice_leave{A, U} to the READ audience, the remaining room participants, AND U (voice_leave.go:96).\n5. Back in handleVoiceJoin, GetVoiceState still returns the row for A, so the abort branch at voice_join.go:165 runs: c.setVoiceState(A, T), Subscribe(VoiceTopic(A)), updateKeyHolder(A), and an INTERNAL error to U. No voice_state is broadcast.\n\nEnd state: the hub, the voice_states row and the LiveKit participant all still have U in channel A, but every connected client removed U from A's roster, and U's own client ran leaveVoice(false) + leaveVoiceChannel() and shows \"not in voice\". U cannot rejoin A — handleVoiceJoin:124 answers ALREADY_JOINED — while still consuming a slot in JoinVoiceChannelIfCapacity's COUNT(*) and still appearing in every freshly built ready payload (buildReady reads GetAllVoiceStates). The stale-voice sweep cannot heal it either: sweepStaleVoiceStates only reaps rows whose channel disagrees with the client's voiceChID, and the abort deliberately made them agree.",
   "evidence": "voice_join.go:151-179\n\t\th.handleVoiceLeave(ctx, c)            // -> finishVoiceLeave broadcasts voice_leave (incl. to c)\n\t\tvs, err := h.db.GetVoiceState(ctx, c.userID)\n\t\t...\n\t\tif vs != nil {\n\t\t\tslog.Warn(\"handleVoiceJoin: stale voice state persists after leave, aborting switch\", ...)\n\t\t\tc.setVoiceState(vs.ChannelID, vs.JoinedAt)\n\t\t\th.pubsub.Subscribe(c, VoiceTopic(vs.ChannelID))\n\t\t\th.updateKeyHolder(vs.ChannelID)\n\t\t\tc.sendMsg(buildErrorMsg(ErrCodeInternal, \"voice channel switch failed — please try again\"))\n\t\t\treturn      // <-- no broadcastVoiceEvent(ctx, vs.ChannelID, buildVoiceState(*vs))\n\t\t}\n\nvoice_leave.go:96-99 (the leaver is always in the voice_leave audience)\n\tif _, ok := seen[c.userID]; !ok {\n\t\taudience = append(audience, c.userID)\n\t}\n\th.broadcastChannelScopedTo(oldChID, buildVoiceLeave(oldChID, c.userID), audience, \"voice event\")\n\nvoice_leave.go:129-134 (an empty join token makes the delete a silent no-op, guaranteeing the abort branch)\n\tif joinToken == \"\" {\n\t\tslog.Warn(\"LeaveVoiceChannelIfMatch skipped due to missing join token\", ...)\n\t\treturn nil\n\t}\n\nClient/tauri-client/src/lib/dispatcher.ts:790-815 (a self voice_leave tears the session down)\n\tconst shouldTeardownSession = isSelf && voiceStore.getState().currentChannelId === payload.channel_id;\n\t... if (shouldTeardownSession) void leaveVoice(false);\n\tif (isSelf) { leaveVoiceChannel(); }",
   "suggestedFix": "In the abort branch (voice_join.go:165-179), stop restoring the session: the voice_leave already broadcast has made every client (and the user's own media session) treat the user as departed, so restoring resurrects a session that no longer exists anywhere else. Delete the c.setVoiceState/Subscribe/updateKeyHolder restore and just send the error — with the client state left cleared, sweepStaleVoiceStates' DB loop (row present, voiceChID=0 mismatch) removes the stale row within one tick and re-broadcasts voice_leave, and the user_id-PK upsert lets the user rejoin immediately. If the restore must stay for some reason, the alternative is to add h.broadcastVoiceEvent(ctx, vs.ChannelID, buildVoiceState(*vs)) after updateKeyHolder so clients re-add the participant.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-ws",
   "finder": "opus",
   "round": 4,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Server/ws/voice_handlers_test.go",
    "revertProof": "pass",
    "branchCommit": "c67d25ed"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0035",
   "title": "Deleting a voice channel races a concurrent voice_join, producing a permanent hub/SFU ghost participant that no sweep can ever detect or heal",
   "file": "Server/admin/handlers_channels.go",
   "line": 288,
   "severity": "medium",
   "why": "handleDeleteChannel evicts the CURRENT voice participants via hub.CleanupVoiceForChannel(id) and only afterward calls database.AdminDeleteChannel(id), which deletes the channel row and relies purely on the voice_states FK cascade to clean up (Server/db/admin_queries.go:192-196 — a plain DELETE FROM channels, no check for live voice participants). Nothing marks the channel as going away between those two calls (contrast with the archive path in the same file, lines 257-269, which sets Archived=true in the DB *before* calling CleanupVoiceForChannel, so a racing voice_join sees ch.Archived==true and is refused — voice_join.go:92). The delete path has no such guard, so a voice_join that reads the still-live channel row via GetChannel (voice_join.go:70) during this window proceeds to insert a voice_states row and set the hub client's in-memory voice state (voice_join.go:222, c.setVoiceState — done deliberately *before* the LiveKit token round trip per the BUG-088 comment) exactly as it would for a channel that isn't being deleted. If AdminDeleteChannel's cascade fires after that insert commits, the freshly-created voice_states row is silently deleted by the cascade, but the hub client's in-memory voiceChID, its VoiceTopic subscription, and (if the channel had capacity) the LiveKit room are left completely untouched — nothing in handleVoiceJoin re-checks that the channel still exists after the insert. The resulting ghost is then invisible to both of sweepStaleVoiceStates's healing loops (Server/ws/hub_sweep.go:140-250): the DB-driven loop (lines 193-249) only iterates rows returned by GetAllVoiceStates, and the cascade-deleted row is no longer among them, so it can never flag a hub client with no matching DB row; the permission-revocation loop (lines 152-191) calls hasChannelPermChecked, whose GetChannelPermissions query (Server/db/channel_queries.go:141-153) returns (0,0,nil) — not an error — for a nonexistent channel ID (it's a plain lookup keyed by channel_id with sql.ErrNoRows mapped to a clean zero), so the effective-permission check collapses to the user's bare role bits; any role whose base permissions include CONNECT_VOICE (the common default) is reported 'allowed' and never evicted. The user is left stuck 'in voice' forever (mic hot if publishing, SFU room orphaned) with the client UI showing nothing to leave from (client-side channel_delete handling in dispatcher.ts:617-633 only redirects the sidebar/active-channel view; it performs no voice teardown at all), until they manually reconnect the whole client.",
   "repro": "1) Create a voice channel with at least one connected participant so cleanup takes real wall-clock time (CleanupVoiceForChannel's per-participant LiveKit RemoveParticipant call can take up to lkTimeout=5s each — livekit.go:153,181). 2) As an admin, DELETE that channel via the admin API/UI. 3) While CleanupVoiceForChannel is still evicting the existing participants (i.e., before AdminDeleteChannel's DELETE has executed), have a different, already-connected user send voice_join for that same channel_id — it passes GetChannel, permission, and archived checks (all still see the live row) and its JoinVoiceChannel/JoinVoiceChannelIfCapacity insert commits before the channel row is deleted. 4) AdminDeleteChannel then runs, cascading away the new voice_states row along with the channel. 5) Observe: the joining client's hub-side voiceChID stays set to the deleted channel, its VoiceTopic subscription and (if configured) LiveKit SFU membership are never torn down, and it is never picked up by either loop of sweepStaleVoiceStates on any subsequent tick — it stays a permanent ghost until that client's socket disconnects on its own.",
   "suggestedFix": "Mirror the archive path's guard: in handleDeleteChannel, persist archived=1 on the channel (e.g. via AdminUpdateChannel with Archived:true, or a dedicated UPDATE) BEFORE calling hub.CleanupVoiceForChannel, so any voice_join racing the cleanup is refused by the existing archived gate at voice_join.go:92; then delete the row as today. (Defense-in-depth alternative: in handleVoiceJoin, re-fetch GetChannel after the voice_states insert commits and call rollbackVoiceJoin if the channel is gone or archived.)",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-ws",
   "finder": "sonnet",
   "round": 4,
   "confidence": "medium",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Server/admin/api_test.go",
    "revertProof": "pass",
    "branchCommit": "4bb0cbf1"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0036",
   "title": "Slow mode consumes its cooldown token before content and attachment validation, so a rejected send locks the composer for the full window",
   "file": "Server/service/message_crud.go",
   "line": 64,
   "severity": "medium",
   "why": "SendMessage calls limiter.Allow on the per-(user, channel) slow-mode key — which records a timestamp — before sanitizeContent, before the ATTACH_FILES check, and before the insert. Any of those can reject the send, but the cooldown has already been spent, so the user is refused with SLOW_MODE for up to maxSlowModeSeconds (21600 s = 6 h) without ever having posted anything.",
   "repro": "Set slow_mode = 3600 on #general. As a member without MANAGE_MESSAGES, send a 5000-rune chat_send. Line 66 records the slow-mode timestamp, then sanitizeContent (message.go:216) returns ErrBadRequest \"message content exceeds maximum length\" — nothing is stored and nothing is broadcast. Shorten the text and resend immediately: line 66 now returns false and the send is refused with ErrSlowMode for the next hour. The same holds for an attachment-only send by a user lacking ATTACH_FILES (rejected at line 80) and for a CreateMessageWithMentions failure at line 93. No test locks the current ordering — Server/ws/coverage_chat_test.go:241 only asserts that a second *successful* send is throttled.",
   "evidence": "Server/service/message_crud.go:63-82 — the Allow (which records the timestamp) precedes both validations:\n\t// Slow mode (non-DM only).\n\tif !isDM && ch.SlowMode > 0 && !s.perms.HasChannelPerm(ctx, p.UserID, p.ChannelID, permissions.ManageMessages) {\n\t\tslowKey := auth.Key(auth.Key(\"slow\", p.UserID), p.ChannelID)\n\t\tif s.limiter != nil && !s.limiter.Allow(slowKey, 1, time.Duration(ch.SlowMode)*time.Second) {\n\t\t\treturn nil, fmt.Errorf(\"%w: channel has %ds slow mode\", ErrSlowMode, ch.SlowMode)\n\t\t}\n\t}\n\n\t// Validate and sanitize content.\n\tcontent, err := sanitizeContent(p.Content, len(p.AttachmentIDs) > 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Attachment permission (non-DM).\n\tif !isDM && len(p.AttachmentIDs) > 0 {\n\t\tif !s.perms.HasChannelPerm(ctx, p.UserID, p.ChannelID, permissions.AttachFiles) {\n\t\t\treturn nil, fmt.Errorf(\"%w: missing ATTACH_FILES permission\", ErrForbidden)\n\t\t}\n\t}\n\nServer/auth/ratelimit.go:149-154 — Allow appends the timestamp on the permitted path, so the token is spent even though the caller then errors out:\n\tif len(e.timestamps) >= limit { return false }\n\te.timestamps = append(e.timestamps, now)\n\treturn true\n\nServer/ws/command.go:401-441 — the chat_send constructor validates only channel_id and the attachment count/length; content length and emptiness are never checked before the service call, so an over-length body reaches line 72.\n\nServer/admin/handlers_channels.go:147 — maxSlowModeSeconds = 21600.",
   "suggestedFix": "Move the slow-mode block (message_crud.go:63-69) below the sanitizeContent call and the ATTACH_FILES permission check (i.e., to just after line 82, before resolveMentions), so the once-per-window token is only consumed once the send has passed every request-shaped validation.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-service",
   "finder": "opus",
   "round": 4,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Server/service/message_crud_test.go",
    "revertProof": "pass",
    "branchCommit": "86acf049"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0037",
   "title": "Tray Status menu bypasses the client's own status state, so a tray-set Do Not Disturb neither silences notifications nor survives the idle timer or a reconnect",
   "file": "Client/tauri-client/src/main.ts",
   "line": 251,
   "severity": "medium",
   "why": "The `status-change` listener only puts a `presence_update` on the wire. Unlike both in-app status surfaces (UserBar.ts:150-157 and settings/AccountTab.ts:883-884, which call `saveUserStatus(status)` and `applyPresence(status)`), it never writes the `userStatus` preference and never calls `updatePresence()`. `lib/userStatus.ts` is documented as \"the single client-side source of truth\" for the chosen status, and three separate consumers read it — so after a tray selection the server and the client disagree permanently, and two independent code paths then silently undo the user's choice.",
   "repro": "Pick \"Do Not Disturb\" from the tray Status submenu while signed in. The server stores dnd and every other client sees dnd, but `loadUserStatus()` still returns \"online\" with origin \"manual\". Consequences, all reachable: (1) every incoming message still raises a desktop notification and plays the chime, because notifications.ts:85 gates on `loadUserStatus() === \"dnd\"` — DND set from the tray does nothing it promises; (2) after ten quiet minutes autoIdle's `apply(true)` computes `nextAutoStatus(\"online\", \"manual\", true) === \"idle\"` and sends `presence_update {status:\"idle\"}`, overwriting the DND — the module's own doc comment states \"a manually chosen Do Not Disturb or Invisible is never touched\"; (3) on the next WS reconnect, `auth_ok` carries the user's own true status (\"dnd\", serve_ready.go:45), so `restoreSavedPresence()` sees serverStatus \"dnd\" != loadUserStatus() \"online\" and sends `presence_update {status:\"online\"}` plus a local `updatePresence(online)`, silently reverting the tray choice; (4) the UserBar dot and the settings Account tab keep rendering the pre-tray status for the whole session, because both re-render off `onUserStatusChange`, which only fires from `saveUserStatus`.",
   "evidence": "main.ts:251-256\n  void listen<string>(\"status-change\", (e) => {\n    const status = e.payload;\n    if (status === \"online\" || status === \"idle\" || status === \"dnd\" || status === \"offline\") {\n      ws.send({ type: \"presence_update\", payload: { status } });\n    }\n  });\n\ncontrast — UserBar.ts:150-157\n  onStatusChange: (status: UserStatus) => {\n    saveUserStatus(status);\n    updateFromState();\n    ... ws.send({ type: \"presence_update\", payload: { status } })\n  }\n\nconsumers of the pref the tray path never writes:\n  lib/notifications.ts:85   const dnd = loadUserStatus() === \"dnd\";\n  lib/autoIdle.ts:374       const next = nextAutoStatus(loadUserStatus(), loadUserStatusOrigin(), idle);\n  pages/MainPage.ts:180-191 restoreSavedPresence(): compares loadUserStatus() with authStore.user.status and re-sends the local value on every transition to \"connected\"",
   "suggestedFix": "In the main.ts status-change listener, mirror UserBar's path instead of raw-sending: map the tray's legacy \"offline\" to \"invisible\" (matching userStatus.ts's migration), call saveUserStatus(mapped) (origin \"manual\") before ws.send({type:\"presence_update\",payload:{status: mapped}}). Persisting via saveUserStatus makes notifications, autoIdle, restoreSavedPresence, and the UserBar/Account-tab renders (via onUserStatusChange) all agree with the wire state in one place.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-client-tauri-client-src",
   "finder": "opus",
   "round": 5,
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/main.test.ts",
    "revertProof": "pass",
    "branchCommit": "c3a20a95"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0038",
   "title": "The LiveKit participant_left teardown never tells the leaver, unlike every sibling eviction path",
   "file": "Server/ws/livekit_webhook.go",
   "line": 229,
   "severity": "medium",
   "why": "handleWebhookParticipantLeft clears the client's voice state, drops its VoiceTopic subscription, deletes the DB row and re-elects the key holder, then announces the departure with the plain broadcastVoiceEvent. That helper's audience is (READ_MESSAGES holders) ∪ (clients whose getVoiceChID() still equals the channel) — and the leaver was just removed from the second set. Voice membership is gated on CONNECT_VOICE alone, so a participant without READ_MESSAGES on that voice channel receives nothing. The two sibling teardown paths, finishVoiceLeave (voice_leave.go:96-98) and CleanupVoiceForChannel (hub_sweep.go:337-342), both explicitly append the evicted user to the audience for exactly this reason; this path does not, leaving the client believing it is still in a call the server has already torn down.",
   "repro": "1. Configure voice channel V so role R has CONNECT_VOICE but a channel_overrides deny on READ_MESSAGES (the configuration the code repeatedly documents as supported — see the audience comments in voice_leave.go:74-82 and hub_broadcast.go:61-66). 2. User U (role R) joins V: voice_states row committed, c.voiceChID=V, c.voiceJoinToken=JoinedAt, subscribed to VoiceTopic(V). 3. U's SFU connection drops (network blip, media-port loss) while the WebSocket stays up; LiveKit fires participant_left with identity \"user-U:JoinedAt\" for room \"channel-V\". 4. matched is true, so the server clears c.voiceChID/voiceJoinToken/e2eePubKey, unsubscribes VoiceTopic(V), deletes the voice_states row, and re-elects the key holder. 5. broadcastVoiceEvent resolves the audience: channelReadAudience takes the non-DM role-scan branch and excludes U (no READ_MESSAGES); the participant union cannot see U because step 4 already zeroed getVoiceChID(). U receives no voice_leave. 6. U's client still renders itself in the call with the mic hot and keeps auto-reconnecting to LiveKit with a token whose voice_states row no longer exists — every retry is ejected by handleWebhookParticipantJoined's rogue-participant check (livekit_webhook.go:132), and nothing on U's socket ever reports the eviction.",
   "evidence": "c.voiceMu.Lock()\nmatched := c.voiceChID == channelID && c.voiceJoinToken != \"\" && c.voiceJoinToken == joinToken\nif matched {\n\tc.voiceChID = 0\n\t...\n}\nc.voiceMu.Unlock()\n\nif matched {\n\th.pubsub.Unsubscribe(c, VoiceTopic(channelID))\n\t...\n\th.broadcastVoiceEvent(ctx, channelID, buildVoiceLeave(channelID, userID))\n\n// hub_broadcast.go:67-79 — broadcastVoiceEvent's audience, with no leaver term:\naudience := h.channelReadAudience(ctx, channelID)\n...\nfor uid, c := range h.clients {\n\tif _, ok := seen[uid]; !ok && c.getVoiceChID() == channelID {\n\t\taudience = append(audience, uid)\n\t}\n}\n\n// voice_leave.go:96-98 — the sibling path that DOES include the leaver:\nif _, ok := seen[c.userID]; !ok {\n\taudience = append(audience, c.userID)\n}",
   "suggestedFix": "Extract finishVoiceLeave's audience construction (voice_leave.go:83-99: channelReadAudience ∪ remaining participants ∪ the leaver) into a shared helper, and call it from handleWebhookParticipantLeft's matched branch in place of the bare h.broadcastVoiceEvent(ctx, channelID, buildVoiceLeave(channelID, userID)) at livekit_webhook.go:229.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-ws",
   "finder": "opus",
   "round": 5,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Server/ws/livekit_test.go + Server/ws/livekit_webhook_joined_test.go",
    "revertProof": "pass",
    "branchCommit": "9981220f"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0039",
   "title": "DeleteMessage treats a GetChannel read error as \"not a DM\", letting a moderator hard-delete another user's private DM message",
   "file": "Server/service/message_crud.go",
   "line": 346,
   "severity": "medium",
   "why": "`isDM` collapses a lookup failure into false, so a DM falls into the non-DM branch where authority is a plain role check against a channel id that has no override rows. The DM-participant gate is skipped entirely, and `isMod` is then passed to `s.st.DeleteMessage`, which documents that it \"skips the ownership check when ismod is true\".",
   "repro": "Alice and Bob have a 1:1 DM; Bob posts message 42. Moderator Mallory (role holds READ_MESSAGES|MANAGE_MESSAGES, not a participant) sends chat_delete{message_id:42} at a moment when the reader pool returns an error for GetChannel (SQLITE_BUSY / \"database is locked\" under write contention, or a pool error). chErr != nil -> isDM=false -> HasChannelPermBatch(rolePerms, overrides, dmChannelID, READ|MANAGE) sees no override entry for a DM channel, so it answers from the base mask and returns true -> canManage=true, isMod=true -> db.DeleteMessage skips the ownership check and soft-deletes Bob's message in a DM Mallory is not in. Any ADMINISTRATOR passes unconditionally via checker.go:70-72. The correct answer, and the one every ws-layer sibling gives for the same failed lookup, is Forbidden.",
   "evidence": "ch, chErr := s.st.GetChannel(ctx, msg.ChannelID)\nisDM := chErr == nil && ch != nil && ch.Type == \"dm\"\n...\n} else {\n\tisMsgOwner := msg.UserID == userID\n\tcanManage := s.perms.HasChannelPerm(ctx, userID, msg.ChannelID, permissions.ReadMessages|permissions.ManageMessages)\n\tcanDelete := canManage || (isMsgOwner && ...)\n\tif !canDelete { return nil, fmt.Errorf(\"%w: cannot delete this message\", ErrForbidden) }\n\tisMod = canManage\n}",
   "suggestedFix": "Fail closed like SendMessage does: replace lines 345-346 with `ch, chErr := s.st.GetChannel(ctx, msg.ChannelID); if chErr != nil || ch == nil { return nil, fmt.Errorf(\"%w: cannot delete this message\", ErrForbidden) }; isDM := ch.Type == \"dm\"`.",
   "status": "declined",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-service",
   "finder": "opus",
   "round": 5,
   "confidence": "high",
   "fix": null,
   "rationale": "Already fixed by db0275a2 (#1369, 2026-08-14): DeleteMessage GetChannel error path fails closed with ErrForbidden before isDM is computed; locked by TestDeleteMessage_FailsClosedWhenChannelLookupErrors (message_crud_test.go:288), confirmed passing on current code. No failing test can be written."
  },
  {
   "id": "OC-0040",
   "title": "Scroll-to-bottom button and \"Jump to Present\" pill are absolutely positioned inside the scroll container, so they scroll out of view exactly when they are shown",
   "file": "Client/tauri-client/src/components/MessageList.ts",
   "line": 810,
   "severity": "medium",
   "why": "Both controls are appended to `root` (.messages-container), which is itself the `overflow-y: auto` scroller, and are styled `position: absolute; bottom: 8px`. Per CSS Overflow, boxes whose containing block is the scroll container are part of its scrollable overflow region, so they translate with the scrolled content: the button sits at the viewport bottom only at scrollTop ≈ 0 and is painted scrollTop px above the visible area otherwise. Both controls are only made visible when the user is NOT at the bottom, i.e. precisely when scrollTop is large and they are off-screen.",
   "repro": "Open a channel with ~5000px of content. Scroll up 2000px: updateScrollToBottomBtn() adds .visible (opacity 1, pointer-events auto) but the button's painted position is (clientHeight - 48) - 2000 px, far above the scrollport, clipped away by the container's overflow/`contain: strict` — the user has a \"visible\" control they can neither see nor click. Same for the pill: jump to an old message via scrollToMessage (which sets root.scrollTop = offsetBefore(idx)), updateJumpToPresentPill() adds .visible, and the only signal that the loaded window is detached from the live tail is painted off-screen. jsdom has no layout, so tests/unit/message-jump.test.ts:636-677 assert only the class, not visibility.",
   "evidence": "root.appendChild(scrollToBottomBtn);\nroot.appendChild(jumpToPresentPill);\n// src/styles/app.css:896 .messages-container { flex:1; overflow-y:auto; contain:strict; position:relative; }\n// src/styles/app.css:913 .scroll-to-bottom-btn { position:absolute; bottom:8px; right:16px; … }\n// src/styles/app.css:948 .jump-to-present-pill { position:absolute; bottom:8px; left:50%; … }",
   "suggestedFix": "Give the controls a non-scrolling positioned ancestor: in mount(), wrap the scroller in a position:relative wrapper div and append scrollToBottomBtn and jumpToPresentPill to the wrapper instead of root (root keeps the scroll listener and children; the wrapper becomes what is appended to parentContainer).",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "opus",
   "round": 5,
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "a50a9d3",
    "test": "Client/tauri-client/tests/unit/message-list.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0041",
   "title": "Any user whose username is exactly \"System\" has every message rendered as a server system notice, with no author and no moderation controls",
   "file": "Client/tauri-client/src/components/message-list/renderers.ts",
   "line": 182,
   "severity": "medium",
   "why": "renderMessage dispatches to renderSystemMessage purely on `msg.user.username === \"System\"` — it never checks user.id (the tests use id 0) and the server never emits such messages, so the only way to reach that branch in production is a real account named \"System\". Server-side ValidateUsername (Server/auth/helpers.go:19) only rejects control/invisible characters and the \"[deleted-…]\" namespace, so the name is registrable.",
   "repro": "Register an account with username \"System\" and post \"Your session was flagged — re-enter your password at …\". Every client renders it through renderSystemMessage: a system icon, muted italic text and a timestamp, with no avatar, no author name and no role colour — visually identical to a server notice. Because renderSystemMessage returns before the hover action bar is built, the row also carries no react/reply/pin/edit/delete buttons and there is no message context menu anywhere in the client, so a moderator with canManageMessages() has no UI path to delete it.",
   "evidence": "export function renderMessage(msg, isGrouped, allMessages, opts, signal) {\n  if (msg.user.username === \"System\") {\n    return renderSystemMessage(msg);\n  }\n// renderSystemMessage builds only icon + text + time and returns — the\n// `if (!msg.deleted && msg.status === \"sent\")` action-bar block is unreachable.",
   "suggestedFix": "Reserve the name server-side in auth.ValidateUsername: reject strings.EqualFold(strings.TrimSpace(username), \"System\") alongside the existing \"[deleted-\" reservation (covers both register and rename since both funnel through it). Per docs/security.md, route the fix through a GitHub Security Advisory rather than a public issue.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "opus",
   "round": 5,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Client/tauri-client/tests/unit/renderers.test.ts",
    "revertProof": "pass",
    "branchCommit": "e25fe56a"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0042",
   "title": "leaveVoice() stops manual camera/screen tracks without bumping the enable/disable race-guard generation, so a camera/screenshare enable that is mid-flight (awaiting the OS permission prompt / device picker) when the user leaves voice resurrects a track after the room is gone",
   "file": "Client/tauri-client/src/lib/livekitSession.ts",
   "line": 1361,
   "severity": "medium",
   "why": "The `generation` counter on CameraTrackState/ScreenTrackState exists specifically so a concurrent enable() that captured its value before a multi-second device-acquisition await (getUserMedia/getDisplayMedia) can detect it was superseded by a disable and discard the track instead of publishing over it (see the doc comment at screenShare.ts:152-159). doDisableCamera/doDisableScreenshare (screenShare.ts:276, screenShare.ts:399) correctly call bumpGeneration(state) before stopping tracks. leaveVoice() performs the exact same operation — it calls stopManualCameraTrack(this._cameraState, this._room) and stopManualScreenTracks(this._screenState, this._room) directly (lines 1361-1362) and even resets setLocalCamera(false)/setLocalScreenshare(false) (lines 1386-1387) — but never touches state.generation. Because `_cameraState`/`_screenState` are single per-session fields never reinitialized across join/leave cycles (declared once at lines 259-260), a stale enableCamera()/enableScreenshare() continuation that resumes after leaveVoice() ran will pass the `(state.generation ?? 0) !== generation` check at screenShare.ts:235/334, believe it is still current, set state.manualCameraTrack/manualScreenTracks to the newly created track(s), and attempt room.localParticipant.publishTrack() against `room` — a reference captured before the leave, i.e. a room that leaveVoice() has already called room.disconnect() on (line 1373). If that publish does not synchronously throw, the store is left saying camera/screenshare is whatever enableCamera set (or, worse, a mismatched state: the track object sits in state.manualCameraTrack referencing a track published to an already-disconnected room), and the physical camera/mic-capture device stays open. Nothing frees it: the next enableCamera()/disableCamera() call only calls stopManualCameraTrack when `deps.getRoom()` is non-null (screenShare.ts:206, :220), i.e. only once the user has rejoined a voice channel — until then the camera hardware (LED) stays active after the user has already left the call.",
   "repro": "1) Join a voice channel (room R1 live). 2) Click 'Enable camera' — enableCamera() runs setLocalCamera(true), captures room=R1 and generation=0, then awaits createLocalVideoTrack(...), which blocks on the browser's camera permission prompt. 3) Before responding to the prompt, click 'Leave Voice' — leaveVoice() runs synchronously: stopManualCameraTrack no-ops (nothing published yet), room.disconnect() is called on R1, setLocalCamera(false) is set, generation stays 0. 4) Grant camera permission — createLocalVideoTrack resolves; enableCamera() checks `(state.generation ?? 0) !== generation` → 0 !== 0 → false (not superseded), sets state.manualCameraTrack = videoTrack, and calls `room.localParticipant.publishTrack(videoTrack, ...)` on the already-disconnected R1. The camera device is now held open by a track that was never cleaned up, and the app has already visually left the voice call.",
   "suggestedFix": "Export a supersede helper from screenShare.ts (e.g. `export function supersedeVideoEnable(state: GenerationGuarded): void { state.generation = (state.generation ?? 0) + 1; }` — reuse it inside bumpGeneration) and call it on this._cameraState and this._screenState in leaveVoice immediately before the stopManualCameraTrack/stopManualScreenTracks calls at livekitSession.ts:1361-1362, so the stale enable discards its track at the existing screenShare.ts:235/334 check.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-client-tauri-client-src",
   "finder": "sonnet",
   "round": 6,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Client/tauri-client/tests/unit/livekit-session.test.ts",
    "revertProof": "pass",
    "branchCommit": "db7d518b"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0043",
   "title": "The built-in \"light\" theme overrides only 4 of the ~45 design tokens and has no stylesheet, so the message composer and every form input render near-invisible dark-on-dark",
   "file": "Client/tauri-client/src/components/settings/helpers.ts",
   "line": 37,
   "severity": "medium",
   "why": "`applyThemeByName` applies built-in themes by adding a `body.theme-<name>` class, but `src/styles/` contains a rule for `body.theme-neon-glow` only — there is no `body.theme-light` (or `body.theme-midnight`) block anywhere. The entire \"light\" theme is therefore the 4 inline custom properties `applyTheme` writes onto `document.documentElement`. `--text-normal` flips to the dark `#313338` while `--bg-input` keeps the dark-theme `#383a40` from `tokens.css:11`, so every surface painted with `var(--bg-input)` ends up carrying dark text on a dark box (contrast ≈1.1:1).",
   "repro": "Settings -> Appearance -> click \"Light\". `applyTheme(\"light\")` sets `--bg-primary:#ffffff` and `--text-normal:#313338` on `<html>`; `--bg-input` stays `#383a40`. The chat composer (`.message-input-box` + `.msg-textarea`) now paints `#313338` glyphs on a `#383a40` background — typed text is unreadable. Same for the login form's Server Address / Username / Password fields (`login.css:586`) and the reply bar. The setting persists (`applyStoredAppearance` re-runs `applyTheme` on startup), so the state survives restart.",
   "evidence": "helpers.ts:37-42 — light: { \"--bg-primary\": \"#ffffff\", \"--bg-secondary\": \"#f2f3f5\", \"--bg-tertiary\": \"#e3e5e8\", \"--text-normal\": \"#313338\" }  (4 keys, applied via applyTheme -> root.style.setProperty)\nthemes.ts:61-62 — if (BUILT_IN_THEMES.includes(name)) { document.body.classList.add(`theme-${name}`); }   // no CSS backs theme-light / theme-midnight\n`grep -rn \"theme-light\\|theme-midnight\" src/styles/` -> no matches; only `theme-neon-glow.css:4  body.theme-neon-glow { ... }`\ntokens.css:11 — --bg-input: #383a40;   (never overridden by the light map)\napp.css:2342 — .message-input-box { background: var(--bg-input); }\napp.css:2377-2380 — .msg-textarea { background: transparent; color: var(--text-normal); }\nlogin.css:586-590 — .form-input { background: var(--bg-input); color: var(--text-normal); }\napp.css:2173-2183 — .reply-bar-inner { background: var(--bg-input); } / .reply-bar-inner strong { color: var(--text-normal); }",
   "suggestedFix": "Give the light theme a complete palette: add a body.theme-light block (new theme-light.css, mirroring theme-neon-glow.css) that overrides every dark token used against --text-normal — at minimum --bg-input, --bg-hover, --bg-active, --bg-modifier-*, --border, --border-strong, --text-muted, --text-faint, --text-micro, --header-primary, --header-secondary, --interactive-* — with light-mode values. (Extending the THEMES.light map works too, but the CSS block matches how neon-glow already ships its extra tokens.)",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "opus",
   "round": 6,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Client/tauri-client/tests/unit/settings-helpers.test.ts",
    "revertProof": "pass",
    "branchCommit": "2c0960cb"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0044",
   "title": "rollbackVoiceJoin deletes voice_states by userID alone, letting a stale/failed join's rollback destroy a concurrently-established newer voice membership",
   "file": "Server/ws/voice_join.go",
   "line": 464,
   "severity": "medium",
   "why": "rollbackVoiceJoin (called from handleVoiceJoin's two failure paths at lines 208 and 300, both after the DB row for `channelID` has already been inserted and, on the second path, after c.setVoiceState has already been applied) unconditionally clears c's in-memory voice channel via c.clearVoiceChID() and deletes the user's voice_states row via `h.db.LeaveVoiceChannel(context.WithoutCancel(ctx), c.userID)` — a plain `DELETE FROM voice_states WHERE user_id = ?` with no channel_id/joined_at condition. Every sibling leave path in this same package (finishVoiceLeave -> leaveVoiceChannelWithRetry, handleVoiceLeaveIfStillIn) instead uses `LeaveVoiceChannelIfMatch(userID, expectedChannelID, expectedJoinedAt)` specifically, per that function's own comment, 'to prevent a race where a delayed retry could wipe a newer voice membership.' rollbackVoiceJoin never received that same protection, despite its own comment acknowledging that a dying connection ('the join failed BECAUSE the connection died — that cancellation is the most common rollback trigger') is its main trigger, which is exactly the scenario where a second, independent connection for the same user can already have re-established a legitimate new voice_states row by the time this delayed rollback runs (context.WithoutCancel is used precisely so the delete keeps running after the original connection and its context are gone).",
   "repro": "User A's connection c1 sends voice_join for channel X; the DB insert for X succeeds and (on the token-generation failure path, after line 222) c1.setVoiceState(X, joinedAt) has already run. Before GenerateToken/GetVoiceState-verify on c1 completes, the underlying connection drops (network blip); c1's readPump goroutine is still live and blocked inside handleVoiceJoin. The client immediately opens a new connection c2 for the same user; the server's registerNow (hub.go:399) swaps h.clients[userID] to c2. The user then sends voice_join for channel Y on c2, which succeeds and inserts a fresh voice_states row (Y, newJoinedAt), with c2 now subscribed to VoiceTopic(Y) and live in the LiveKit room. Meanwhile c1's stalled call finally errors (GetVoiceState fails at voice_join.go:205-211, or GenerateToken fails at voice_join.go:297-303), so `rollbackVoiceJoin(ctx, c1, X, false)` runs and executes `h.db.LeaveVoiceChannel(context.WithoutCancel(ctx), userID)` — deleting the voice_states row for Y that c2 legitimately just created. Result: c2 is still marked in-memory as voiceChID=Y, still subscribed to the voice topic, and still present in the LiveKit room, but its DB voice_states row is gone — a permanent DB/hub/SFU desync (missing from GetChannelVoiceStates, `ready` resyncs, and channel-capacity counts for Y) that nothing subsequently repairs, matching the same ghost-state class as the already-known CleanupVoiceForChannel non-atomicity bug but triggered from the opposite (failed-join rollback) direction.",
   "suggestedFix": "Scope the compensating delete to the join instance it is undoing: thread the join's identity into rollbackVoiceJoin (pass state.JoinedAt at the voice_join.go:300 call site; at the :208 site, where GetVoiceState failed, re-read the row with context.WithoutCancel and proceed only if it still names channelID) and replace h.db.LeaveVoiceChannel(ctx, c.userID) with h.db.LeaveVoiceChannelIfMatch(ctx, c.userID, channelID, joinedAt), mirroring leaveVoiceChannelWithRetry.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-ws",
   "finder": "sonnet",
   "round": 7,
   "confidence": "medium",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/ws/coverage_voice_lifecycle_test.go",
    "revertProof": "pass",
    "residual": "review-confirmed ceiling matching this record's own suggestedFix: on the empty-joinedAt rollback path the re-read adopts the row's current joined_at, so a concurrent re-join of the SAME channel by a second connection can still be deleted; cross-channel re-joins are fully protected. Hardening option: have JoinVoiceChannel return the joined_at it wrote and thread it to the rollback call site.",
    "branchCommit": "e694a8ad",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0045",
   "title": "Role demotion's live-subscription revocation is gated on a cosmetic role re-read, so a failed lookup leaves the demoted user subscribed to channels they can no longer read",
   "file": "Server/admin/handlers_users.go",
   "line": 192,
   "severity": "medium",
   "why": "After ChangeUserRole commits, the only call that revokes the user's live pub/sub subscriptions (hub.BroadcastMemberUpdate -> revokeUnreadableChannels) and the only call that re-derives visibility (hub.RefreshAllChannelVisibility) are both nested inside `if role, err := database.GetRoleByID(...); err == nil && role != nil`, a lookup whose only real product is the role NAME for the member_update payload. When that read fails or returns nil the demotion is committed and the permission cache is invalidated, but the socket keeps every ChannelTopic subscription its old role earned — and READ_MESSAGES is only ever checked at channel_focus, never again on the delivery path.",
   "repro": "User U holds Moderator, which has a channel_overrides ALLOW of READ_MESSAGES on private #staff; U has #staff focused, so ws/handlers.go:170 has subscribed the socket to ChannelTopic(#staff). Admin A demotes U to a non-default role R via PATCH /admin/api/users/{U} {\"role_id\": R}. ModerationService.ChangeUserRole commits and InvalidateUser(U) runs. Admin B now deletes role R (DELETE /admin/api/roles/{R}) in the window before A's handler reaches line 192 — or the single-writer SQLite pool returns SQLITE_BUSY for that one read. GetRoleByID returns (nil, nil) or (nil, err), so the whole block is skipped: no member_update, no revokeUnreadableChannels, no RefreshAllChannelVisibility, no bumpVisibilityWatermark. U's socket stays in ChannelTopic(#staff) and keeps receiving every chat_message, chat_edited, chat_deleted and reaction_update posted in #staff for the entire life of the connection; every other client also still renders U as Moderator. The sibling handlers handleDeleteRole (handlers_roles.go:206-208) and handlePatchRole's permsChanged branch (handlers_roles.go:160-174) both run the identical fan-out unconditionally.",
   "evidence": "if permInvalidator != nil {\n\tpermInvalidator.InvalidateUser(id)\n}\nif role, err := database.GetRoleByID(r.Context(), *req.RoleID); err == nil && role != nil {\n\tif hub != nil {\n\t\thub.BroadcastMemberUpdate(id, role.Name)\n\t\thub.RefreshAllChannelVisibility()\n\t}\n}\n\n// hub_broadcast.go:470 — the only caller of the revocation routine\nfunc (h *Hub) BroadcastMemberUpdate(userID int64, roleName string) {\n\th.BroadcastToAll(buildMemberUpdate(userID, roleName))\n\th.revokeUnreadableChannels(userID)\n}",
   "suggestedFix": "Decouple the fan-out from the name lookup: have ModerationService.ChangeUserRole return the *db.Role it already loads at moderation.go:159, then in handlePatchUser run hub.BroadcastMemberUpdate(id, role.Name) and hub.RefreshAllChannelVisibility() unconditionally (when hub != nil), deleting the GetRoleByID re-read entirely.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-service",
   "finder": "opus",
   "round": 7,
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Server/admin/handlers_users_broadcast_test.go",
    "revertProof": "pass",
    "branchCommit": "93d4790b"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0046",
   "title": "The Font Size slider and the \"Large Font\" accessibility toggle are no-ops — `--font-size` is written but no stylesheet ever reads it",
   "file": "Client/tauri-client/src/styles/base.css",
   "line": 22,
   "severity": "medium",
   "why": "Three separate code paths write the `--font-size` custom property (`applyStoredAppearance` at startup, the Appearance-tab slider on input, and the `.large-font` rule in app.css), but `var(--font-size)` appears nowhere in the repository. `base.css:22` sets `body { font-size: 14px }` as a hard literal, and every other rule uses the fixed `--font-size-xxs … --font-size-xxl` scale from tokens.css. The token is a dead end, so both user-facing font-size controls change persisted state and nothing else.",
   "repro": "Open Settings -> Appearance and drag the Font Size slider from 16 to 20. `document.documentElement.style.getPropertyValue(\"--font-size\")` becomes \"20px\" and localStorage records `owncord:settings:fontSize = 20`, but no text in the app changes size — the computed font-size of body stays 14px from base.css:22 and every component stays on the fixed --font-size-* scale. Identically, Settings -> Accessibility -> \"Large Font\" adds the `large-font` class to <html>, whose only declaration is `--font-size: 18px`, and nothing renders larger. The existing tests (tests/unit/settings-overlay.test.ts:189, tests/unit/accessibility-tab.test.ts:321) assert only that the property/class is set, never that a rendered size changes, so they pass while the feature does nothing. Note also that the default pref is 16px while base.css hard-codes 14px, so the two sources already disagree.",
   "evidence": "src/styles/base.css:22  ->  body { font-family: var(--font-body); font-size: 14px; ... }\nsrc/styles/app.css:5211-5213  ->  .large-font { --font-size: 18px; }\nsrc/lib/appearance.ts:36-39  ->  document.documentElement.style.setProperty(\"--font-size\", `${loadPref<number>(\"fontSize\", 16)}px`);\nsrc/components/settings/AppearanceTab.ts:100  ->  document.documentElement.style.setProperty(\"--font-size\", `${size}px`);\nsrc/components/settings/AccessibilityTab.ts:57  ->  document.documentElement.classList.toggle(\"large-font\", nowOn);\n\nVerification: `grep -rn \"var(--font-size)\" . --include=*.css --include=*.html --include=*.ts` (excluding node_modules) returns zero hits. tokens.css defines only --font-size-xxs/xs/sm/md/lg/xl/xxl, never --font-size.",
   "suggestedFix": "Make the variable actually feed the type scale: in tokens.css derive the scale from it (e.g. --font-size-md: var(--font-size, 14px) and the other steps via calc() multipliers of --font-size), and change base.css:22 to `font-size: var(--font-size-md)`. Align the appearance.ts default (16) with the actual base (14) so the slider's initial position matches what is rendered.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "opus",
   "round": 7,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Client/tauri-client/tests/unit/base-font-size-css.test.ts",
    "revertProof": "pass",
    "branchCommit": "ca1e7d93"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0047",
   "title": "Attachment/avatar fetches lose their bearer token and their cert-pinned proxy when the server host is stored with an explicit :443",
   "file": "Client/tauri-client/src/components/message-list/attachments.ts",
   "line": 158,
   "severity": "medium",
   "why": "`isServerUrl` compares `new URL(url).host` against the raw `_serverHost` string without the \":443\"-stripping normalization the rest of the client applies (`normalizeHostForCertCompare` in lib/ws.ts, `cert_store_key` in src-tauri/src/tofu.rs). WHATWG `URL` drops the default port for `https:`, so a host stored as `example.com:443` never matches, `fetchServerFile` takes the \"external host\" branch, and every server file is fetched with no `Authorization` header and outside the TOFU-pinned loopback proxy.",
   "repro": "1. Add/enter the server host as `chat.example.com:443` (accepted: `isValidHost` in lib/api.ts:82 is `/^[\\w.-]+(:\\d+)?$/`; ServerPanel.ts:310 uses the same regex).\n2. Log in. MainPage.ts:96 calls `setServerHost(\"chat.example.com:443\")`.\n3. Open any channel with an image attachment, or any user with an uploaded avatar. `resolveServerUrl(\"/api/v1/files/abc\")` yields `https://chat.example.com:443/api/v1/files/abc`; `new URL(...).host` is `\"chat.example.com\"` (default port dropped) which !== `\"chat.example.com:443\"`.\n4. `fetchServerFile` therefore returns `tauriFetch(url)` with no Authorization header and bypassing `ensureHttpProxy`. The server's AuthMiddleware answers 401, `res.ok` is false, `fetchImageAsDataUrl` returns null — every attachment image, custom emoji and uploaded avatar silently falls back to its placeholder for the whole session. On a self-signed deployment the direct https fetch also fails TLS in the webview, which is the exact failure the TOFU proxy exists to avoid.\nSame root cause makes `isTrustedServerUrl` (attachments.ts:169) return false, so embeds.ts:135's trusted-server exemption stops applying and link previews to a LAN-hosted OwnCord server are blocked as SSRF.\nExisting tests only cover the port-less form (tests/unit/attachments-auth.test.ts:63 `setServerHost(\"chat.example.com\")`), so nothing locks the current behavior.",
   "evidence": "attachments.ts:36-48,152-186\n  export function setServerHost(host: string): void { _serverHost = host.toLowerCase(); }   // no \":443\" strip\n  export function resolveServerUrl(url) { ... return `https://${_serverHost}${url}`; }\n  function isServerUrl(url: string): boolean {\n    if (_serverHost === null) return false;\n    try { const parsed = new URL(url); return parsed.host === _serverHost; } catch { return false; }\n  }\n  async function fetchServerFile(url: string): Promise<Response> {\n    if (!isServerUrl(url)) return tauriFetch(url);        // <- no token, no TOFU proxy\n    ...\n    headers[\"Authorization\"] = `Bearer ${token}`;\n    return tauriFetch(`${origin}${parsed.pathname}${parsed.search}`, { headers });\n  }\n\nContrast — lib/ws.ts:120-127 documents that config hosts are stored verbatim in this exact shape:\n  /** ... Profile/config hosts are stored verbatim (e.g. \"Example.COM:443\"), but the proxies\n   *  always emit the normalized (stripped, lowercased) form ... */\n  export function normalizeHostForCertCompare(host: string): string {\n    return host.replace(/:443$/, \"\").toLowerCase();\n  }\n\nServer side, the endpoint is auth-gated — Server/api/upload_handler.go:123\n  r.With(AuthMiddleware(database)).Get(\"/api/v1/files/{id}\", handleServeFile(...))",
   "suggestedFix": "Normalize once at the single entry point: in setServerHost (attachments.ts:37), store `_serverHost = host.replace(/:443$/, \"\").toLowerCase();` (mirroring normalizeHostForCertCompare). resolveServerUrl then emits the port-less form (same effective https origin), isServerUrl's parsed.host comparison matches for both port-less and explicit-:443 input URLs, and ensureHttpProxy(parsed.host) resolves the same TOFU pin because cert_store_key strips :443 anyway. Non-default ports are preserved on both sides.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-client-tauri-client-src",
   "finder": "opus",
   "round": 8,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Client/tauri-client/tests/unit/attachments-auth.test.ts",
    "revertProof": "pass",
    "branchCommit": "687c51ff"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0048",
   "title": "Self-account-deletion emits no member_ban: router.go never supplies the optional AuthBroadcaster, so every other client keeps the deleted user and the deleted user's own socket survives",
   "file": "Server/api/router.go",
   "line": 104,
   "severity": "medium",
   "why": "`MountAuthRoutes` accepts a variadic `AuthBroadcaster` that `handleDeleteAccount` uses to fan out `member_ban` (and, via `Hub.BroadcastMemberBan`, to force-disconnect the target). The only production call site omits it because it is mounted at line 104, before the hub exists at line 141 — so `ab` is always nil and the `if broadcaster != nil` guard in `handleDeleteAccount` is never taken in a real server. The event the code was written to send is dead in production; only tests ever pass a broadcaster.",
   "repro": "Users A and B are both connected over WebSocket. B calls `DELETE /api/v1/auth/account` with the correct password. The row is anonymised + banned and B's DB sessions are revoked (auth_handler.go:560-604), and the handler reaches `if broadcaster != nil { broadcaster.BroadcastMemberBan(user.ID) }` at auth_handler.go:616 with `broadcaster == nil`. Result: (1) A's member list, DM sidebar and message authorship keep showing B under B's pre-deletion username indefinitely — the admin ban path (admin/handlers_users.go → hub.BroadcastMemberBan) removes them instantly for the byte-identical DB state; (2) `Hub.DisconnectUser` (hub_broadcast.go:430) is never called, so B's already-open WebSocket stays live and can keep sending frames until the periodic re-validation fires — `SessionCheckInterval = 10` (ws/client.go:21), so up to 9 further messages (chat_message, voice_join, …) are accepted from the deleted, banned account.",
   "evidence": "router.go:104  `MountAuthRoutes(r, database, limiter, cfg.Server.TrustedProxies, totpKey)`  // no broadcaster\nauth_handler.go:91  `func MountAuthRoutes(..., broadcaster ...AuthBroadcaster) { var ab AuthBroadcaster; if len(broadcaster) > 0 { ab = broadcaster[0] } ...`\nauth_handler.go:120 `Delete(\"/account\", handleDeleteAccount(database, limiter, ab))`\nauth_handler.go:616 `if broadcaster != nil { broadcaster.BroadcastMemberBan(user.ID) }`\nws/hub_broadcast.go:428-431 `func (h *Hub) BroadcastMemberBan(userID int64) { h.BroadcastToAll(buildMemberBan(userID)); h.DisconnectUser(userID) }`\nGrep for `MountAuthRoutes` shows the only non-test call site is router.go:104; `api/auth_handler_delete_broadcast_test.go:54` even labels the no-broadcaster form \"the shape every existing MountAuthRoutes call\".",
   "suggestedFix": "In Server/api/router.go, move the MountAuthRoutes call from line 104 to after `hub := ws.NewHub(database, limiter, svc)` (line 141) and pass the hub: `MountAuthRoutes(r, database, limiter, cfg.Server.TrustedProxies, totpKey, hub)`. chi allows route registration in any order before serving, so no other change is needed.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "opus",
   "round": 8,
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Server/api/router_delete_account_broadcast_test.go",
    "revertProof": "pass",
    "branchCommit": "aa8cd13a"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0049",
   "title": "High Contrast accessibility toggle's main effect is dead: `.high-contrast { --text-normal }` is on <html>, which already carries an inline --text-normal written by applyTheme()",
   "file": "Client/tauri-client/src/lib/appearance.ts",
   "line": 21,
   "severity": "medium",
   "why": "`applyStoredAppearance()` calls `applyTheme(name)`, which writes the theme's four tokens — including `--text-normal` — as an *inline* style on `document.documentElement`, and then toggles the `high-contrast` class on the *same* element. An inline declaration always beats a class rule on the same element, so `.high-contrast { --text-normal: #ffffff }` (app.css:5204) can never take effect. The toggle's headline promise (pure-white body text) is silently a no-op; only `--text-muted` and `--bg-active`, which `THEMES` does not set inline, actually change.",
   "repro": "Fresh install, no stored theme. main.ts:100 calls `applyStoredAppearance()`. `getActiveThemeName()` returns \"neon-glow\", which is in `THEMES`, so line 21 runs `applyTheme(\"neon-glow\")` → helpers.ts:95 sets `document.documentElement.style['--text-normal'] = '#dbdee1'`. Line 50 then sets `document.documentElement.classList.add('high-contrast')` when the pref is on. Computed `--text-normal` on <html> is `#dbdee1`, not `#ffffff` — inspect any message body text with High Contrast enabled and it is identical to High Contrast off. Same for every other built-in theme, and re-triggered every time the Appearance tab renders (AppearanceTab.ts:230) or a theme is clicked (AppearanceTab.ts:49). The existing tests (tests/unit/accessibility-tab.test.ts:276, tests/unit/stored-appearance.test.ts:49) only assert the class is toggled, never the resulting token value.",
   "evidence": "lib/appearance.ts:19-24  `const activeThemeName = getActiveThemeName(); if (activeThemeName in THEMES) { applyTheme(activeThemeName as ThemeName); }`\nlib/appearance.ts:49-52  `document.documentElement.classList.toggle(\"high-contrast\", loadPref<boolean>(\"highContrast\", false));`\ncomponents/settings/helpers.ts:93-96  `const root = document.documentElement; for (const [key, value] of Object.entries(theme)) { root.style.setProperty(key, value); }`\ncomponents/settings/helpers.ts:22 / :27 / :34 / :40  every THEMES entry defines `\"--text-normal\"`\nstyles/app.css:5203-5207  `.high-contrast { --text-normal: #ffffff; --text-muted: #cccccc; --bg-active: rgba(255,255,255,0.15); }`",
   "suggestedFix": "In styles/app.css, make the high-contrast tokens important and cover the body-level custom-theme case: `.high-contrast, .high-contrast body { --text-normal: #ffffff !important; --text-muted: #cccccc !important; --bg-active: rgba(255,255,255,0.15) !important; }` — important author declarations beat normal inline styles, which is exactly the relationship needed here.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "opus",
   "round": 8,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Client/tauri-client/tests/unit/appearance-high-contrast.test.ts",
    "revertProof": "pass",
    "branchCommit": "a2387480"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0050",
   "title": "CleanupVoiceForChannel's check-then-clear is not atomic, so a concurrent voice_join is silently wiped from the hub while its DB row survives",
   "file": "Server/ws/hub_sweep.go",
   "line": 316,
   "severity": "low",
   "why": "The function's own comment claims \"the client-state clear [is] conditional on the participant still being in THIS channel: a user who moved to another voice channel between the snapshot above and this loop must not be clobbered\". The implementation reads `client.getVoiceChID()` (one voiceMu acquisition), then calls `clearVoiceAndUnsubscribe`, whose `c.clearVoiceState()` (client.go:148) clears unconditionally under a *second* voiceMu acquisition. Nothing spans the compare and the clear. Every sibling site got this right — `sweepStaleVoiceStates` uses `handleVoiceLeaveIfStillIn` → `clearVoiceStateIfMatch` (client.go:164), and the LiveKit webhook inlines a token-aware compare-and-clear under one voiceMu (livekit_webhook.go:203-211).",
   "repro": "User U is in voice channel A. An admin archives or deletes A, so an HTTP handler goroutine runs CleanupVoiceForChannel(A). At the same moment U sends voice_join for channel W on their readPump goroutine. Interleaving: (1) cleanup reads client.getVoiceChID() == A → passes the guard; (2) U's handleVoiceJoin completes, running c.setVoiceState(W, joinedAt) (voice_join.go:222), subscribing VoiceTopic(W) and broadcasting voice_state for W; (3) cleanup calls clearVoiceAndUnsubscribe(client), which unconditionally zeroes voiceChID/voiceJoinToken/e2eePubKey and returns oldChID=W, then does pubsub.Unsubscribe(client, VoiceTopic(W)). U is now in voice W per voice_states but not per the hub: their VoiceTopic(W) subscription is gone (so every voice_e2ee_announce/offer relay for W is missed), broadcastVoiceEvent's participant union can no longer see them, and within 60s sweepStaleVoiceStates sees c.getVoiceChID()==0 != W, deletes the row, broadcasts voice_leave and removes them from the SFU — silently ejecting them from the call they just joined.",
   "evidence": "313:\t\t\th.mu.RLock()\n314:\t\t\tclient, ok := h.clients[vs.UserID]\n315:\t\t\th.mu.RUnlock()\n316:\t\t\tif ok && client.getVoiceChID() == channelID {\n317:\t\t\t\th.clearVoiceAndUnsubscribe(client)   // clearVoiceState() clears unconditionally\n318:\t\t\t}",
   "suggestedFix": "Replace the check+clear at hub_sweep.go:316-318 with the compare-and-clear primitive under one voiceMu acquisition: `if ok { if _, cleared := client.clearVoiceStateIfMatch(channelID); cleared { h.pubsub.Unsubscribe(client, VoiceTopic(channelID)) } }` (also clear the E2EE fields, which clearVoiceStateIfMatch already does).",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "ws-hub",
   "finder": "opus",
   "round": 1,
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Server/ws/hub_sweep_test.go",
    "revertProof": "pass",
    "branchCommit": "5cf6d1c5"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0051",
   "title": "handleReconnect returns true after a failed handshake write, so the full disconnect teardown runs twice",
   "file": "Server/ws/serve.go",
   "line": 353,
   "severity": "low",
   "why": "`unregisterFailedHandshake` is documented (serve.go:413-414) as safe because \"No readPump ever starts for this connection\". That invariant holds on the fresh-connect branch (handleFreshConnect returns an error and ServeWS returns without starting pumps) but is false on the reconnect branch: handleReconnect returns `true` after calling unregisterFailedHandshake and closing the socket, and ServeWS treats `true` as success and calls startPumps() (serve.go:69-72). readPump then runs against the closed conn, returns immediately, and its defer executes the whole teardown a second time — because unregisterNow(c) now finds no entry and reports replaced=false (a deliberate distinction locked by hub_sweep_test.go:74). This also doubles the window described in the previous finding.",
   "repro": "A client resumes with last_seq > 0 and replay succeeds, so handleReconnect calls registerNow(c) and then conn.Write(auth_ok) — which fails (peer already gone / write timeout). Path: (1) unregisterFailedHandshake(ctx, c) removes c from h.clients, runs handleVoiceLeave if a voice session was transferred, writes MarkUserDisconnected and broadcasts presence{offline} (serve.go:422-439); (2) handleReconnect returns true; (3) ServeWS calls startPumps(), spawning writePump and running readPump on the closed conn; (4) readPump returns on the first Read error and its defer calls unregisterNow(c) again — c is absent, so replaced=false — and issues a second MarkUserDisconnected plus a second BroadcastToAll(presence offline), which consumes a second hub seq, a second replay-buffer slot and a second persisted event row for a duplicate of an event already sent.",
   "evidence": "serve.go:349-353\n\t\tif err := conn.Write(ctx, websocket.MessageText, h.buildAuthOK(...)); err != nil {\n\t\t\th.unregisterFailedHandshake(ctx, c)\n\t\t\t_ = conn.Close(websocket.StatusInternalError, \"handshake failed\")\n\t\t\treturn true\n\nserve.go:69-72\n\t\tif lastSeq > 0 {\n\t\t\tif hub.handleReconnect(ctx, conn, c, database, lastSeq) {\n\t\t\t\tstartPumps()\n\t\t\t\treturn\n\nserve.go:413-414 (contradicted invariant)\n\t// ... No readPump ever starts for this connection, ...",
   "suggestedFix": "Make the two handshake-write-failure paths in handleReconnect signal 'handled, do not start pumps' — e.g. change its return to (handled, startPumps bool) returning (true, false) there and (true, true) on success, with ServeWS calling startPumps() only when both are true. (Equivalently: drop the unregisterFailedHandshake+Close calls on those two paths and let readPump's defer perform the single teardown, since pumps do start on this branch.)",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "ws-hub",
   "finder": "opus",
   "round": 1,
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/ws/serve_reconnect_double_teardown_test.go",
    "revertProof": "pass",
    "branchCommit": "14de5f22",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0052",
   "title": "GET /channels/{id}/pins has no LIMIT and no pin cap; past ~32k pins the endpoint fails permanently",
   "file": "Server/db/message_queries.go",
   "line": 635,
   "severity": "low",
   "why": "GetPinnedMessages is the only read path into scanAndEnrichMessages with no LIMIT — GetMessagesForAPI, GetMessagesAroundForAPI and both search queries are all clamped to <=100 by the service layer. Nothing caps how many messages may be pinned in a channel either (SetMessagePinned has no count check and, unlike SendMessage/handleReaction, no rate limiter), and the handler hardcodes `HasMore: false`. Because scanAndEnrichMessages then builds three `IN (?,?,...)` lists with one bound parameter per returned message, a channel with more pins than SQLite's SQLITE_MAX_VARIABLE_NUMBER (32766) makes the request fail with \"too many SQL variables\" — the pins endpoint then returns 500 for that channel forever, with no way to unpin through the UI that lists them.",
   "repro": "Any ordinary user, no moderator role required: service/message_query.go:207-214 lets any DM participant pin, so open a 1:1 DM with another user, post N messages, then PUT the pin route once per message. At N >= 32766 pins, GET /api/v1/channels/{dmId}/pins runs GetPinnedMessages, gets 32766 rows, and getReactionsBatch builds an IN list with 32767 bound parameters; SQLite rejects it with \"too many SQL variables\", scanAndEnrichMessages returns an error, and the endpoint answers 500 on every subsequent call for that channel. Below that threshold the same call still loads and JSON-serialises every pinned message with its reactions, attachments and mentions in one unpaginated response (has_more is hardcoded false, so no client can page past it).",
   "evidence": "db/message_queries.go:636-644\n\trows, err := d.reader.QueryContext(ctx,\n\t\t`SELECT m.id, m.channel_id, m.user_id, u.username, u.avatar, ...\n\t\t FROM messages m JOIN users u ON m.user_id = u.id\n\t\t WHERE m.channel_id = ? AND m.pinned = 1 AND m.deleted = 0\n\t\t ORDER BY m.id DESC`,      // <- no LIMIT\n\t\tchannelID,\n\t)\n\ndb/message_queries.go:529-537 (one bound parameter per pinned message)\n\tquery := fmt.Sprintf(\n\t\t`SELECT r.message_id, r.emoji, COUNT(*) as cnt, ...\n\t\t FROM reactions r WHERE r.message_id IN (%s) GROUP BY ...`, placeholders)\n\targs = append([]any{requestingUserID}, args...)\n\napi/channel_handler.go:373\n\twriteJSON(w, http.StatusOK, response{Messages: msgs, HasMore: false})",
   "suggestedFix": "Chunk the IN-list batches in the shared enrichment path (getReactionsBatch, getAttachmentsBatch, GetMentionsByMessageIDs) at the existing 500-id chunk size used by auth_queries.go/mention_queries.go — one guard in the shared functions covers every caller; optionally also add a pins-per-channel cap in SetMessagePinned.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "db-storage",
   "finder": "opus",
   "round": 1,
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Server/db/message_queries_test.go",
    "revertProof": "pass",
    "branchCommit": "87bf3e3a"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0053",
   "title": "Quick-switch overlay's teardown guard never fires — an orphaned modal is mounted on document.body after MainPage is destroyed",
   "file": "Client/tauri-client/src/pages/main-page/SidebarArea.ts",
   "line": 722,
   "severity": "low",
   "why": "`openQuickSwitch` awaits `profileManager.loadProfiles()` and then checks `sidebarWrapper.parentElement === null` as its \"were we torn down while awaiting?\" test. That check can never be true: MainPage tears down by removing an *ancestor* (`root.remove()` in MainPage.destroy) and never removes `sidebarWrapper` from its parent `app` div, so `sidebarWrapper.parentElement` stays non-null forever. The overlay is then created and mounted to `document.body` — outside the removed subtree — after every reference to it (`quickSwitchInstance`, still `null` when `closeQuickSwitch` ran during teardown) is gone.",
   "repro": "1. Signed in, MainPage mounted. Click the disconnect/switch button in UserBar -> `openQuickSwitch()` runs and awaits `profileManager.loadProfiles()` (a Tauri IPC round trip).\n2. While that await is pending, the session ends asynchronously — e.g. a REST 401 fires main.ts's `onUnauthorized` -> `clearAuth()`, or the server broadcasts `server_restart` with reason \"shutdown\" (dispatcher.ts:879 `clearAuth(\"server_shutdown\")`), or an `auth_error`/`BANNED` frame arrives.\n3. main.ts's authStore subscriber runs `router.navigate(\"connect\")` -> `renderPage(\"connect\")` -> `currentPage.destroy()` -> MainPage.destroy(). That runs `closeQuickSwitch()` (no-op: `quickSwitchInstance` is still null) and then `root.remove()`.\n4. `loadProfiles()` resolves. `sidebarWrapper.parentElement` is still the `app` div, so the guard passes. `createQuickSwitchOverlay(...).mount(document.body)` runs.\nResult: a full-screen `.quick-switch-backdrop` modal plus its document-level `keydown` listener (QuickSwitchOverlay.ts:167) and focus trap sit on top of the freshly-rendered ConnectPage. Nothing holds a reference to it any more, so nothing can call its `destroy()`; its own \"Switch\"/\"Add server\" buttons call `clearAuth()` against a session that no longer exists. Fix: use a `destroyed` flag set from the teardown callback (or `document.contains(sidebarWrapper)`) instead of `parentElement === null`.",
   "evidence": "function openQuickSwitch(): void {\n  if (quickSwitchInstance !== null || openingQuickSwitch) return;\n  openingQuickSwitch = true;\n  ...\n  void (async () => {\n    try {\n      ...\n      await profileManager.loadProfiles();\n      ...\n      // Ensure we haven't been cleaned up while awaiting\n      if (sidebarWrapper.parentElement === null) return;   // <-- never true\n      quickSwitchInstance = createQuickSwitchOverlay({ ... });\n      quickSwitchInstance.mount(document.body);            // <-- escapes the removed subtree\n    } finally { openingQuickSwitch = false; }\n  })();\n}\n\n// MainPage.ts destroy():\n//   for (const unsub of unsubscribers) unsub();   // includes closeQuickSwitch() -> no-op, instance is null\n//   ...\n//   finally { if (root !== null) { root.remove(); root = null; } }   // sidebarWrapper.parentElement is still `app`",
   "suggestedFix": "In createSidebarArea, add `let tornDown = false;` and change the pushed unsubscriber to `unsubscribers.push(() => { tornDown = true; closeQuickSwitch(); });`, then replace the dead guard at line 722 with `if (tornDown) return;`. (A flag beats `isConnected`, which would change behavior for unit tests that mount into a detached container.)",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "client-state",
   "finder": "opus",
   "round": 1,
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Client/tauri-client/tests/unit/sidebar-area.test.ts",
    "revertProof": "pass",
    "branchCommit": "a1a1aa96",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0054",
   "title": "blocksStore survives clearAuth(), so a previous server's block list can gate DM composers on the next server",
   "file": "Client/tauri-client/src/stores/auth.store.ts",
   "line": 93,
   "severity": "low",
   "why": "`clearAuth()` deliberately resets voiceStore, messagesStore and channelsStore because their ids are per-server, but leaves `blocksStore.blockedByMe` untouched. Block state is keyed by *user id*, which is also only unique per server. The only thing that restates it on the next session is dispatcher.ts's fire-and-forget `api.listBlocks()`, whose failure is swallowed with a `log.warn` — so a single failed request leaves the previous server's blocked-user ids applied for the whole new session.",
   "repro": "1. On server A, block the user whose id is 7 -> `setUserBlockedByMe(7, true)`, `blockedByMe = {7}`.\n2. Log out (UserBar disconnect / Settings logout / quick-switch) -> `clearAuth()`. `blockedByMe` is still `{7}`.\n3. Log into server B, where user id 7 is an unrelated person. `ready` arrives; `api.listBlocks()` is issued but rejects (transient network blip, 500, or the proxy not yet warm) — the rejection is only logged.\n4. Open a 1:1 DM with server B's user 7. ChannelController.ts:412 calls `dmComposerBlockReason(blocksStore.getState(), 7)`, which returns BLOCKED_BY_ME_REASON, so the composer is disabled for the rest of the session with \"You've blocked this user. Unblock to send messages.\" for a user that was never blocked here.\n5. MemberList.ts:289 reads the same set (`isBlocked = blockedByMe.has(member.id)`), so that member's context menu offers \"Unblock\"; clicking it sends DELETE /blocks/7 to server B.",
   "evidence": "// auth.store.ts clearAuth():\n  resetVoiceStore();\n  resetMessagesStore();\n  resetChannelsStore();\n  clearNsfwAcknowledgements();\n  cleanupNotificationAudio();\n  authStore.setState(() => ({ ...INITIAL_STATE, ... }));\n  // <-- blocksStore is never reset\n\n// dispatcher.ts READY handler — the only repopulation path:\n  clearBlockedByThem();          // only the *other* direction is cleared\n  if (api !== undefined) {\n    api.listBlocks()\n      .then((r) => setBlockedByMe(r.blocked_user_ids))\n      .catch((err) => log.warn(\"Failed to load block list\", { error: String(err) }));  // stale set survives\n  }",
   "suggestedFix": "Add `export function resetBlocksStore(): void { blocksStore.setState(() => ({ blockedByMe: new Set(), blockedByThem: new Set() })); }` to blocks.store.ts and call it in clearAuth alongside resetChannelsStore() (auth.store.ts:93). Same-server reconnects don't go through clearAuth, so the keep-until-refetch behavior there is preserved.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "client-state",
   "finder": "opus",
   "round": 1,
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/auth-store.test.ts",
    "revertProof": "pass",
    "branchCommit": "478dd94b"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0055",
   "title": "InviteManagerController.open() re-uses a pre-await root reference; a page teardown during the getInvites() fetch resurrects the overlay with a live document-level keydown listener that outlives the page",
   "file": "Client/tauri-client/src/pages/main-page/OverlayManagers.ts",
   "line": 166,
   "severity": "low",
   "why": "open() captures `const root = opts.getRoot()` and checks `instance !== null` BEFORE `await opts.api.getInvites()` (line 167-171), but never re-checks getRoot()/liveness after the await. If MainPage.destroy() runs while the fetch is in flight, its unsubscribers call headerInviteCtrl.cleanup(), but `instance` is still null (createInviteManager hasn't run yet) so cleanup() no-ops; destroy() then nulls its own `root` variable and detaches the DOM node, but the closure-local `root` const in open() still references the now-detached node. When the fetch resolves after teardown, open()'s continuation runs unconditionally: it creates a new InviteManager instance and mounts it on the stale, detached `root` (the `if (root !== null)` check on line 201 only checks the stale local, never re-derives liveness). createInviteManager's mount() (Client/tauri-client/src/components/InviteManager.ts:218) registers `document.addEventListener('keydown', ...)` for Escape-to-close, scoped to that instance's own AbortController. Because InviteManagerController.cleanup() already fired and is never invoked again for this newly-created instance, that global keydown listener is never torn down — it lives on `document` indefinitely, closing over the destroyed page's `api`/`getToast`, and will fire options.onClose() the next time Escape is pressed anywhere in the app (e.g. after the user has navigated back to the connect/login page). SidebarArea.ts's own openQuickSwitch() (same file family, lines ~703-745) demonstrates the intended fix: it re-checks `sidebarWrapper.parentElement === null` AFTER the await before mounting, exactly the guard missing here (and in PinnedPanelController.toggle at OverlayManagers.ts:252-298, which has the identical pattern though its component has no document-level listener so the blast radius is smaller — a detached, un-destroyable component instance rather than a global listener leak).",
   "repro": "1) Open the sidebar, click the Invite button (SidebarArea.ts headerInviteBtn) while the network is slow, so `opts.api.getInvites()` is pending. 2) Before it resolves, log out / get banned / server-shutdown-kick (any path that calls MainPage.destroy()). destroy() runs headerInviteCtrl.cleanup() while `instance` is still null, so nothing happens; destroy() proceeds to null/remove `root`. 3) The pending getInvites() promise resolves; open()'s continuation creates a fresh InviteManager instance and mounts it onto the now-detached root, registering a document-level 'keydown' listener via createInviteManager's own AbortController. 4) The user is now on ConnectPage (or a new MainPage from re-login). Pressing Escape anywhere triggers the zombie instance's onClose→close(), which is the only thing that will ever call its destroy() — until then this dangling document listener is a real leak that nothing in MainPage's teardown chain can reach.",
   "suggestedFix": "In open(), after the await re-derive the mount target: `const liveRoot = opts.getRoot(); if (liveRoot === null) return;` and mount on liveRoot instead of the pre-await const (delete the dead `if (root !== null)` check). getRoot() returns MainPage's `root`, which destroy() nulls, so this is an exact liveness signal. Apply the same two-line change in PinnedPanelController.toggle.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "client-state",
   "finder": "sonnet",
   "round": 1,
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Client/tauri-client/tests/unit/overlay-managers.test.ts",
    "revertProof": "pass",
    "branchCommit": "8875523c",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0056",
   "title": "ws.disconnect() cannot cancel an in-flight connect(), so a cancelled session still opens its WebSocket and re-registers Tauri listeners after teardown",
   "file": "Client/tauri-client/src/lib/ws.ts",
   "line": 585,
   "severity": "low",
   "why": "connect() is async and has three await points (ensureTauriApis, setupEventListeners' 3 tauriListen IPC round-trips, then ws_connect) after it has already bumped wsGeneration. disconnect() is fully synchronous and does NOT bump wsGeneration, so it has no way to invalidate an attempt that is mid-await: it drains eventUnsubs while that array is still partially filled, nulls config, and returns — then the suspended connect() resumes, pushes fresh (never-cleaned) unsub handles into eventUnsubs, and calls invoke(\"ws_connect\"), opening the very socket the teardown was meant to prevent.",
   "repro": "main.ts's ConnectPage `onAutoLoginCancel` (main.ts:572-588) is the exact interleaving, and its own comment says so: \"by the time a click reaches here the session is already in flight (wirePostAuth has called ws.connect and registered listeners)\". Click Cancel while auto-login is connecting → disconnect() runs during connect()'s awaits → connect() resumes and invokes ws_connect → Rust's WsState.begin_connection claims a fresh generation and completes the WSS handshake to the server the user just cancelled. The \"open\" event then flips the UI to `authenticating` (mapped to \"reconnecting\" by toConnectionStatus, so ServerBanner shows \"Reconnecting...\" on the connect page) and, because `config === null`, no auth frame is ever sent, so the socket sits unauthenticated until the server's 10s authDeadline closes it. The three tauriListen unsubs registered after disconnect()'s cleanupEventListeners() are never removed until the next connect(). The same shape applies to the logout path (main.ts:746, 814).",
   "evidence": "connect(): `wsGeneration++; config = cfg; intentionalClose = false; ... await ensureTauriApis(); ... cleanupEventListeners(); await setupEventListeners(); try { await tauriInvoke(\"ws_connect\", { url: wsUrl }) }`.  disconnect(): `intentionalClose = true; certMismatchBlock = false; cancelReconnect(); stopHeartbeat(); cleanupEventListeners(); void disconnectProxy(); setState(\"disconnected\"); config = null; lastSeq = 0; reconnectAttempt = 0;` — no `wsGeneration++`, no cancellation token consulted by connect().  The ws-state handler then hits `setState(\"authenticating\"); if (config === null) return;`",
   "suggestedFix": "In disconnect(), add `wsGeneration++;`. In connect(), capture `const gen = wsGeneration;` after the initial increment and bail (`if (gen !== wsGeneration) return;`) after `await ensureTauriApis()` and after `await setupEventListeners()`, before invoking ws_connect.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "lifecycle",
   "finder": "opus",
   "round": 2,
   "confidence": "high",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "28aa0da",
    "test": "Client/tauri-client/tests/unit/ws-lifecycle.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0057",
   "title": "showContextMenu registers a permanent \"abort\" listener on the caller's component-lifetime signal on every open, pinning each removed menu subtree",
   "file": "Client/tauri-client/src/lib/context-menu.ts",
   "line": 88,
   "severity": "low",
   "why": "The teardown hook is attached with `signal.addEventListener(\"abort\", ...)` with no `{ once: true }` and no removal path — and, unlike the per-menu `dismissAc`, the caller's `signal` is the component's whole lifetime. Each invocation therefore adds one more listener to that signal, and each listener's closure retains its `menu` element, so menus removed from the DOM (by dismissal, by the `querySelectorAll(...).remove()` sweep at line 36, or by an item click) stay reachable until the component is destroyed.",
   "repro": "Right-click DM rows N times without the DM sidebar being rebuilt: DmSidebar's `ac.signal` accumulates N abort listeners, each holding a detached `.dm-context-menu` div (plus its item children) that was already removed from the document. Nothing releases them until DmSidebar.destroy() fires the abort. Secondary consequence on the same line: if `signal` is already aborted when showContextMenu is called, the freshly-appended `menu` on document.body gets no teardown at all, because addEventListener(\"abort\") on an already-aborted signal never fires.",
   "evidence": "  // Clean up if parent component is destroyed\n  signal.addEventListener(\"abort\", () => {\n    menu.remove();\n    dismissAc.abort();\n  });\n\n// caller (DmSidebar.ts:268) passes the sidebar-lifetime signal:\nshowContextMenu({ x: e.clientX, y: e.clientY, items, signal, className: \"dm-context-menu\" });\n// where signal === ac.signal, aborted only in destroy() (DmSidebar.ts:347-348)",
   "suggestedFix": "Register the teardown hook so menu dismissal releases it: `signal.addEventListener(\"abort\", () => { menu.remove(); dismissAc.abort(); }, { signal: dismissAc.signal })`, and abort dismissAc whenever the menu is removed (item click and outside-click already do).",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "lifecycle",
   "finder": "opus",
   "round": 2,
   "confidence": "high",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "d02e647",
    "test": "Client/tauri-client/tests/unit/context-menu.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0058",
   "title": "Unban emits no WS event — *ws.Hub does not implement memberUnbanBroadcaster",
   "file": "Server/admin/handlers_users.go",
   "line": 169,
   "severity": "low",
   "why": "The ban path calls hub.BroadcastMemberBan(id) directly (a method *ws.Hub really has), but the unban path routes through a type assertion to memberUnbanBroadcaster, and BroadcastMemberUnban exists nowhere on *ws.Hub (grep finds it only in this file and admin/handlers_users_broadcast_test.go). The assertion always misses, so the DB (users.banned=0, the user is back in ListMembers) and every already-connected client's membersStore — which hard-deleted the row on member_ban — permanently disagree.",
   "repro": "Admin bans user U: BroadcastMemberBan fans member_ban out, every connected client runs removeMember(U) and drops U from membersStore, and U's socket is kicked. Admin then unbans U via PATCH /api/v1/admin/users/{id} {\"banned\": false}. ModerationService.UnbanUser commits, then the `case !*req.Banned && hub != nil` branch type-asserts and silently does nothing. U is absent from the member list, from mention autocomplete and from getTypingUsers on every client that was connected during the ban, while any client that connects afterwards gets U in its ready payload — two clients side by side showing different rosters. It only converges for the stale clients if U reconnects (handleFreshConnect broadcasts member_join) or they reconnect themselves; an unbanned user who never comes back online stays missing indefinitely. admin/handlers_users_broadcast_test.go:51 asserts the call happens against a double that implements the interface, so the suite stays green.",
   "evidence": "case *req.Banned && hub != nil:\n\thub.BroadcastMemberBan(id)          // real method on *ws.Hub\ncase !*req.Banned && hub != nil:\n\tif mub, ok := hub.(memberUnbanBroadcaster); ok {\n\t\tmub.BroadcastMemberUnban(id)    // *ws.Hub has no such method — assertion always false\n\t}",
   "suggestedFix": "Implement `func (h *Hub) BroadcastMemberUnban(userID int64)` on *ws.Hub that loads the user and role from h.db and calls h.BroadcastToAll(buildMemberJoin(user, roleName)) — the client already maps member_join to addMember, so no protocol change is needed. Add a compile-time `var _ memberUnbanBroadcaster = (*ws.Hub)(nil)` where admin is wired to the real hub so the assertion cannot silently miss again.",
   "status": "blocked",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "state-desync",
   "finder": "opus",
   "round": 2,
   "confidence": "high",
   "fix": null,
   "rationale": "cross-cluster edit: shares Server/ws/hub_broadcast.go with the hub_broadcast cluster - needs a human (agent edits saved in .superpowers/debris-2026-08-14.patch)",
   "blockedDate": "2026-08-14"
  },
  {
   "id": "OC-0059",
   "title": "Composer slow-mode cooldown is applied to whichever channel happens to be mounted when a chat_send_ok/SLOW_MODE frame arrives, not the channel the message was actually sent to",
   "file": "Client/tauri-client/src/pages/main-page/ChannelController.ts",
   "line": 450,
   "severity": "low",
   "why": "The `chat_send_ok` and `error`/SLOW_MODE listeners registered in mountChannel are global ws.on subscriptions (no per-channel filter is possible: ChatSendOkPayload has only message_id/timestamp, ErrorPayload has only code/message — neither carries channel_id). They are torn down and re-registered on every channel switch, so a frame that was actually produced by a send in the *previous* channel gets delivered to the *newly mounted* channel's handler, which unconditionally calls startSlowMode(ch.slowMode) for the channel currently mounted — desyncing the client's local slow-mode countdown (source: WS-listener side effect) from the server's actual per-channel rate-limit state (source of truth: the server's limiter, correctly scoped by channel_id there).",
   "repro": "1) Open channel A, which has slow_mode > 0. 2) Send a message in A (chat_send is sent, correlationId cid_A pending). 3) Immediately switch to channel B before the server's chat_send_ok (or a SLOW_MODE error, if A was already on cooldown) for cid_A arrives. destroyChannel() unsubscribes A's chat_send_ok/error listeners; mountChannel(B) installs B's. 4) The late chat_send_ok (or SLOW_MODE error) for the A-message arrives and is delivered only to B's handler, which reads channelsStore.get(channelId=B) and calls startSlowMode(B.slowMode) — disabling B's composer with 'Slow mode — Ns' even though B was never sent to and has no active server-side cooldown. This reproduces even with B.slowMode=0 replaced by any nonzero value; with B.slowMode=0 the call is a harmless no-op, but any channel with its own slow mode configured is falsely gated whenever the user switches into it right after posting in a slow-mode channel.",
   "suggestedFix": "Record the originating channel per correlation id (the send path already keys draftByCorrelation by correlation id — add a channelId field, or keep a controller-scoped Map<correlationId, channelId>). In both handlers, gate startSlowMode on that recorded channel equaling the mounted channelId; the server echoes the request id on SLOW_MODE errors too (buildErrorMsgWithID, Server/ws/handlers_chat.go:165), so the error handler can use the same correlation check via the second listener argument.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "state-desync",
   "finder": "sonnet",
   "round": 2,
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/channel-controller.test.ts",
    "revertProof": "pass",
    "branchCommit": "88033f02"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0060",
   "title": "A single malformed stored server profile makes the client discard all saved profiles, and the next login overwrites the on-disk list with that empty set",
   "file": "Client/tauri-client/src/lib/profiles.ts",
   "line": 112,
   "severity": "low",
   "why": "`createTauriBackend().load()` returns `null` both for \"nothing stored\" and \"stored payload failed validation\", and `isValidStoredData` is all-or-nothing over the whole array — one bad entry rejects every profile. `loadProfiles` then does nothing (`if (data !== null)`), leaving the store empty rather than surfacing a read failure, and `saveProfiles` unconditionally writes that empty in-memory list back over the stored record. `importProfiles` on the same file shows the intended tolerance (it counts `skipped` per item); the load path has none.",
   "repro": "A user has five saved server profiles. One stored entry fails `isValidProfileShape` — e.g. it was written by a build predating the `color` field, or a profile whose `name` is empty (`obj.name.length > 0`), or any hand-edit/partial write of the Tauri settings store. On launch, main.ts:625 calls `loadProfiles()`; `load()` returns null, so `profiles` stays `[]` and the connect page falls back to the synthetic \"Local Server\" entry (main.ts:439). Note main.ts:624-628's `catch` never fires — nothing throws. The user logs in; `ensureProfileExists` (main.ts:454) adds one profile and calls `persistProfiles()` (main.ts:449) → `save_settings(\"owncord:profiles\", {schemaVersion:1, profiles:[the one new profile]})`. All five originals are now permanently gone from disk. Note tests/unit/profiles.test.ts:757 pins `load()` returning null for an invalid shape, but nothing pins the manager's behaviour after that null — the destructive overwrite is untested.",
   "evidence": "async load(): Promise<StoredData | null> {\n  const raw = settings[STORAGE_KEY];\n  if (raw === undefined || raw === null) return null;\n  if (isValidStoredData(raw)) return raw;\n  return null;                       // validation failure == \"nothing stored\"\n},\n...\nasync loadProfiles(): Promise<void> {\n  const data = await backend.load();\n  if (data !== null) { setProfiles(data.profiles); }   // silently keeps []\n},\nasync saveProfiles(): Promise<void> {\n  await backend.save(toStoredData());                  // writes [...currentProfiles()]\n},",
   "suggestedFix": "Make load() salvage instead of discard: when the envelope shape is valid, return { schemaVersion, profiles: obj.profiles.filter(isValidProfileShape) } (mirroring importProfiles' per-item tolerance) so one corrupt entry drops only itself rather than nulling the whole store that the next save then overwrites.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "error-paths",
   "finder": "opus",
   "round": 2,
   "confidence": "medium",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "f1923eb",
    "test": "Client/tauri-client/tests/unit/profiles.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0061",
   "title": "NewPersistentRateLimiter silently discards LoadActiveLockouts errors, dropping all active login lockouts with no log line",
   "file": "Server/auth/ratelimit.go",
   "line": 78,
   "severity": "low",
   "why": "The constructor only populates the in-memory lockout map inside `if ... err == nil`; there is no `else` branch, so a failed DB read (SQLITE_BUSY, disk I/O error, or any other transient error from the underlying `SELECT` in LoadActiveLockouts) is dropped with zero logging anywhere in the call chain. This is inconsistent with the same package's other persistence paths (Lockout/Reset also swallow their UpsertLockout/DeleteLockout errors silently) and starkly inconsistent with this codebase's own D8 'a drop is never silent' policy that the audit writer and event persister enforce for comparable best-effort persistence. The practical effect: every account currently serving a login/password/TOTP lockout (auth/ratelimit.go callers in api/auth_handler.go, api/profile_handler.go, api/totp_handler.go) has that lockout wiped from the in-memory limiter on any server restart where the load query errors — silently re-opening the account to brute force with no operator-visible signal that recovery failed.",
   "repro": "1) An operator has an account under an active login lockout (auth_handler.go's `limiter.Lockout(...)` after repeated failed logins), persisted via UpsertLockout into the lockout_log-style table. 2) The server restarts (deploy, crash-restart, container recycle) while the SQLite writer is briefly busy/locked or the disk hiccups, so `d.q.LoadActiveLockouts` returns an error. 3) `router.go`'s `auth.NewPersistentRateLimiter(database)` call hits the `err != nil` branch of the `if` in NewPersistentRateLimiter, which has no body — the function returns a RateLimiter with an empty lockouts map for every shard, and nothing is logged. 4) The account that was mid-lockout is now immediately unlocked, and there is no log entry anywhere indicating the load failed, so the gap is invisible until someone notices the lockout 'reset itself'.",
   "suggestedFix": "Add an else branch: else { slog.Warn(\"ratelimit: failed to load persisted lockouts; starting with none\", \"err\", err) } — one log line in the constructor makes the degradation operator-visible without changing the constructor's signature.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "error-paths",
   "finder": "sonnet",
   "round": 2,
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Server/auth/ratelimit_persist_test.go",
    "revertProof": "pass",
    "branchCommit": "c8e6252a"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0062",
   "title": "Cold-tier reconnect replay has no interior-gap detection, so events the EventPersister dropped are silently skipped and presented as a complete resume",
   "file": "Server/ws/serve.go",
   "line": 210,
   "severity": "low",
   "why": "`EventPersister.Enqueue` drops on a full queue and `PersistEvents` can lose individual rows on a per-row insert failure, so the `events` table can contain interior holes. handleReconnect's cold tier guards only two of the three gap shapes: a *prefix* gap (the `GetEventsSince(ctx, 0, 1)` oldest-seq probe, serve.go:198-209) and a *tail* gap (the ring-buffer coverage check, serve.go:223-233). Nothing checks for a hole in the middle, so the `default:` branch accepts a lossy result as authoritative, sends `replay_source: \"db\"`, and the client — which tracks only `max(seq)` — advances past the missing seq and can never ask for it again.",
   "repro": "A broadcast burst overflows the 4096-entry persister queue (or one `PersistEvents` row fails), so seq 1005 is never written to `events` while 1001..1004 and 1006..1200 are. A client disconnected at last_seq=1000 stays offline long enough for the 1000-entry ring buffer to evict seq 1000, forcing the cold tier. `GetEventsSinceForChannels(1000, ...)` returns 1001..1004,1006..1200; the oldest-seq probe returns a row with seq <= 1001 so serve.go:203 passes; the buffer covers the tail so serve.go:224 passes. The client receives auth_ok with `replay_source:\"db\"`, applies 199 frames, and sets lastSeq=1200. If seq 1005 was a `chat_deleted`, `channel_update` or `member_update`, that state is permanently wrong on this client with no `ready` and no refetch to repair it.",
   "evidence": "Server/ws/serve.go:210-214 `default: persistedTail = make([][]byte, 0, len(persisted)); for _, p := range persisted { persistedTail = append(persistedTail, p.Payload) }` — accepted with no contiguity/loss check.\nServer/ws/event_persister.go:114-118 `select { case p.queue <- ...: default: p.dropped.Add(1) }` — silent drop on full queue.\nServer/ws/event_persister.go:191-196 `if failed := len(batch) - persisted; failed > 0 { p.errors.Add(...); slog.Warn(\"event persister: flush lost events\", ...) }` — rows lost on insert failure are counted and logged, never surfaced to the replay path.\nCompare serve.go:188-197, whose own comment says \"Accepting it as-is would present a hole as a complete resume, since the client tracks only max(seq)\" — the exact hazard, guarded only for the prefix case.",
   "suggestedFix": "In serve.go's cold tier, before accepting persistedTail (the default branch at ~210), verify unfiltered contiguity of the covered range: query the store for COUNT(*) of events with lastSeq < seq <= maxPersistedSeq (unfiltered) and require it to equal maxPersistedSeq - lastSeq; on mismatch, log and force the full-ready fallback like the sibling guards. Contiguity is guaranteed absent losses because every allocated seq is persisted.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "flow-reconnect",
   "finder": "opus",
   "round": 3,
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Server/ws/reconnect_interior_gap_test.go",
    "revertProof": "pass",
    "branchCommit": "1740a148"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0063",
   "title": "Connected overlay reads authStore before the auth_ok payload is dispatched, so server_name and motd are always the pre-handshake values",
   "file": "Client/tauri-client/src/main.ts",
   "line": 388,
   "severity": "low",
   "why": "`ws.onStateChange` listeners are invoked synchronously inside `setState(\"connected\")`, which ws.ts runs *before* `dispatch(msg)` — and `setAuth(token, payload.user, payload.server_name, payload.motd)` only runs inside the dispatcher's auth_ok handler during that later `dispatch`. So `authStore.getState()` at main.ts:388 still holds the pre-auth_ok state. On a first login `wirePostAuth` has written only `token`, leaving `serverName`/`motd` at their `INITIAL_STATE` value of `null`, so both `?? ` fallbacks fire and the overlay renders the raw host string and a blank MOTD even though auth_ok carried both. Nothing later repairs it: the `ws.on(\"ready\", ...)` handler at main.ts:403 only calls `markReady()`, and `createConnectedOverlay` captures its options by value at construction.",
   "repro": "Configure a server with `server_name = \"My Guild\"` and a non-empty `motd`. Launch the client fresh and log in to `192.168.1.10:8443`. auth_ok carries `server_name:\"My Guild\"` and the motd, but the connected overlay shows the title/avatar initial derived from `\"192.168.1.10:8443\"` (initial `1`) and an empty MOTD line, because setAuth has not run when line 388 executes. ChannelSidebar/SidebarArea, which subscribe to `authStore.serverName`, show \"My Guild\" once MainPage mounts — proving the value did arrive and only the overlay read it too early.",
   "evidence": "ws.ts:307-322 `if (msg.type === \"auth_ok\") { ... setState(\"connected\"); ... } dispatch(msg);` and ws.ts:171-182 `setState` → `for (const listener of stateListeners) listener(state)` (synchronous).\ndispatcher.ts:192-197 `ws.on(S.AUTH_OK, (payload) => { ... setAuth(authStore.getState().token ?? \"\", payload.user, payload.server_name, payload.motd); ...})` — the only writer of serverName/motd.\nmain.ts:344 `authStore.setState((prev) => ({ ...prev, token }));` — the only pre-connect write; serverName/motd untouched.\nstores/auth.store.ts:43-48 `const INITIAL_STATE: AuthState = { token: null, user: null, serverName: null, motd: null, isAuthenticated: false };`\nmain.ts:388-394 `const auth = authStore.getState(); ... serverName: auth.serverName ?? host, ... motd: auth.motd ?? \"\",`",
   "suggestedFix": "Create the overlay from the auth_ok payload instead of the store: in wirePostAuth, replace the onStateChange(\"connected\") trigger with a one-shot ws.on(\"auth_ok\", (payload) => { ... serverName: payload.server_name ?? host, motd: payload.motd ?? \"\" ... }) (registered after wireDispatcher), keeping the same self-unsubscribe and destroy-before-create logic.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "flow-reconnect",
   "finder": "opus",
   "round": 3,
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/main.test.ts",
    "revertProof": "pass",
    "branchCommit": "c3a20a95"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0064",
   "title": "The dispatcher's catch-all server-error branch writes to `transientError`, which only ConnectPage renders — every unhandled error is invisible in-app and then resurfaces stale on the login screen",
   "file": "Client/tauri-client/src/lib/dispatcher.ts",
   "line": 1002,
   "severity": "low",
   "why": "`setTransientError` has exactly one consumer in the whole client: ConnectPage's subscription/mount read (ConnectPage.ts:267 and :276), which pushes it into the login form. MainPage never subscribes and never clears it. So the branch that the code comments call \"the one place every remaining server error lands ... so it must not be silently dropped\" does in fact drop it while the user is in the app, and leaves it latched in the store until the login page next mounts.",
   "repro": "grep confirms only two read sites for `transientError` (ui.store.ts declaration aside): ConnectPage.ts:267,276. In a voice call, have a user with a LOWER user id join — the incumbent key holder's `voice_e2ee_offer` is answered with NOT_KEY_HOLDER (Server/ws/voice_e2ee.go:199), which matches none of the special-cased codes above (BANNED / pendingSends / reaction / CHANNEL_FULL / VIDEO_LIMIT) and falls into line 1002. Nothing is shown. Later the user hits Disconnect/logout; ConnectPage mounts, reads the latched value at line 276 and shows `loginForm.showError(\"only the key holder may send key offers\")` on the login form — an error from a different screen, minutes earlier, presented as a login failure.",
   "evidence": "dispatcher.ts:1002\n  setTransientError(payload.message || \"Server error\");\n\nConnectPage.ts:274-280\n  const pendingError = uiStore.getState().transientError;\n  if (pendingError) {\n    loginForm.showError(pendingError);\n    setTransientError(null);\n  }\n\n(no other module reads uiStore.transientError)",
   "suggestedFix": "In the catch-all branch (dispatcher.ts:1002), surface in-app errors the same way the sibling CHANNEL_FULL/VIDEO_LIMIT branches do — showToast(payload.message || \"Server error\", \"error\") — keeping setTransientError only for flows that also leave the session (BANNED, shutdown), and update the dispatcher tests that assert the store write for the catch-all codes.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "flow-voice",
   "finder": "opus",
   "round": 3,
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/dispatcher.test.ts",
    "revertProof": "pass",
    "branchCommit": "4aa9c4fc"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0065",
   "title": "participant_joined webhook treats a GetVoiceState read error as proof of a rogue participant and ejects a legitimate one from the SFU",
   "file": "Server/ws/livekit_webhook.go",
   "line": 132,
   "severity": "low",
   "why": "`stateErr != nil` is OR'd into the same condition as `state == nil || state.ChannelID != channelID`, so a transient DB read failure is indistinguishable from \"no membership row\" and results in `RemoveParticipant`. The sibling eviction path deliberately refuses to make that conflation: `sweepStaleVoiceStates` uses `hasChannelPermChecked` precisely because \"a transient read failure (I/O error, lock contention, a maintenance window) is not a revocation\" and skips the tick instead of evicting. The webhook has no such guard, and its removal is one-sided: it does not delete the voice_states row and does not broadcast voice_leave, so the server keeps believing the user is in voice.",
   "repro": "User joins voice; the client connects to the SFU; LiveKit posts participant_joined. If `h.db.GetVoiceState(ctx, userID)` returns a transient error (SQLITE_BUSY under concurrent writes, an I/O error, a maintenance window), the handler logs \"rogue participant_joined\" and calls `h.livekit.RemoveParticipant(...)`. The user is kicked out of the SFU mid-call while their voice_states row and hub voice state stay intact; other participants see no voice_leave, and their E2EE key holder does not rotate. The victim's client sees a non-CLIENT_INITIATED Disconnected and enters attemptAutoReconnect — which, per the 5-minute token TTL finding, also fails for any session older than 5 minutes.",
   "evidence": "Server/ws/livekit_webhook.go:131-142\n  state, stateErr := h.db.GetVoiceState(ctx, userID)\n  if stateErr != nil || state == nil || state.ChannelID != channelID {\n      slog.Warn(\"livekit webhook: rogue participant_joined — no matching voice state, removing\", ...)\n      if h.livekit != nil { h.livekit.RemoveParticipant(ctx, channelID, userID, joinToken) }\n      return\n  }\n\n// contrast, Server/ws/hub_sweep.go:166-177\n  if err != nil {\n      // A transient read failure ... is not a revocation ... Skip this client this tick\n      continue\n  }",
   "suggestedFix": "Split the condition in handleWebhookParticipantJoined: on stateErr != nil, slog.Error and return WITHOUT calling RemoveParticipant (optionally retry the read once), so only a definitive nil row or channel mismatch is treated as rogue — mirroring sweepStaleVoiceStates' skip-on-error guard.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "flow-voice",
   "finder": "opus",
   "round": 3,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Server/ws/livekit_test.go + Server/ws/livekit_webhook_joined_test.go",
    "revertProof": "pass",
    "branchCommit": "9981220f"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0066",
   "title": "applyMentionCounts runs after SendMessage returns, so a mark_read that lands in between leaves a permanent mention badge on a channel with zero unread",
   "file": "Server/service/message_crud.go",
   "line": 218,
   "severity": "low",
   "why": "`applyMentionCounts` is dispatched to a background goroutine after the message is committed, and `IncrementMentionCounts` upserts `mention_count = mention_count + 1` unconditionally — it never compares against the recipient's read state. `UpdateReadState` (the only writer that zeroes `mention_count`) can therefore run *before* the increment. The in-code rationale asserts the opposite outcome (\"if a reader's channel_focus clears it in the tiny window before the increment lands, the badge simply does not reappear\"); it does reappear, and because `GetChannelUnreadCounts` reports `mention_count` straight from the row while `unread_count` is computed from `last_message_id`, the next `ready` ships mention_count=1 with unread_count=0.",
   "repro": "User U has channel C focused (read_states row: last_message_id=500, mention_count=0). User A posts message 501 containing `@U`; `SendMessage` commits row 501 and spawns the badge goroutine. Before that goroutine reaches `IncrementMentionCounts`, U switches channels — `ChannelController.mountChannel` fires `markChannelRead(C)` → `mark_read` → `HandleChannelFocus` → `UpdateReadState(U, C, 501)`, setting last_message_id=501 and mention_count=0. The goroutine then runs and sets mention_count=1. The row is now (last=501, mention=1): `GetChannelUnreadCounts` reports unread_count=0, mention_count=1, so the next `ready` paints a red mention badge on C with nothing unread behind it, `hasUnread(C)` stays true and \"Mark All as Read\" stays lit until U opens C again.",
   "evidence": "Server/service/message_crud.go:214-220  `// The count is advisory: if a reader's channel_focus clears it in the tiny window before the increment lands, the badge simply does not reappear` … `s.bg(func() { s.applyMentionCounts(context.WithoutCancel(ctx), channelID, authorID, mentions, isDM, participantIDs) })` with `bg: func(fn func()) { go fn() }` (Server/service/message.go:144)\nServer/db/mention_queries.go:214-218  `INSERT INTO read_states (…) VALUES %s ON CONFLICT(user_id, channel_id) DO UPDATE SET mention_count = mention_count + 1`\nServer/db/dbgen/messages.sql.go:254-260  `UpdateReadState … DO UPDATE SET last_message_id = excluded.last_message_id, mention_count = 0`\nServer/db/message_queries.go:588-594  ready's unread query: `COUNT(*) … m.id > COALESCE(rs.last_message_id, 0)` for unread, but `COALESCE(rs.mention_count, 0)` verbatim for mentions",
   "suggestedFix": "Thread the triggering message id into applyMentionCounts → IncrementMentionCounts and make the upsert read-state-aware: ON CONFLICT(user_id, channel_id) DO UPDATE SET mention_count = mention_count + 1 WHERE read_states.last_message_id < ?msgID. A reader whose read state already advanced past the mentioning message then gets a no-op instead of a phantom badge — one guard in the shared query, no caller changes beyond passing msgID.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "flow-message",
   "finder": "opus",
   "round": 3,
   "confidence": "medium",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/db/mention_queries_test.go",
    "revertProof": "pass",
    "branchCommit": "081bb169",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0067",
   "title": "The identical GetDMParticipantIDs-failure gap silently drops chat_edited fan-out for DM edits",
   "file": "Server/service/message_crud.go",
   "line": 316,
   "severity": "low",
   "why": "EditMessage already wrote the new content via s.st.EditMessage before this block. When s.st.GetDMParticipantIDs then errors, the function logs and falls through (no early return) leaving result.ParticipantIDs at its nil zero value while still returning (result, nil). handleChatEditV2 (Server/ws/handlers_chat.go:122-128) builds MessageEditedDMEvent{participantIDs: result.ParticipantIDs} from that nil slice; EmitEvents -> sendSequencedToUsers iterates zero recipients (same code path as the SendMessage finding above), so the chat_edited frame reaches nobody, not even the editor's own other sessions. The other DM participant's client keeps showing the pre-edit content indefinitely (there is no other WS signal that would prompt a refetch of that message), even though the DB row and any REST re-fetch of channel history would already show the edited text -- a live desync between what is persisted and what every connected client displays.",
   "repro": "A and B share a DM; A previously sent message M. A edits M while s.st.GetDMParticipantIDs(ctx, channelID) transiently fails inside EditMessage (Server/service/message_crud.go:316-321). The DB row for M is updated with the new content and edited_at, but result.ParticipantIDs stays nil, so MessageEditedDMEvent fans out to zero users. B's already-loaded message list keeps showing the original, pre-edit text with no edited marker, and nothing server-side ever pushes a correction to B's live session.",
   "suggestedFix": "Same shared guard as the send path: use context.WithoutCancel(ctx) for the GetDMParticipantIDs lookup (the edit is already committed, so the fan-out bookkeeping must not die with the editor's socket), and in handleChatEditV2 fall back to MessageEditedChannelEvent when result.IsDM && result.ParticipantIDs is empty so focused DM viewers still receive the edit live.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "flow-message",
   "finder": "sonnet",
   "round": 3,
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/service/message_crud_test.go",
    "revertProof": "pass",
    "followUp": "9cdef406",
    "branchCommit": "081bb169",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0068",
   "title": "A DM message delete is committed but its chat_deleted fan-out is silently dropped when GetDMParticipantIDs fails",
   "file": "Server/service/message_crud.go",
   "line": 388,
   "severity": "low",
   "why": "DeleteMessage logs a GetDMParticipantIDs error and returns a DeleteMessageResult with a nil ParticipantIDs, after the soft-delete has already committed. handleChatDeleteV2 builds MessageDeletedDMEvent from that nil slice and EmitEvents routes it to sendSequencedToUsers, whose recipient loop then iterates zero users — the delete succeeds server-side and reaches nobody, with no error returned to the deleter.",
   "repro": "User A deletes their own message in a DM with B. The DeleteMessage row commits (message_crud.go:371) and the audit row is written, then GetDMParticipantIDs returns an error (SQLITE_BUSY under write contention, or a context deadline on a loaded server). ParticipantIDs stays nil, so MessageDeletedDMEvent carries no recipients and sendSequencedToUsers delivers to zero clients. The client only removes a row from messages.store on the CHAT_DELETED dispatcher event (dispatcher.ts:547-551) — ChannelController's onDeleteClick just sends chat_delete and toasts \"Message deleted\" — so A sees the success toast while the message stays on screen for A and for B until a full refetch. The frame did consume a seq and sits in the replay buffer, but every connected client's lastSeq watermark advances past it on the next frame, so a later reconnect can never request it back.",
   "evidence": "service/message_crud.go:387-394\n\tif isDM {\n\t\tparticipantIDs, pErr := s.st.GetDMParticipantIDs(ctx, msg.ChannelID)\n\t\tif pErr != nil {\n\t\t\tslog.Error(\"MessageService.DeleteMessage GetDMParticipantIDs\", \"err\", pErr, ...)\n\t\t} else {\n\t\t\tresult.ParticipantIDs = participantIDs\n\t\t}\n\t}\n\treturn result, nil\n\nws/hub_broadcast.go:607-619\nfunc (h *Hub) sendSequencedToUsers(channelID int64, userIDs []int64, msg []byte) {\n\t...\n\tseq := h.nextSeq()\n\twrapped := wrapWithSeq(msg, seq)\n\th.replayBuf.Push(seq, channelID, wrapped)\n\th.persistEvent(seq, channelID, wrapped)\n\tfor _, userID := range userIDs {   // empty -> delivered to nobody\n\t\th.SendToUser(userID, wrapped)\n\t}\n}",
   "suggestedFix": "In DeleteMessage, call s.st.GetDMParticipantIDs BEFORE s.st.DeleteMessage (participants do not change as a result of the delete) and return an error on failure, so no committed-but-unbroadcast state can exist. At minimum, wrap the existing post-commit fetch in context.WithoutCancel(ctx) to close the disconnect-after-commit window.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-client-tauri-client-src",
   "finder": "opus",
   "round": 4,
   "confidence": "medium",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/service/message_crud_test.go",
    "revertProof": "pass",
    "followUp": "9cdef406",
    "branchCommit": "081bb169",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0069",
   "title": "A DM reaction is persisted but its reaction_update fan-out is silently dropped when GetDMParticipantIDs fails",
   "file": "Server/service/message_reactions.go",
   "line": 147,
   "severity": "low",
   "why": "Same shape as DeleteMessage: handleReaction commits the AddReaction/RemoveReaction row, then leaves result.ParticipantIDs nil on a GetDMParticipantIDs error. reactionV2Handler builds ReactionDMEvent from that nil slice, so the reaction_update reaches no participant while the DB row exists.",
   "repro": "User A reacts to a message in a DM with B. s.st.AddReaction commits, then GetDMParticipantIDs errors (transient DB failure/context deadline). ParticipantIDs is nil, so sendSequencedToUsers delivers the reaction_update to nobody. B never sees the pill. On A's side the optimistic pill from addOptimisticReaction stays rendered but its pendingReactions entry (keyed by the WS envelope id) is never consumed by updateReaction, so it lingers until a disconnect rolls it back — at which point A's pill reverts even though the reaction is persisted server-side, and the two sides disagree until a refetch. No error is returned to A.",
   "evidence": "service/message_reactions.go:146-155\n\tif isDM {\n\t\tparticipantIDs, pErr := s.st.GetDMParticipantIDs(ctx, msg.ChannelID)\n\t\tif pErr != nil {\n\t\t\tslog.Error(\"MessageService.handleReaction GetDMParticipantIDs\", \"err\", pErr, ...)\n\t\t} else {\n\t\t\tresult.ParticipantIDs = participantIDs\n\t\t}\n\t}\n\treturn result, nil\n\nws/handlers_reaction.go:46-52\n\t\tif result.IsDM {\n\t\t\treturn Result{Events: []Event{ReactionDMEvent{\n\t\t\t\tchannelID:      result.ChannelID,\n\t\t\t\tparticipantIDs: result.ParticipantIDs,   // nil\n\t\t\t\tpayload:        reactionPayload,\n\t\t\t}}}\n\t\t}",
   "suggestedFix": "In handleReaction, fetch GetDMParticipantIDs before performing the AddReaction/RemoveReaction mutation and fail the request on error (participants are unaffected by the mutation), eliminating the committed-but-unbroadcast state. At minimum, use context.WithoutCancel(ctx) for the post-commit fetch.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-client-tauri-client-src",
   "finder": "opus",
   "round": 4,
   "confidence": "medium",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/service/message_reactions_test.go",
    "revertProof": "pass",
    "branchCommit": "76d94578",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0070",
   "title": "channel_focus has no archived-channel gate, so a client can subscribe to the live event stream of a channel every visibility surface hides — and reconnect replay then filters those same events out",
   "file": "Server/service/channel.go",
   "line": 245,
   "severity": "low",
   "why": "HandleChannelFocus gates only on READ_MESSAGES, and permissions.Checker.HasChannelPerm ignores ch.Archived (only VisibleChannelIDs applies the archived rule, checker.go:119). Every sibling path — buildReady, REST ListVisibleChannels, computeAllowedChannels, RefreshChannelVisibility and handleVoiceJoin — refuses or hides archived channels explicitly, so focus is the one path that lets a socket re-attach to one.",
   "repro": "1. Admin archives #foo via PATCH /admin/api/channels/{id}. handlePatchChannel calls RefreshChannelVisibility, which sends channel_delete to every client and calls pubsub.Unsubscribe(c, ChannelTopic(foo)) plus clears c.channelID — the channel is now hidden from ready, REST ListVisibleChannels and computeAllowedChannels.\n2. A user who still holds READ_MESSAGES on #foo sends {\"type\":\"channel_focus\",\"payload\":{\"channel_id\":<fooID>}}.\n3. HandleChannelFocus passes (the archived flag is never consulted), so handlers.go:170 re-subscribes the socket to ChannelTopic(foo) and UpdateReadState advances the user's read state on a channel that is not in their ready payload.\n4. The socket now receives every chat_edited / reaction_update / chat_deleted / chat_bulk_deleted broadcast for #foo live (the archived read-only rule exists only on SendMessage), while computeAllowedChannels — used to filter reconnect replay — excludes #foo. On the next resume those identical events are dropped from replay, so the live stream and the resume path permanently disagree about the same channel, and the client's focused channel points at one its own channel list no longer contains.",
   "evidence": "service/channel.go:240-247 (no ch.Archived branch)\n\tif ch.Type == \"dm\" {\n\t\tok, err := s.st.IsDMParticipant(ctx, userID, channelID)\n\t\tif err != nil || !ok { return nil, fmt.Errorf(\"%w: access denied\", ErrForbidden) }\n\t} else if !s.perms.HasChannelPerm(ctx, userID, channelID, permissions.ReadMessages) {\n\t\treturn nil, fmt.Errorf(\"%w: access denied\", ErrForbidden)\n\t}\n\npermissions/checker.go:116-119 (archived is applied ONLY in VisibleChannelIDs)\n\t\t// Archived channels are hidden from every client surface (admins ...)\n\t\tif ch.Archived {\n\nws/voice_join.go:92-95 (the sibling gate that does exist)\n\tif ch.Archived {\n\t\tc.sendMsg(buildErrorMsg(ErrCodeBadRequest, \"channel is archived\"))\n\t\treturn\n\t}\n\nws/handlers.go:158-172 (a successful focus subscribes the socket to ChannelTopic)\n\tif result.SetChannelID != nil { ... c.hub.pubsub.Subscribe(c, ChannelTopic(newChID)) }",
   "suggestedFix": "One guard in the shared service function (covers both channel_focus and mark_read): in HandleChannelFocus after the GetChannel lookup, add `if ch.Type != \"dm\" && ch.Archived { return nil, fmt.Errorf(\"%w: access denied\", ErrForbidden) }`.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-ws",
   "finder": "opus",
   "round": 4,
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Server/service/channel_test.go",
    "revertProof": "pass",
    "branchCommit": "56bdc1d2"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0071",
   "title": "A sidebar re-render during a channel drag detaches the drop container, so the reorder silently no-ops",
   "file": "Client/tauri-client/src/components/channel-sidebar/drag-reorder.ts",
   "line": 111,
   "severity": "low",
   "why": "`activeDrag` captures the `channelsContainer` element that existed when the row was rendered. `ChannelSidebar.renderChannels()` does `clearChildren(channelList)` and rebuilds every category group, so any re-render while the mouse button is down leaves `drag.containerEl` (and `drag.sourceEl`, and the stale `drag.channels` snapshot) detached from the document. The global `mouseup` hit-test then queries the detached subtree, where `getBoundingClientRect()` returns an all-zero DOMRect for every row, so no row can ever satisfy `e.clientY >= rect.top && e.clientY <= rect.bottom` and `dropTargetId` stays null. The handler returns at the `dropTargetId === null` guard, and the drag is discarded with no error, no toast and no visual trace. The same staleness silently kills the drop indicator during `mousemove` (line 74-89 also queries the detached container), so the user watches the indicator disappear and then the drop does nothing.",
   "repro": "Sign in with MANAGE_CHANNELS. Press the mouse down on a channel row and move >5px to start a drag. While still holding the button, have another user post a message in any channel that is not the active one (this calls `incrementUnread`, which builds a new `channels` Map, which fires the `subscribeSelector` at ChannelSidebar.ts:847, which runs `renderChannels()` and detaches the container captured in `activeDrag`). Release the mouse over a different channel row. Expected: the channel moves. Actual: `drag.containerEl.querySelectorAll(...)` returns rows whose `getBoundingClientRect()` is `{top:0,bottom:0}`, `dropTargetId` stays null, the handler returns, `onReorder` is never called and no position is written — the drag is lost with no feedback. Same happens on a category collapse, a connection-status flip, or any voice mute/camera change during the drag.",
   "evidence": "drag-reorder.ts:100-125\n      const drag = activeDrag;\n      activeDrag = null;\n      ...\n      const items = drag.containerEl.querySelectorAll(\"[data-drag-channel-id]\");\n      let dropTargetId: number | null = null;\n      ...\n      for (const item of items) {\n        const rect = item.getBoundingClientRect();\n        if (e.clientY >= rect.top && e.clientY <= rect.bottom) { ... }\n      }\n      if (dropTargetId === null || dropTargetId === drag.channelId) {\n        return;\n      }\n\nChannelSidebar.ts:751-796 (renderChannels)\n    clearChildren(channelList);\n    ...\n    for (const [category, channels] of grouped) {\n      channelList.appendChild(renderCategoryGroup(...));   // new channelsContainer every time\n    }\n\nrenderChannels() is wired to high-frequency stores:\nChannelSidebar.ts:847  channelsStore.subscribeSelector((s) => s.channels, () => renderChannels());\nChannelSidebar.ts:891  voiceStore.subscribeSelector(<structural sig>, () => renderChannels());\n\nchannels.store.ts:337-353 (incrementUnread) replaces the channel object AND the Map on every\nmessage delivered to a non-active channel, so the selector above fires.",
   "suggestedFix": "In the global mousemove/mouseup handlers, when !drag.containerEl.isConnected, re-resolve the live container via document.querySelector(`[data-drag-channel-id=\"${drag.channelId}\"]`)?.closest('.category-channels-container') (and rebuild the channel snapshot for that group from channelsStore) before hit-testing; or equivalently have renderChannels() re-target activeDrag's containerEl/sourceEl/channels when it rebuilds while a drag it owns is in flight.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "opus",
   "round": 4,
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "4b4fc0a",
    "test": "Client/tauri-client/tests/unit/drag-reorder.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0072",
   "title": "voice_mod_move's pre-flight omits the archived-channel gate that voice_join enforces, so the move drops the target out of voice for nothing",
   "file": "Server/ws/voice_moderation.go",
   "line": 295,
   "severity": "low",
   "why": "handleVoiceModMoveV2 documents itself as a pre-flight that \"refuse[s] a move the re-join would only bounce, so the target is never dropped from voice for nothing\", and it validates destination existence, type, the TARGET's CONNECT_VOICE, and capacity. It never checks dest.Archived, but the re-join it depends on (handleVoiceJoin, voice_join.go:92) refuses an archived channel with BAD_REQUEST. The handler has `dest` (a *db.Channel carrying Archived) in hand and simply does not consult it, so the move commits its destructive half — DB row deleted, LiveKit participant removed, voice_leave broadcast — for a re-join that is guaranteed to be rejected.",
   "repro": "1. Admin PATCHes voice channel B to archived=true (admin/handlers_channels.go:266 fires CleanupVoiceForChannel, so B is empty; B stays type=\"voice\" with Archived=1). 2. Target user T is in voice channel A. 3. A moderator with MUTE_MEMBERS outranking T sends {\"type\":\"voice_mod_move\",\"payload\":{\"user_id\":T,\"to_channel_id\":B}} (to_channel_id is client-supplied; no UI is needed). 4. Pre-flight passes: dest != nil, dest.Type == \"voice\", T holds CONNECT_VOICE on B (Archived is not part of permission resolution), capacity is free. 5. disconnectFromVoiceIn evicts T from A — voice_states row deleted, LiveKit participant removed, voice_leave broadcast — and voice_moved is sent. 6. T's client answers with voice_join B, which handleVoiceJoin rejects at voice_join.go:92 with BAD_REQUEST \"channel is archived\". T ends the sequence out of voice entirely, with an error and no way back to A except a manual rejoin — exactly the outcome the handler's doc comment says the pre-flight exists to prevent.",
   "evidence": "dest, err := d.DB.GetChannel(ctx, c.ToChannelID())\n...\nif dest.Type != \"voice\" {\n\treturn Result{Error: ClientError{Code: ErrCodeBadRequest, Message: \"destination is not a voice channel\"}}\n}\n// ...no `if dest.Archived` branch anywhere in handleVoiceModMoveV2...\nif !disconnectFromVoiceIn(ctx, d.Mod, c.TargetID(), state.ChannelID) { ... }\nd.Mod.SendToUser(c.TargetID(), buildVoiceMoved(c.ToChannelID()))\n\n// voice_join.go:92 — the gate the re-join actually applies:\nif ch.Archived {\n\tc.sendMsg(buildErrorMsg(ErrCodeBadRequest, \"channel is archived\"))\n\treturn\n}",
   "suggestedFix": "In handleVoiceModMoveV2, immediately after the dest.Type check (voice_moderation.go:295-297), add: if dest.Archived { return Result{Error: ClientError{Code: ErrCodeBadRequest, Message: \"channel is archived\"}} } — same error shape voice_join.go:92 uses.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-ws",
   "finder": "opus",
   "round": 5,
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/ws/voice_moderation_test.go",
    "revertProof": "pass",
    "branchCommit": "6e21556f",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0073",
   "title": "channelReadAudience does not exclude archived channels, so admin edits to an archived channel are broadcast directly to every user whose base role has READ_MESSAGES",
   "file": "Server/ws/hub_broadcast.go",
   "line": 126,
   "severity": "low",
   "why": "channelReadAudience (used by broadcastChannelScoped -> BroadcastChannelUpdate/BroadcastChannelCreate, by broadcastVoiceEvent, and by CleanupVoiceForChannel's audience build) fetches the channel row at line 141 and only special-cases ch.Type==\"dm\"; it never checks ch.Archived. Its sibling RefreshChannelVisibility (same file, ~line 321: `case ch.Archived: visible = false`) explicitly treats an archived channel as invisible to everyone regardless of role, matching VisibleChannelIDs (permissions/checker.go:119, `if ch.Archived { continue }`) and the doc comment on RefreshChannelVisibility ('Archived channels are hidden from every client regardless of permissions'). channelReadAudience's own doc comment claims it 'Mirrors RefreshChannelVisibility, which resolves visibility the same way' but the archived check present there was never added here. The underlying HasChannelPerm/HasChannelPermBatch calls it delegates to (permissions/checker.go:69, service/permission.go:53-68) also never consult Archived — only the higher-level VisibleChannelIDs does. Delivery bypasses pub/sub entirely: deliverBroadcast's bm.recipients!=nil branch calls h.SendToUser per audience member directly (hub_broadcast.go ~line 667), so even a client that was never subscribed to the channel's topic (and never had it in its ready payload / sidebar) still receives the frame on its live socket.",
   "repro": "1) Admin archives voice channel #42 (handlePatchChannel, admin/handlers_channels.go, Archived: true committed to DB). Ordinary members' role has base READ_MESSAGES on #42 but the channel is now invisible everywhere else (VisibleChannelIDs excludes it from ready/reconnect, RefreshChannelVisibility sent them channel_delete/never showed it). 2) Admin PATCHes #42 again while it stays archived (e.g. edits topic/nsfw/slow_mode) — `existing.Archived == updated.Archived` so RefreshChannelVisibility is never called, but `hub.BroadcastChannelUpdate(updated)` always runs (admin/handlers_channels.go line 253) -> ws/hub_broadcast.go broadcastChannelScoped -> channelReadAudience(ctx, 42) returns every connected user whose role has READ_MESSAGES (archived not checked) -> deliverBroadcast SendToUser's the channel_update JSON (id, name, topic, category, archived flag) straight to those sockets, none of whom ever had #42 in their store or subscribed to its topic. Same gap fires if the admin archives a voice channel while people are still in it: CleanupVoiceForChannel (hub_sweep.go:332) calls channelReadAudience on the now-archived channel and broadcasts each evicted participant's voice_leave to the same over-broad, archived-blind audience, disclosing who was in the hidden voice channel to users who should never learn it exists.",
   "suggestedFix": "In channelReadAudience, inside the h.db != nil block after the GetChannel error handling (hub_broadcast.go:149), add: if ch != nil && ch.Archived { return []int64{} } — one guard in the shared audience function covers BroadcastChannelCreate/Update, broadcastVoiceEvent, finishVoiceLeave and CleanupVoiceForChannel at once (the archive-transition voice_leave fan-out keeps working because CleanupVoiceForChannel's audience is resolved before the eviction ordering matters only client-side, and its evicted-participant append is unconditional).",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-ws",
   "finder": "sonnet",
   "round": 5,
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Server/ws/hub_broadcast_test.go",
    "revertProof": "pass",
    "branchCommit": "96ac3992"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0074",
   "title": "EditMessage's DM detection fails open on a GetChannel error, skipping the block gate and misrouting the edit fan-out",
   "file": "Server/service/message_crud.go",
   "line": 253,
   "severity": "low",
   "why": "`chanType` stays \"\" when the channel read fails, so a DM edit takes the non-DM branch: `requireDMNotBlocked` and `IsDMParticipant` never run, and `result.IsDM` is false, so the ws layer emits MessageEditedChannelEvent (topic fan-out) instead of MessageEditedDMEvent (participant fan-out).",
   "repro": "Bob has blocked Alice. Alice edits her own older DM message while GetChannel returns a transient error. isDM=false, so the `requireDMNotBlocked` branch at line 265 is skipped and `checkSendPermission(ctx, userID, msg.ChannelID, \"\")` runs the non-DM path, which passes on the base role mask (no override rows exist for a DM channel). The edit commits with arbitrary new text and, because result.IsDM is false, handleChatEditV2 (ws/handlers_chat.go:129) returns MessageEditedChannelEvent -> BroadcastToChannel(dmChannelID), delivering it to whoever holds the DM topic subscription rather than to the participant list — the exact channel back to the blocker that the requireDMNotBlocked doc comment says it exists to close.",
   "evidence": "ch, chErr := s.st.GetChannel(ctx, msg.ChannelID)\nchanType := \"\"\nif chErr == nil && ch != nil {\n\tchanType = ch.Type\n}\nisDM := chanType == \"dm\"",
   "suggestedFix": "Fail closed: after line 253, `if chErr != nil || ch == nil { return nil, fmt.Errorf(\"%w: cannot edit this message\", ErrForbidden) }` and derive chanType from ch.Type unconditionally.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-service",
   "finder": "opus",
   "round": 5,
   "confidence": "medium",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/service/message_crud_test.go",
    "revertProof": "pass",
    "branchCommit": "081bb169",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0075",
   "title": "handleReaction's DM detection fails open on a GetChannel error, letting a non-participant react inside a private DM",
   "file": "Server/service/message_reactions.go",
   "line": 105,
   "severity": "low",
   "why": "Identical swallowed-error pattern: a failed channel read makes a DM take the role-based branch, bypassing IsDMParticipant and requireDMNotBlocked, and the reaction is then fanned out as ReactionChannelEvent instead of ReactionDMEvent.",
   "repro": "Mallory (any role with READ_MESSAGES|ADD_REACTIONS, or any ADMINISTRATOR) sends reaction_add for a message id belonging to Alice and Bob's private DM while GetChannel errors. isDM=false -> HasChannelPerm resolves from the base mask on a channel with no override rows -> true -> the reaction row is written to a DM Mallory is not a participant of, and reactionV2Handler (ws/handlers_reaction.go:53) emits ReactionChannelEvent, publishing it onto the DM's channel topic where Alice and Bob see an outsider's reaction on their private message.",
   "evidence": "ch, chErr := s.st.GetChannel(ctx, msg.ChannelID)\nisDM := chErr == nil && ch != nil && ch.Type == \"dm\"\n\nif isDM {\n\tok, dmErr := s.st.IsDMParticipant(ctx, userID, msg.ChannelID)\n\t...\n} else if !s.perms.HasChannelPerm(ctx, userID, msg.ChannelID, permissions.ReadMessages|permissions.AddReactions) {",
   "suggestedFix": "Fail closed: after line 105, `if chErr != nil || ch == nil { return nil, fmt.Errorf(\"%w: message not found\", ErrBadRequest) }` and compute `isDM := ch.Type == \"dm\"`.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-service",
   "finder": "opus",
   "round": 5,
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Server/service/message_reactions_test.go",
    "revertProof": "pass",
    "branchCommit": "8243e60d"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0076",
   "title": "The admin setup rate limiter is never reaped, so its window map grows without bound for the life of the process",
   "file": "Server/admin/api.go",
   "line": 34,
   "severity": "low",
   "why": "`setupLimiter` is a dedicated auth.RateLimiter that nothing ever calls Cleanup or StartCleanup on — unlike the API limiter, which api/router.go:76 puts on a 5-minute reaper. Its `windows` map therefore accumulates one permanently-live entry per distinct source IP.",
   "repro": "handleSetup calls limiter.Allow(\"setup:\"+host, 5, time.Minute) at setup_handler.go:125, BEFORE the CreateOwnerIfEmpty check at :172 that rejects an already-configured server. So on a fully set-up, production server, every unauthenticated POST /admin/api/setup still allocates an `entry` in setupLimiter.shards[...].windows keyed by the peer IP and appends a time.Time — and nothing ever deletes it (RateLimiter.Cleanup is the only eviction path and is never invoked on this instance). A host reachable on an IPv6 /64 sees the map grow one entry (~key string + up to 5 time.Time) per source address indefinitely; the entries survive even though every request is 403ing.",
   "evidence": "// admin/api.go:34\nsetupLimiter := auth.NewRateLimiter()\nr.Post(\"/setup\", handleSetup(database, setupLimiter, allowedOrigins, hub, setupOpts))\n\n// vs api/router.go:76\ngo limiter.StartCleanup(rateLimiterCleanupInterval, rateLimiterCleanupMaxWindow, limiterStopCh)",
   "suggestedFix": "Mirror api/router.go: in NewAdminAPI start `go setupLimiter.StartCleanup(5*time.Minute, 15*time.Minute, stopCh)` (plumbing the router's existing limiterStopCh through, or reusing the router's already-reaped limiter for the setup endpoint).",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-service",
   "finder": "opus",
   "round": 5,
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Server/admin/setup_limiter_reap_test.go",
    "revertProof": "pass",
    "branchCommit": "8d6dee6b"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0077",
   "title": "DeleteMessage has no archived-channel gate — the read-only invariant has a fifth hole",
   "file": "Server/service/message_crud.go",
   "line": 329,
   "severity": "low",
   "why": "SendMessage was fixed to refuse writes into an archived channel (message_crud.go:54-56, locked by TestSendMessage_RefusedInArchivedChannel), and the already-known finding at message_crud.go:268 documents that EditMessage, handleReaction, SetMessagePinned and PurgeMessages were left uncovered by that fix. DeleteMessage (lines 329-397) has the identical gap and was not named in that list: it fetches the channel at line 345 (`ch, chErr := s.st.GetChannel(ctx, msg.ChannelID)`) purely to determine `isDM`, and `ch.Archived` is never read anywhere in the function. Both the ownership-only DM path and the READ_MESSAGES|MANAGE_MESSAGES / owner-SEND_MESSAGES channel path proceed straight to `s.st.DeleteMessage(ctx, msgID, userID, isMod)` at line 371 regardless of the channel's archived flag, and the underlying db.DeleteMessage (db/message_queries.go:165) has no archived check either. This lets a member soft-delete their own message, or a moderator soft-delete anyone's message, in a channel the send path and every visibility surface treat as frozen — directly contradicting the SendMessage comment's stated invariant that 'History stays readable; only writes are refused.'",
   "repro": "Archive channel 10 (`UPDATE channels SET archived = 1 WHERE id = 10`) after it has message history. A member who authored a message in channel 10 (or a moderator with READ_MESSAGES|MANAGE_MESSAGES on it) sends chat_delete for that message id. GetChannel returns Archived=true but DeleteMessage never inspects it; ownership/permission checks pass as normal; s.st.DeleteMessage soft-deletes the row and the handler broadcasts chat_deleted to the channel — the archive's history is silently mutated exactly the way SendMessage was fixed to prevent.",
   "suggestedFix": "In DeleteMessage, after the (fail-closed) GetChannel fetch: `if !isDM && ch.Archived { return nil, fmt.Errorf(\"%w: channel is archived\", ErrForbidden) }` — matching SendMessage lines 54-56 (and the same one-line gate belongs in the sibling write sinks already tracked in the ledger).",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-service",
   "finder": "sonnet",
   "round": 5,
   "confidence": "medium",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/service/message_crud_test.go",
    "revertProof": "pass",
    "followUp": "9cdef406",
    "branchCommit": "081bb169",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0078",
   "title": "renderAll's rapid-fire breaker discards the update instead of deferring it, leaving the message list permanently stale",
   "file": "Client/tauri-client/src/components/MessageList.ts",
   "line": 658,
   "severity": "low",
   "why": "When more than 20 renderAll calls occur inside the 2s window the function returns before rebuildItems(), so the store change that triggered it is simply dropped. Nothing re-schedules a render when renderAllResetTimer clears the counter, so the DOM keeps showing pre-burst state until some later, unrelated store event happens to arrive.",
   "repro": "In a busy channel, have 21+ non-append store updates land in separate microtask notifications inside 2s — e.g. a moderator purge that arrives as 25 individual chat_deleted frames, or a burst of reaction_update frames. tryAppendMessages() returns false for all of them (prefix comparison fails / next.length <= prev.length), so each one calls renderAll(). Calls 21-25 log \"renderAll called >20 times in 2s\" and return; allMessages/virtualItems still contain the deleted rows. Two seconds later the counter resets but no render is queued, so the deleted messages stay on screen — and stay clickable — until the next unrelated update (a new message, a roleRevision bump) triggers another renderAll.",
   "evidence": "renderAllCount++;\nif (renderAllCount > 20) {\n  log.error(\"[MessageList] renderAll called >20 times in 2s — breaking loop\");\n  return;            // <- update dropped, nothing re-queued\n}\nif (renderAllResetTimer === 0) {\n  renderAllResetTimer = window.setTimeout(() => { renderAllCount = 0; renderAllResetTimer = 0; }, 2000);\n}",
   "suggestedFix": "When the breaker trips, remember it (e.g. renderAllSuppressed = true) and have the 2s reset timeout call renderAll() once if the flag is set, so the final state of a burst is always rendered.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "opus",
   "round": 5,
   "confidence": "medium",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "a910975",
    "test": "Client/tauri-client/tests/unit/message-list.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0079",
   "title": "An emptied message edit is submitted (and edit mode torn down) when an attachment is queued in the composer",
   "file": "Client/tauri-client/src/components/MessageInput.ts",
   "line": 472,
   "severity": "low",
   "why": "The empty-content early return is disabled by `hasAttachments`, but `pendingAttachments` is only meaningful for a new message — the edit branch never reads it. So with a file queued, an edit whose text the user cleared reaches `onEditMessage(id, \"\")`, which the host rejects with a toast, and `cancelEdit()` then runs unconditionally, dropping the user out of edit mode and wiping the textarea. The identical keystroke with no attachment queued is a harmless no-op that preserves edit state.",
   "repro": "In a channel with uploads wired: (1) click \"+\" and attach any small image — the preview bar shows it and pendingAttachments.length === 1; (2) press ArrowUp on the empty composer (or click Edit on one of your messages) to enter edit mode — startEdit fills the textarea with the original content, pendingAttachments is untouched; (3) select all and delete the text, then press Enter. Expected (and what happens with no attachment queued): the send is refused at line 472 and the user stays in edit mode. Actual: `hasAttachments` is true, so the guard is skipped, `onEditMessage(messageId, \"\")` fires, a \"Message cannot be empty\" error toast appears, and `cancelEdit()` immediately exits edit mode and clears the textarea — the user has lost the edit and must re-open it.",
   "evidence": "function handleSend(): void {\n  if (disabledReason !== null) return;\n  if (textarea === null) return;\n  const content = textarea.value.trim();\n  const hasAttachments = pendingAttachments.length > 0;\n  if (content.length === 0 && !hasAttachments) return;   // <-- line 472\n  ...\n  if (state.editing !== null) {\n    options.onEditMessage(state.editing.messageId, content);   // content === \"\"\n    cancelEdit();                                             // runs regardless\n  }\n\n// ChannelController.ts:357-362 (the onEditMessage host):\n//   const trimmed = content.trim();\n//   if (trimmed === \"\") { showToast(\"Message cannot be empty\", \"error\"); return; }\n\n// handlePasteFile only refuses attachments queued DURING an edit (MessageInput.ts:539):\n//   if (state.editing !== null) { showUploadError(\"Can't attach files while editing a message\"); return; }\n// It does not cover attach-then-edit, so pendingAttachments can be non-empty while state.editing !== null.",
   "suggestedFix": "In handleSend, make the empty-content guard ignore attachments when editing (edits are text-only): change line 472 to `if (content.length === 0 && (state.editing !== null || !hasAttachments)) return;`.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-client-tauri-client-src",
   "finder": "opus",
   "round": 6,
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "760686c",
    "test": "Client/tauri-client/tests/unit/message-input.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0080",
   "title": "teardownForReconnect() has the same generation-guard gap as leaveVoice(), so a camera/screenshare enable racing an unexpected LiveKit disconnect can publish a track to the room being torn down for auto-reconnect",
   "file": "Client/tauri-client/src/lib/livekitSession.ts",
   "line": 348,
   "severity": "low",
   "why": "roomEventHandlers.ts's handleDisconnected (line 184) calls deps.teardownForReconnect() on every unexpected disconnect that is eligible for auto-reconnect, before nulling the room and calling room.disconnect() (roomEventHandlers.ts:187-193). teardownForReconnect (livekitSession.ts:329-352) mirrors leaveVoice: it tells the server camera/screenshare are off, then calls stopManualCameraTrack(this._cameraState, this._room) and stopManualScreenTracks(this._screenState, this._room) directly (lines 348-349) and resets setLocalCamera(false)/setLocalScreenshare(false) (lines 350-351) — again without bumping state.generation, unlike doDisableCamera/doDisableScreenshare. An enableCamera()/enableScreenshare() call that is awaiting device acquisition when an unexpected disconnect fires will, on resuming, pass the stale-generation check and attempt to publish onto the room object that is about to be (or already was) disconnected and replaced by attemptAutoReconnect's fresh Room, leaving a leaked/orphaned local track and a store state that can disagree with what is actually being sent once the new room comes up.",
   "repro": "1) Join voice (room R1). 2) Click 'Enable camera'; enableCamera() captures room=R1, generation=0, and is awaiting createLocalVideoTrack() (device prompt already granted previously, so this await is just the getUserMedia latency, still enough for the race). 3) The LiveKit connection drops unexpectedly (network blip) — RoomEvent.Disconnected fires handleDisconnected, which calls teardownForReconnect(): stops manual tracks (no-op, nothing published yet), sends voice_camera(false)/voice_screenshare(false) if they were on, resets the store, but leaves this._cameraState.generation at 0; then the room is disconnected and replaced via attemptAutoReconnect. 4) createLocalVideoTrack resolves; enableCamera()'s stale-generation check still reads 0 === 0, so it sets state.manualCameraTrack and calls publishTrack on the old, disconnected R1 reference — a publish that races the reconnect instead of being cleanly superseded the way an explicit disableCamera() would have caused.",
   "suggestedFix": "Same one-line-per-state fix as the leaveVoice finding: call the shared supersede/bumpGeneration helper on this._cameraState and this._screenState at the top of the teardownForReconnect callback (before livekitSession.ts:348-349).",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-client-tauri-client-src",
   "finder": "sonnet",
   "round": 6,
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Client/tauri-client/tests/unit/livekit-session.test.ts",
    "revertProof": "pass",
    "branchCommit": "db7d518b"
   },
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0081",
   "title": "voice_max_video cap counts the requester's own camera row, so a user whose server-side camera flag is already 1 can never re-enable",
   "file": "Server/db/queries/sqlite/voice.sql",
   "line": 92,
   "severity": "low",
   "why": "EnableCameraIfUnderLimit's guard subquery counts every camera=1 row in the channel, including the very row the UPDATE targets. An enable request from a user whose row already has camera=1 therefore needs maxVideo-1 other publishers to pass, so at the cap it is refused against the requester's own stream. The zero-rows result is also indistinguishable from \"no voice_states row for this channel\", and handleVoiceCameraV2 maps both to VIDEO_LIMIT \"maximum N video streams reached\".",
   "repro": "Channel with voice_max_video = 1. User A enables their camera: COUNT(camera=1)=0 < 1, row updated to camera=1. A's client-side localCamera then falls out of sync with the row while the row stays 1 — the confirmed enableCamera supersession gap (Client/tauri-client/src/lib/screenShare.ts:243) does exactly this: a disableCamera that lands during publishTrack resets localCamera to false but the server row keeps camera=1. A now presses the camera button (VoiceCallbacks.ts:110 computes next = !localCamera = true) and the server runs EnableCameraIfUnderLimit(A, ch, 1): the subquery counts A's own row, 1 < 1 is false, 0 rows affected, ok=false. A receives VIDEO_LIMIT \"maximum 1 video streams reached\" while being the only video publisher in the room, and every retry repeats it — there is no path that clears camera back to 0 except A sending voice_camera{enabled:false}, which the UI will not do because it believes the camera is already off.",
   "evidence": "Server/db/queries/sqlite/voice.sql:90-92 — `UPDATE voice_states SET camera = 1 WHERE voice_states.user_id = ? AND voice_states.channel_id = ? AND (SELECT COUNT(*) FROM voice_states AS vs2 WHERE vs2.channel_id = ? AND vs2.camera = 1) < ?;` (no `AND vs2.user_id <> ?` exclusion, and no `AND camera = 0` on the outer UPDATE). Consumed at Server/ws/voice_controls.go:116 `ok, limitErr := d.DB.EnableCameraIfUnderLimit(ctx, userID, voiceChID, ch.VoiceMaxVideo)` with the refusal at voice_controls.go:121-126 returning ErrCodeVideoLimit.",
   "suggestedFix": "Exclude the requester's own row from the count in EnableCameraIfUnderLimit: change the subquery to `WHERE vs2.channel_id = ? AND vs2.camera = 1 AND vs2.user_id <> voice_states.user_id` (or bind userID again with `AND vs2.user_id <> ?`), then regenerate the sqlc layer via the db-change workflow. This makes re-enable idempotent while still refusing a genuinely new publisher at the cap.",
   "status": "blocked",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-ws",
   "finder": "opus",
   "round": 6,
   "confidence": "high",
   "fix": null,
   "rationale": "cross-cluster edit: shares Server/db/voice_queries.go with Server/ws/hub_sweep.go - needs a human (agent edits saved in .superpowers/debris-2026-08-14.patch)",
   "blockedDate": "2026-08-14"
  },
  {
   "id": "OC-0082",
   "title": "Pinning a soft-deleted message returns HTTP 500: SetMessagePinned leaks db.ErrNotFound unwrapped, and lacks the deleted-message guard its siblings have",
   "file": "Server/service/message_query.go",
   "line": 227,
   "severity": "low",
   "why": "`SetMessagePinned` is the only method in MessageService that returns a raw store error to its caller instead of wrapping it in the service error taxonomy. The pin SQL carries `AND deleted = 0`, so a soft-deleted target produces `db.ErrNotFound`, which `errors.Is(err, service.ErrNotFound)` does not match — `writeServiceError` falls through to `default:` and answers 500 INTERNAL_ERROR instead of 404. It is also the only message mutation with no `msg.Deleted` check: EditMessage returns ErrDeletedMessage (message_crud.go:248) and handleReaction returns ErrBadRequest (message_reactions.go:101).",
   "repro": "Moderator A has the pinned-messages panel open showing message M (GET /channels/{id}/pins). Moderator B deletes M (soft delete: `deleted = 1`, pinned still 1). A clicks unpin → DELETE /api/v1/channels/{id}/pins/{M}. GetMessage still returns the row (db.GetMessage deliberately returns soft-deleted rows), so the channel/message checks pass; the UPDATE matches 0 rows, db.ErrNotFound propagates unwrapped, and the client gets `500 {\"error\":\"INTERNAL_ERROR\"}` plus a server-side `slog.ErrorContext(\"service error\")` line, rather than the 404 the sibling not-found paths return (locked by TestSetPinned_MessageNotFound / TestSetPinned_ChannelNotFound in api/channel_handler_test.go — neither covers the deleted case).",
   "evidence": "service/message_query.go:223-227\n```\n\tmsg, err := s.st.GetMessage(ctx, msgID)\n\tif err != nil || msg == nil || msg.ChannelID != channelID {\n\t\treturn fmt.Errorf(\"%w: message not found in this channel\", ErrNotFound)\n\t}\n\treturn s.st.SetMessagePinned(ctx, msgID, pinned)\n```\n(no `msg.Deleted` branch; raw store error returned)\n\ndb/queries/sqlite/messages.sql:27  `UPDATE messages SET pinned = ? WHERE id = ? AND deleted = 0;`\ndb/message_queries.go:732  `return fmt.Errorf(\"SetMessagePinned: message %d: %w\", id, ErrNotFound)`  — that is `db.ErrNotFound` (db/errors.go:11), a distinct sentinel from `service.ErrNotFound` (service/message.go:24).\napi/channel_handler.go:407-426 (`writeServiceError`) has no `db.ErrNotFound` arm, so this lands in `default:` → 500.",
   "suggestedFix": "In service.SetMessagePinned, wrap the store call: `if err := s.st.SetMessagePinned(ctx, msgID, pinned); err != nil { if errors.Is(err, db.ErrNotFound) { return fmt.Errorf(\"%w: message not found in this channel\", ErrNotFound) }; return fmt.Errorf(\"%w: %v\", ErrInternal, err) }`. This maps the deleted case to 404, keeps genuine failures as 500, and — unlike only adding `|| msg.Deleted` to the line-224 guard — also covers a delete racing between GetMessage and the UPDATE.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-service",
   "finder": "opus",
   "round": 6,
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/service/message_test.go",
    "revertProof": "pass",
    "branchCommit": "6a32319a",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0083",
   "title": "ConnectPage.destroy() never clears uiStore.settingsOpen, so the settings panel pops open over MainPage immediately after login",
   "file": "Client/tauri-client/src/pages/ConnectPage.ts",
   "line": 286,
   "severity": "low",
   "why": "MainPage.destroy() explicitly calls `closeSettings()` for exactly this reason (\"the next page to mount an (initially hidden) SettingsOverlay off that flag — ConnectPage, after logout — would show it over the login screen\"). ConnectPage.destroy() only destroys its own lazily-created overlay and leaves `settingsOpen === true` in the store. MainPage eagerly mounts a SettingsOverlay whose `mount()` ends with `if (uiStore.getState().settingsOpen) show()`, so the stale flag opens the full settings panel on top of the freshly loaded app.",
   "repro": "On the connect page, type credentials and press Login; while the request is in flight (or during an auto-login), click the settings gear. `openSettings()` sets `settingsOpen = true` and the SettingsOverlay chunk starts loading. Login succeeds -> `wirePostAuth` -> WS `ready` -> `ConnectedOverlay.markReady()` fires `onReady` after READY_DELAY_MS (800 ms, ConnectedOverlay.ts:26/116) with no user interaction -> `router.navigate(\"main\")` -> `renderPage` destroys ConnectPage (settingsOpen still true) -> MainPage mounts and its SettingsOverlay calls `show()`. The user lands in the app with the settings panel covering it, having never asked for it there.",
   "evidence": "ConnectPage.ts:286-306 — destroy() { abortController.abort(); unsubSettingsOpen?.(); unsubTransientError?.(); settingsOverlay?.destroy?.(); settingsOverlay = null; setTransientError(null); ... }   // no closeSettings()\nMainPage.ts:756-762 — closeSettings();  // with the comment naming the symmetric ConnectPage case\nMainPage.ts:416 + 501 — const settingsOverlay = createSettingsOverlay({...}); settingsOverlay.mount(root);\nSettingsOverlay.ts:392-395 — // Sync initial state\\n    if (uiStore.getState().settingsOpen) { show(); }\nConnectPage.ts:78 — onSettingsOpen: () => openSettings()   // the gear is never disabled during \"loading\"/\"connecting\" (LoginForm.updateFormInputsDisabled only touches host/username/password/invite)",
   "suggestedFix": "In ConnectPage.destroy() (ConnectPage.ts:286), call closeSettings() alongside the existing setTransientError(null), mirroring MainPage.destroy().",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "opus",
   "round": 6,
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Client/tauri-client/tests/unit/connect-page.test.ts",
    "revertProof": "pass",
    "branchCommit": "152a32f9",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0084",
   "title": "VideoGrid's track-mute handler adds a `track-muted` class that no stylesheet defines, so a stalled remote camera keeps showing a frozen frame",
   "file": "Client/tauri-client/src/components/VideoGrid.ts",
   "line": 151,
   "severity": "low",
   "why": "The handler's stated job is to hide the tile's video while the remote track is muted, but the hiding is expressed purely by toggling `track-muted`, and there is no `.track-muted` rule in app.css, base.css, login.css, tokens.css or theme-neon-glow.css. Nothing else in the mute path touches the element's visibility, so the branch is a no-op.",
   "repro": "Join a video call with a remote peer, then have that peer's camera track fire `mute` (network stall, or the sender pausing the track). `onTrackMute` runs and adds `track-muted` to the `.video-cell`. Because no CSS matches that class, the `<video>` element keeps rendering its last decoded frame at full opacity — the viewer sees a live-looking but frozen tile with no indication the stream stalled, which is the exact state the handler was written to hide.",
   "evidence": "VideoGrid.ts:148-156 —\n    const onTrackMute = (): void => {\n      // Temporarily hide video — track may unmute after network recovery\n      const cell = cells.get(userId);\n      if (cell !== undefined) cell.el.classList.add(\"track-muted\");\n    };\n    const onTrackUnmute = (): void => { ... classList.remove(\"track-muted\"); };\n`grep -rn \"track-muted\" src/styles/` -> no matches (compare `.video-focus-main .video-cell` at app.css:5091 and `.video-focus-strip .video-cell` at app.css:5104, which do exist).",
   "suggestedFix": "Add a rule to app.css alongside the other .video-cell styles, e.g. `.video-cell.track-muted video { visibility: hidden; }` (optionally with a background on .video-cell.track-muted), so the tile blanks while the track is muted and reappears on unmute.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "opus",
   "round": 6,
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/video-grid-track-muted-css.test.ts",
    "revertProof": "pass",
    "branchCommit": "3ba8cd36"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0085",
   "title": "Collapsed sidebar categories are persisted under the server's display name, not its host, so two default-named servers share one localStorage entry",
   "file": "Client/tauri-client/src/pages/main-page/SidebarArea.ts",
   "line": 230,
   "severity": "low",
   "why": "`loadCollapsedCategories(serverHost)` builds the localStorage key `owncord:collapsed:<arg>` and `saveCollapsedCategories` writes back under the same `currentServerHost`. The one caller passes `authStore.getState().serverName` — the operator-configured display name from `auth_ok` — not `api.getConfig().host`. Every sibling per-server preference in this client is host-scoped for exactly this reason (`setChannelMutesHost`, `setNsfwGateHost`, `setAudioVolumeHost`, all wired from `MainPage.ts:105-107` with `apiConfig.host`), and channel-mutes.ts's own doc comment names `ui.store.ts`'s `loadCollapsedCategories` as following that per-connection host convention. The server's default name is `\"OwnCord Server\"` (Server/config/config.go:212), so unmodified instances all collide on one key.",
   "repro": "Save two profiles pointing at two different self-hosted servers, both left at the default `server.name = \"OwnCord Server\"`, each with a category named e.g. \"Text Channels\". 1. Connect to server A, collapse \"Text Channels\" -> `toggleCategory` writes localStorage[\"owncord:collapsed:OwnCord Server\"] = [\"Text Channels\"]. 2. Log out, connect to server B. SidebarArea calls loadCollapsedCategories(\"OwnCord Server\") -> reads A's entry -> B's \"Text Channels\" renders collapsed although the user never collapsed it there. 3. Expand it on B -> the same key is rewritten to [] -> A's collapse state is destroyed. Renaming either server also orphans all of that host's saved state, because the key follows the name.",
   "evidence": "// SidebarArea.ts:228-230\n// Load per-server collapsed category state from localStorage\nconst initialServerName = authStore.getState().serverName ?? \"Server\";\nloadCollapsedCategories(initialServerName);\n\n// ui.store.ts:122-133\nconst COLLAPSED_KEY_PREFIX = \"owncord:collapsed:\";\nlet currentServerHost: string | null = null;\nexport function loadCollapsedCategories(serverHost: string): void {\n  currentServerHost = serverHost;\n  const raw = localStorage.getItem(COLLAPSED_KEY_PREFIX + serverHost);\n\n// MainPage.ts:105-107 — the sibling prefs, all host-scoped\nsetChannelMutesHost(apiConfig.host ?? null);\nsetNsfwGateHost(apiConfig.host ?? null);\nsetAudioVolumeHost(apiConfig.host ?? null);",
   "suggestedFix": "Scope the key to the connected host like the sibling prefs: in MainPage.ts next to setChannelMutesHost/setNsfwGateHost/setAudioVolumeHost (lines 105-107), call loadCollapsedCategories(apiConfig.host ?? \"\") and delete the loadCollapsedCategories(initialServerName) call at SidebarArea.ts:228-230 (matching the per-connection wiring channel-mutes.ts:55-57 already describes).",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-client-tauri-client-src",
   "finder": "opus",
   "round": 7,
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/sidebar-area.test.ts",
    "revertProof": "pass",
    "branchCommit": "4d167fd4"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0086",
   "title": "sweepStaleVoiceStates classifies ghost rows from a snapshot and then deletes them without re-checking, so an in-flight voice_join is ejected from the SFU while the hub still believes the user is in the room",
   "file": "Server/ws/hub_sweep.go",
   "line": 220,
   "severity": "low",
   "why": "The ghost loop decides staleness under one h.mu.RLock (lines 202-218) and then acts on that decision in a second, much longer loop that performs a DB delete, a channelReadAudience resolution, a broadcast and a LiveKit RemoveParticipant (5s timeout) per entry. The LeaveVoiceChannelIfMatch guard only protects against the user having moved to a *different* row — it matches the very row the in-flight join just created, because joined_at is identical. The revocation loop in the same function (lines 182-187) applies exactly the opposite discipline via handleVoiceLeaveIfStillIn, with a comment explaining why (\"a voice_join to a still-permitted channel may have committed while it ran\"); that reasoning was never carried into the ghost loop below it.",
   "repro": "Voice channel V already holds several genuine ghost rows (e.g. after a server restart, or several crashed clients), so the `stale` loop has work to do and each iteration costs a channelReadAudience resolution plus a LiveKit RemoveParticipant with a 5s timeout.\n1. The 60s voiceSweepTicker fires. sweepStaleVoiceStates reads GetAllVoiceStates and takes the h.mu.RLock snapshot at T0.\n2. At T0, user X's voice_join has committed its row via JoinVoiceChannel (voice_join.go:196) but has not yet reached c.setVoiceState (voice_join.go:222) — one GetVoiceState round trip away. X's client still reports getVoiceChID() == 0, so X's row is appended to `stale`.\n3. X's join then completes normally: setVoiceState, Subscribe(VoiceTopic(V)), updateKeyHolder(V), broadcastVoiceEvent(voice_state) — every other client is told X joined, and X's client connects to the SFU.\n4. Seconds later the sweep reaches X's entry. LeaveVoiceChannelIfMatch(X, V, joinedAt) matches — it is literally the row X's join created — and deletes it. voice_leave is broadcast for X. RemoveParticipant(V, X, joinedAt) uses the same identity and kicks X out of the LiveKit room.\n5. Nothing clears X's in-memory state: c.voiceChID is still V and c.voiceJoinToken is still joinedAt, and X remains subscribed to VoiceTopic(V).\nOutcome: X is silently ejected from the SFU seconds after joining while the hub and X's own client both still believe X is in voice. updateKeyHolder(V) at line 245 scans h.clients, sees X's live voiceChID == V, and can elect X key holder for a room X is not in — every other participant's voice_e2ee_offer is then rejected with NOT_KEY_HOLDER. X's voice_mute/voice_camera writes hit zero rows and voiceStateBroadcast returns Result{} (state == nil), so the toggles silently no-op, and no later sweep can heal it because the sweep only iterates DB rows.",
   "evidence": "hub_sweep.go:202-249\n\th.mu.RLock()\n\tvar stale []struct{ userID, channelID int64; joinedAt string }\n\tfor _, vs := range allStates {\n\t\tc, ok := h.clients[vs.UserID]\n\t\tif !ok || c.getVoiceChID() != vs.ChannelID {   // <-- decided here, under one RLock\n\t\t\tstale = append(stale, ...)\n\t\t}\n\t}\n\th.mu.RUnlock()\n\n\tfor _, s := range stale {                        // <-- acted on here, seconds later, no re-check\n\t\tdeleted, err := h.db.LeaveVoiceChannelIfMatch(ctx, s.userID, s.channelID, s.joinedAt)\n\t\t...\n\t\th.broadcastVoiceEvent(ctx, s.channelID, buildVoiceLeave(s.channelID, s.userID))\n\t\th.updateKeyHolder(s.channelID)\n\t\tif h.livekit != nil { _ = h.livekit.RemoveParticipant(ctx, s.channelID, s.userID, s.joinedAt) }\n\t}\n\ncontrast, same function, hub_sweep.go:181-187\n\t\t// The permission check is a DB round-trip; a voice_join to a\n\t\t// still-permitted channel may have committed while it ran. The\n\t\t// eviction is conditional on the client still being in the checked\n\t\t// channel — never on whatever channel it is in by now.\n\t\tif !h.handleVoiceLeaveIfStillIn(ctx, c, chID) { continue }\n\nthe window being raced, voice_join.go:196-222\n\t\tif err := h.db.JoinVoiceChannel(ctx, c.userID, channelID); ... // row committed\n\t\tstate, err := h.db.GetVoiceState(ctx, c.userID)                // still voiceChID == 0 here\n\t\t...\n\t\tc.setVoiceState(channelID, state.JoinedAt)                     // only now non-zero",
   "suggestedFix": "In the ghost-classification loop (hub_sweep.go:208-217), add the grace-period guard the codebase's own cross_batch note prescribes: parse vs.JoinedAt and `continue` for rows younger than a grace window (e.g. 2x the 60s sweep interval), so a just-committed join can never be classified as a ghost regardless of when c.setVoiceState lands.",
   "status": "blocked",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-ws",
   "finder": "opus",
   "round": 7,
   "confidence": "high",
   "fix": null,
   "rationale": "cross-cluster edit: shares Server/db/voice_queries.go with Server/db/queries/sqlite/voice.sql - needs a human (agent edits saved in .superpowers/debris-2026-08-14.patch)",
   "blockedDate": "2026-08-14"
  },
  {
   "id": "OC-0087",
   "title": "Global search silently drops every DM hit when the DM-id lookup fails, and reports success",
   "file": "Server/service/message_perms.go",
   "line": 44,
   "severity": "low",
   "why": "GetAccessibleChannelIDs discards the error from GetUserDMChannelIDs entirely — no return, no log, not even a slog.Warn — so a transient failure yields an accessible-channel set with every DM missing. SearchMessages then runs SearchMessagesInChannels over that truncated set and returns HTTP 200 with an authoritative-looking result list. The identical lookup in the WS sibling (ws/serve.go:505, computeAllowedChannels) is deliberately fatal, with a comment stating that a silently DM-stripped set is a permanent hole.",
   "repro": "User U has one DM containing the message \"deploy key rotated\". GET /api/v1/search?q=deploy normally returns that hit via SearchMessages' global branch (message_query.go:100). Make GetUserDMChannelIDs fail once — SQLITE_BUSY against the single writer, or the request ctx being cancelled between the ListChannels/role reads and this call. GetAccessibleChannelIDs returns only the guild-channel ids, SearchMessagesInChannels is scoped to those, and the handler writes 200 {\"results\":[]}. Nothing is logged, and the user reads it as 'that message does not exist'. Worse: if U's role also has no visible guild channels, accessibleIDs is empty and SearchMessages returns (nil, nil) at message_query.go:104, i.e. a successful empty search rather than a 500.",
   "evidence": "// Server/service/message_perms.go:43-49\n// Also include DM channels the user participates in. Only the IDs are\n// needed here, so skip the full DM query's preview/unread work.\ndmIDs, err := s.st.GetUserDMChannelIDs(ctx, userID)\nif err == nil {\n\tids = append(ids, dmIDs...)\n}\n\nreturn ids, nil\n\n// Server/ws/serve.go:505-508 — same call, opposite posture\ndmIDs, dmErr := database.GetUserDMChannelIDs(ctx, user.ID)\nif dmErr != nil {\n\treturn nil, fmt.Errorf(\"computeAllowedChannels GetUserDMChannelIDs: %w\", dmErr)\n}",
   "suggestedFix": "Fail like the three sibling lookups in the same function: `if err != nil { return nil, fmt.Errorf(\"%w: failed to fetch DM channels: %v\", ErrInternal, err) }`.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-service",
   "finder": "opus",
   "round": 7,
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Server/service/message_perms_test.go",
    "revertProof": "pass",
    "branchCommit": "bd3b9e6b"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0088",
   "title": "Registry.DispatchCommand reads runtimePlatform without the registry lock that Close() writes it under",
   "file": "Server/plugin/host_commands.go",
   "line": 71,
   "severity": "low",
   "why": "DispatchCommand dereferences r.runtimePlatform (an interface-typed field, two words) with no lock, while Registry.Close sets it to nil under r.mu.Lock(). Registry.activate reads the same field under r.mu.RLock() and its doc comment states explicitly that the guard exists so a concurrent Close cannot be observed mid-use — DispatchCommand is the one reader that skips it, so the nil check can pass against a runtime Close has already torn down.",
   "repro": "Build with -tags wazero and a plugin owning /roll. A WS client sends {\"type\":\"chat_command\",\"payload\":{\"command\":\"roll\",...}} on a readPump goroutine at the moment shutdown runs Registry.Close on the main goroutine. DispatchCommand's unsynchronised read of r.runtimePlatform races Close's write: `go test -race` reports a data race on the field, and on a torn or stale-non-nil read invokeCommand proceeds into a wazero runtime whose modules Close has already deactivated (registry.go:120), panicking the readPump goroutine instead of returning the ErrRuntimeUnavailable diagnostic.",
   "evidence": "// host_commands.go:71 — unguarded read\nif r.runtimePlatform == nil {\n\treturn &CommandResult{...}, true\n}\nreturn r.invokeCommand(ctx, inst, userID, channelID, cmd, args)\n\n// registry.go:132-135 — concurrent write under r.mu\nr.platformClose = nil\nr.runtimePlatform = nil\nr.mu.Unlock()\n\n// registry.go:447-452 — the sibling reader, guarded\nr.mu.RLock()\nplatform := r.runtimePlatform\nr.mu.RUnlock()\nif platform == nil {\n\treturn ErrRuntimeUnavailable\n}",
   "suggestedFix": "Capture the field under the RLock already held for the map lookup: `r.mu.RLock(); inst, ok := r.commands[cmd]; platform := r.runtimePlatform; r.mu.RUnlock()` and test `platform == nil` at line 71 (matching activate's pattern).",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-service",
   "finder": "opus",
   "round": 7,
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/plugin/host_commands_race_test.go",
    "revertProof": "pass",
    "revertProofNote": "race-class fix: proven red/green manually under go test -race; plain-run verify-fixes reported a false VACUOUS before the -race escalation was added",
    "branchCommit": "7071c64d",
    "pr": 1369
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0089",
   "title": "`additionalBrowserArgs` silently drops wry's default `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection` on Windows",
   "file": "Client/tauri-client/src-tauri/tauri.conf.json",
   "line": 22,
   "severity": "low",
   "why": "Tauri/wry pass `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection` to the WebView2 browser process by default; setting `additionalBrowserArgs` REPLACES that default rather than appending to it (documented on `WindowConfig::additional_browser_args` / `WebViewBuilder::with_additional_browser_args`: \"you also need to disable these components by yourself\"). This config supplies only the two media flags, so the three suppressed WebView2 features are re-enabled in every Windows build — including SmartScreen, which performs URL-reputation lookups against a Microsoft service for navigations and downloads inside the webview. For a client whose entire threat model is a self-hosted, TOFU-pinned server, that leaks the operator's server and attachment URLs off-box, and the msWebOOUI overlays reappear in the chrome-less window.",
   "repro": "Build the Windows (nsis) bundle and run it. Because the config's `additionalBrowserArgs` overrides wry's default argument string, the WebView2 process starts without `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection`: SmartScreen is active for in-webview navigations/downloads (attachment and OG-preview URLs from the self-hosted server are submitted for reputation checks), and the msWebOOUI out-of-process UI surfaces render over the custom window. Fix is to prepend `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection` to the same string. (Confidence note: verified against the documented Tauri/wry contract and the absence of the flag anywhere in the repo, not by running a Windows build.)",
   "evidence": "Client/tauri-client/src-tauri/src-tauri/tauri.conf.json:22 (app.windows[0]):\n  \"additionalBrowserArgs\": \"--autoplay-policy=no-user-gesture-required --use-fake-ui-for-media-stream\"\n\nNo occurrence of `--disable-features` anywhere in the repo:\n  grep -rn \"disable-features\" Client/tauri-client -> no hits\ntauri = 2.11.5 (src-tauri/Cargo.lock:4809-4810), which carries the replace-not-append semantics.",
   "suggestedFix": "Prepend the dropped default to the same string in tauri.conf.json:22: \"additionalBrowserArgs\": \"--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection --autoplay-policy=no-user-gesture-required --use-fake-ui-for-media-stream\".",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "opus",
   "round": 7,
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/tauri-conf-webview2-args.test.ts",
    "revertProof": "pass",
    "branchCommit": "7bb555a5"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0090",
   "title": "channelReadAudience falls through to a server-wide role scan when the channel row is gone, leaking a private group-DM's voice_leave to every connected member",
   "file": "Server/ws/hub_broadcast.go",
   "line": 149,
   "severity": "low",
   "why": "The DM-audience branch is guarded on `ch != nil && ch.Type == \"dm\"`. A deleted channel yields `ch == nil` (db.GetChannel returns (nil, nil) on sql.ErrNoRows), so control drops into the generic role scan, which — for an id whose channel row and ON DELETE CASCADE'd channel_overrides no longer exist — resolves to \"every connected user whose base role holds READ_MESSAGES\". The read error above is deliberately failed closed; the missing-row case is not.",
   "repro": "Group DM #G with alice, bob, carol. bob and carol leave. alice is alone in #G and is in its voice call (voice_states row + hub voiceChID set). alice calls DELETE /api/v1/dms/G. service.CloseDM -> db.LeaveGroupDM removes the last dm_participants row and, with remaining == 0, deletes the channels row, returning ChannelDeleted=true. api/dm_handler.go:236 then calls hub.DisconnectFromVoiceInChannel(alice, G) -> handleVoiceLeaveIfStillIn -> finishVoiceLeave (Server/ws/voice_leave.go:76) -> h.channelReadAudience(ctx, G). GetChannel(G) now returns (nil, nil), the `ch.Type == \"dm\"` branch is skipped, and the loop at hub_broadcast.go:171-178 calls h.perms.HasChannelPerm(uid, G, ReadMessages) for every connected user — with no override rows left for G, every ordinary member passes. Each of them receives {\"type\":\"voice_leave\",\"payload\":{\"channel_id\":G,\"user_id\":alice}} for a private conversation they were never part of. The live-row form of exactly this leak is locked shut by Server/ws/voice_dm_access_test.go:179 (TestVoiceJoin_DMCall_VoiceStateNotLeakedToThirdConnectedUser); the nil-row branch bypasses it.",
   "evidence": "ch, err := h.db.GetChannel(ctx, channelID)\nif err != nil {\n    slog.Error(\"ws: channelReadAudience GetChannel failed, denying\", ...)\n    return []int64{}\n}\nif ch != nil && ch.Type == \"dm\" {   // <- nil (deleted) channel skips the DM audience entirely\n    participantIDs, err := h.db.GetDMParticipantIDs(ctx, channelID)\n    ...\n    return audience\n}\n...\nfor _, uid := range userIDs {\n    if h.perms.HasChannelPerm(ctx, uid, channelID, permissions.ReadMessages) {\n        audience = append(audience, uid)\n    }\n}",
   "suggestedFix": "In channelReadAudience (Server/ws/hub_broadcast.go), fail closed on a missing row the same way the lookup-error branch does: after the `if err != nil` block, add `if ch == nil { return []int64{} }` before the `ch.Type == \"dm\"` check. This is safe for every caller: finishVoiceLeave (voice_leave.go:88-98) and CleanupVoiceForChannel (hub_sweep.go:333-342) both union the room's remaining participants and the leaver into the audience after the call, so eviction/E2EE-teardown signals still reach everyone entitled to them, while non-participants get nothing.",
   "status": "blocked",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-ws",
   "finder": "opus",
   "round": 8,
   "confidence": "high",
   "fix": null,
   "rationale": "cross-cluster edit: shares Server/ws/hub_broadcast.go with Server/admin/handlers_users.go - needs a human (agent edits saved in .superpowers/debris-2026-08-14.patch)",
   "blockedDate": "2026-08-14"
  },
  {
   "id": "OC-0091",
   "title": "chat_command is the only client message type registered without a rate limiter, and each frame runs a WASM plugin invocation",
   "file": "Server/ws/hub.go",
   "line": 155,
   "severity": "low",
   "why": "`PluginDeps` (deps.go:86) carries only `Registry` and `MessageSvc` — no `*auth.RateLimiter` — while every other deps struct built alongside it gets `h.limiter` (`PingDeps` line 130, `ChatDeps` line 132, `PresenceDeps` line 135, `CallDeps` line 138, `VoiceDeps` line 160). `handleChatCommandV2` correspondingly contains no `Allow(...)` call, and there is no connection-level inbound message-rate cap either: `serve.go:50` only sets `SetReadLimit` (a per-frame byte cap), and `TopicRateLimiter` meters outbound per-topic broadcast, not inbound frames. So one authenticated socket can drive unbounded `Registry.invokeCommand` executions.",
   "repro": "An authenticated client loops `{\"type\":\"chat_command\",\"payload\":{\"command\":\"/<any registered plugin command>\",\"args\":[]}}` as fast as the socket allows. handleMessage → DispatchV2 → handleChatCommandV2 → `reg.DispatchCommand` → `invokeCommand` runs the wazero guest module once per frame with no throttle. Compare `handleChatSendV2`, which is capped at 10/s via `auth.Key(\"chat\", userID)` (service/message_crud.go:32-35), and `handleCallRingV2`, capped at 1 per 3s (handlers_call.go:40-43). The command is not even required to be broadcast-eligible: the `canPluginBroadcast` gate is reached only after the plugin has already executed.",
   "evidence": "ws/hub.go:155-158\n\treg.RegisterV2(MsgTypeChatCommand, handleChatCommandV2, PluginDeps{\n\t\tRegistry:   func() *plugin.Registry { return h.pluginRegistry },\n\t\tMessageSvc: h.messageSvc,\n\t})\n\nws/deps.go:86-89\n\ttype PluginDeps struct {\n\t\tRegistry   func() *plugin.Registry\n\t\tMessageSvc *service.MessageService\n\t}   // no Limiter field\n\nws/hub.go:130-138 (every sibling gets one)\n\tregisterPingHandler(reg, PingDeps{Limiter: h.limiter})\n\tchatDeps := ChatDeps{Limiter: h.limiter}\n\tpresenceDeps := PresenceDeps{Limiter: h.limiter}\n\tcallDeps := CallDeps{Limiter: h.limiter}",
   "suggestedFix": "Add `Limiter *auth.RateLimiter` to PluginDeps in Server/ws/deps.go, populate it with h.limiter in the RegisterV2 call at Server/ws/hub.go:155, and at the top of handleChatCommandV2 (Server/ws/handlers_command.go) add the standard idiom: `if d.Limiter != nil && !d.Limiter.Allow(auth.Key(\"plugin_cmd\", cc.userID), 5, time.Second) { return Result{Error: ClientError{Code: ErrCodeRateLimited, ...}} }` before DispatchCommand.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-service",
   "finder": "opus",
   "round": 8,
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Server/ws/handlers_command_test.go",
    "revertProof": "pass",
    "branchCommit": "d28c124c"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0092",
   "title": "Plugin slash-command broadcast can post live content into an archived (read-only) channel",
   "file": "Server/service/message_perms.go",
   "line": 57,
   "severity": "low",
   "why": "CanPost (and the checkSendPermission it delegates to) checks only DM participation/blocks or HasChannelPerm(ReadMessages|SendMessages) for non-DM channels — neither ever consults ch.Archived, and permissions.Checker.HasChannelPermBatch (checker.go:93-98) has no notion of archived state either (only VisibleChannelIDs filters archived, and that's a separate, unrelated predicate used for channel *listing*). SendMessage itself was hardened against this at message_crud.go:54 ('Archived channels are read-only'), but CanPost is a distinct entrypoint used only by the WS plugin slash-command broadcast path (Server/ws/handlers_command.go:68-72, canPluginBroadcast -> MessageSvc.CanPost) and never goes through SendMessage at all: on success it builds a PluginBroadcastEvent (Server/ws/event.go:333-343) and fans it out directly as a channel-scoped WS event, with no DB write and no archived check anywhere in the path.",
   "repro": "Archive a text channel (channel_archive), leaving a plugin registered that owns a slash command. Have any user with ordinary SEND_MESSAGES on that (now-archived, UI-hidden) channel invoke `/command` there over the WS connection (the client still holds the channel id even though it's no longer listed — same premise as the already-confirmed SendMessage archived-gate hole). handleChatCommandV2 -> canPluginBroadcast -> CanPost -> checkSendPermission passes because ReadMessages|SendMessages is present and archived is never checked; the plugin's Broadcast text is wrapped in a plugin_broadcast event and delivered live to every subscriber of the channel (per the already-confirmed hub_broadcast.go:126 finding, archived channels are not excluded from that audience either), producing new, visible traffic in a channel every other surface treats as frozen/hidden — without ever touching the messages table or the SendMessage gate that was supposed to make archived channels read-only.",
   "suggestedFix": "In MessageService.CanPost (Server/service/message_perms.go:57), after the GetChannel lookup succeeds, mirror message_crud.go:54: `if ch.Type != \"dm\" && ch.Archived { return fmt.Errorf(\"%w: channel is archived\", ErrForbidden) }` before delegating to checkSendPermission.",
   "status": "declined",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "hotspot-server-service",
   "finder": "sonnet",
   "round": 8,
   "confidence": "high",
   "fix": null,
   "declinedDate": "2026-08-14",
   "rationale": "Already fixed on dev before this run: PR #1370 (OC-0022) routed every write sink through a shared requireChannelWritable gate, which CanPost reaches via checkSendPermission. A probe test per this finding's repro passes against current code, so there is no red state to pin."
  },
  {
   "id": "OC-0093",
   "title": "Registration records the reverse-proxy's address as the session IP while login records the real client IP",
   "file": "Server/api/auth_handler.go",
   "line": 241,
   "severity": "low",
   "why": "`handleRegister` is constructed without the `trustedProxies` list and uses `clientIP(r)`, which is hardcoded to `clientIPWithProxies(r, nil)` — i.e. always `r.RemoteAddr`. The sibling `handleLogin` resolves the same value with `clientIPWithProxies(r, proxyNets)`. Both feed the identical `sessions.ip` column that the client's \"Active sessions\" screen shows the user, so the two session-creation paths store two different things behind the same reverse proxy.",
   "repro": "Deploy behind nginx at 10.0.0.2 with `server.trusted_proxies: [\"10.0.0.2/32\"]`. A client at 203.0.113.9 registers via `POST /api/v1/auth/register`: line 241 yields `ip = \"10.0.0.2\"` and line 257 stores that in the session row (and the audit/slog line). The same client then logs in via `POST /api/v1/auth/login`: line 307 yields `ip = \"203.0.113.9\"`, stored by `issueSession` at line 451. The user's session-management list now shows one bogus 10.0.0.2 entry alongside correct ones, defeating the \"is this session from somewhere I recognise?\" purpose of the column. Note `handleRegister(database)` (line 137) does not even receive `trustedProxies`, although `MountAuthRoutes` has it (line 91) and passes it to every rate-limit middleware on the same route.",
   "evidence": "auth_handler.go:137 `func handleRegister(database *db.DB) http.HandlerFunc {`   // trustedProxies not threaded in\nauth_handler.go:241 `ip := clientIP(r)`\nauth_handler.go:257 `database.CreateSession(r.Context(), uid, auth.HashToken(token), device, ip)`\nauth_handler.go:284 `proxyNets := parseCIDRList(trustedProxies)`\nauth_handler.go:307 `ip := clientIPWithProxies(r, proxyNets)`\nauth_handler.go:451 `issueSession(r.Context(), database, user.ID, truncateDevice(...), ip)`\nmiddleware.go:251-253 `func clientIP(r *http.Request) string { return clientIPWithProxies(r, nil) }`\nmiddleware.go:274-276 `if len(trustedNets) == 0 { return remoteHost }`",
   "suggestedFix": "Thread the proxy list into the register handler: change the signature to handleRegister(database *db.DB, trustedProxies []string), parse once at construction like handleLogin does (proxyNets := parseCIDRList(trustedProxies)), replace line 241 with `ip := clientIPWithProxies(r, proxyNets)`, and update the mount at auth_handler.go:104 to pass trustedProxies.",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "opus",
   "round": 8,
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Server/api/auth_handler_test.go",
    "revertProof": "pass",
    "branchCommit": "e5d75fac"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0094",
   "title": "\"Back\" from DM sidebar can silently jump the user to an unrelated channel when DM mode was entered via \"View all messages\"",
   "file": "Client/tauri-client/src/pages/main-page/SidebarArea.ts",
   "line": 523,
   "severity": "low",
   "why": "`channelBeforeDm` (declared line 90, only ever written at line 393 inside `selectDmConversation`'s `setChannelBeforeDm` callback) is meant to remember which channel to restore when leaving the DM sidebar. But `SidebarDmSection.ts`'s \"View all messages\" button (line 66-68) switches to DM mode via a bare `setSidebarMode(\"dms\")`, bypassing `selectDmConversation` entirely, so `channelBeforeDm` is never recorded for that entry path. When the user then clicks \"Back\" without selecting a specific DM, `onBack` (lines 523-536) sees `channelBeforeDm === null` and falls into the `else` branch, which activates the *first* `type === \"text\"` channel found in `channelsStore` Map-iteration order — not the channel that was actually on screen. If that first channel differs from the one the user was viewing, `setActiveChannel` (line 531) silently switches them to a different channel/conversation they never asked to leave.",
   "repro": "User is viewing channel #random (not the first text channel in the sidebar's insertion order, e.g. #general is first). They click \"View all messages\" in the embedded DM section (SidebarDmSection.ts onclick -> setSidebarMode(\"dms\") with no channelBeforeDm set). The DM sidebar opens, still showing #random underneath. They click \"Back\" without picking a DM. onBack sees channelBeforeDm === null and calls setActiveChannel(<id of #general>), so the app now displays #general instead of #random, with no user action having asked to leave #random.",
   "suggestedFix": "In onBack's else branch (SidebarArea.ts:528-535), keep the current channel when it is already a non-DM channel and only fall back when it is null or a DM: `const st = channelsStore.getState(); const cur = st.activeChannelId !== null ? st.channels.get(st.activeChannelId) : undefined; if (cur === undefined || cur.type === \"dm\") { /* existing first-text-channel loop */ }`. (fallBackFromDm at line 437 has the same pattern but is only reached after the active DM was closed, where the fallback is the intended behavior.)",
   "status": "fixed",
   "found": "2026-08-12",
   "hunt": "general-2026-08-12",
   "lens": "fresh-eyes",
   "finder": "sonnet",
   "round": 8,
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/sidebar-area.test.ts",
    "revertProof": "pass",
    "branchCommit": "4d167fd4"
   },
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0095",
   "title": "Voice E2EE is never actually enabled — room.setE2EEEnabled(true) is never called, so every frame reaches the SFU in plaintext while the UI shows \"🔒 Secured\"",
   "file": "Client/tauri-client/src/lib/livekitSession.ts",
   "line": 410,
   "severity": "critical",
   "why": "createRoom() passes `e2ee: { keyProvider, worker }` to the livekit-client Room, but nothing in the client ever calls `room.setE2EEEnabled(true)`. In livekit-client 2.21.0 the Room constructor's `setupE2EE()` only wires the manager; it never enables encryption. `LocalParticipant.encryptionType` therefore stays `Encryption_Type.NONE`, so on `SignalConnected` the E2EEManager calls `setParticipantCryptorEnabled(localParticipant.isE2EEEnabled /* false */, localIdentity)` and the worker's `encodeFunction` takes the `if (!this.isEnabled()) { ... return controller.enqueue(encodedFrame); }` branch — the frame is forwarded unencrypted. Published tracks are also advertised with `encryption: NONE`, so every remote peer's `setParticipantCryptorEnabled(pub.trackInfo.encryption !== Encryption_Type.NONE, ...)` is false too and their decode transforms pass through as well. The entire ECDH/HKDF/AES-GCM key exchange, the TOFU identity layer, key-holder election and 5-minute rotation distribute a room key that is never used to encrypt or decrypt a single media frame. The call still works end to end, which is why this has never surfaced as a symptom.",
   "repro": "Join any voice channel with two clients. setupKeyExchange() completes, the key holder generates a room key, the peer unwraps it and keyProvider.setKey() succeeds, and both clients display \"🔒 Secured\". Because room.setE2EEEnabled(true) was never called, the local cryptor is disabled (`encryptionEnabledMap` has no true entry for the local identity), so the worker's encodeFunction enqueues each frame unmodified. Capture the RTP payload at the LiveKit SFU (or run livekit-server with track egress / a recording) and the audio/video decodes as ordinary Opus/VP8 — no SFrame header, no AES-GCM tag. Equivalent one-line check in the running client: `room.isE2EEEnabled` is false and `room.localParticipant.encryptionType === Encryption_Type.NONE` at every point of a \"Secured\" call.",
   "evidence": "livekitSession.ts:408-413\n      // End-to-end encryption: SFrame-based E2EE using a server-distributed\n      // per-channel symmetric key. The SFU only sees encrypted frames.\n      e2ee: {\n        keyProvider: this._e2ee.keyProvider,\n        worker: this._e2eeWorker,\n      },\n\n(no `setE2EEEnabled` / `isE2EEEnabled` anywhere under Client/tauri-client/src or tests/)\n\nnode_modules/livekit-client/dist/livekit-client.esm.mjs:29027\n    this.encryptionType = Encryption_Type.NONE;          // LocalParticipant default\nnode_modules/livekit-client/dist/livekit-client.esm.mjs:29268\n    get isE2EEEnabled() { return this.encryptionType !== Encryption_Type.NONE; }\nnode_modules/livekit-client/dist/livekit-client.esm.mjs:29424 (LocalParticipant.setE2EEEnabled — the ONLY writer of encryptionType)\n        this.encryptionType = enabled ? Encryption_Type.GCM : Encryption_Type.NONE;\nnode_modules/livekit-client/dist/livekit-client.esm.mjs:15632 (E2EEManager.setupEventListeners, on SignalConnected)\n      this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled, this.room.localParticipant.identity);\nnode_modules/livekit-client/dist/livekit-client.esm.mjs:15602\n    room.on(RoomEvent.TrackPublished, (pub, participant) => this.setParticipantCryptorEnabled(pub.trackInfo.encryption !== Encryption_Type.NONE, participant.identity));\nnode_modules/livekit-client/dist/livekit-client.e2ee.worker.mjs:6741-6751 (Cryptor.encodeFunction)\n      if (!this.isEnabled()) {\n        this.appendFrameMetadata(encodedFrame);\n        return controller.enqueue(encodedFrame);   // <-- plaintext passthrough\n      }\n\nClient/tauri-client/src/components/VoiceWidget.ts:196\n      securedBadge.style.display = status === \"connected\" ? \"inline-flex\" : \"none\";   // \"🔒 Secured\" shown purely on connection state",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "voice-e2ee",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Client/tauri-client/tests/unit/livekit-session.test.ts",
    "revertProof": "pass",
    "branchCommit": "df221814"
   },
   "suggestedFix": "Enable E2EE on the one room construction site so both connect paths get it: make createRoom() async and `await newRoom.setE2EEEnabled(true);` immediately after `new Room({...})` (livekitSession.ts:414), then `await this.createRoom()` at the two call sites (486, 950 — both already async). Pre-connect this only sets localParticipant.encryptionType = GCM (identity is still '' so the manager call is skipped); the manager's SignalConnected handler then posts enable=true with the real identity, and published tracks advertise encryption: GCM so peers enable their decode cryptors. The key is already set before connect (setupKeyExchange at 977 runs ahead of room.connect at 1009), so there is no encode-before-key window.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0096",
   "title": "Message search 500s on any query containing a hyphen — sanitizeFTSQuery allowlists the one character that is an FTS5 operator",
   "file": "Server/db/message_queries.go",
   "line": 36,
   "severity": "high",
   "why": "sanitizeFTSQuery is documented as stripping \"FTS5 operator characters\" but explicitly keeps '-'. In FTS5's MATCH grammar '-' is not a bareword character: it introduces a column-filter (`-col : expr`), so `well-known` parses as the term `well` followed by a filter on a column named `known` and SQLite raises `no such column: known`. That error propagates out of SearchMessages/SearchMessagesInChannels as service.ErrInternal, and the handler's isInvalidSearchQueryError (api/channel_handler.go:25-34) only matches \"fts5\"/\"malformed\"/\"syntax error\"/\"unterminated string\" — \"no such column\" matches none of them — so writeServiceError returns HTTP 500 instead of results.",
   "repro": "Verified against the repo's exact FTS table (`fts5(content, content='messages', content_rowid='id')`) on modernc.org/sqlite v1.56.0:\n  MATCH 'well-known'  -> ERROR: SQL logic error: no such column: known\n  MATCH 'e-mail'      -> ERROR: SQL logic error: no such column: mail\n  MATCH '2026-08-13'  -> ERROR: SQL logic error: no such column: 08\n  MATCH '-'           -> ERROR: fts5: syntax error near \"\"\n  MATCH 'well known'  -> ok, 1 row\nSo: GET /api/v1/messages/search?q=well-known (or any hyphenated term, e-mail address fragment, ISO date, \"state-of-the-art\", a username with a hyphen) returns 500 INTERNAL_ERROR. Only the pure-punctuation case (q=\"-\") happens to produce an \"fts5:\"-prefixed message and gets the intended 400; every realistic hyphenated search is a 500. Global search (SearchMessagesInChannels, same MATCH) fails identically.",
   "evidence": "db/message_queries.go:32-47\n\tfor _, r := range q {\n\t\tif unicode.IsLetter(r) || unicode.IsDigit(r) || r == ' ' || r == '-' {   // <- '-' kept\n\t\t\tsb.WriteRune(r)\n\t\t}\n\t}\n\ndb/message_queries.go:348 / :360 / :410\n\tWHERE messages_fts MATCH ? AND m.deleted = 0\n\ndb/message_queries.go:366\n\treturn nil, fmt.Errorf(\"SearchMessages: %w\", err)\nservice/message_query.go:94 / :110\n\treturn nil, fmt.Errorf(\"%w: search failed: %v\", ErrInternal, err)\napi/channel_handler.go:29-33\n\tmsg := strings.ToLower(err.Error())\n\treturn strings.Contains(msg, \"fts5\") || ... || strings.Contains(msg, \"syntax error\")",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "db-storage",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Server/db/message_queries_test.go",
    "revertProof": "pass",
    "branchCommit": "96a98b8b"
   },
   "suggestedFix": "One line in sanitizeFTSQuery: emit a space for '-' instead of keeping it, so the term still matches the indexed tokens (dropping it entirely would turn \"well-known\" into \"wellknown\", which matches nothing). At Server/db/message_queries.go:35-39: `for _, r := range q { switch { case unicode.IsLetter(r) || unicode.IsDigit(r) || r == ' ': sb.WriteRune(r); case r == '-': sb.WriteRune(' ') } }`. Both SearchMessages and SearchMessagesInChannels route through it, so one edit covers both. Also fix the vacuous guard: insert one message row in fuzzOpenMigratedMemory (Server/db/sanitize_fuzz_test.go:23-34) so the FTS cursor actually opens — without that, the seed corpus will keep passing on the next regression.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0097",
   "title": "Admin \"Restore backup\" writes to a hardcoded data/chatserver.db, so a restore silently no-ops on any server with a configured database.path",
   "file": "Server/admin/handlers_backup.go",
   "line": 177,
   "severity": "high",
   "why": "The restore handler hardcodes the destination as `filepath.Join(\"data\", \"chatserver.db\")` while the live database is opened from `cfg.Database.Path` (main.go:129, default `data/chatserver.db` but a documented, editable config key). The pre-restore safety copy and the WAL checkpoint operate on the *real* DB, then `copyFile(target, dbPath)` writes the backup over an unrelated (possibly newly created) file. The handler then returns 200 \"database restored — server restarting\" and respawns. After the restart the server reopens `cfg.Database.Path`, which was never touched — an irreversible-looking operation is reported as success while doing nothing.",
   "repro": "Set `database.path: data/oc.db` in config.yaml (or any non-default path) and start the server. Create a backup from the admin panel, make further changes (post messages, delete a channel), then click Restore on that backup. Response is 200 \"database restored\", the server restarts, and every post-backup change is still present — the backup was copied to `data/chatserver.db`, a file the server never opens. The operator, believing the rollback happened, may delete the backup.",
   "evidence": "dbPath := filepath.Join(\"data\", \"chatserver.db\")\n...\nif err := copyFile(target, dbPath); err != nil { ... }\n...\nwriteJSON(w, http.StatusOK, map[string]string{\"message\": \"database restored — server restarting\", \"backup\": name})",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "error-paths",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Server/admin/handlers_backup_test.go",
    "revertProof": "pass",
    "branchCommit": "19b3df2a"
   },
   "suggestedFix": "Give db.DB the path it was opened with (store `path` in openFile/openMemory, add `func (d *DB) Path() string`) and use `database.Path()` in handleRestoreBackup instead of the hardcoded join — one accessor fixes both the copy and the rollback, and the existing tests keep passing since the temp DB is opened at data/chatserver.db.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0098",
   "title": "A joining key holder sends its room-key offers before its own announce, so every existing participant drops them as \"unknown peer\"",
   "file": "Client/tauri-client/src/lib/livekitE2EE.ts",
   "line": 230,
   "severity": "high",
   "why": "setupKeyExchange drains the queued announces (which, for a key holder, emit a voice_e2ee_offer per peer) at lines 223-228, and only afterwards sends the holder's own voice_e2ee_announce at line 232. The receiver needs the sender's ephemeral ECDH public key to unwrap, so handleOfferInner's `_peerPublicKeys.get(fromUserId)` guard (line 737-741) discards every one of those offers. Nothing re-requests them: handleAnnounce answers an announce with an offer, never a counter-announce, and mid-call peers never re-announce on their own.",
   "repro": "Server has users 1 (owner) and 50. User 50 joins voice channel #7 alone -> becomes key holder, roomKey R50. User 1 then joins the same channel. Server's computeIsKeyHolder (Server/ws/voice_join.go:311) returns true for uid 1 and voice_join relays user 50's stored announce to user 1 (voice_join.go:353), which queues in `_pendingAnnounces` because `_ecdhKeyPair` is still null. User 1's setupKeyExchange: `_isKeyHolder=true`, generates R1, keyProvider.setKey(R1), then the drain at line 224 calls handleAnnounce(50) -> wrap-and-offer branch (line 677-701) sends `voice_e2ee_offer{target_user_id:50}`; the announce for user 1 goes out only at line 232, i.e. AFTER that offer, on the same WS connection and therefore behind it in user 50's inbound FIFO (both relays land in the same `c.send` queue, see Server/ws/voice_e2ee.go:239 and :270). User 50 processes the offer first: `_peerPublicKeys.get(1)` is undefined -> logs \"E2EE: received offer from unknown peer\" and returns. User 50 then processes user 1's announce, stores the key, and — still `_isKeyHolder` — offers R50 back, which the server rejects with NOT_KEY_HOLDER (voice_e2ee.go:198, the map already names uid 1). Result: user 1 encrypts with R1, user 50 with R50, neither can decrypt the other, and the only repair is user 1's KEY_ROTATION_INTERVAL_MS timer 5 minutes later. Reproducible on every join where the joiner has the lowest user id in an ongoing call. The existing unit test (tests/unit/livekit-e2ee.test.ts:128) asserts only that an offer is sent during the drain, not its order relative to the announce, so moving the holder's announce above line 223 does not break it.",
   "evidence": "    this._ecdhKeyPair = ecdhKeyPair;\n    const queued = this._pendingAnnounces.splice(0);\n    for (const { userId: qId, publicKeyBase64: qKey, signatureBase64: qSig } of queued) {\n      await this.handleAnnounce(qId, qKey, qSig);   // <- key holder sends voice_e2ee_offer here\n      log.info(\"E2EE: drained queued announce\", { userId: qId });\n    }\n\n    if (this._isKeyHolder) {\n      // Announce our (signed) key so existing participants can see us.\n      this.deps.getWs()?.send({ type: \"voice_e2ee_announce\", payload: announcePayload });\n\n// ...and the receiving side, line 737:\n      const peerKey = this._peerPublicKeys.get(fromUserId);\n      if (!peerKey) {\n        log.warn(\"E2EE: received offer from unknown peer\", { fromUserId });\n        return;\n      }",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "flow-voice",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Client/tauri-client/tests/unit/livekit-e2ee.test.ts",
    "revertProof": "pass",
    "branchCommit": "9e375c93"
   },
   "suggestedFix": "Hoist the key holder's announce above the drain: send `{type:\"voice_e2ee_announce\", payload: announcePayload}` immediately after `this._ecdhKeyPair = ecdhKeyPair;` (:217) when `this._isKeyHolder`, and delete the send at :232. Do NOT hoist the non-holder send at :244 — it must stay after the _roomKeyResolver is installed at :237-240, or an immediate offer resolves nothing and setupKeyExchange stalls to timeout.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0099",
   "title": "Registration HTML-escapes the username but login does not, so any account whose name contains ' \" & is permanently unloggable",
   "file": "Server/api/auth_handler.go",
   "line": 180,
   "severity": "high",
   "why": "handleRegister runs the username through the bare `sanitizer.Sanitize` (bluemonday StrictPolicy), whose output is always HTML-escaped, and stores the escaped form. handleLogin at line 295 does the opposite — it only trims — and GetUserByUsername matches the column exactly (`username = ? COLLATE NOCASE`). The two paths therefore canonicalize the same typed name differently. The codebase already solved exactly this for every other user-facing text field: `sanitizeToFixpoint` (service/message.go:167) exists because \"a plain sanitizer.Sanitize call would persist and display literal &#39;/&gt;/&amp; entities\" (service/user.go:107-110), and display_name/about/custom_status all go through it. Username is the one field left on the raw call.",
   "repro": "POST /api/v1/auth/register {username:\"O'Brien\", password:…, invite_code:…}. auth.ValidateUsername accepts it (only control/Cf runes are rejected; length 2-32). Line 180 stores `O&#39;Brien` — verified against the vendored bluemonday: StrictPolicy().Sanitize(\"O'Brien\") == \"O&#39;Brien\", Sanitize(\"Bob & Alice\") == \"Bob &amp; Alice\", Sanitize(`Say \"hi\"`) == \"Say &#34;hi&#34;\". Now POST /api/v1/auth/login {username:\"O'Brien\", password:…}: GetUserByUsername(\"O'Brien\") returns (nil,nil), storedHash stays \"\", CheckPassword fails, 401 \"invalid credentials\" — forever. After 9 attempts the per-IP and per-username lockouts (auth_handler.go:389-395) lock the account for 15 minutes. Secondary symptom on the same line: escaping runs BEFORE auth.ValidateUsername (line 192), so a legal 30-rune name like \"Sean O'Brien & Mary O'Sullivan\" expands to 42 runes and is rejected with \"username must be at most 32 characters\". Third symptom: the stored name renders as the literal entity everywhere (client renders usernames via textContent) and cannot be @mentioned by typing the real name.",
   "evidence": "api/auth_handler.go:180  req.Username = strings.TrimSpace(sanitizer.Sanitize(req.Username))\napi/auth_handler.go:295  req.Username = strings.TrimSpace(req.Username)   // login — no Sanitize\ndb/queries/sqlite/users.sql:5  FROM users WHERE username = ? COLLATE NOCASE;\nservice/message.go:167  return html.UnescapeString(sanitizer.Sanitize(html.UnescapeString(s)))  // the fixpoint helper username never uses",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "hotspot-server-api",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Server/api/auth_handler_test.go",
    "revertProof": "pass",
    "branchCommit": "47eeb930"
   },
   "suggestedFix": "Stop HTML-escaping the username. Export the existing fixpoint helper (service/message.go:167 sanitizePass/sanitizeToFixpoint) as e.g. service.SanitizeText and replace the bare call at auth_handler.go:180 with `req.Username = strings.TrimSpace(service.SanitizeText(req.Username))` — one shared helper used by both this call site and profile_handler.go:180. That keeps tag-stripping, drops the entity encoding, and keeps the length check operating on the real rune count.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0100",
   "title": "Profile rename applies the same bare Sanitize, so renaming to a name with an apostrophe locks the user out of their own account",
   "file": "Server/api/profile_handler.go",
   "line": 180,
   "severity": "high",
   "why": "handleUpdateProfile escapes the new username with the same bare `sanitizer.Sanitize` and hands the escaped string straight to svc.Users.UpdateProfile, which writes it verbatim (service/user.go: `s.st.UpdateUserProfile(ctx, userID, patch.Username, …)` — username is the one ProfilePatch field that never goes through cleanText/sanitizeToFixpoint, unlike display_name and about right beside it). The login path never applies the same transform, so the rename silently changes the credential the account is reachable by. This is a separate call site from the register one: fixing either leaves the other broken.",
   "repro": "Logged in as \"alice\", PATCH /api/v1/users/me {\"username\":\"O'Brien\"}. Line 180 turns it into `O&#39;Brien`; UpdateProfile commits that to users.username and returns 200 with the escaped name. The session keeps working (it is token-based), so the damage is invisible until the token expires or the user signs out. On the next login with \"O'Brien\" the row is not found and the user is locked out permanently. Same line also inflates length before auth.ValidateUsername at line 187, so renaming to a 30-rune name containing three apostrophes 400s with \"username must be at most 32 characters\". Every subsequent profile save re-sends the stored escaped name (MainPage.ts:433 fills patch.username from authStore) — verified idempotent, so it does not compound, but the escaped name is now permanent.",
   "evidence": "api/profile_handler.go:180  req.Username = strings.TrimSpace(sanitizer.Sanitize(req.Username))\napi/profile_handler.go:187  if err := auth.ValidateUsername(req.Username); err != nil {   // runs on the escaped string\nservice/user.go (UpdateProfile)  s.st.UpdateUserProfile(ctx, userID, patch.Username, avatar, displayName, about)  // username not cleanText'd\nservice/user.go:107-110  // \"a plain sanitizer.Sanitize call would persist and display literal &#39;/&gt;/&amp; entities\"",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "hotspot-server-api",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Server/api/profile_handler_test.go",
    "revertProof": "pass",
    "branchCommit": "a5c99209"
   },
   "suggestedFix": "Same shared helper: replace the bare Sanitize at profile_handler.go:180 with the exported fixpoint sanitizer used at auth_handler.go:180, so both write-paths canonicalize identically to what login reads. (Existing rows already escaped need a one-off unescape migration, but the code fix is the single helper.)",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0101",
   "title": "Channel-visibility watermark is bumped after the fan-out loop, so a client reconnecting during the loop replays past the change and never converges",
   "file": "Server/ws/hub_broadcast.go",
   "line": 365,
   "severity": "medium",
   "why": "RefreshChannelVisibility delivers the visibility change as targeted, unsequenced channel_create/channel_delete frames to a snapshot of clients taken at line 252, and only calls bumpVisibilityWatermark() at line 365 after the whole per-client loop finishes. A client that reconnects while the loop is still running is in neither audience: it was not in the snapshot, and handleReconnect's mustFullResync check (serve.go:125) reads the still-unbumped watermark and admits it to the replay path, which by construction cannot carry an unsequenced targeted message. revokeUnreadableChannels has the identical gap via `defer h.bumpVisibilityWatermark()` at hub_broadcast.go:497.",
   "repro": "Server has N connected clients. Admin edits a channel_override on channel C (or edits a role, which drives RefreshAllChannelVisibility over every channel). RefreshChannelVisibility(C) snapshots h.clients at hub_broadcast.go:252-257, then loops lines 315-357 running 1-4 permission lookups plus a sendMsg + pubsub mutation per client. User U is offline at snapshot time (or drops immediately after) and reconnects mid-loop with last_seq = L, where L exceeds the previous watermark. handleReconnect evaluates mustFullResync(L) against the unbumped visibilityChangeSeq -> false -> U resumes from the ring buffer, never receives a ready payload, and never receives the targeted channel_create/channel_delete (it was not in the snapshot). Line 365 bumps the watermark only after U's handshake has already committed to replay. Revoked case: U's sidebar keeps rendering channel C forever, and clicking it is dead because registerNow's READ-gated re-subscribe correctly refused the topic. Granted case: U's computeAllowedChannels includes C so chat_message frames for C start arriving for a channel the client has no entry for. Neither converges until U reconnects with last_seq=0 or an unrelated visibility change pushes the watermark past L.",
   "evidence": "hub_broadcast.go:252 `h.mu.RLock(); clients := make([]*Client, 0, len(h.clients))` … loop 315-357 … 365 `h.bumpVisibilityWatermark()`  // comment at 359-364: \"Clients not connected right now missed the targeted sends above. Move the watermark so any resume from a seq at or before this point is forced onto the full-ready path\" — but the bump happens after, not before, the sends. Same shape at hub_broadcast.go:497 `defer h.bumpVisibilityWatermark()`.",
   "status": "blocked",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "ws-hub",
   "finder": "opus",
   "confidence": "medium",
   "fix": null,
   "suggestedFix": "Bump before the audience is snapshotted instead of after it is served, in the one place each: in RefreshChannelVisibility move h.bumpVisibilityWatermark() from line 365 to immediately before the h.mu.RLock() snapshot at line 252; in revokeUnreadableChannels drop the `defer` on line 497 so the existing first-statement call runs eagerly (it already sits at the top, so early returns stay covered). That shrinks the hole from 'the whole fan-out loop' to the few instructions between the bump and the RLock. Residual, if you want it fully closed: re-check h.mustFullResync(lastSeq) inside the h.seqMu section right before h.registerNow in serve.go and fall back to full ready.",
   "rationale": "cross-cluster edit: shares Server/ws/hub_broadcast.go with Server/admin/handlers_users.go - needs a human (agent edits saved in .superpowers/debris-2026-08-14.patch)",
   "blockedDate": "2026-08-14"
  },
  {
   "id": "OC-0102",
   "title": "Avatar upload rewrites the username from a pre-lock snapshot, silently reverting a concurrent rename",
   "file": "Server/api/profile_handler.go",
   "line": 575,
   "severity": "medium",
   "why": "UserService.UpdateProfile serializes its read-merge-write under a per-user keyedMutex precisely because \"PATCH /users/me can race POST /users/me/avatar ... silently reverting whatever the winner just changed\". That lock only protects the fields merged from the row read *inside* it (avatar, display_name, about). `Username` is not merged — it is taken verbatim from the caller, and handleUploadAvatar supplies `user.Username`, a snapshot AuthMiddleware read at the *start* of the request, before the lock and before the whole multipart parse / image decode / disk write. So the exact lost update the lock was added to fix still happens, for the username column.",
   "repro": "User \"alice\" is logged in on two clients. Client B starts POST /api/v1/users/me/avatar with a ~1 MiB PNG (AuthMiddleware snapshots user.Username = \"alice\"). While the upload is still parsing/decoding/writing, client A sends PATCH /api/v1/users/me {\"username\":\"bob\"} — it takes the lock, commits, and broadcasts user_update{username:\"bob\"}. Client B's handler then reaches UpdateProfile, takes the now-free lock, and writes patch.Username = \"alice\", reverting the rename. broadcastUserUpdate then pushes username \"alice\" to every connected client, so the rename is undone in the DB and on every peer with no error reported to either client. Same mechanism reverts db.DeleteAccount's \"[deleted-<id>]\" anonymisation if a self-delete lands during an in-flight avatar upload.",
   "evidence": "api/profile_handler.go:573-577\n    avatarURL := service.AvatarFileURL(fileID)\n    updated, err := svc.Users.UpdateProfile(r.Context(), user.ID, service.ProfilePatch{\n        Username: user.Username,   // <- snapshot taken by AuthMiddleware, outside profileLocks\n        Avatar:   &avatarURL,\n    })\n\nservice/user.go:156-171 (UpdateProfile)\n    unlock := s.profileLocks.lock(userID)\n    defer unlock()\n    current, err := s.st.GetUserByID(ctx, userID)   // avatar/display_name/about merged from HERE\n    ...\n    s.st.UpdateUserProfile(ctx, userID, patch.Username, avatar, displayName, about)  // username NOT merged",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "api-authz",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Server/service/profile_fields_test.go",
    "revertProof": "pass",
    "branchCommit": "a5c99209"
   },
   "suggestedFix": "Make the username a merge like the other fields, in the shared function rather than at each caller: in UpdateProfile after `current` is read, `username := patch.Username; if username == \"\" { username = current.Username }`, pass `username` to UpdateUserProfile and to the audit/log lines, and drop `Username: user.Username` from the avatar handler's ProfilePatch. Empty is a safe sentinel because the only other caller (PATCH) already rejects an empty username at api/profile_handler.go:180-186.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0103",
   "title": "WAF inline engine rejects every request body >= 1 MiB, breaking plugin install and large avatar uploads when waf_enabled is on",
   "file": "Server/api/waf.go",
   "line": 213,
   "severity": "medium",
   "why": "The inline Coraza engine sets `SecRequestBodyLimit 1048576` but never sets `SecRequestBodyLimitAction`, and coraza's default is Reject (internal/corazawaf/waf.go:320 `RequestBodyLimitAction: types.BodyLimitActionReject`), so ReadRequestBodyFrom returns a 413 interruption as soon as the buffer reaches the limit. Its body-inspection exclusion (rule 900003) covers only `/api/v1/uploads`, while `bodyCapExemptPrefixes` exempts three routes from the app's own 1 MiB cap — `/api/v1/uploads`, `/api/v1/admin/plugins/install` (16 MiB) and `/api/v1/users/me/avatar` (2 MiB). The CRS engine built immediately below sets `SecRequestBodyLimitAction ProcessPartial` with the comment \"never reject on size — request size enforcement belongs to the app middleware\"; the inline engine contradicts its own sibling.",
   "repro": "Set server.waf_enabled: true. As an Administrator on an allowed CIDR, POST a 2 MiB plugin .zip to /api/v1/admin/plugins/install (documented cap 16 MiB): the request never reaches PluginAdminHandler.install — the middleware answers 413 {\"error\":\"request blocked by security rules\"}. Same for POST /api/v1/users/me/avatar with an image at or just under maxAvatarFileBytes (1 MiB), whose multipart envelope pushes the body past 1,048,576 bytes. /api/v1/uploads is unaffected because rule 900003 turns requestBodyAccess off for it.",
   "evidence": "api/waf.go:209-244 (inline engine — no SecRequestBodyLimitAction)\n    SecRequestBodyLimit 1048576\n    ...\n    SecRule REQUEST_URI \"@beginsWith /api/v1/uploads\" \"id:900003,phase:1,pass,nolog,ctl:requestBodyAccess=Off\"\n\napi/waf.go:111-112 (CRS engine, right next to it)\n    SecRequestBodyLimit 1048576\n    SecRequestBodyLimitAction ProcessPartial\n\napi/constants.go:144-151\n    var bodyCapExemptPrefixes = []string{\"/api/v1/uploads\", \"/api/v1/admin/plugins/install\", \"/api/v1/users/me/avatar\"}\n\ncoraza v3 internal/corazawaf/transaction.go ReadRequestBodyFrom:\n    if tx.requestBodyBuffer.length == tx.RequestBodyLimit {\n        if tx.WAF.RequestBodyLimitAction == types.BodyLimitActionReject {\n            return setAndReturnBodyLimitInterruption(tx, 413)\n\napi/waf.go:364-367\n    it, written, err := tx.ReadRequestBodyFrom(r.Body)\n    if it != nil { handleWAFInterruption(w, it); return }",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "api-authz",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Server/api/waf_test.go",
    "revertProof": "pass",
    "branchCommit": "0a38a3fe"
   },
   "suggestedFix": "Extend the existing body-access exclusion instead of changing the limit action: make inline rule 900003 (and CRS rule 1001 for symmetry) cover the same prefixes as bodyCapExemptPrefixes, i.e. add `SecRule REQUEST_URI \"@beginsWith /api/v1/admin/plugins/install\" \"id:900004,phase:1,pass,nolog,ctl:requestBodyAccess=Off\"` and the same for /api/v1/users/me/avatar. Do NOT 'fix' this by copying SecRequestBodyLimitAction ProcessPartial onto the inline engine: with written > 0 the middleware replaces r.Body with the truncated 1 MiB buffer (api/waf.go:394-400), which would silently hand the handler a corrupt zip/image instead of a 413.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0104",
   "title": "Hot plugin re-install leaves plugins.enabled = 1 while the runtime instance is deactivated, so the plugin silently stops working and the admin panel still shows it enabled",
   "file": "Server/plugin/registry.go",
   "line": 379,
   "severity": "medium",
   "why": "InstallPlugin's upsert deliberately does not touch the `enabled` column, and installFromDisk tears down the old *Instance and registers a fresh one with Enabled:false without re-activating it. At startup that is fine because LoadAll follows installFromDisk with activateAll, which re-reads the store rows and re-activates every enabled one. InstallFromZip (the runtime upgrade path) calls installFromDisk and returns — nothing re-activates. The store row and the runtime therefore disagree: DB says enabled, the module is unloaded and its command bindings were dropped.",
   "repro": "1. Install plugin \"foo\" and enable it (POST /admin/plugins/{id}/enable): plugins.enabled = 1, module compiled, its slash commands registered in r.commands.\n2. Upload a new foo.zip to POST /admin/plugins/install. InstallFromZip renames the new dir in and calls installFromDisk, which calls platformDeactivate(old), deletes old's command bindings, and inserts a new Instance with Enabled:false. The upsert leaves plugins.enabled = 1.\n3. Result: foo's slash commands 404/no-op and it receives no events, but GET /admin/plugins still returns enabled:true, so the operator has no reason to click Enable. The plugin only comes back on the next server restart (LoadAll -> activateAll).",
   "evidence": "plugin/registry.go:378-385 (InstallFromZip, Stage 4)\n\tif err := r.installFromDisk(ctx, foundPlugin{...}); err != nil { ... }\n\treturn manifest.Name, nil          // no activateAll / activate\n\nplugin/registry.go:199-217 (installFromDisk)\n\tif old := r.byName[found.Manifest.Name]; old != nil {\n\t\tr.platformDeactivate(ctx, old)\n\t\tfor cmd, owner := range r.commands { if owner == old { delete(r.commands, cmd) } }\n\t...\n\tinst := &Instance{ ID: id, ..., Enabled:  false }\n\ndb/plugin_queries.go:20-23\n\tINSERT INTO plugins (name, version, enabled, manifest_json) VALUES (?, ?, 0, ?)\n\tON CONFLICT(name) DO UPDATE SET version = excluded.version, manifest_json = excluded.manifest_json\n\t-- enabled is NOT reset, so the row stays 1\n\napi/plugins_handler.go:118 (list)\n\trows, err := h.store.ListPlugins(ctx)   // reports enabled=1",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "db-storage",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/plugin/registry_test.go",
    "revertProof": "pass",
    "followUp": "cac4d13e",
    "branchCommit": "9075f248",
    "pr": 1369
   },
   "suggestedFix": "Re-activate at the one place that skips it, reusing the existing lifecycle call instead of duplicating activation logic. In InstallFromZip after the installFromDisk block (Server/plugin/registry.go:385): `if row, err := r.cfg.Store.GetPluginByName(ctx, manifest.Name); err == nil && row != nil && row.Enabled { if err := r.EnablePlugin(ctx, row.ID); err != nil { slog.Warn(\"plugin: reactivate after upgrade failed\", \"name\", manifest.Name, \"err\", err) } }`. EnablePlugin already sets inst.Enabled, activates, and rolls the DB flag back on failure, so the store row and the runtime can no longer disagree. Do not put this inside installFromDisk — LoadAll would then activate twice.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0105",
   "title": "secret_store::delete reports success while the fallback credential survives on disk and resurrects on next launch",
   "file": "Client/tauri-client/src-tauri/src/secret_store.rs",
   "line": 407,
   "severity": "medium",
   "why": "`clear_fallback` removes the entry from the tauri-plugin-store's in-memory map and then flushes with `store.save()`. A `save()` failure is only `log::warn!`-ed, never propagated, so `delete()` (line 215–219) still returns the keyring result — `Ok(())`. The on-disk fallback file still holds the sealed secret, so the \"deleted\" login token/password or voice-E2EE identity key comes back the next time the app starts. This is exactly the failure `delete`'s own doc comment claims to prevent (\"a delete that left the fallback copy behind would resurrect a 'deleted' secret on the next read\").",
   "repro": "On a machine where the fallback engaged (Linux with no Secret Service, or after a keyring write failed its read-back), a credential is sealed into the fallback store file. Make that file (or its directory) read-only, or fill the disk. Call `delete_credential` (\"Forget this server\" / logout): keyring delete succeeds, `store.save()` fails, only a warn is logged, and the command resolves Ok so the UI reports the credential removed. Restart the client — `get_fallback` returns the still-present sealed blob and auto-login uses the supposedly deleted credential.",
   "evidence": "fn clear_fallback(app: &AppHandle, account: &str) {\n    ...\n    if store.delete(account) {\n        if let Err(e) = store.save() {\n            log::warn!(\"failed to flush credential fallback removal for '{account}': {e}\");\n        }\n    }\n}\n\npub fn delete(app: &AppHandle, account: &str) -> Result<(), String> {\n    let keyring_result = keyring_delete(account);\n    clear_fallback(app, account);\n    keyring_result\n}",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "error-paths",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "8579cb5d",
    "test": "Client/tauri-client/src-tauri/src/secret_store.rs",
    "revertProof": "pass (manual hunk-level: behavioral line reverted, propagation test red, green at HEAD)",
    "branchCommit": "66862cca"
   },
   "suggestedFix": "Make clear_fallback return Result<(), String> (propagate the save() error) and have delete() return `keyring_result.and(clear_fallback(app, account))`; keep set_with's fallback_clear closure best-effort with `let _ = ...`, since there the keyring copy is authoritative.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0106",
   "title": "Every DM message re-emits dm_channel_open and bumps the global visibility watermark, so ordinary DM traffic forces every other client's next reconnect onto the full-resync tier",
   "file": "Server/service/message_crud.go",
   "line": 205,
   "severity": "medium",
   "why": "`OpenDM` is `INSERT OR IGNORE ... :exec` (dm.sql:2) and returns nil whether or not a row was actually inserted; `dm_queries.go:427-435` discards the result too. SendMessage therefore appends *every* recipient to `OpenedDMFor` on *every* DM send, not just on a genuine (re)open. handlers_chat.go:75 then emits a `DMChannelOpenEvent` per recipient, and emit.go:41-47 calls `h.bumpVisibilityWatermark()` for each one, ratcheting `visibilityChangeSeq` up to the current global `h.seq`. `mustFullResync(lastSeq)` is `w > 0 && lastSeq <= w` (hub_events.go:86), so after any DM message every client whose `lastSeq` sits at or below that seq is denied both replay tiers on its next reconnect. This is distinct from the known hub_broadcast.go:365 ordering defect: here the watermark is a *global* gate being tripped by a strictly per-user event that only the addressee could ever have missed.",
   "repro": "Alice and Bob have an already-open DM and exchange messages continuously. Each Alice→Bob send re-appends Bob to OpenedDMFor, emits a redundant dm_channel_open, and pushes visibilityChangeSeq to the current h.seq. Carol, unrelated, is idle in #general with lastSeq equal to the newest seq she has received. Her wifi blips; she reconnects with that last_seq. handleReconnect hits `mustFullResync` first (serve.go:125), logs \"replay skipped (visibility changed since last_seq)\", increments reconnectTierFull, and returns false — the ring buffer and the cold-tier EventStore are never consulted even though both fully cover her gap. handleFreshConnect sends a full `ready`; the dispatcher's second-ready branch (dispatcher.ts:301-327) then calls `invalidateLoadedMessageWindows()`, dropping every loaded channel's message window and refetching only the active channel. With steady DM traffic on the server the seq-resume design is effectively unreachable for every user who is not currently posting.",
   "evidence": "Server/db/queries/sqlite/dm.sql:2  INSERT OR IGNORE INTO dm_open_state (user_id, channel_id) VALUES (?, ?);\nServer/service/message_crud.go:201-206\n  if openErr := s.st.OpenDM(ctx, pid, p.ChannelID); openErr != nil { ...continue }\n  result.OpenedDMFor = append(result.OpenedDMFor, pid)      // appended even when the row already existed\nServer/ws/handlers_chat.go:75  if len(result.OpenedDMFor) > 0 { ... events = append(events, DMChannelOpenEvent{...}) }\nServer/ws/emit.go:41-47  if _, isOpen := ev.(DMChannelOpenEvent); isOpen { h.bumpVisibilityWatermark() }\nServer/ws/hub_events.go:84-87  func (h *Hub) mustFullResync(lastSeq uint64) bool { w := h.visibilityChangeSeq.Load(); return w > 0 && lastSeq <= w }",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "flow-message",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/service/message_crud_test.go",
    "revertProof": "pass",
    "branchCommit": "081bb169",
    "pr": 1369
   },
   "suggestedFix": "Make the insert report whether it actually inserted, and gate the event on it. Change dm.sql OpenDM to `:execrows`, regen via the db-change skill, have db.OpenDM return (bool, error) (only production caller is message_crud.go:201; the two db tests just check err), and append to result.OpenedDMFor only when rows == 1. One guard in the shared path; handlers_chat.go and emit.go stay untouched.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0107",
   "title": "Session termination before MainPage mounts never tears down the WS client, so a banned/revoked token reconnects forever",
   "file": "Client/tauri-client/src/main.ts",
   "line": 729,
   "severity": "medium",
   "why": "The only place that calls `ws.disconnect()`, `deleteCredential(host)` and `router.navigate(\"connect\")` on logout is the `authStore` subscriber, and its entire body is gated on `router.getCurrentPage() === \"main\"`. MainPage is not mounted until the connected overlay's `onReady` fires, so every session that dies during login / auto-login / the connected-overlay window skips the teardown: `intentionalClose` stays false in `ws.ts`, and `rustState === \"closed\"` therefore calls `scheduleReconnect()` (bounded delay 30s, no attempt cap) with the same dead token, forever. The server-side ban rejection makes this the default path: `authenticateConn` answers a banned user with `buildErrorMsg(ErrCodeBanned, ...)` — a generic `error` frame — not `auth_error`, and `ws.ts` only sets `intentionalClose = true` for `auth_error`.",
   "repro": "Ban a user (admin panel), then start their client with auto-login enabled for that server (or have them log in and let the ban land while the 'Connected' overlay is still showing). Flow: `wirePostAuth` -> `ws.connect` -> server `authenticateConn` sees `IsEffectivelyBanned` -> writes `{type:\"error\",payload:{code:\"BANNED\"}}` -> closes with StatusPolicyViolation. Client: dispatcher's `S.ERROR` handler calls `clearAuth()`. In the auto-login case `isAuthenticated` was never true, so `subscribeSelector` (false->false) never fires at all; in the overlay case it fires but `router.getCurrentPage()` is still \"connect\", so the `if` body is skipped. Either way `ws.disconnect()` is never called, `intentionalClose` stays false, and the `closed` proxy event calls `scheduleReconnect()`. Result: the client re-sends the banned token every <=30s indefinitely, the UI stays stuck on 'Auto-connecting...', and the stale credential is never deleted (`deleteCredential` lives inside the same gated block). The only escape is the user clicking Cancel (main.ts:585) or killing the app.",
   "evidence": "main.ts:726-746\n  authStore.subscribeSelector(\n    (s) => s.isAuthenticated,\n    (isAuthenticated) => {\n      if (!isAuthenticated && router.getCurrentPage() === \"main\") {   // <-- gate\n        ...\n        ws.disconnect();\n        ...\n        if (host && authStore.getState().logoutReason !== \"server_shutdown\") {\n          void deleteCredential(host);\n\nlib/ws.ts:296-303 (only auth_error sets intentionalClose)\n  if (msg.type === \"auth_error\") { intentionalClose = true; ... }\nlib/ws.ts:439-441\n  if (!intentionalClose) { scheduleReconnect(); }\nlib/ws.ts:209-210\n  function scheduleReconnect(): void { if (intentionalClose || certMismatchBlock || !config) return;  // no attempt cap\n\nServer/ws/serve_auth.go:85-87\n  if auth.IsEffectivelyBanned(user) {\n    _ = conn.Write(ctx, websocket.MessageText, buildErrorMsg(ErrCodeBanned, \"you are banned\"))\n\nlib/dispatcher.ts:930-934 (BANNED handler calls clearAuth() only)\n  if (payload.code === \"BANNED\") { setTransientError(...); clearAuth(); return; }\n\nlib/store.ts subscribeSelector fires only when the slice changes, so false->false never notifies.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "flow-session",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Client/tauri-client/tests/unit/dispatcher.test.ts",
    "revertProof": "pass",
    "branchCommit": "38fd7475"
   },
   "suggestedFix": "In dispatcher.ts's S.ERROR BANNED branch (line ~930), call `ws.disconnect()` before `clearAuth()` — `ws` is already in wireDispatcher's scope and disconnect() sets intentionalClose/cancels the reconnect timer, so it is idempotent with the main-page subscriber's own ws.disconnect(). One guard in the shared handler covers every router state instead of adding a third hand-copied teardown block.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0108",
   "title": "A username/nickname/avatar change never repaints the open message list — updateMemberProfile is the one members.store mutator that does not bump roleRevision, and MessageList subscribes to nothing else",
   "file": "Client/tauri-client/src/stores/members.store.ts",
   "line": 152,
   "severity": "medium",
   "why": "`updateMemberProfile` returns `{ ...prev, members: next }` while every sibling mutator (`setMembers`:78, `addMember`:102, `removeMember`:111, `updateMemberRole`:122) returns `roleRevision: (prev.roleRevision ?? 0) + 1`. `MessageList` holds exactly one members subscription — `membersStore.subscribeSelector((s) => s.roleRevision ?? 0, () => renderAll())` at MessageList.ts:897-903 — so the profile patch mutates the store without ever waking the only renderer that reads it. That renderer does read it live: `renderers.ts:200` calls `resolveAuthor(msg.user)`, and `formatting.ts:143` resolves the name/avatar out of `membersStore.getState().members`, with a doc comment (formatting.ts:131-135) stating the store is preferred precisely because \"a rename or an avatar change arrives as a user_update and patches every member\". The store is patched; the pixels are not.",
   "repro": "1. User A and user B are both in #general; B has posted several messages that are on A's screen. 2. B renames themselves (or sets a nickname, or changes their avatar) — the server emits `user_update`. 3. `dispatcher.ts:700` calls `updateMemberProfile`, which patches `membersStore.members` but leaves `roleRevision` unchanged. 4. `MessageList`'s only members subscription selects `roleRevision`, so `shallowEqual(prev, next)` on the unchanged counter is true and `renderAll()` never fires. A's message list keeps showing B's OLD name and OLD avatar. 5. It does not self-heal on the next message either: `messagesStore.subscribeSelector` at MessageList.ts:859 runs `if (!tryAppendMessages()) renderAll();` — the append path succeeds for a new tail message, so only the new row is built and the already-rendered rows keep the stale identity. The stale rows persist until something forces a full `renderAll()`: a channel switch, a history page load, or an unrelated member join/leave/role change. Meanwhile `MemberList` (which subscribes to the whole store, MemberList.ts:463-467) shows the new name — so the sidebar and the message list disagree about who B is. No test locks the current behavior: `roleRevision` appears nowhere under tests/.",
   "evidence": "members.store.ts:137-154 (updateMemberProfile)\n    return { ...prev, members: next };          // <-- no roleRevision bump\nvs. members.store.ts:122 (updateMemberRole)\n    return { ...prev, members: next, roleRevision: (prev.roleRevision ?? 0) + 1 };\n\nMessageList.ts:896-903 — the ONLY membersStore subscription in the component:\n    membersStore.subscribeSelector(\n      (s) => s.roleRevision ?? 0,\n      () => { renderAll(); },\n    )\n\nformatting.ts:143 — read live per rendered row:\n    const member = membersStore.getState().members.get(user.id);\n    if (member !== undefined) return { username: member.username, displayName: member.displayName ?? null, avatar: member.avatar };\n\ndispatcher.ts:698-705 — the event that lands here:\n    ws.on(S.USER_UPDATE, (payload) => { updateMemberProfile(payload.user_id, { username, avatar, displayName, identityPublicKey }); })",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-2",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Client/tauri-client/tests/unit/members.store.test.ts",
    "revertProof": "pass",
    "branchCommit": "f8248684"
   },
   "suggestedFix": "One line in the shared mutator: make updateMemberProfile return `{ ...prev, members: next, roleRevision: (prev.roleRevision ?? 0) + 1 }` (members.store.ts:152), and update the MembersState doc comment at line 30-34 (and MessageList.ts:894) to say the counter covers membership, role, and profile changes — still excluding presence/typing, which is the exclusion the counter exists for.",
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0109",
   "title": "GIF proxy's log redaction misses the percent-encoded API key, so an upstream failure writes the Klipy credential to stdout and the admin log stream",
   "file": "Server/api/gif_handler.go",
   "line": 176,
   "severity": "medium",
   "why": "The upstream URL is built with `params.Encode()`, which percent-encodes every character outside [A-Za-z0-9-_.~]. `url.Error` embeds that encoded URL in `err.Error()`. `redactKey` does a literal `strings.ReplaceAll(s, apiKey, \"[REDACTED]\")` against the *decoded* key, so it never matches the encoded form and the credential survives into the log line. The sibling in the same package got this right: livekit_proxy.go redacts the raw query blob first \"so an encoded form is caught too\", then the decoded token.",
   "repro": "Set gif.api_key to any key containing a character Encode() escapes (base64-style keys routinely contain '+', '/' or '='), e.g. \"ab+cd/ef=\". Make api.klipy.com unreachable (block DNS or the outbound dial). Call GET /api/v1/gif/trending. gifClient.Do fails with a *url.Error whose message contains `...?key=ab%2Bcd%2Fef%3D&limit=20...`; redactKey compares against the literal \"ab+cd/ef=\" and matches nothing, so the full encoded key lands in stdout and in admin.RingBuffer, from which any admin can read it live over the SSE /admin/api/logs/stream endpoint.",
   "evidence": "gif_handler.go:150  results, err := fetchGIFs(r, gifAPIBase+upstreamPath+\"?\"+params.Encode(), apiKey, limit)\ngif_handler.go:117  \"key\": {apiKey},\ngif_handler.go:176  slog.Warn(\"gif proxy: upstream request failed\", \"error\", redactKey(err.Error(), apiKey))\ngif_handler.go:215  return strings.ReplaceAll(s, apiKey, \"[REDACTED]\")\nlivekit_proxy.go:191-192  safeErr := redactKey(err.Error(), backendURL.RawQuery)   // raw query FIRST\n                          safeErr = redactKey(safeErr, backendURL.Query().Get(\"access_token\"))",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "hotspot-server-plugin",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "8579cb5d",
    "test": "Server/api/gif_handler_internal_test.go",
    "revertProof": "pass",
    "branchCommit": "eba1ba02"
   },
   "suggestedFix": "Fix it once in the shared helper rather than at each call site — gif_handler.go:211: `func redactKey(s, apiKey string) string { if apiKey == \"\" { return s }; s = strings.ReplaceAll(s, apiKey, \"[REDACTED]\"); return strings.ReplaceAll(s, url.QueryEscape(apiKey), \"[REDACTED]\") }`. `net/url` is already imported in this file, the second pass is a no-op when the key needs no escaping, and both the three GIF call sites and the livekit proxy inherit the fix.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0110",
   "title": "Every error attribute is blanked to `{}` in the admin live log stream — `err` never reaches the log viewer",
   "file": "Server/admin/logstream.go",
   "line": 298,
   "severity": "medium",
   "why": "`ringHandler.Handle` stores `a.Value.Any()` into a `map[string]any` and then `json.Marshal`s it. Go error values (`*errors.errorString`, `*fmt.wrapError`) have only unexported fields, so they marshal to `{}`. slog's own JSONHandler special-cases `error` and emits `err.Error()`; this handler does not, so the stdout sink and the admin ring buffer disagree on the single most important field of every error line.",
   "repro": "Trigger any `slog.Error(msg, \"err\", err)` — e.g. logstream.go:95 `slog.Error(\"failed to issue log stream ticket\", \"err\", err)`, or the hundreds of `\"err\", err` / `\"error\", err` call sites across ws/, db/, service/. stdout shows `err=\"generating ticket: ...\"`. The admin panel's Logs section (and the SSE /admin/api/logs/stream feed) shows `ERROR [admin] failed to issue log stream ticket {\"err\":{}}`. Searching the log viewer for any substring of the error message never matches, because attrs contains only `{}`.",
   "evidence": "logstream.go:293-307\n\tr.Attrs(func(a slog.Attr) bool {\n\t\tkey := a.Key\n\t\t...\n\t\tattrs[key] = a.Value.Any()\n\t\treturn true\n\t})\n\tvar attrsJSON string\n\tif len(attrs) > 0 {\n\t\tif b, err := json.Marshal(attrs); err == nil {\n\t\t\tattrsJSON = string(b)\n\t\t}\n\t}\n\nVerified: json.Marshal(map[string]any{\"err\": fmt.Errorf(\"wrap: %w\", errors.New(\"boom\"))}) -> {\"err\":{}} (marshal error nil, so the empty object is silently kept).\n\nConsumer: Server/admin/static/index.html:1540 renders `entry.attrs` inline, and :1530 log search matches against `entry.attrs`.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-1",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/admin/multihandler_test.go",
    "revertProof": "pass",
    "branchCommit": "a555d9ee",
    "pr": 1369
   },
   "suggestedFix": "One shared conversion in ringHandler.Handle, applied to both the rh.attrs loop (line 290) and the r.Attrs callback (line 298), instead of a.Value.Any(): `func logAttrValue(v slog.Value) any { v = v.Resolve(); if e, ok := v.Any().(error); ok { if _, jm := e.(json.Marshaler); !jm { return e.Error() } }; return v.Any() }`. The Resolve() half matters too: Record.Attrs does not resolve slog.LogValuer, so the ring path currently also bypasses the redaction in Server/db/logvalue.go and Server/config/logvalue.go, storing the raw User/Session/Config value instead of the redacted one. This mirrors what slog's own JSONHandler does for error values.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0111",
   "title": "Auto-idle's return-to-online presence_update is always swallowed by the 1-per-10s presence limiter, so every user shows as Idle to everyone else after returning to the keyboard",
   "file": "Client/tauri-client/src/pages/MainPage.ts",
   "line": 200,
   "severity": "medium",
   "why": "applyPresence() writes the local presence store unconditionally but only sends the wire frame if limiters.presence.tryConsume() succeeds, and the presence limiter is 1 token per 10 000 ms (rate-limiter.ts:154). autoIdle fires apply(true)->onStatusChange(\"idle\") and then, on the very first mouse event (unthrottled by design, autoIdle.ts:119-124), apply(false)->onStatusChange(\"online\") milliseconds later. The second call always loses the token, so the local store/localStorage say \"online\" while the server and every other client keep the user at \"idle\", with no retry and no user feedback.",
   "repro": "1. Sit idle 10 min. autoIdle.apply(true) -> MainPage.applyPresence(\"idle\") -> updatePresence local + ws.send consumes the single presence token at t=0. 2. Move the mouse at t=+50 ms. autoIdle.onActivity sees idleByTimer===true, calls apply(false) -> MainPage.applyPresence(\"online\"). 3. updatePresence(userId,\"online\") runs; limiters.presence.tryConsume() returns false (sliding window still holds the t=0 stamp), so ws.send({type:\"presence_update\",payload:{status:\"online\"}}) never runs. 4. Own client renders Online; every other member list and the server DB still hold \"idle\". Nothing retries — restoreSavedPresence only runs on a connectionStatus transition to \"connected\".",
   "evidence": "MainPage.ts:195-203\n  function applyPresence(status: UserStatus): void {\n    const userId = getCurrentUserId();\n    if (userId !== 0) { updatePresence(userId, status); }\n    if (limiters.presence.tryConsume()) {\n      ws.send({ type: \"presence_update\", payload: { status } });\n    }\n  }\nrate-limiter.ts:153-155  export function createPresenceLimiter(): RateLimiter { return createRateLimiter(1, 10_000); }\nautoIdle.ts:119-124  if (idleByTimer) { apply(false); ... }",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-1",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Client/tauri-client/tests/unit/main-page.test.ts",
    "revertProof": "pass",
    "branchCommit": "f5d9645b"
   },
   "suggestedFix": "In applyPresence (the shared function all three call sites route through), stop dropping the frame silently — on a failed tryConsume, schedule one retry: keep a module-level `let presenceRetry: ReturnType<typeof setTimeout> | null`, and in the else branch clearTimeout(presenceRetry) then presenceRetry = setTimeout(() => applyPresence(loadUserStatus()), limiters.presence.getRemainingMs()); clear it in the page teardown next to autoIdle.destroy(). Coalescing on the latest status means a burst still costs one frame, and restoreSavedPresence should call applyPresence rather than duplicating the same unguarded shape.",
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0112",
   "title": "handleServeFile's admin bypass covers the DM branch, so an ADMINISTRATOR can download attachments from private DMs they are not a participant in",
   "file": "Server/api/upload_handler.go",
   "line": 302,
   "severity": "medium",
   "why": "`if !isAdmin { ... }` wraps the entire access-control block, including the `aa.ChannelType == \"dm\"` participant check. Every sibling DM read gate in the codebase deliberately has NO admin bypass — service.requireChannelRead (message_query.go:25-30) returns ErrNotFound for a DM the caller is not in even for an Administrator, and PermissionService.RequireChannelAccess (permission.go:73-82) and MessageService.checkSendPermission (message_perms.go:70-80) do the same. The file route is the one path where the admin bit opens a private DM.",
   "repro": "Alice and Bob exchange a 1:1 DM with an attachment; the attachment row gets channel_id = the DM channel, channel_type = \"dm\". An operator with the ADMINISTRATOR bit (not a DM participant) calls GET /api/v1/files/{id}: isAdmin is true at line 300, the whole `if !isAdmin` block at 302-359 is skipped, IsDMParticipant is never consulted, and the file is served 200. The same operator calling GET /api/v1/channels/{dmChannelID}/messages gets 404 \"access denied\" from requireChannelRead. The file id is discoverable without DB access: handleUpload logs it at line 229 (`slog.Info(\"file uploaded\", \"id\", fileID, \"filename\", safeFilename, ...)`), and that line is streamed verbatim to the admin panel's live log viewer. TestServeFile_AdminBypassesAllChecks (upload_handler_test.go:1214) only exercises an unlinked attachment, so the DM case is not test-locked.",
   "evidence": "upload_handler.go:300-302,335-350\n  isAdmin := role != nil && permissions.HasAdmin(role.Permissions)\n  if !isAdmin {\n      ...\n      if aa.ChannelType == \"dm\" {\n          ok, dmErr := database.IsDMParticipant(r.Context(), user.ID, *aa.ChannelID)\n          if dmErr != nil || !ok { ...403... }\nvs Server/service/message_query.go:25-30 (no admin arm)\n  if ch.Type == \"dm\" {\n      ok, dmErr := s.st.IsDMParticipant(ctx, userID, channelID)\n      if dmErr != nil || !ok { return fmt.Errorf(\"%w: access denied\", ErrNotFound) }",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-1",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8579cb5d",
    "test": "Server/api/upload_handler_test.go",
    "revertProof": "pass",
    "branchCommit": "37227919"
   },
   "suggestedFix": "Move the DM arm out of the bypass so participation is required of everyone, matching requireChannelRead: hoist `if aa.ChannelID != nil && aa.ChannelType == \"dm\"` to just above `if !isAdmin` and 403 there when user == nil or IsDMParticipant is false, leaving the `if !isAdmin` block to cover only the unlinked/avatar and guild-channel arms.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0113",
   "title": "Selecting \"Default\" microphone never changes the capture device — the mute/unmute cycle re-acquires nothing",
   "file": "Client/tauri-client/src/lib/deviceManager.ts",
   "line": 71,
   "severity": "medium",
   "why": "`cycleMicForDeviceSwitch` is the entire implementation of \"switch back to the default input device\", but it only calls `setMicrophoneEnabled(false)` then `(true)`. On an already-published mic that is livekit's `track.mute()` → `track.unmute()`, and with the default `stopMicTrackOnMute: false` neither call touches the device: `mute()` skips the `_mediaStreamTrack.stop()` branch, and `unmute()` only restarts when `stopOnMute || readyState === 'ended' || pendingDeviceChange`. Nothing ever clears `Room.options.audioCaptureDefaults.deviceId` or `LocalAudioTrack._constraints.deviceId`, which a previous `switchActiveDevice('audioinput', id)` left as `{exact: <old device>}`. So the non-empty branch (`room.switchActiveDevice`) really switches, and the empty/\"Default\" branch silently does not.",
   "repro": "Join a voice channel. Open Settings → Voice & Audio and pick a specific microphone (e.g. a USB headset); `VoiceAudioTab.ts:404-407` saves the pref and calls `switchInputDevice(\"usb-mic-id\")`, which reaches `room.switchActiveDevice(\"audioinput\", \"usb-mic-id\")` and pins `audioCaptureDefaults.deviceId = {exact: \"usb-mic-id\"}`. Now select \"Default\" in the same dropdown: `inputSelect.value` is `\"\"`, so `switchInputDevice(\"\")` takes the else branch and only mutes/unmutes the existing publication. The UI and the `audioInputDevice` pref both read \"Default\", but the room keeps capturing from the USB headset for the rest of the session — unplug the headset and the mic dies rather than falling back. The same helper backs `handleDeviceChange`'s device-removed fallback (deviceManager.ts:130), so that \"switched to default\" path cannot reach the default device either. The existing test `tests/unit/device-manager.test.ts:231-237 (\"re-enables microphone for empty deviceId (default fallback)\")` asserts only the `setMicrophoneEnabled(false)`/`(true)` call pair against a mocked Room, so it locks the mechanism, not the outcome the name claims.",
   "evidence": "deviceManager.ts:71-79\n  private async cycleMicForDeviceSwitch(room: Room): Promise<void> {\n    await room.localParticipant.setMicrophoneEnabled(false);\n    if (this.room !== room) return;\n    if (isMicPolicyGated()) { ...return; }\n    await room.localParticipant.setMicrophoneEnabled(true);\n  }\n\ndeviceManager.ts:167-171\n      if (deviceId) {\n        await room.switchActiveDevice(\"audioinput\", deviceId);\n      } else {\n        await this.cycleMicForDeviceSwitch(room);   // <-- no device reset at all\n      }\n\nnode_modules/livekit-client/dist/livekit-client.esm.mjs:19174  stopMicTrackOnMute: false,   (OwnCord never overrides it — `grep -rn stopMicTrackOnMute src/` is empty)\nesm.mjs:29446-29448  setTrackEnabled(..., enabled=true) -> `if (track) { yield track.unmute(); }`  (no createTracks, no new constraints)\nesm.mjs:20966-20971  mute(): `if (source === Microphone && this.stopOnMute && !isUserProvided) { this._mediaStreamTrack.stop(); }`  -> skipped\nesm.mjs:20990-20993  unmute(): `if (source === Microphone && (this.stopOnMute || readyState === 'ended' || this.pendingDeviceChange) ...) { yield this.restart(undefined, true); }`  -> all three false\nesm.mjs:32852-32853  switchActiveDevice audioinput: `_this3.options.audioCaptureDefaults.deviceId = deviceConstraint;` (never reset by the cycle)\nlivekitSession.ts:1119-1122  on (re)connect the saved input is only applied when non-empty: `if (savedInput !== \"\") { await localRoom.switchActiveDevice(\"audioinput\", savedInput); }` — so \"\" never resets it there either.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-2",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "ca9d12b",
    "test": "Client/tauri-client/tests/unit/device-manager.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "suggestedFix": "Fix it once in the shared helper rather than in both callers: make cycleMicForDeviceSwitch reset the pinned constraint before the cycle by adding `await room.switchActiveDevice(\"audioinput\", \"default\", false);` as its first statement (exact=false yields a plain 'default' string, i.e. an `ideal` constraint, matching livekit's own audioDefaults `{ideal:'default'}`, so it degrades gracefully where no 'default' id exists). That clears room.options.audioCaptureDefaults.deviceId and drives setDeviceId -> restartTrack on the live publication, so both switchInputDevice('') and the hot-swap fallback actually reach the default device; the existing mute/PTT gate at deviceManager.ts:74 and its two tests stay untouched.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0114",
   "title": "In a group DM, one participant's decline silences every other participant's incoming ring — and never reaches the actual caller",
   "file": "Server/ws/handlers_call.go",
   "line": 84,
   "severity": "medium",
   "why": "handleCallDeclineV2 addresses call_declined to every OTHER participant of the DM (RingTargets excludes only the sender), so fellow callees receive it alongside the ringer. The client's handler `ws.on(\"call_declined\", p => ringCtrl?.cancel(p.channel_id))` (Client/tauri-client/src/pages/MainPage.ts:579-581) cancels purely on channel_id and ignores `from_user`, so it cannot tell \"the caller hung up\" from \"another callee declined\". Meanwhile the caller itself never received call_incoming (RingTargets excludes the sender at handlers_call.go:52 / dm.go:377-380), so `ringCtrl.current()` is null on the caller and cancel() is a no-op there — the decline's stated purpose (\"so a ringing client can stop ringing before the 30s timeout\") is unreachable, and its only observable effect is to kill the other callees' rings.",
   "repro": "Group DM C with A, B, D. A opens C and clicks the call button → voice_join(C) + call_ring(C). Server sends call_incoming{channel_id:C, from_user:A} to B and D; both banners appear and both chimes start. B clicks Decline → call_decline{channel_id:C}. Server RingTargets(B,C)=[A,D] and sends call_declined{channel_id:C, from_user:B} to A and D. D's ring state is {channelId:C, fromUserId:A}, so cancel(C) matches → D's banner is torn down and the chime stops; D can no longer answer a call A is still sitting in. A, having no ring state, ignores the frame entirely — so the one client the decline was meant for is the one it does nothing to.",
   "evidence": "handlers_call.go:79-93:\n  targets, err := d.DMSvc.RingTargets(ctx, info.UserID, declineCmd.ChannelID())\n  payload := buildCallSignal(MsgTypeCallDeclined, declineCmd.ChannelID(), info.UserID, info.Username)\n  for _, pid := range targets { events = append(events, CallSignalEvent{eventType: MsgTypeCallDeclined, targetUserID: pid, payload: payload}) }\n\nMainPage.ts:578-582:\n  ws.on(\"call_declined\", (payload) => { ringCtrl?.cancel(payload.channel_id); })\n\ncall-ring.ts:114-117:\n  function cancel(channelId: number): void { if (state === null || state.channelId !== channelId) return; stopRinging(); }\n\nThe payload carries `from_user` (messages.go:310-314, types.ts:571-575) but the client never reads it. No test locks this: tests/unit/call-ring.test.ts:158-186 only covers channel-id scoping.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-1",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Client/tauri-client/tests/unit/main-page.test.ts",
    "revertProof": "pass",
    "branchCommit": "4eca1171",
    "pr": 1369
   },
   "suggestedFix": "Guard the client handler by ringer identity instead of channel alone: in MainPage.ts:579-581, `const r = ringCtrl?.current(); if (r && payload.from_user === r.fromUserId) ringCtrl?.cancel(payload.channel_id);`. That keeps the legitimate glare case (both users ringing each other, the peer declines) working and stops a fellow callee's decline from cancelling an unrelated ring. Server fan-out can stay as-is — it has no call state to target with.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0115",
   "title": "Link-preview fetch buffers the whole response body with no timeout and no size cap — the documented 50 KB bound is applied after the bytes are already in memory",
   "file": "Client/tauri-client/src/components/message-list/embeds.ts",
   "line": 202,
   "severity": "medium",
   "why": "The 5 s AbortController timer is cleared at line 182, the moment response *headers* arrive, so `await res.text()` at line 202 runs with the abort signal already disarmed and reads the body to completion before `html.slice(0, 50_000)` is applied. The slice is therefore not a memory bound at all (the comment at line 49 and line 203 both claim it is), and there is no timeout covering the body phase.",
   "repro": "Any message author posts a plain https URL (no code fence, no masked-link syntax) pointing at a host that answers `Content-Type: text/html` and then streams an endless / multi-GB body. media.ts:549 calls renderGenericLinkPreview() automatically for every such URL when showLinkPreviews is on (default true, media.ts:29), so every client that merely renders the message issues the fetch with no user interaction. tauriFetch resolves as soon as headers arrive, clearTimeout(timer) disarms the only abort, and res.text() accumulates the stream forever: the renderer's memory climbs without limit and the in-flight entry in ogInFlight never settles, so the card stays on its \"loading\" fallback title permanently. Ten such links in one channel = ten simultaneous unbounded reads.",
   "evidence": "const timer = setTimeout(() => controller.abort(), 5000);\n...\nconst res = await tauriFetch(url, fetchOpts);\nclearTimeout(timer);          // <-- signal disarmed once headers land\n...\nconst html = await res.text();                     // unbounded, untimed\nconst meta = parseOgTags(html.slice(0, 50_000));   // \"memory bound\" applied too late",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-2",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "20d7537",
    "test": "Client/tauri-client/tests/unit/embeds.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "suggestedFix": "Move the disarm past the body read instead of adding a second timer: drop `clearTimeout(timer)` at line 182 and wrap the response handling so it runs after `const html = await res.text();` (or put `clearTimeout(timer)` in a `finally` on the async IIFE). That makes the existing 5 s AbortController cover the body phase, and the stream's abort listener errors res.text() and drops the body on the Rust side.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0116",
   "title": "A failed TOTP verify tears down the TOTP overlay, so the code cannot be re-entered",
   "file": "Client/tauri-client/src/pages/connect-page/LoginForm.ts",
   "line": 667,
   "severity": "medium",
   "why": "handleTotpSubmit's catch calls transitionTo(\"error\", …). transitionTo runs updateTotpOverlay(), which adds `totp-overlay--hidden` for every state that is not \"totp\". A rejected verification therefore closes the code prompt and drops the user back on the login form; there is no showTotp() call on any error path, so the second factor is unreachable without re-submitting the password.",
   "repro": "showTotp() → overlay visible. Enter a code the server rejects; onTotpSubmit rejects; the catch sets formState=\"error\"; updateTotpOverlay hides the overlay and updateFormInputsDisabled re-enables host/username/password. The error banner (LoginForm.ts:191, a child of the form panel behind the overlay) is the only feedback, and the code input is gone. tests/e2e/totp-flow.spec.ts:99 asserts only that the banner becomes visible — nothing locks the overlay staying open or a retry succeeding.",
   "evidence": "LoginForm.ts:663-671:\n  try { await onTotpSubmit(code); }\n  catch (err) {\n    const message = err instanceof Error ? err.message : \"Verification failed.\";\n    transitionTo(\"error\", message);   // ← state leaves \"totp\"\n  } finally { totpSubmitBtn.disabled = false; setText(totpSubmitBtn, \"Verify\"); }\n\nLoginForm.ts:519-527:\n  function updateTotpOverlay(): void {\n    if (formState === \"totp\") { totpOverlay.classList.remove(\"totp-overlay--hidden\"); ... }\n    else { totpOverlay.classList.add(\"totp-overlay--hidden\"); }\n  }\n\nThe `finally` re-enables the Verify button on an overlay that is already hidden.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-3",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/login-form-totp-retry.test.ts",
    "revertProof": "pass",
    "branchCommit": "c3a20a95"
   },
   "suggestedFix": "Keep the overlay up while a challenge is outstanding instead of tying it to formState alone: add a `totpPending` flag set in showTotp() and cleared in handleTotpCancel() (and on successful auth), then change updateTotpOverlay's condition to `if (formState === \"totp\" || (formState === \"error\" && totpPending))`, and only clear/focus totpInput on the fresh `formState === \"totp\"` entry so a retry keeps its context. This is the single shared point both the click and Enter paths route through. Pair it with retaining pendingTotpPartialToken in main.ts (move the clear out of `finally` into the success branch plus cancel), otherwise the re-opened prompt hits the empty-token guard at main.ts:520.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0117",
   "title": "Channel create/edit/delete modals lock up permanently on an API failure — the caller swallows the rejection the modal needs to re-enable its button",
   "file": "Client/tauri-client/src/pages/main-page/SidebarArea.ts",
   "line": 280,
   "severity": "medium",
   "why": "CreateChannelModal (and EditChannelModal/DeleteChannelModal) disable their submit button, relabel it \"Creating…\"/\"Saving…\"/\"Deleting…\", and rely on `await onCreate(...)` REJECTING to restore the button and render the inline error. SidebarArea's callbacks catch the API error themselves and only show a toast, so the promise resolves normally: the modal's own catch never runs, the button stays disabled with the in-flight label forever, and the modal's `errorEl` (data-testid=\"channel-create-error\") is dead code on every real code path. The user cannot retry after a recoverable error (duplicate name, 403, transient network) without cancelling and losing everything typed.",
   "repro": "Log in as an admin, click \"+\" on a category, type a channel name that already exists (or disconnect the network), press \"Create Channel\". The server returns an error -> a toast appears, but the button stays greyed out reading \"Creating...\" and no inline error is shown. Fixing the name and clicking again does nothing; only Cancel/Escape/X recovers, discarding the form.",
   "evidence": "SidebarArea.ts:275-284 (create)\n  onCreate: async (data) => {\n    try { await api.adminCreateChannel(data); modal.destroy?.(); activeModal = null; }\n    catch (err) {\n      const msg = err instanceof Error ? err.message : \"Failed to create channel\";\n      getToast()?.show(msg, \"error\");   // <- swallowed, never rethrown\n    }\n  },\n\nCreateChannelModal.ts:163-177\n  createBtn.setAttribute(\"disabled\", \"true\");\n  setText(createBtn, \"Creating...\");\n  try { await onCreate({...}); }\n  catch (err) { errorEl.style.display = \"block\"; ...; createBtn.removeAttribute(\"disabled\"); setText(createBtn, \"Create Channel\"); }\n\nIdentical pattern at SidebarArea.ts:314 (onSave -> EditChannelModal.ts:377-384) and SidebarArea.ts:337 (onConfirm -> DeleteChannelModal.ts:91-98).\ntests/unit/sidebar-area.test.ts:1761 mocks createCreateChannelModal, so nothing locks the integrated behavior; tests/unit/create-channel-modal.test.ts only exercises the modal with a rejecting onCreate.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-3",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "f653578",
    "test": "Client/tauri-client/tests/unit/sidebar-area.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "suggestedFix": "Preserve the modals' reject-to-recover contract in the shared caller: in SidebarArea.ts's three catch blocks, keep the toast and add `throw err;` (or drop the try/catch entirely and let the modal render the inline error). One line per callback; the six sidebar-area.test.ts cases that `await modalCallArgs.onCreate/onSave/onConfirm(...)` must then be updated to `await expect(...).rejects.toThrow(...)`. Restoring the button in a `finally` inside each modal is the alternative but leaves errorEl dead code and touches three files instead of one.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0118",
   "title": "Identity-keyring account namespace collides between a legacy host-only entry and a scoped host+userId entry, letting one server's voice identity private key be adopted on another server",
   "file": "Client/tauri-client/src/lib/identity.ts",
   "line": 211,
   "severity": "low",
   "why": "The B3-3 per-user scope is folded into the single opaque `host` field as `${host}:${userId}`, and the Rust side turns that into the keyring account `identity:{host}`. A host that carries an explicit port therefore produces exactly the same account string as the pre-B3-3 legacy (host-only) entry of a different server: `identityScopeKey(\"chat.example\", 8443)` -> account `identity:chat.example:8443`, which is byte-identical to `identity_account(\"chat.example:8443\")`. `loadOrGenerateIdentityKeyPair` reads that account directly, so it silently adopts the other server's long-term identity private key instead of minting a fresh one — and `ensureIdentityKeyPublished` then publishes that key's public half to the second server, linking the two identities. Host scoping exists precisely to prevent one host's identity key ever being used on another.",
   "repro": "Same desktop install. (1) Sign in to a self-hosted server reachable as `chat.example:8443` on a build that predates the host+user scoping — the identity private key is stored under keyring account `identity:chat.example:8443`. (2) Sign in to a different server reachable as `chat.example` (port 443) as the user whose id is 8443. `loadOrGenerateIdentityKeyPair(\"chat.example\", 8443)` computes scope `chat.example:8443`, `loadIdentityKey` reads account `identity:chat.example:8443`, `importIdentityKeyPair` succeeds on the first server's blob, and the client signs its voice announces on `chat.example` with `chat.example:8443`'s identity key while `ensureIdentityKeyPublished` PATCHes that public key onto `chat.example`.",
   "evidence": "Client/tauri-client/src/lib/identity.ts:211-213\n  function identityScopeKey(host: string, userId: number): string {\n    return `${host}:${userId}`;\n  }\nClient/tauri-client/src/lib/identity.ts:298-299\n    const scope = identityScopeKey(host, userId);\n    const stored = await loadIdentityKey(scope);        // -> invoke(\"load_identity_key\", { host: scope })\n\nClient/tauri-client/src-tauri/src/credentials.rs:46-48\n  fn identity_account(host: &str) -> String {\n      format!(\"identity:{host}\")\n  }\nClient/tauri-client/src-tauri/src/credentials.rs:227-232 (load_identity_key -> secret_store::get(&app, &identity_account(&host)))",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "voice-e2ee",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/identity.test.ts",
    "revertProof": "pass",
    "branchCommit": "43c7e5ea"
   },
   "suggestedFix": "One line in identityScopeKey (identity.ts:211-213): use a delimiter that cannot appear in a valid host, e.g. `return `${userId}@${host}`;` (isValidHost forbids '@' and '/'), which makes a scoped key structurally unable to equal any legacy host-only account. Existing scoped accounts re-mint once — the same one-time re-verify the B3-3 comment at 187-189 already accepts; add a scope-to-scope migration only if that churn matters.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0119",
   "title": "Group-DM creation only block-checks the creator against each recipient, so a third party can force two users who blocked each other into a shared room",
   "file": "Server/service/dm.go",
   "line": 250,
   "severity": "low",
   "why": "CreateGroupDM documents the creation-time check as answering \"may these two be in a room together\", and requireDMNotBlocked deliberately exempts group DMs from every downstream sink (send, edit, react, pin, typing, ring) on the strength of that. But the loop only evaluates IsEitherBlocked(creator, recipient) — never recipient↔recipient. Since group DMs are exempt from the send-time block gate, the two mutually-blocked members can then message each other freely, which is exactly what the block is supposed to prevent.",
   "repro": "C blocks B (PUT /api/v1/blocks/{B}). A blocks nobody. A sends POST /api/v1/dms/group {\"recipient_ids\":[B,C]}. Both IsEitherBlocked(A,B) and IsEitherBlocked(A,C) are false, so the group is created with A, B and C. B now sends a message into that channel: checkSendPermission takes the DM branch, IsDMParticipant(B) is true, requireDMNotBlocked short-circuits on IsGroupDM, and the message is delivered to C. C receives messages from a user they blocked. Existing tests only cover creator↔recipient (api/dm_group_handler_test.go:158 TestCreateGroupDM_BlockerCannotAddBlocked, :172 TestCreateGroupDM_BlockedCannotAddBlocker), so nothing locks the recipient↔recipient case.",
   "evidence": "service/dm.go:239-256\n    for _, rid := range unique {\n        user, err := s.st.GetUserByID(ctx, rid)\n        ...\n        blocked, err := s.st.IsEitherBlocked(ctx, userID, rid)   // creator vs recipient ONLY\n        ...\n        if blocked { return nil, fmt.Errorf(\"%w: cannot add a blocked user to a group DM\", ErrForbidden) }\n    }\n\nservice/message_perms.go:118-122 (requireDMNotBlocked)\n    isGroup, gErr := st.IsGroupDM(ctx, channelID)\n    if gErr == nil && isGroup { return nil }   // groups skip the block gate entirely",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "api-authz",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Server/api/dm_group_handler_test.go",
    "revertProof": "pass",
    "branchCommit": "a353f9ad"
   },
   "suggestedFix": "Check every pair, not just the creator's, in the one place that already owns the gate: build `participantIDs := append([]int64{userID}, unique...)` before the validation loop and run IsEitherBlocked over each i<j pair (n <= db.MaxGroupDMParticipants, so the O(n^2) scan is trivial), returning the same ErrForbidden. That subsumes the existing creator-vs-recipient check rather than adding a second one.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0120",
   "title": "Reaction-users endpoint has no soft-deleted-message guard, unlike its sibling in the same file",
   "file": "Server/service/message_reactions.go",
   "line": 42,
   "severity": "low",
   "why": "GetReactionUsers validates emoji shape, read access and channel ownership of the message, but never checks msg.Deleted. Its siblings do: handleReaction (same file, line 101-103) refuses a deleted message, GetMessagesAround refuses one as ErrNotFound, and handleServeFile was specifically hardened so a deleted message's attachments stop being servable. So a message the client renders as a tombstone still exposes who reacted to it, forever, by direct URL.",
   "repro": "In channel 5, user X posts message 42 and several members react with 👍. A moderator deletes message 42 (soft delete; history and GET /channels/5/messages now omit it and clients render a tombstone). Any member with READ_MESSAGES on channel 5 then calls GET /api/v1/channels/5/messages/42/reactions/%F0%9F%91%8D/users and still receives the full reactor list with 200 OK, because requireChannelRead passes and the deleted flag is never consulted.",
   "evidence": "service/message_reactions.go:41-44 (GetReactionUsers)\n    msg, err := s.st.GetMessage(ctx, msgID)\n    if err != nil || msg == nil || msg.ChannelID != channelID {\n        return nil, fmt.Errorf(\"%w: message not found\", ErrNotFound)\n    }\n    // no msg.Deleted check\n\nservice/message_reactions.go:97-103 (handleReaction, same file)\n    msg, err := s.st.GetMessage(ctx, msgID)\n    if err != nil || msg == nil { ... }\n    if msg.Deleted {\n        return nil, fmt.Errorf(\"%w: cannot react to deleted message\", ErrBadRequest)\n    }\n\nservice/message_query.go:151-153 (GetMessagesAround)\n    if msg == nil || msg.ChannelID != channelID || msg.Deleted {\n        return nil, fmt.Errorf(\"%w: message not found in this channel\", ErrNotFound)",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "api-authz",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Server/service/message_reaction_users_test.go",
    "revertProof": "pass",
    "branchCommit": "8243e60d"
   },
   "suggestedFix": "Add `|| msg.Deleted` to the existing not-found condition at service/message_reactions.go:42, so it reads `if err != nil || msg == nil || msg.ChannelID != channelID || msg.Deleted`. One clause in the service function covers both API and WS callers.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0121",
   "title": "Message jumps and permalinks into a DM fail with \"That channel isn't available\" until the DM has been opened once this session",
   "file": "Client/tauri-client/src/lib/channel-navigation.ts",
   "line": 36,
   "severity": "low",
   "why": "`findChannelById` and `navigateToChannel` gate on `channelsStore.channels`, but a DM's row in that store is *synthesized on open* by `addDmToChannelsStore` — the `ready` payload never carries DM rows, and dmStore is the client's only record of DM membership until the user clicks the conversation. Every jump affordance (global search hit, `owncord://message/...` permalink, pinned/reply jump) routes through `MessageJump.jumpTo`, whose very first check is `findChannelById(channelId) === null`, so a legitimate, visible DM is rejected as invisible.",
   "repro": "Sign in fresh (so `ready` populates dmStore with, say, DM channel 50, and channelsStore holds zero `type: \"dm\"` rows). Without clicking that DM, open the search overlay (it is wired to `jumper.jumpTo` via ChatArea.ts:99-104) and search for a word that appears in DM 50. The server returns the hit (GetAccessibleChannelIDs unions the user's DM ids). Click it: `jumpTo(50, msgId)` calls `findChannelById(50)`, channelsStore has no entry for 50, so it toasts \"That channel isn't available\" and returns false — `getMessagesAround` is never called. Identical failure for an `owncord://message/50/<id>` deep link (main.ts:833 → jumpToMessage) and for a `#`-less permalink chip. Clicking the DM in the sidebar once (selectDmConversation → addDmToChannelsStore) makes the exact same jump work. tests/unit/message-jump.test.ts:221 only locks the case where the id is absent from *both* stores, so this path is not test-covered.",
   "evidence": "channel-navigation.ts:36-39\n  export function findChannelById(channelId: number): { id: number; name: string } | null {\n    const ch = channelsStore.getState().channels.get(channelId);\n    return ch === undefined ? null : { id: ch.id, name: ch.name };\n  }\nchannel-navigation.ts:17-18\n  export function navigateToChannel(channelId: number): void {\n    if (!channelsStore.getState().channels.has(channelId)) return;\nMessageJump.ts:75-78\n  if (findChannelById(channelId) === null) {\n    showToast(\"That channel isn't available\", \"info\");\n    return false;\n  }\ndispatcher.ts:444-448 (the codebase's own statement of the invariant)\n  // Synthesize the channelsStore mirror row before activating: it is\n  // only ever created by addDmToChannelsStore (on open, via\n  // selectDmConversation), so a DM present in dmStore from `ready`\n  // but never opened this session has none\nServer/service/message_perms.go:42-46 (search covers DMs)\n  // Also include DM channels the user participates in.\n  dmIDs, err := s.st.GetUserDMChannelIDs(ctx, userID)\n  if err == nil { ids = append(ids, dmIDs...) }",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "client-state",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "fa15fe5",
    "test": "Client/tauri-client/tests/unit/channel-navigation.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "suggestedFix": "Make the shared resolver DM-aware instead of patching each affordance: in channel-navigation.ts, when channelsStore has no row for channelId, look the id up in dmStore — findChannelById returns { id, name: dmDisplayName(dm) }, and navigateToChannel calls addDmToChannelsStore(dm) before setActiveChannel so ChannelController can resolve it (dispatcher.ts:449 already crosses the same lib->pages import boundary for exactly this reason).",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0122",
   "title": "dm_channel_close fallback activates a DM without clearing its dmStore unread badge, leaving a permanent phantom badge on the conversation being read",
   "file": "Client/tauri-client/src/lib/dispatcher.ts",
   "line": 450,
   "severity": "low",
   "why": "Every other \"open this DM\" path pairs activation with `clearDmUnread` (`selectDmConversation`, `navigateToChannel`, `markChannelRead`), because a DM's badge lives in dmStore while `setActiveChannel` only clears the channelsStore mirror. The dispatcher's close-fallback calls bare `setActiveChannel`, so dmStore's `unreadCount`/`mentionCount` survive — and because the dispatcher then treats that DM as the active one (`isDmActive` → `updateDmLastMessagePreview`, no increment), the stale count is frozen and never clears for the rest of the session.",
   "repro": "Two open DMs: A (channelId 50, active) and B (channelId 60, unreadCount 3). From another signed-in device, close DM A. The server sends `dm_channel_close{channel_id:50}`; `closeDmLocally(50, fallback)` sees A was active and runs the fallback, which activates B via `setActiveChannel(60)`. dmStore's row for 60 still has `unreadCount: 3`, so `buildDmConversations`/`SidebarDmSection.renderDmListItems` (line 97: `if (dm.unreadCount > 0)`) keep rendering a red \"3\" on the conversation now filling the screen, and it also inflates the DIRECT MESSAGES header total (SidebarDmSection.ts:128). New messages arriving in B take the `isDmActive` branch, so the count never moves; `hasUnread(60)` stays true, so \"Mark All as Read\" fires a redundant `mark_read` for it. tests/unit/dispatcher.test.ts:2931 exercises this fallback with `unreadCount: 0` on both DMs, so the behavior is not locked.",
   "evidence": "dispatcher.ts:449-450\n  addDmToChannelsStore(remaining[0]!);\n  setActiveChannel(remaining[0]!.channelId);\ncontrast SidebarDmHelpers.ts:53-57 (the sibling path)\n  clearDmUnread(dmChannel.channelId);\n  addDmToChannelsStore(dmChannel);\n  setActiveChannel(dmChannel.channelId);\ncontrast SidebarArea.ts:437-440 (the local close path)\n  function fallBackFromDm(): void {\n    const remaining = dmStore.getState().channels;\n    if (remaining.length > 0) { selectDmConversation(remaining[0]!, dmDeps); return; }\ndispatcher.ts:502-518 (why the count then freezes)\n  if (isOwnMessage || isDmActive || ws.isReplaying()) {\n    updateDmLastMessagePreview(...)   // no unread increment",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "client-state",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "d1c104d",
    "test": "Client/tauri-client/tests/unit/dispatcher.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "suggestedFix": "Replace the two lines with `addDmToChannelsStore(remaining[0]!); navigateToChannel(remaining[0]!.channelId);` — navigateToChannel is already the shared 'open this channel' entry point and does setActiveChannel + clearUnread + clearDmUnread in one call (a bare `clearDmUnread(remaining[0]!.channelId)` before line 450 is the even smaller equivalent).",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0123",
   "title": "markAllRead's paced tail marks messages that arrived after the click as read, destroying a genuinely-new unread badge",
   "file": "Client/tauri-client/src/lib/read-state.ts",
   "line": 118,
   "severity": "low",
   "why": "`markAllRead` snapshots the unread set at click time but defers most of the sends by up to `ceil(n/4) * 1100 ms`. Each deferred timer calls `markChannelRead(id)` unconditionally, which both sends `mark_read` (advancing the server's read state to the channel's current tail) and calls `clearUnread`/`clearDmUnread` locally. A message that arrives in one of those channels during the pacing window is therefore marked read and its badge wiped, even though the user never saw it and it postdates the action they took.",
   "repro": "Have 6 unread channels (ids 1..6) and click \"Mark All as Read\". Channels 1-4 are sent synchronously; 5 and 6 are queued for t+1100 ms. At t+500 ms a new message arrives in channel 6: the dispatcher's chat_message handler calls `incrementUnread(6)` and the sidebar badge shows 1. At t+1100 ms the queued timer fires `markChannelRead(6)`, which sends `mark_read` for channel 6 (advancing the server read state past the new message) and calls `clearUnread(6)`. The message is gone from every unread surface and the server agrees it was read, though it arrived after the click and was never displayed. With ~100 unread conversations the window stretches to ~27 s. tests/unit/read-state.test.ts:156 locks the pacing itself but never delivers a message during the window.",
   "evidence": "read-state.ts:112-120\n  const ids = unreadChannelIds();\n  for (const [i, id] of ids.entries()) {\n    const delay = Math.floor(i / MARK_ALL_READ_BURST_SIZE) * MARK_ALL_READ_BURST_INTERVAL_MS;\n    if (delay === 0) { markChannelRead(id); }\n    else { pendingMarkAll.push(setTimeout(() => markChannelRead(id), delay)); }\n  }\nread-state.ts:42-51 (no re-check of current unread state)\n  export function markChannelRead(channelId: number): void {\n    const known = ...;\n    if (!known) return;\n    sender?.(channelId);\n    clearUnread(channelId);\n    clearDmUnread(channelId);\n  }\nread-state.ts:103-105 (the stated intent this breaks)\n  // Each channel's local badge is cleared at the moment its own frame actually\n  // goes out, not up front, so a channel whose send hasn't fired yet still\n  // shows unread rather than lying about it.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "client-state",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "95ea82c",
    "test": "Client/tauri-client/tests/unit/read-state.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "suggestedFix": "In markAllRead, snapshot each id's current lastMessageId alongside the id, and in the deferred callback skip markChannelRead when the channel's lastMessageId has moved (the new message is genuinely unread and keeping its badge is the safer side of the tradeoff). ~4 lines, entirely inside markAllRead; do not change markChannelRead, whose synchronous callers want the unconditional advance.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0124",
   "title": "hidePreview overwrites the pending animation timer without clearing it, orphaning timers that later tear down a freshly reopened preview and strand its media-track listeners",
   "file": "Client/tauri-client/src/lib/streamPreview.ts",
   "line": 273,
   "severity": "low",
   "why": "`hidePreview` clears only `state.debounce` (line 249) and then blindly assigns `state.animation = animTimer` (line 273). The `animation` slot may already hold a live timer — either `stopPreviewDelayed`'s 150 ms grace timer (line 315) or a prior `hidePreview`'s 200 ms removal timer — and that timer is never cancelled, so it keeps running with no handle. When an orphaned removal timer fires it runs `previewTimers.delete(row)` (line 269) against whatever state a *later* hover installed, which both destroys that state's `trackCleanup` handle and makes the abort handler's `clearPreviewState` (lines 79-80) a no-op for the row.",
   "repro": "Voice sidebar, remote participant with a live camera. t=0: hover the row -> mouseenter -> startPreview -> after the 300 ms debounce showPreview inserts `.vu-preview`, adds `ended`/`mute` listeners to the remote MediaStreamTrack and stores `trackCleanup` on the state (lines 148-158). t=400: move the pointer off the row -> mouseleave -> stopPreviewDelayed arms T1 (150 ms) in state.animation. t=450 (inside that window): scroll the voice list, or Tab away (focusout) -> hidePreview runs, does NOT clear T1, and writes T2 (200 ms removal) into state.animation. t=550: T1 fires, the preview is not `:hover`, so it calls hidePreview again -> writes T3 (200 ms) into state.animation, orphaning T2. t=650: T2 fires -> removePreviewDom + previewTimers.delete(row). t=660: hover the row again -> startPreview's clearPreviewState finds no state (already deleted), installs a fresh state with a 300 ms debounce. t=750: the orphaned T3 fires -> previewTimers.delete(row) removes that brand-new state. t=960: the debounce fires and showPreview builds a new <video>, registers `ended`/`mute` on the remote track, then hits `const state = previewTimers.get(row); if (state !== undefined)` (lines 152-158) -> undefined, so trackCleanup is never stored. Those two track listeners are now unreachable by clearPreviewState, by hidePreview, and by the sidebar-teardown abort handler (lines 52-58); they survive every sidebar rebuild, keep firing onTrackDead against a detached row, and pin the video/previewDiv/row closures for the remote track's lifetime. The user-visible symptom on the way there is the preview closing itself ~200 ms after being reopened.",
   "evidence": "hidePreview (246-275):\n  const state = previewTimers.get(row);\n  if (state !== undefined) {\n    clearTimeout(state.debounce);            // <- only debounce is cleared\n    if (state.trackCleanup !== null) { ... }\n  }\n  ...\n  const animTimer = window.setTimeout(() => {\n    removePreviewDom(row);\n    previewTimers.delete(row);\n  }, 200);\n  if (state !== undefined) {\n    state.animation = animTimer;             // line 273: overwrite, no clearTimeout(state.animation)\n  }\n\nstopPreviewDelayed (311-330) writes the same slot:\n    clearTimeout(state.animation);\n    state.animation = window.setTimeout(() => { ... hidePreview(row); }, 150);\n\nBoth other entry points call hidePreview directly without touching state.animation:\n  row.addEventListener(\"focusout\", stopPreview, { signal });   // line 338 -> hidePreview\n  attachScrollCollapse -> hidePreview(row as HTMLElement);      // line 358",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "concurrency",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "f8f3696",
    "test": "Client/tauri-client/tests/unit/stream-preview.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "suggestedFix": "In hidePreview, cancel the pending animation timer before overwriting it: add `clearTimeout(state.animation);` immediately after `clearTimeout(state.debounce);` at line 249. One line in the shared function covers every entry path (scroll collapse, focusout, delayed stop, preview mouseleave), guarantees at most one live animation timer per state, and keeps that timer cancellable by clearPreviewState/startPreview. clearTimeout(0) on the initial value is a harmless no-op.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0125",
   "title": "Voice & Audio settings tab registers a new permanent abort listener on the overlay-lifetime AbortSignal on every build, pinning every previously built tab",
   "file": "Client/tauri-client/src/components/settings/VoiceAudioTab.ts",
   "line": 490,
   "severity": "low",
   "why": "buildVoiceAudioTabInner adds an \"abort\" listener to the SettingsOverlay-lifetime AbortSignal each time the tab is (re)built, with no {once}, no removeEventListener, and no dedupe. The signal only fires when the whole overlay is destroyed, so the listeners accumulate for the MainPage session and each closure retains that build's entire DOM subtree (selects, sliders, toggles, preview <video>).",
   "repro": "Open Settings, select \"Voice & Audio\", close Settings, reopen it (SettingsOverlay.hide() sets contentLive=false; show() calls renderActiveTab() -> voiceTab.build() -> buildVoiceAudioTabInner). Repeat N times: SettingsOverlay's single AbortController now carries N abort listeners, and the N-1 detached tab subtrees (each with a <video> element and its device <select> lists) are unreachable from the DOM but still strongly held by those closures. Nothing releases them until MainPage is destroyed (logout).",
   "evidence": "490:  signal.addEventListener(\"abort\", () => {\n491:    stopCameraPreview();\n492:  });\n\nThe closure captures stopCameraPreview -> cameraRequestId, registerCamera, previewVideo, and transitively `section`. Contrast the outer factory (line 77, `signal.addEventListener(\"abort\", cleanupMic)`) which is registered exactly once, and lib/modalFactory.ts:128-142 which registers its parent-signal listener with `{ signal: ac.signal }` so it is released when the modal closes.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "lifecycle",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "a100f4e",
    "test": "Client/tauri-client/tests/unit/voice-audio-tab.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "suggestedFix": "Delete the redundant registration at VoiceAudioTab.ts:490-492. Abort teardown is already covered by the factory's single `signal.addEventListener(\"abort\", cleanupMic)` (line 77): cleanupMic calls `invalidateCameraPreviewRequest?.()` (which bumps cameraRequestId/micRequestId for the current build) and stops `cameraPreviewStream` tracks. The only extra thing line 491 does is null `previewVideo.srcObject` on a subtree that is being discarded anyway.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0126",
   "title": "Plugin enable leaves plugins.enabled = 1 in the DB when the in-memory instance is missing — no rollback on that early return",
   "file": "Server/plugin/registry.go",
   "line": 466,
   "severity": "low",
   "why": "`EnablePlugin` writes the DB flag first, then looks up the in-memory instance. The activate-failure path below (line 471–479) carefully rolls the DB flag back with `DisablePlugin`, but the `!ok` path returns `ErrPluginNotFound` with the row already flipped to enabled. The admin sees an error, the persisted state says enabled, and every subsequent startup's `activateAll` just logs \"enabled row has no on-disk manifest, skipping\" — a permanently inconsistent enabled flag with no UI path to clear it (Disable on a plugin the registry does not know still needs the row).",
   "repro": "Install a plugin, stop the server, delete its directory under `plugins/` (or let InstallFromZip's rename fail, see the sibling finding), restart. `scanPluginDirectory` no longer registers it, so `r.plugins[id]` is empty while the `plugins` row survives. Click Enable in the admin panel: the request 404s/errors, but `SELECT enabled FROM plugins WHERE id=?` is now 1 forever, and every restart logs \"enabled row has no on-disk manifest, skipping\".",
   "evidence": "if err := r.cfg.Store.EnablePlugin(ctx, id); err != nil {\n    return err\n}\nr.mu.RLock()\ninst, ok := r.plugins[id]\nr.mu.RUnlock()\nif !ok {\n    return ErrPluginNotFound          // <-- DB row already enabled, never rolled back\n}",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "error-paths",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/plugin/registry_test.go",
    "revertProof": "pass",
    "branchCommit": "9075f248",
    "pr": 1369
   },
   "suggestedFix": "In EnablePlugin, roll back on the not-found path the same way the activate path does: `if !ok { _ = r.cfg.Store.DisablePlugin(ctx, id); return ErrPluginNotFound }`.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0127",
   "title": "Plugin uninstall returns success when the on-disk directory cannot be removed, so the plugin is resurrected on the next startup",
   "file": "Server/plugin/registry.go",
   "line": 538,
   "severity": "low",
   "why": "`UninstallPlugin` deletes the DB row and the in-memory records, then removes the plugin directory best-effort — an `os.RemoveAll` failure is only warned and the function still returns `nil`. The comment two lines above states the removal is what stops `scanPluginDirectory` resurrecting the plugin on the next startup, so the error path silently produces exactly the outcome it was written to prevent while telling the admin the uninstall succeeded.",
   "repro": "On Windows, uninstall a plugin whose .wasm file is still open/mapped (AV scanner, or a wazero module handle not yet released) — `os.RemoveAll` fails with a sharing violation. The admin panel shows the uninstall succeeded and the plugin disappears from the list. Restart the server: `scanPluginDirectory` finds the leftover `plugins/<name>/plugin.json` and `installFromDisk` re-creates the row, so the \"uninstalled\" plugin is back.",
   "evidence": "// Remove on-disk files so the plugin isn't resurrected on the next\n// startup by scanPluginDirectory.\nif pluginDir != \"\" {\n    if err := os.RemoveAll(pluginDir); err != nil {\n        slog.Warn(\"plugin: failed to remove plugin directory after uninstall\", \"dir\", pluginDir, \"err\", err)\n    }\n}\nreturn nil",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "error-paths",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/plugin/registry_test.go",
    "revertProof": "pass",
    "branchCommit": "9075f248",
    "pr": 1369
   },
   "suggestedFix": "Return the error instead of swallowing it: `if err := os.RemoveAll(pluginDir); err != nil { return fmt.Errorf(\"remove plugin dir: %w\", err) }` — the DB row and in-memory records are already gone, so the admin at least learns the files must be cleaned up before the next restart.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0128",
   "title": "An attachment-metadata read failure broadcasts the message with no attachments — an attachment-only send renders as a blank bubble for everyone",
   "file": "Server/service/message_crud.go",
   "line": 135,
   "severity": "low",
   "why": "After the attachments are successfully linked in the DB, `GetAttachmentsByMessageIDs` is read purely to populate the broadcast payload. On error the failure is logged and `attachments` stays nil, but the function returns success — so `handleChatSendV2` builds `chat_message` with an empty attachment list. Because `sanitizeContent` allows empty content when attachments were requested, an image-only message is fanned out to every subscriber as a message with no content and no attachments. Nothing corrects it live; only a history refetch does.",
   "repro": "Post an image with no text. Make `GetAttachmentsByMessageIDs` fail for that one call (transient SQLITE_BUSY on the reader pool, or the request ctx being cancelled right after `LinkAttachmentsToMessage` commits). The row and its attachment link are committed, the sender gets `chat_send_ok`, and every client in the channel receives a `chat_message` with `content: \"\"` and `attachments: []` — an empty message bubble that stays empty until the channel history is refetched.",
   "evidence": "if linked > 0 {\n    attMap, attErr := s.st.GetAttachmentsByMessageIDs(ctx, []int64{msgID})\n    if attErr != nil {\n        slog.Error(\"MessageService.SendMessage GetAttachments\", \"err\", attErr)\n    } else {\n        attachments = attMap[msgID]\n    }\n}",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "error-paths",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Server/service/message_crud_test.go",
    "revertProof": "pass",
    "branchCommit": "86acf049"
   },
   "suggestedFix": "Do the post-commit read on a detached ctx like the compensating deletes in the same function: `s.st.GetAttachmentsByMessageIDs(context.WithoutCancel(ctx), []int64{msgID})`.",
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0129",
   "title": "\"Yesterday\" boundary is computed by subtracting 24h from local midnight, so DST days mislabel message timestamps by a full day",
   "file": "Client/tauri-client/src/components/message-list/formatting.ts",
   "line": 81,
   "severity": "low",
   "why": "`yesterdayStart` is `todayStart.getTime() - 86_400_000` rather than calendar-yesterday's local midnight (`new Date(y, m, d-1)`). On a DST transition the local day is 23 or 25 hours, so the fence post lands inside the wrong calendar day and formatMessageTimestamp — which renders every message's hover/expanded timestamp — labels messages with the wrong relative day.",
   "repro": "Spring forward (US, 23-hour local day): with `now` = Mon Mar 9 10:00 local, todayStart = Mar 9 00:00, todayStart-24h = Sat Mar 7 23:00 local (not Sun Mar 8 00:00). A message posted Sat Mar 7 at 23:30 satisfies `date >= yesterdayStart` and renders as \"Yesterday at 11:30 PM\" although it is two days old. Fall back (25-hour local day): with `now` = Mon Nov 3 10:00, todayStart-24h = Sun Nov 2 01:00, so a message posted Sun Nov 2 at 00:30 fails `date >= yesterdayStart` and renders as \"11/02/2026 12:30 AM\" instead of \"Yesterday at 12:30 AM\".",
   "evidence": "Client/tauri-client/src/components/message-list/formatting.ts:80-88\n  `const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());`\n  `const yesterdayStart = new Date(todayStart.getTime() - 86_400_000);`\n  `if (date >= todayStart) { return \\`Today at ${timeStr}\\`; }`\n  `if (date >= yesterdayStart) { return \\`Yesterday at ${timeStr}\\`; }`\nUsed at Client/tauri-client/src/components/message-list/renderers.ts:238 `formatMessageTimestamp(msg.timestamp)`.\nThe existing test only covers the non-DST case: tests/unit/renderers.test.ts:1186-1190 asserts `now - 24h` matches /^Yesterday at /, so the DST edge is not locked.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "ordering-boundary",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "19315e5",
    "test": "Client/tauri-client/tests/unit/renderers.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "suggestedFix": "Replace line 81 with the calendar day before, mirroring line 80: `const yesterdayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);` (Date normalizes day 0 / negative days across month and year boundaries, so no extra guard is needed).",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0130",
   "title": "GIF freeze compares a raw URL string against the DOM-normalized img.src, so any URL the parser rewrites is never actually frozen while the UI claims it is",
   "file": "Client/tauri-client/src/lib/media-visibility.ts",
   "line": 70,
   "severity": "low",
   "why": "freezeImage only captures and swaps in the still frame when `img.src === entry.originalSrc`. `entry.originalSrc` is the raw string the caller passed (media.ts:318 passes the message-content URL verbatim; embeds.ts:331 passes the embed's image URL), while the `img.src` getter returns the URL after WHATWG normalization — host lowercased, default port stripped, path percent-encoded, dot segments resolved. When those differ the guard is false: no canvas capture, no src swap, so the GIF keeps animating at full frame rate while entry.isPlaying is set false, the button flips to ▶ and the wrapper gets `gif-paused`. Off-screen freeze (observer callback, line 153) and window-blur freeze (pauseAllMedia, line 289) become no-ops too, defeating the module's entire stated purpose.",
   "repro": "Post a message containing `https://EXAMPLE.com/anim.gif` (or any GIF URL with a space/non-ASCII char in the filename, or an explicit `:443`). isDirectImageUrl passes, renderInlineImage sets attrs.src = url and calls observeMedia(img, url, wrap) on load (media.ts:314-321). `img.src` now reads `https://example.com/anim.gif`, which !== `https://EXAMPLE.com/anim.gif`. Click the pause button: updateButton paints ▶ and adds `gif-paused`, but the branch at line 70 is skipped so img.src is untouched and the GIF keeps animating. Scroll it out of view or blur the window — still animating. The existing test only ever uses an already-normalized `https://example.com/cat.gif` (tests/unit/media-visibility.test.ts:106), so nothing locks this.",
   "evidence": "media-visibility.ts:70-77\n  `if (img.src === entry.originalSrc) {`\n  `  if (entry.frozenSrc === null) { entry.frozenSrc = captureStaticFrame(img); }`\n  `  if (entry.frozenSrc !== null) { img.src = entry.frozenSrc; }`\n  `}`\nmedia.ts:268-278 `const attrs: Record<string, string> = { src: url, ... }; const img = createElement(\"img\", attrs);`\nmedia.ts:318 `observeMedia(img, url, wrap, !animateGifsPref);`",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "hotspot-client-tauri-client-src-lib",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "87ab12c",
    "test": "Client/tauri-client/tests/unit/media-visibility.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "suggestedFix": "In freezeImage (media-visibility.ts:70-77) drop the originalSrc identity guard and compare against the frozen frame instead, so the swap no longer depends on string-matching an un-normalized URL:\n\n  if (entry.frozenSrc === null) {\n    entry.frozenSrc = captureStaticFrame(img);\n  }\n  if (entry.frozenSrc !== null && img.src !== entry.frozenSrc) {\n    img.src = entry.frozenSrc;\n  }\n\nOne hunk in the shared function; fixes all three callers (media.ts:318, embeds.ts:331, attachments.ts:573/594) and all freeze triggers (button, observer, pauseAllMedia, startFrozen) at once. Re-entry is still safe: frozenSrc is non-null once captured, so a second freeze never re-captures from the already-frozen frame.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0131",
   "title": "A username containing an uppercase non-ASCII letter can never be @mentioned",
   "file": "Server/db/mention_queries.go",
   "line": 262,
   "severity": "low",
   "why": "resolveMentions lowercases every @token with Go's Unicode-aware strings.ToLower, then GetUserIDsByUsernames matches with `username IN (...)`, relying on the column's `COLLATE NOCASE`. SQLite's NOCASE folds ASCII A-Z only, so a Unicode-lowercased token can never equal a stored name whose letters are non-ASCII uppercase — the lookup silently returns nothing and the mention degrades to plain text.",
   "repro": "auth.ValidateUsername (Server/auth/helpers.go:19-47) only rejects control/format runes, so \"Émile\" is a legal username. Alice posts \"hey @Émile\". parseMentionTokens matches it (the token class is `[\\p{L}\\p{N}_.-]`, Server/service/mentions.go:30) and lowercases it to \"émile\" (mentions.go:69). GetUserIDsByUsernames binds 'émile' and runs `SELECT id, username FROM users WHERE <notBanned> AND username IN ('émile')`; NOCASE compares 'é' (U+00E9) with 'É' (U+00C9) bytewise, so no row comes back. resolveMentions returns an empty set: no message_mentions row is written, applyMentionCounts never bumps Émile's read_states.mention_count, and the broadcast carries an empty `mentions` array so the client renders no highlight. Every spelling fails identically — typing the exact stored \"@Émile\" still gets lowercased to \"émile\" before the query — so the user is permanently unmentionable, while a purely-ASCII \"@bob\" resolves fine.",
   "evidence": "db/mention_queries.go:244-246 — \"// GetUserIDsByUsernames resolves usernames to ids, keyed by the lowercased\\n// username. Matching is case-insensitive because users.username is UNIQUE\\n// COLLATE NOCASE, which makes the column's comparisons case-insensitive too.\"\ndb/mention_queries.go:260-263 — `rows, err := d.reader.QueryContext(ctx, fmt.Sprintf(`SELECT id, username FROM users WHERE %s AND username IN (%s)`, notBannedClause, strings.Join(placeholders, \",\")), args...)`\nservice/mentions.go:69 — `raw := strings.ToLower(m[2])`\nmigrations/001_initial_schema.sql:24 — `username    TEXT    NOT NULL UNIQUE COLLATE NOCASE,`",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "hotspot-server-service",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Server/db/mention_queries_test.go",
    "revertProof": "pass",
    "branchCommit": "c7e87f19"
   },
   "suggestedFix": "Make the mention fold match the column's fold instead of exceeding it: replace the Unicode `strings.ToLower` with an ASCII-only lower in the two places that must agree — service/mentions.go:69 (`raw := strings.ToLower(m[2])`) and db/mention_queries.go:277 (`result[strings.ToLower(name)] = id`). A four-line helper (`func lowerASCII(s string) string` mapping only 'A'-'Z') used in both spots makes \"@Émile\" bind the literal 'Émile' and match the stored row, and keeps the map key and the lookup key identical. This also aligns mentions with every other username comparison in the codebase (dbgen/users.sql.go:99 `WHERE username = ? COLLATE NOCASE`), which already folds ASCII-only. Do not instead add `LOWER()`/`COLLATE` to the query — SQLite's built-in LOWER() is ASCII-only too, so it would not help.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0132",
   "title": "Connection-quality degradation is never reported: the 3 s debounce timer is cleared and rescheduled by every 2 s poll, so onQualityChanged only fires when stats collection fails",
   "file": "Client/tauri-client/src/lib/connectionStats.ts",
   "line": 168,
   "severity": "low",
   "why": "POLL_INTERVAL_MS (2000) is shorter than QUALITY_DEBOUNCE_MS (3000), and `lastQuality` is only advanced inside the timer callback. So while the measured quality differs from `lastQuality`, every single poll re-enters the `newQuality !== lastQuality` branch, clears the pending timer and schedules a fresh 3 s one — the timer can never reach its deadline. The only way it fires is if a poll returns early (`!room` or `reports.length === 0`), i.e. when the stats path is broken, and by then `current.quality` is whatever the last successful poll left. The net effect is that the quality-change notification is structurally unreachable during exactly the condition it exists to detect.",
   "repro": "1. Join voice. `startStatsPoller()` creates the poller; lastQuality = \"excellent\".\n2. t=2000 ms: first poll, candidate-pair currentRoundTripTime = 0.01 -> quality \"excellent\". No branch taken.\n3. Network degrades to RTT 500 ms. t=4000 ms poll: quality \"bad\" != lastQuality \"excellent\" -> timer scheduled for t=7000.\n4. t=6000 ms poll: quality still \"bad\" != \"excellent\" -> clearTimeout, reschedule for t=9000.\n5. t=8000 ms poll: reschedule for t=11000. ... and so on for the entire duration of the bad connection.\n   Result: qualityChangeListeners are never invoked, the VoiceWidget stats pane never auto-expands, and lastQuality stays \"excellent\" forever.\n6. Conversely, unplug the network so `collectAllStats` returns [] (line 142 early-return): the timer is no longer reset and fires ~3 s later, expanding the stats pane at the one moment the numbers on it are stale — the inverse of the intended behaviour.",
   "evidence": "connectionStats.ts:137-177\n  const POLL_INTERVAL_MS = 2000;            // line 7\n  const QUALITY_DEBOUNCE_MS = 3000;         // line 135\n  async function poll() {\n    const room = getRoom();\n    if (!room) return;                      // line 139  <- only escape hatch\n    const reports = await collectAllStats(room);\n    if (reports.length === 0) return;       // line 142  <- only other escape hatch\n    ...\n    const newQuality = current.quality;\n    if (newQuality !== lastQuality) {                       // line 168\n      if (qualityDebounceTimer !== null) clearTimeout(qualityDebounceTimer);  // line 169\n      qualityDebounceTimer = setTimeout(() => {             // line 170\n        if (current.quality !== lastQuality) {\n          const prevQuality = lastQuality;\n          lastQuality = current.quality;                    // line 172-173: ONLY writer of lastQuality\n          qualityChangeListeners.forEach((cb) => cb(current.quality, prevQuality));\n        }\n      }, QUALITY_DEBOUNCE_MS);\n    }\n  }\n\nSole consumer — VoiceWidget.ts:149-154:\n  qualityUnlisten = statsPoller.onQualityChanged((quality, _prevQuality) => {\n    // Auto-expand stats pane when quality degrades\n    if ((quality === \"poor\" || quality === \"bad\") && statsPane !== null) {\n      statsPane.classList.add(\"visible\");\n    }\n  });\n\nNote on the existing test: tests/unit/connection-stats.test.ts:319 is named \"fires quality change callback with debounce\" — i.e. it asserts the intended contract — but it only passes because line 357 sets `roomActive = false` so polls stop resetting the timer. Its comment (lines 320-323) documents the symptom and rationalises it as \"fires after the connection stabilizes\", which is not what the code does: when quality stabilizes it equals `lastQuality`, so the guard at line 171 is false and nothing fires. The test locks the callback's existence, not the perpetual reset.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-1",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "bac1cda",
    "test": "Client/tauri-client/tests/unit/connection-stats.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "suggestedFix": "In poll(), only arm the timer when none is pending, clear it when quality returns to `lastQuality`, and null the handle when it fires:\n\n```ts\nif (newQuality !== lastQuality) {\n  if (qualityDebounceTimer === null) {\n    qualityDebounceTimer = setTimeout(() => {\n      qualityDebounceTimer = null;\n      if (current.quality !== lastQuality) {\n        const prevQuality = lastQuality;\n        lastQuality = current.quality;\n        qualityChangeListeners.forEach((cb) => cb(current.quality, prevQuality));\n      }\n    }, QUALITY_DEBOUNCE_MS);\n  }\n} else if (qualityDebounceTimer !== null) {\n  clearTimeout(qualityDebounceTimer);\n  qualityDebounceTimer = null;\n}\n```\n\nNulling the handle inside the callback is required, otherwise the new `=== null` check would never re-arm after the first fire. stop() (lines 195-198) already nulls it.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0133",
   "title": "UninstallPlugin deletes a directory derived from the manifest name, not the plugin's real on-disk directory, so any plugin whose folder name differs is resurrected on next start",
   "file": "Server/plugin/registry.go",
   "line": 520,
   "severity": "low",
   "why": "`scanPluginDirectory` takes the on-disk directory from the filesystem entry name (`e.Name()`) and never compares it to `manifest.Name`; the real directory is recorded as `foundPlugin.Dir` / `Instance.WASMPath`. `UninstallPlugin` instead rebuilds the path as `filepath.Join(r.cfg.Directory, inst.Manifest.Name)`. When the two differ, `os.RemoveAll` targets a path that does not exist — and `os.RemoveAll` returns nil for a missing path, so even the warning on the next line never fires and the handler answers 204 as if the uninstall succeeded. `AssetHandler` (host_ui.go:59) derives the same plugin root correctly as `filepath.Dir(inst.WASMPath)`, so the two sites disagree about where the plugin lives.",
   "repro": "Install a plugin by hand as `plugins/hello-v2/` containing `plugin.json` = {\"name\":\"hello\",\"version\":\"1\",\"entrypoint\":\"hello.wasm\"} plus `hello.wasm`. Start the server (LoadAll registers it with WASMPath=plugins/hello-v2/hello.wasm). DELETE /api/v1/admin/plugins/{id} -> 204, DB row gone, in-memory record gone; `os.RemoveAll(\"plugins/hello\")` no-ops with a nil error so nothing is logged. Restart the server: LoadAll rescans `plugins/hello-v2`, InstallPlugin re-inserts the row, and the uninstalled plugin is back in the admin list. (The registry test only ever writes the directory with the same name as the manifest, so it never exercises the mismatch.)",
   "evidence": "registry.go:520  pluginDir = filepath.Join(r.cfg.Directory, inst.Manifest.Name)\nregistry.go:538  if err := os.RemoveAll(pluginDir); err != nil { slog.Warn(\"plugin: failed to remove plugin directory after uninstall\", ...) }\nloader.go:52     pluginDir := filepath.Join(dir, e.Name())          // real dir = filesystem entry name\nloader.go:85     wasmPath := filepath.Join(pluginDir, manifest.Entrypoint)\nhost_ui.go:59    pluginDir, dirErr := filepath.Abs(filepath.Dir(inst.WASMPath))  // sibling derives it from WASMPath",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "hotspot-server-plugin",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/plugin/registry_test.go",
    "revertProof": "pass",
    "branchCommit": "9075f248",
    "pr": 1369
   },
   "suggestedFix": "Stop deriving the path from the manifest: add a `Dir string` field to `Instance`, set it from `found.Dir` in installFromDisk (InstallFromZip already passes `Dir: finalDir` in its foundPlugin), and use `inst.Dir` at registry.go:520. One field, one assignment, one call-site change — `filepath.Dir(inst.WASMPath)` is not equivalent because a manifest Entrypoint may be a nested relative path (manifest.go:147 validateRelativePath).",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0134",
   "title": "DM sidebar avatar image load destroys the presence status dot",
   "file": "Client/tauri-client/src/components/DmSidebar.ts",
   "line": 95,
   "severity": "low",
   "why": "paintAvatar() clears the avatar circle with `el.textContent = \"\"` before inserting the fetched <img>. For a 1:1 DM, buildAvatar() appends the `.dm-status` presence dot to that same element synchronously, after paintAvatar() has already started its async fetch. When the bytes arrive the wipe removes the dot along with the letter, so every DM row whose peer has an uploaded avatar permanently loses its online/idle/dnd/offline indicator. The sibling helper `lib/avatar.ts:120` solves exactly this by calling `letter.remove()` instead of clearing the parent.",
   "repro": "Open the DM sidebar with a 1:1 conversation whose peer has an avatar (`avatar: \"/api/v1/files/42\"`, `status: \"online\"`). buildAvatar (DmSidebar.ts:129-137) runs paintAvatar -> setText(el,\"A\") -> starts fetchImageAsDataUrl, then appends the `.dm-status` span. One microtask later the fetch resolves, `el.textContent = \"\"` drops the status span, and `el.appendChild(img)` leaves the circle with the image only. `container.querySelector('.dm-avatar .dm-status')` is null. Peers with `avatar: null` keep their dot, which is why every existing status test (tests/unit/dm-sidebar.test.ts:350-366, 481) passes — makeConvo defaults to `avatar: null`.",
   "evidence": "function paintAvatar(el: HTMLElement, avatar: string | null, label: string): void {\n  setText(el, label.charAt(0).toUpperCase());\n  ...\n  void fetchImageAsDataUrl(resolved).then((dataUrl) => {\n    if (dataUrl === null || !el.isConnected) return;\n    const img = createElement(\"img\", { src: dataUrl, alt: label });\n    ...\n    el.textContent = \"\";      // <-- wipes the .dm-status dot appended at line 136\n    el.appendChild(img);\n  });\n}",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-2",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "8b2652d",
    "test": "Client/tauri-client/tests/unit/dm-sidebar.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "suggestedFix": "In paintAvatar, stop clearing the whole element — remove only the letter. Smallest edit at line 95: replace `el.textContent = \"\";` with `for (const n of [...el.childNodes]) if (n.nodeType === Node.TEXT_NODE) n.remove();` (or mirror lib/avatar.ts: append the initial as a span and call `letter.remove()`). One change in the shared helper covers both the 1:1 and the group-face call sites.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0135",
   "title": "Re-subscribed screenshare-audio tracks leak detached <audio> elements into screenshareAudioElements forever",
   "file": "Client/tauri-client/src/lib/audioElements.ts",
   "line": 132,
   "severity": "low",
   "why": "The screenshare branch of handleTrackSubscribedAudio detaches and DOM-removes any previously attached elements for the track, but never deletes them from `this.screenshareAudioElements.get(userId)` — unlike handleTrackUnsubscribedAudio (line 186), which does exactly that. The set therefore grows with dead elements, and the `audioEls.size === 0` cleanup at line 187 can never fire, so the userId key is never released either.",
   "repro": "LiveKit re-fires TrackSubscribed for an already-attached screenshare-audio track before the old TrackUnsubscribed lands — the exact fast-reconnect ordering the sibling mic branch's comment at line 153-154 cites. Subscribe #1 adds element A to the set. Subscribe #2 does `track.detach()` (returns [A]), `A.remove()`, then `audioEls.add(B)`; A is still in the set. The eventual unsubscribe detaches [B], deletes B, sees `size === 1` (A) and leaves the userId entry alive. A is now an orphaned HTMLAudioElement pinned by the map for the rest of the voice session, and setScreenshareAudioVolume/muteScreenshareAudio keep writing to it; only cleanupAllAudioElements() ever frees it.",
   "evidence": "if (publication.source === Track.Source.ScreenShareAudio) {\n  for (const el of track.detach()) el.remove();   // <-- no audioEls.delete(el)\n  const audioEl = track.attach();\n  ...\n  audioEls.add(audioEl);\n// vs. handleTrackUnsubscribedAudio, which does it right:\n  const detachedEls = track.detach() as HTMLAudioElement[];\n  for (const el of detachedEls) el.remove();\n  const audioEls = this.screenshareAudioElements.get(userId);\n  if (audioEls !== undefined) {\n    for (const el of detachedEls) audioEls.delete(el);\n    if (audioEls.size === 0) this.screenshareAudioElements.delete(userId);",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-2",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/audio-elements.test.ts",
    "revertProof": "pass",
    "branchCommit": "6d123b8e"
   },
   "suggestedFix": "Hoist the Set lookup above the detach loop and delete what you detach: `const prev = this.screenshareAudioElements.get(userId); for (const el of track.detach()) { el.remove(); prev?.delete(el); }` — then reuse `prev` for the existing get-or-create at lines 138-142.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0136",
   "title": "api.setConfig's host validator rejects every IPv6 literal, so login to an IPv6 server is impossible while the rest of the client explicitly supports it",
   "file": "Client/tauri-client/src/lib/api.ts",
   "line": 82,
   "severity": "low",
   "why": "`isValidHost` is `/^[\\w.-]+(:\\d+)?$/` — `:` and `[`/`]` are outside the character class, so `[::1]:8443`, `[fd00::1]`, and bare `2001:db8::1` all fail and `setConfig` throws `Invalid host format`. Every other layer of the same client implements IPv6 host handling deliberately and has tests asserting it: `livekitSession.ensureLiveKitProxy` (src/lib/livekitSession.ts:693-703) branches on bracketed vs. bare IPv6, `livekit_proxy.rs::validate_remote_host` + `parse_server_name` accept and strip brackets (test `accepts_plain_hostnames_and_ports` asserts `[::1]:8443` is OK), and `http_proxy.rs::validate_remote_host` allows `[` and `]` with the same assertion. The one gate on the login path is the only place that refuses.",
   "repro": "Enter `[::1]:8443` (or any IPv6 literal) in the connect page's Server Address field and press Log In. ServerPanel's health check succeeds — `profiles.pingHost` → `ensureHttpProxy(host)` → `start_http_proxy` accepts the bracketed host and the tunnel connects, so the profile shows \"online\". main.ts:495 then calls `api.setConfig({ host })`, `isValidHost(\"[::1]:8443\")` returns false, and api.ts:212 throws `new Error(\"Invalid host format\")` before any request is issued. The user sees a generic failure on a server the app just reported reachable. Same for register (main.ts:512) and auto-login (main.ts:686). No test locks this behaviour (tests/unit/api.test.ts only exercises DNS-name hosts).",
   "evidence": "function isValidHost(host: string): boolean {\n  return /^[\\w.-]+(:\\d+)?$/.test(host) && host.length <= 253;\n}\n...\nif (newConfig.host !== undefined && !isValidHost(newConfig.host)) {\n  log.error(\"setConfig rejected invalid host\", { host: newConfig.host });\n  throw new Error(\"Invalid host format\");\n}",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "hotspot-client-tauri-client-src-lib",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "aefcd27",
    "test": "Client/tauri-client/tests/unit/api.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "suggestedFix": "Widen the one regex in api.ts:82 to allow a bracketed IPv6 literal: return /^(\\[[0-9A-Fa-f:.]+\\]|[\\w.-]+)(:\\d+)?$/.test(host) && host.length <= 253; (single shared gate, all three callers route through it).",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0137",
   "title": "Upload rejection echoes the raw storage error, disclosing absolute server filesystem paths to any authenticated user",
   "file": "Server/api/upload_handler.go",
   "line": 193,
   "severity": "low",
   "why": "The 400 body is built with fmt.Sprintf(\"upload rejected: %s\", saveErr) and storage.Save's error strings embed the resolved absolute destination path (\"creating file %s\", \"syncing file %s\", \"resolved path %q escapes storage directory\"). Every other error path in this file returns a fixed message; this one forwards internal detail to the caller.",
   "repro": "Any authenticated user POSTs a multipart upload while the storage directory is unwritable (disk full, permissions changed, read-only mount). storage.Save returns `creating file /srv/owncord/data/uploads/9f1c...-uuid: permission denied` from storage.go:127, and handleUpload returns HTTP 400 with body {\"error\":\"BAD_REQUEST\",\"message\":\"upload rejected: creating file /srv/owncord/data/uploads/9f1c...: permission denied\"}, handing the client the server's absolute storage path and the generated file UUID.",
   "evidence": "Server/api/upload_handler.go:189-195\n  if saveErr != nil {\n      slog.Warn(\"file upload rejected\", \"error\", saveErr)\n      writeJSON(w, http.StatusBadRequest, errorResponse{\n          Error:   \"BAD_REQUEST\",\n          Message: fmt.Sprintf(\"upload rejected: %s\", saveErr),\n      })\nServer/storage/storage.go:127  return 0, fmt.Errorf(\"creating file %s: %w\", dst, err)\nServer/storage/storage.go:152  return 0, fmt.Errorf(\"syncing file %s: %w\", dst, syncErr)",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-1",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Server/api/upload_handler_test.go",
    "revertProof": "pass",
    "branchCommit": "08e5ebaa"
   },
   "suggestedFix": "Keep the detail in the existing slog.Warn and stop echoing it: return a fixed `Message: \"upload rejected\"`. If the user-facing reasons matter (file type, size), match on the known sentinel/validation errors from storage and map those to their own fixed messages, defaulting everything else to 500 with the generic body.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0138",
   "title": "The status picker is never actually disabled while the socket is down — a custom status set then is silently dropped and never re-sent",
   "file": "Client/tauri-client/src/components/UserBar.ts",
   "line": 187,
   "severity": "low",
   "why": "updatePickerDisabled's only effect is toggling the class `ub-status-picker--disabled`, which no stylesheet defines — the class appears nowhere in src/styles/*.css, only in UserBar.ts and its unit test. StatusPicker has no internal disabled state either, so the dropdown and its custom-status input stay fully interactive while connectionStatus !== \"connected\". onCustomStatusChange then persists the text locally but skips ws.send, and nothing ever re-sends it: restoreSavedPresence (MainPage.ts:180) re-sends only `status`, never `custom_status`, and StatusPicker's commit() sets lastCommittedCustom before calling onChange, so a later blur/Enter with the same text short-circuits and never retries.",
   "repro": "The WS drops (uiStore.connectionStatus becomes \"reconnecting\"). The status dot is still clickable — no CSS makes it otherwise. Open the picker, type \"in a meeting\" in the custom-status input and press Enter. commit() sets lastCommittedCustom = \"in a meeting\" and calls onCustomStatusChange, which saveCustomStatus()s it to localStorage but skips ws.send because canSetStatus() is false. The socket reconnects; restoreSavedPresence sends only { status }. The UserBar input and the local prefs show \"in a meeting\" indefinitely, no other user ever sees it, and re-opening the picker and pressing Enter again is a no-op because text === lastCommittedCustom. The user must type a different string first to get it to the server.",
   "evidence": "UserBar.ts:185-193 (the entire 'disable' implementation):\n  const updatePickerDisabled = (): void => {\n    const enabled = canSetStatus();\n    statusPickerWrap.classList.toggle(\"ub-status-picker--disabled\", !enabled);\n    if (!enabled) { statusPickerWrap.title = \"Offline\"; } else { statusPickerWrap.title = \"\"; }\n  };\n\nrg 'ub-status-picker--disabled' over the client tree returns only UserBar.ts:187 and tests/unit/status-picker-userbar.test.ts — no CSS rule.\n\nUserBar.ts:160-169:\n  onCustomStatusChange: (text: string) => {\n    saveCustomStatus(text);\n    const ws = options?.ws;\n    if (ws !== null && ws !== undefined && canSetStatus()) { ws.send({ ... custom_status: text }) }\n  }\n\nStatusPicker.ts:183-189:\n  const commit = (): void => {\n    const text = input.value.trim()...;\n    if (text === lastCommittedCustom) return;\n    lastCommittedCustom = text;   // advanced even though onChange may drop the send\n    input.value = text; onChange(text);\n  };\n\nMainPage.ts:180-191 (reconnect repair covers status only):\n  function restoreSavedPresence(): void {\n    const status = loadUserStatus(); ... ws.send({ type: \"presence_update\", payload: { status } });\n  }",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-3",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "6c379c4",
    "test": "Client/tauri-client/tests/unit/status-picker-userbar.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "suggestedFix": "Add the missing rule to src/styles/app.css so the documented disable is real: `.user-bar .ub-status-picker--disabled { pointer-events: none; opacity: 0.5; }`. One rule at the wrap element covers the dot, the options and the custom-status input, so no send site needs a second guard.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0139",
   "title": "Emoji create/delete fan-out is tied to the request context, so an aborted request commits the mutation and silently skips the emoji_update broadcast",
   "file": "Server/api/emoji_handler.go",
   "line": 250,
   "severity": "low",
   "why": "broadcastEmojiSet is called with r.Context() after the row has already been committed. If the client aborts (or the request deadline fires) between the commit and the re-read, svc.Emoji.List(ctx) fails with context.Canceled, the error is logged and swallowed, and no emoji_update is sent — every connected client keeps the stale set. The same file's service layer already uses context.WithoutCancel for its post-commit work (service/emoji.go: db.WriteAudit(context.WithoutCancel(ctx), ...)), so the correct pattern is established and not applied to the fan-out.",
   "repro": "An admin issues DELETE /api/v1/emoji/7 and the connection is dropped (client navigates away, proxy times out, user hits Escape in the admin UI) right after svc.Emoji.Delete commits. r.Context() is cancelled, so svc.Emoji.List(ctx) inside broadcastEmojiSet returns context.Canceled, the branch logs and returns, and BroadcastEmojiUpdate is never called. Emoji 7 is gone from the DB and its image route now 404s, but every already-connected client still lists :shortcode: in the picker, still renders it in the autocomplete, and gets a broken image for every message that uses it, until each client reconnects. Same failure on the create path at line 217: the emoji exists but nobody sees it appear.",
   "evidence": "emoji_handler.go:239-251:\n  removed, err := svc.Emoji.Delete(r.Context(), user.ID, id)   // row is gone here\n  ...\n  broadcastEmojiSet(r.Context(), svc, broadcaster)             // request ctx\n  w.WriteHeader(http.StatusNoContent)\n\nemoji_handler.go:258-268:\n  func broadcastEmojiSet(ctx context.Context, svc *service.Services, broadcaster EmojiBroadcaster) {\n    if broadcaster == nil { return }\n    list, err := svc.Emoji.List(ctx)\n    if err != nil { slog.Error(\"failed to load emoji for broadcast\", \"error\", err); return }\n    broadcaster.BroadcastEmojiUpdate(list)\n  }\n\nservice/emoji.go (the pattern that was applied to the audit write but not the fan-out):\n  db.WriteAudit(context.WithoutCancel(ctx), s.st, actorID, \"emoji_delete\", ...)\n\nemoji_handler.go:217 is the identical call on the create path.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-3",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/api/emoji_handler_test.go",
    "revertProof": "pass",
    "branchCommit": "14c8faf0",
    "pr": 1369
   },
   "suggestedFix": "Detach cancellation at the single shared helper rather than at both call sites: inside broadcastEmojiSet, `list, err := svc.Emoji.List(context.WithoutCancel(ctx))`.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0140",
   "title": "Group-DM creation ties its dm_channel_open fan-out to the request context, so an aborted request creates a group DM nobody can see",
   "file": "Server/api/dm_handler.go",
   "line": 312,
   "severity": "low",
   "why": "This is the same defect already confirmed at emoji_handler.go:250, at a sibling that a fix there would not touch. CreateGroupDM has already committed when broadcastDMOpen is called with r.Context(); if the caller disconnects, that context is cancelled mid-handler, every svc.DMs.DMSummaryFor(ctx, …) inside the loop fails with context.Canceled, and the `continue` at dm_handler.go:268 swallows each one at Debug level. The recovery path the comment relies on — markDMVisibilityChanged forcing a full-ready resync — is a documented no-op today (*ws.Hub does not implement dmVisibilityMarker, dm_handler.go:29-32), so nothing redelivers the event.",
   "repro": "Client A POSTs /api/v1/dms/group with recipients B and C, then aborts the request (closes the window, kills the app, or the client-side AbortSignal fires) after the service commits but before the loop finishes. The channel row and its participant rows exist. Inside broadcastDMOpen the first DMSummaryFor call returns context.Canceled, logs at Debug, and `continue`s for B and C alike — neither ever receives dm_channel_open, and dm_channel_open is unsequenced so the seq-replay resume path can never deliver it. B and C have a group DM they are members of that is absent from their sidebar until they fully re-login. The identical pattern is at line 223 (group-leave refresh — survivors keep rendering the member who left) and line 351 (rename refresh — participants keep the old group name). context.WithoutCancel is used two lines below at 236 for the voice eviction, so the file already knows the distinction.",
   "evidence": "api/dm_handler.go:312  broadcastDMOpen(r.Context(), svc, broadcaster, result.Channel.ID, result.ParticipantIDs)\napi/dm_handler.go:265-269  summary, pErr := svc.DMs.DMSummaryFor(ctx, pid, channelID)\n                           if pErr != nil { slog.Debug(...); continue }\napi/dm_handler.go:236  ve.DisconnectFromVoiceInChannel(context.WithoutCancel(r.Context()), ...)  // the correct pattern, 76 lines up\napi/dm_handler.go:29-32  // NOTE: *ws.Hub does not export this yet — ... the assertion below misses and this is a no-op.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "hotspot-server-api",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "db0275a2",
    "test": "Server/api/dm_handler_visibility_ctx_test.go",
    "revertProof": "pass",
    "branchCommit": "108bbe42",
    "pr": 1369
   },
   "suggestedFix": "One line at the top of the shared helper: in broadcastDMOpen (dm_handler.go:252), after the nil/empty guard, add `ctx = context.WithoutCancel(ctx)`. That covers all three call sites (create :312, rename :351, group-leave :223) without touching any caller.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0141",
   "title": "Autostart toggle's read-back races its own write, leaving the switch showing OFF while the OS setting is ON",
   "file": "Client/tauri-client/src/components/settings/AdvancedTab.ts",
   "line": 264,
   "severity": "low",
   "why": "buildAutostartRow renders the toggle immediately in the OFF position and corrects it from an unawaited IIFE that resolves a dynamic import and then `isEnabled()`. The toggle is clickable during that window, and createToggle flips the class optimistically before invoking onChange (helpers.ts:66-71). If the user clicks before the init's `isEnabled()` resolves, the two async chains race: the init's stale `false` result unconditionally overwrites both the `enabled` variable and the visual state that the click path just set, so the OS ends up with autostart enabled while the UI and the local `enabled` shadow both say OFF.",
   "repro": "OS autostart is currently OFF. Open Settings → Advanced; the Launch on Login row paints immediately with the toggle OFF while `await import(\"@tauri-apps/plugin-autostart\")` is still fetching the chunk. Click the toggle during that window: onChange(true) runs enable(), the OS registers autostart. The init IIFE's `isEnabled()` call, issued before enable() completed, resolves false → line 264 sets enabled=false and line 265 removes the \"on\" class. The panel now shows OFF, `enabled` is false, and the app really does launch on login. The user's next click is read as \"turn on\" and calls enable() again, so the state cannot be corrected from that panel without closing and reopening it.",
   "evidence": "AdvancedTab.ts:239-270:\n  let enabled = false;\n  const toggle = createToggle(false, { signal, onChange: (nowOn) => { void (async () => {\n      const { enable, disable } = await import(\"@tauri-apps/plugin-autostart\");\n      if (nowOn) await enable(); else await disable();\n      enabled = nowOn;\n    } catch { toggle.classList.toggle(\"on\", enabled); ... } )(); }});\n  ...\n  void (async () => {\n    const { isEnabled } = await import(\"@tauri-apps/plugin-autostart\");\n    enabled = await isEnabled();                       // line 264 — no guard against a click already applied\n    toggle.classList.toggle(\"on\", enabled);\n    toggle.setAttribute(\"aria-checked\", String(enabled));\n  })();\n\nhelpers.ts:66-71 (optimistic flip before onChange):\n  const nowOn = !toggle.classList.contains(\"on\");\n  toggle.classList.toggle(\"on\", nowOn);\n  opts.onChange(nowOn);",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-1",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "1270085",
    "test": "Client/tauri-client/tests/unit/advanced-tab.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "suggestedFix": "One boolean in buildAutostartRow: set `let touched = false;` and `touched = true;` as the first line of onChange, then guard the init write — `if (!touched) { enabled = await isEnabled(); toggle.classList.toggle(\"on\", enabled); toggle.setAttribute(\"aria-checked\", String(enabled)); }` (keep the isEnabled() call inside the try so the catch still removes the row outside Tauri). Alternative one-liner: render the toggle with `aria-disabled`/pointer-events off until the init IIFE resolves.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0142",
   "title": "ChannelSidebar never repaints on a role change, so channel-management and voice-moderation affordances stay stale after a promotion or demotion",
   "file": "Client/tauri-client/src/components/ChannelSidebar.ts",
   "line": 859,
   "severity": "low",
   "why": "canManageChannels() (line 627, and attachDragHandlers/attachChannelContextMenu) and canModerateVoice() (line 311) are evaluated at render time from authStore.user.role and the roles store, but the sidebar's only authStore subscription selects `s.serverName`. Nothing subscribes to authStore.user or to the roles store, so MEMBER_UPDATE (dispatcher.ts:672 updateUser({role})) and ROLES_UPDATE (dispatcher.ts:682 setRoles) change the answer without triggering renderChannels().",
   "repro": "User A is an admin with MANAGE_CHANNELS. An owner demotes A to a plain member; the server sends member_update, dispatcher.ts:672 writes the new role into authStore.user. The sidebar does not re-render, so A still sees the category \"+\" button, Edit/Delete Channel in the right-click menu, the voice-moderation submenu, and live drag handles. A then drags a channel: drag-reorder.ts:162 calls updateChannelPosition() optimistically on the local store and only afterwards issues the PATCHes, which the server now 403s — the sidebar is left showing an order the server rejected and never rolls back. The mirror case is equally real: a freshly promoted moderator gets none of these affordances until an unrelated channel/voice event happens to fire renderChannels() (or the socket reconnects).",
   "evidence": "const unsubAuth = authStore.subscribeSelector(\n  (s) => s.serverName,\n  (serverName) => { if (serverNameEl !== null) setText(serverNameEl, serverName ?? \"Server Name\"); },\n);\n// subscriptions registered in mount(): dmStore.channels, channelsStore.channels,\n// channelsStore.activeChannelId, authStore.serverName, uiStore.collapsedCategories,\n// uiStore.connectionStatus, voiceStore struct-sig, voiceStore speaking — no role source.\n// vs dispatcher.ts:664-672 \"...without this a promotion or demotion of the current user\n// would leave every affordance stale until the socket reconnects\"",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-2",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/channel-sidebar.test.ts",
    "revertProof": "pass",
    "branchCommit": "b0f9576e"
   },
   "suggestedFix": "One extra subscription in mount(), next to the existing authStore one: `unsubscribers.push(authStore.subscribeSelector((s) => s.user?.role ?? \"\", () => renderChannels()));` and, for permission-mask edits, `unsubscribers.push(channelsStore.subscribeSelector((s) => s.roles, () => renderChannels()));`",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0143",
   "title": "DM profile notes are saved under the legacy unscoped key on every real code path — MainPage never passes `host`, so notes bleed between servers",
   "file": "Client/tauri-client/src/pages/MainPage.ts",
   "line": 253,
   "severity": "low",
   "why": "DmProfileSidebarOptions.host exists specifically to scope the note's localStorage key per server (DmProfileSidebar.ts:35-44), and loadNote/saveNote fall back to `owncord:dm-note:{userId}` when it is \"\". The only production caller omits it, even though MainPage already has apiConfig.host in scope and uses it to scope channel mutes, the NSFW gate and audio volume (MainPage.ts:105-107). Only the unit tests ever exercise the scoped path.",
   "repro": "Connect to server A (multi-profile client, profiles.ts), open the DM with user id 5, type a private note (\"owes me money\"). It is written to localStorage key `owncord:dm-note:5`. Disconnect, connect to unrelated server B, open the DM with that server's user id 5 — a different person — and the note about server A's user is displayed in their profile panel. Editing it there overwrites the original, which is unrecoverable. Every per-server local state the same page owns (channel mutes, NSFW gate, per-user volume) is host-scoped; DM notes are the one that was left unscoped.",
   "evidence": "// MainPage.ts:253\ndmProfileSidebar = createDmProfileSidebar({\n  user: { id: recipient.id, username: ..., avatar: ..., status, about: null, joinDate: null },\n  onClose: () => { dmProfileSidebar?.destroy?.(); dmProfileSidebar = null; },\n});   // <-- no `host`\n\n// DmProfileSidebar.ts:107\nconst key = host !== \"\" ? scopedNoteKey(userId, host) : legacyNoteKey(userId);",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-2",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "7be9ccd2",
    "test": "Client/tauri-client/tests/unit/main-page.test.ts",
    "revertProof": "pass",
    "branchCommit": "f5d9645b"
   },
   "suggestedFix": "Add one property at MainPage.ts:253: `host: apiConfig.host ?? \"\",` in the createDmProfileSidebar options (apiConfig is already in scope from line 95). loadNote already falls back to the legacy key, so existing notes migrate on first save.",
   "fixed": "2026-08-14"
  },
  {
   "id": "OC-0144",
   "title": "Bare URLs ending in a closing paren are linkified to a truncated address",
   "file": "Client/tauri-client/src/components/message-list/content-parser.ts",
   "line": 171,
   "severity": "low",
   "why": "renderMentions strips every trailing `)` from an autolinked URL as \"sentence-level punctuation\", with no bracket balancing. The anchor's href becomes a different URL than the one the author typed and than the visible link text's source, so the link points at a wrong (usually 404) address. The markdown layer deliberately keeps the paren in the token (markdown.ts urlEnd only trims `*_~|`), and the masked-link path preserves it — this is the one path that mangles it.",
   "repro": "Send the message `https://en.wikipedia.org/wiki/Rust_(programming_language)` as plain text (no brackets). parseInline emits it as one text node; renderMentions strips the final `)`; the rendered anchor's href and text are `https://en.wikipedia.org/wiki/Rust_(programming_language` and a bare `)` text node follows. Clicking it opens a broken URL.",
   "evidence": "content-parser.ts:170-181:\n  const rawUrl = match[0];\n  const stripped = rawUrl.replace(/[.,;:!?)]+$/, \"\");\n  const trailing = rawUrl.slice(stripped.length);\n  const url = stripped || rawUrl;\n  if (isSafeUrl(url)) {\n    const link = createElement(\"a\", { class: \"msg-link\", href: url, ... });\n    setText(link, url);\n\nmarkdown.ts:87-106 urlEnd keeps `)` in the token (it only trims runs of `*_~|`), so the full URL reaches renderMentions.\n\ntests/unit/content-markdown.test.ts:400 only locks the *masked*-link form `[wiki](https://en.example.org/wiki/Foo_(bar))`, which goes through buildMaskedLink and is unaffected.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-3",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/renderers.test.ts",
    "revertProof": "pass",
    "branchCommit": "826b8aa7"
   },
   "suggestedFix": "In content-parser.ts:171, only strip a trailing `)` when it is unbalanced — after the existing strip, if the removed trailing text starts with `)` and the URL contains more `(` than `)`, give one `)` back. Smallest form: strip `[.,;:!?]+$` first, then drop a single trailing `)` only when `(stripped.match(/\\(/g)||[]).length < (stripped.match(/\\)/g)||[]).length`. One change in the shared renderMentions covers every caller.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0145",
   "title": "Admin API-token creation accepts a negative expires_hours and mints a token that never expires",
   "file": "Server/admin/handlers_tokens.go",
   "line": 89,
   "severity": "low",
   "why": "ExpiresHours has no validation. The `> 0` test sends any negative value down the nil-expiresAt branch, which db.CreateAPIToken stores as \"never expires\" — the caller asked for a bounded credential and silently received a permanent one. Symmetrically, a value above ~2.56e6 overflows time.Duration(int64 ns) and produces a past timestamp, so the response hands the admin a raw token that GetActiveAPIToken will never resolve.",
   "repro": "POST /admin/api/tokens as Owner with {\"label\":\"ci\",\"expires_hours\":-1}. Expected: 400, or a token already expired. Actual: 201 with a raw bearer token whose api_tokens.expires_at is NULL — a permanent credential that survives password change and bulk logout. Conversely {\"expires_hours\":3000000}: 3e6 * 3.6e12 ns overflows int64, time.Now().Add(negative) yields a past instant, and the returned token 401s on first use with no error reported at creation.",
   "evidence": "handlers_tokens.go:88-103:\n  var expiresAt *time.Time\n  if req.ExpiresHours > 0 {\n    t := time.Now().Add(time.Duration(req.ExpiresHours) * time.Hour)\n    expiresAt = &t\n  }\n  id, err := database.CreateAPIToken(r.Context(), user.ID, auth.HashToken(raw), req.Label, expiresAt)\n  ...\n  writeJSON(w, http.StatusCreated, createTokenResponse{ID: id, Token: raw, ...})\n\ncreateTokenRequest.ExpiresHours is a plain `int` (line 42) decoded straight from JSON with no bounds check. The doc comment at line 41 states \"ExpiresHours 0 means never expires\" — negatives are undocumented and fall into the same branch.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-3",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Server/admin/api_test.go",
    "revertProof": "pass",
    "branchCommit": "d9bf6003"
   },
   "suggestedFix": "One guard in handleCreateAPIToken, next to the label check: `if req.ExpiresHours < 0 || req.ExpiresHours > 24*365*10 { writeErr(w, http.StatusBadRequest, \"BAD_REQUEST\", \"expires_hours must be between 0 and 87600\"); return }`. That kills both the never-expires-on-negative case and the Duration overflow with a single bounds check before line 88.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0146",
   "title": "CheckForUpdate has no in-flight dedupe, so cache expiry stampedes GitHub and burns the server's API quota for everyone",
   "file": "Server/updater/updater.go",
   "line": 170,
   "severity": "low",
   "why": "The release-metadata cache is a plain check-then-act: every caller that finds the cache expired drops the lock and issues its own outbound GitHub API call. The same file already imports and uses `golang.org/x/sync/singleflight` (`textAssetSF`) to dedupe the sibling text-asset fetch — `FetchTextAssetCached` — and `api/client_update.go:73-75` states the intent explicitly (\"Cached with the same TTL as the release info so this unauthenticated endpoint does not perform an outbound fetch on every request (DoS hardening)\"). CheckForUpdate is the one fetch in the package that never got that treatment, and it is reachable unauthenticated.",
   "repro": "Route `/api/v1/client-update/{target}/{current_version}` is mounted unauthenticated (api/router.go:292) behind only a 30-req/min per-IP limiter (clientUpdateRateLimitPerMinute = 30, api/constants.go:35). With the 1h cache expired, fire 30 concurrent GETs from one IP: all 30 pass the expiry check before any of them repopulates `u.cache`, so 30 concurrent `GET api.github.com/repos/.../releases/latest` calls go out (each with a 30s fetchTimeout). Two such minutes exceed GitHub's 60/hr unauthenticated quota for the server's egress IP; GitHub then answers 403, `fetchLatestRelease` returns `github API returned status 403`, and that error is written to the process-wide `cachedErr` for errorCacheTTL. For the next 5 minutes every caller — including the owner-only admin update handlers at admin/update_handlers.go:25 and :56, which share the same Updater — gets the cached 403. Repeating the burst every 5 minutes keeps update checks dead indefinitely. The same stampede occurs benignly in normal operation: every client auto-polling at the moment the hourly cache expires triggers its own outbound call.",
   "evidence": "u.mu.Lock()\nif u.cache != nil && now.Before(u.cacheExpiry) { cached := *u.cache; u.mu.Unlock(); return cached, nil }\nif u.cachedErr != nil && now.Before(u.errCacheExpiry) { ... }\nu.mu.Unlock()\n\nfetchCtx, cancel := detachFetch(ctx)\ndefer cancel()\n\ninfo, err := u.fetchLatestRelease(fetchCtx)   // <- no singleflight, unlike textAssetSF\nif err != nil {\n\tu.mu.Lock()\n\tu.cachedErr = err\n\tu.errCacheExpiry = now.Add(errorCacheTTL)\n\tu.mu.Unlock()\n\treturn UpdateInfo{}, err\n}",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-1",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "8787b906",
    "test": "Server/updater/release_singleflight_test.go",
    "revertProof": "pass",
    "branchCommit": "2d7643ad"
   },
   "suggestedFix": "Add `releaseSF singleflight.Group` to Updater and route the fetch through it, mirroring assets.go:100 — replace line 173 with `v, err, _ := u.releaseSF.Do(\"latest-release\", func() (any, error) { return u.fetchLatestRelease(fetchCtx) })` and keep the existing cache/errCache writes inside that func so a single winner fills the cache for the whole herd. One change in the shared method covers both the public route and the admin handlers.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0147",
   "title": "SearchOverlay re-registers per-result click listeners on the component-lifetime AbortSignal on every render, pinning every discarded result row",
   "file": "Client/tauri-client/src/components/SearchOverlay.ts",
   "line": 96,
   "severity": "low",
   "why": "`renderResults()` detaches the old rows with `clearChildren` and then calls `item.addEventListener(\"click\", ..., { signal })` for each new row, where `signal` is the single overlay-lifetime AbortController created at factory time (line 40-41). Detaching a node does not remove its listeners, and an abort algorithm registered on a signal holds a reference to its target until the signal aborts — which only happens in `destroy()`. Every re-render therefore adds N more permanently-retained abort algorithms, each keeping a detached `<div>` subtree alive. Same defect class as the already-confirmed context-menu.ts:88 and VoiceAudioTab.ts:490 findings.",
   "repro": "Open the search overlay and type a 10-character query. Debounced search fires and `renderResults()` runs once per completed search; each keystroke that lands past the 300 ms debounce plus the 500 ms rate-limit window triggers another. Then press ArrowDown/ArrowUp to walk the list — lines 171-186 call `renderResults()` on *every* arrow keypress. With 20 results and 100 arrow presses, 2000 detached `<div class=\"search-result-item\">` subtrees (each with a header, three spans and a content div) plus their closures are retained by `ac.signal` and are unreachable for GC until the overlay is destroyed. Verified in a heap snapshot pattern identical to the confirmed context-menu.ts:88 case.",
   "evidence": "const ac = new AbortController();\nconst signal = ac.signal;            // overlay lifetime, aborted only in destroy()\n\nfunction renderResults(): void {\n  clearChildren(resultsDiv);         // detaches rows; listeners are NOT removed\n  for (let i = 0; i < results.length; i++) {\n    const item = createElement(\"div\", {...});\n    ...\n    item.addEventListener(\"click\", () => { options.onSelectResult(r); options.onClose(); }, { signal });\n    resultsDiv.appendChild(item);\n  }\n}",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-1",
   "finder": "opus",
   "confidence": "medium",
   "fix": {
    "commit": "c3837fa",
    "branchCommit": "7b1779a",
    "test": "Client/tauri-client/tests/unit/search-overlay.test.ts",
    "revertProof": "self-reported",
    "pr": 1367
   },
   "suggestedFix": "Register one delegated click listener on resultsDiv at mount time instead of one per row: `resultsDiv.addEventListener(\"click\", (e) => { const row = (e.target as Element).closest(\".search-result-item\"); if (!row) return; const r = results[Number(row.getAttribute(\"data-testid\")!.slice(\"search-result-\".length))]; if (r) { options.onSelectResult(r); options.onClose(); } }, { signal });` and delete the per-row addEventListener at line 96-103. One listener for the overlay's whole lifetime, no per-render accumulation.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0148",
   "title": "A failed channel delete leaves the modal stuck on \"Deleting...\" forever — its error path is unreachable",
   "file": "Client/tauri-client/src/components/DeleteChannelModal.ts",
   "line": 93,
   "severity": "low",
   "why": "The confirm handler disables the button, writes \"Deleting...\", and relies on `onConfirm()` REJECTING to restore the button and show the inline error. Its only caller catches the rejection itself and returns a resolved promise, so the catch block (and the whole `delete-channel-error` element) is dead code and the button is never re-enabled.",
   "repro": "As a user whose delete is refused (403 from adminDeleteChannel, or with the server unreachable), open a channel's context menu → Delete Channel → click \"Delete Channel\". SidebarArea.ts:333-340 awaits `api.adminDeleteChannel`, catches the error, shows a toast, and returns normally; DeleteChannelModal's `await onConfirm()` therefore resolves. The button stays `disabled` reading \"Deleting...\", `errorEl` stays `display:none`, and retrying is impossible without closing (Cancel/X/Escape) and reopening the dialog.",
   "evidence": "// DeleteChannelModal.ts:91-98 — only re-enables on rejection\ntry { await onConfirm(); } catch (err) { errorEl.style.display = \"block\"; ... deleteBtn.removeAttribute(\"disabled\"); setText(deleteBtn, \"Delete Channel\"); }\n\n// SidebarArea.ts:332-341 — never rethrows, so the catch above can never run\nonConfirm: async () => {\n  try { await api.adminDeleteChannel(channel.id); modal.destroy?.(); activeModal = null; }\n  catch (err) { getToast()?.show(msg, \"error\"); }\n},",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-2",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "b1fb565",
    "branchCommit": "58fd21b",
    "test": "Client/tauri-client/tests/unit/delete-channel-modal.test.ts",
    "revertProof": "self-reported",
    "pr": 1366
   },
   "suggestedFix": "Restore the button in the shared function rather than in the caller: in DeleteChannelModal.ts wrap the call as `try { await onConfirm(); } catch (err) { …existing inline error… } finally { if (overlay?.isConnected === true) { deleteBtn.removeAttribute(\"disabled\"); setText(deleteBtn, \"Delete Channel\"); } }`. On success the caller already destroy()s the modal so `overlay` is null and the finally is a no-op; on failure the button is re-armed regardless of whether the caller rethrows or swallows. One guard, covers every present and future caller, and keeps both existing test suites green.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0149",
   "title": "The reaction emoji picker drops the server's custom emoji, so custom-emoji reactions are unreachable except by accident",
   "file": "Client/tauri-client/src/pages/main-page/ReactionController.ts",
   "line": 84,
   "severity": "low",
   "why": "createEmojiPicker builds the \"Server\" category only when `customEmoji` is supplied (EmojiPicker.ts:580). The composer passes `listCustomEmoji()`; the reaction picker passes nothing. Custom-emoji reactions are a fully supported, rendered feature — reactions.ts:30 resolves a `:shortcode:` reaction through buildCustomEmojiNode — so the picker for the one surface that needs them is the one that hides them.",
   "repro": "Upload a custom emoji, then click the \"+\" add-reaction chip on any message. The picker shows Smileys/People/… but no Server category, so no custom emoji can be chosen. Inconsistently, if the user previously inserted that emoji from the composer picker, the shared `owncord:recent-emoji` localStorage key puts the `:shortcode:` in the \"Recent\" row of the reaction picker, where it works — so the same emoji is selectable or not depending on unrelated composer history.",
   "evidence": "// ReactionController.ts:84 — no customEmoji passed\nconst picker = createEmojiPicker({ onSelect: ..., onClose: ... });\n\n// EmojiPicker.ts:580 — the Server category is conditional on it\nif (options.customEmoji && options.customEmoji.length > 0) {\n  cats.push({ name: SERVER_CATEGORY, emoji: options.customEmoji.map((e) => `:${e.shortcode}:`) });\n}\n\n// MessageInput.ts — the sibling call site does pass it (listCustomEmoji())",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-2",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "db0275a2",
    "test": "Client/tauri-client/tests/unit/reaction-controller.test.ts",
    "revertProof": "pass",
    "branchCommit": "6d1a785b",
    "pr": 1369
   },
   "suggestedFix": "Pass the set at open time, exactly as the composer does: import { listCustomEmoji } from \"@stores/emoji.store\" in ReactionController.ts and add `customEmoji: listCustomEmoji(),` to the createEmojiPicker({ … }) call at line 84. Reading it inside openPicker (not at controller construction) keeps an emoji_update reflected in the next picker opened, matching the MessageInput.ts:886-888 comment.",
   "fixedDate": "2026-08-14"
  },
  {
   "id": "OC-0150",
   "title": "Ctrl+K quick switcher is dead with CapsLock on, fires on AltGr+K, and ignores the settings-overlay suspension every other global shortcut honours",
   "file": "Client/tauri-client/src/pages/main-page/OverlayManagers.ts",
   "line": 119,
   "severity": "low",
   "why": "The quick-switcher shortcut compares `e.key === \"k\"` case-sensitively and checks only `ctrlKey || metaKey`. `KeyboardEvent.key` reflects CapsLock and Shift, so with CapsLock on (or Ctrl+Shift+K) the key is \"K\" and the shortcut silently does nothing. It also does not exclude `altKey`, so AltGr (which Chromium/WebView2 reports as ctrlKey+altKey on Windows) opening the overlay and calling `e.preventDefault()` swallows AltGr-produced characters on non-US layouts. And unlike every other app-wide shortcut it has no `isSuspended` gate, so Ctrl+K while the Settings overlay is open stacks the switcher on top and can switch channels behind it. GlobalKeybinds.ts:43-45 documents exactly this case-insensitivity requirement and guards altKey at line 40 and suspension at MainPage.ts:518; the quick switcher, explicitly carved out of that file, never got any of the three.",
   "repro": "(a) Turn CapsLock on, press Ctrl+K -> nothing happens; Ctrl+Shift+K likewise. (b) On a German/Polish layout press AltGr+K -> the quick switcher opens and the intended character is never inserted into the composer. (c) Open Settings, press Ctrl+K -> the quick switcher mounts over the settings overlay and selecting a row switches the channel behind it, while Ctrl+F/Ctrl+M correctly no-op.",
   "evidence": "OverlayManagers.ts:118-127\n  const handler = (e: KeyboardEvent): void => {\n    if ((e.ctrlKey || e.metaKey) && e.key === \"k\") {   // case-sensitive, no !e.altKey, no isSuspended\n      e.preventDefault();\n      if (instance !== null) { close(); } else { open(); }\n    }\n  };\n\nSame condition duplicated in QuickSwitcher.ts:155 (handleGlobalKeydown), so the in-overlay close path is dead under CapsLock too.\n\nContrast GlobalKeybinds.ts:40-45\n  if (!(e.ctrlKey || e.metaKey) || e.altKey) return;\n  if (handlers.isSuspended?.() === true) return;\n  // `e.key` is layout-dependent and uppercases with Shift held — compare\n  // case-insensitively so Ctrl+Shift+V arrives as \"V\", not a missed \"v\".\n  const key = e.key.toLowerCase();\n\nMainPage.ts:505-506 attaches the quick-switcher manager with no isSuspended; MainPage.ts:518 passes `isSuspended: () => uiStore.getState().settingsOpen` to attachGlobalKeybinds only.",
   "status": "fixed",
   "found": "2026-08-13",
   "hunt": "2026-08-13-postopt",
   "lens": "explore-3",
   "finder": "opus",
   "confidence": "high",
   "fix": {
    "commit": "8787b906",
    "test": "Client/tauri-client/tests/unit/overlay-managers.test.ts",
    "revertProof": "pass",
    "branchCommit": "185a420a"
   },
   "suggestedFix": "Mirror the GlobalKeybinds guard in the two handlers: at OverlayManagers.ts:119 and QuickSwitcher.ts:155 use `if (!(e.ctrlKey || e.metaKey) || e.altKey || e.key.toLowerCase() !== \"k\") return;`. For the suspension gap, add an optional `isSuspended?: () => boolean` to createQuickSwitcherManager and early-return on it, wiring `isSuspended: () => uiStore.getState().settingsOpen` at MainPage.ts:505 so both attach sites read the same source of truth.",
   "fixedDate": "2026-08-14"
  }
 ]
}