switchroom 0.13.20 → 0.13.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -47331,8 +47331,8 @@ var {
47331
47331
  } = import__.default;
47332
47332
 
47333
47333
  // src/build-info.ts
47334
- var VERSION = "0.13.20";
47335
- var COMMIT_SHA = "9962efb4";
47334
+ var VERSION = "0.13.22";
47335
+ var COMMIT_SHA = "1706f857";
47336
47336
 
47337
47337
  // src/cli/agent.ts
47338
47338
  init_source();
@@ -48699,6 +48699,8 @@ function applyHindsightSettingsOverrides(pluginDestPath) {
48699
48699
  return;
48700
48700
  }
48701
48701
  settings.retainEveryNTurns = 1;
48702
+ settings.recallMaxMemories = 8;
48703
+ settings.recallMinOverlap = 0.1;
48702
48704
  writeFileSync5(settingsPath, JSON.stringify(settings, null, 2) + `
48703
48705
  `, "utf-8");
48704
48706
  }
@@ -62230,6 +62232,14 @@ var HINDSIGHT_IMAGE = "ghcr.io/switchroom/switchroom-hindsight:latest";
62230
62232
  var HINDSIGHT_DEFAULT_MODEL = "claude-sonnet-4-6";
62231
62233
  var HINDSIGHT_DEFAULT_MCP_STATELESS = true;
62232
62234
  var HINDSIGHT_BROKER_SOCK_VOLUME = `auth-broker-${HINDSIGHT_CONSUMER_NAME}-sock`;
62235
+ var HINDSIGHT_DEFAULT_RERANKER_BUCKET_BATCHING = "true";
62236
+ var HINDSIGHT_DEFAULT_RERANKER_MAX_CANDIDATES = 150;
62237
+ var HINDSIGHT_DEFAULT_RERANKER_LOCAL_MAX_CONCURRENT = 2;
62238
+ var HINDSIGHT_DEFAULT_RECALL_MAX_CONCURRENT = 8;
62239
+ var HINDSIGHT_DEFAULT_MEM_LIMIT = "4g";
62240
+ var HINDSIGHT_DEFAULT_MEM_RESERVATION = "2g";
62241
+ var HINDSIGHT_DEFAULT_CPUS = "2.0";
62242
+ var HINDSIGHT_DEFAULT_PIDS_LIMIT = 1000;
62233
62243
  function isPortFree(port) {
62234
62244
  return new Promise((resolve25) => {
62235
62245
  const server = createServer3();
@@ -62300,7 +62310,15 @@ function startHindsight(ports) {
62300
62310
  "-e",
62301
62311
  `HINDSIGHT_API_LLM_MODEL=${HINDSIGHT_DEFAULT_MODEL}`,
62302
62312
  "-e",
62303
- `HINDSIGHT_API_MCP_STATELESS=${HINDSIGHT_DEFAULT_MCP_STATELESS}`
62313
+ `HINDSIGHT_API_MCP_STATELESS=${HINDSIGHT_DEFAULT_MCP_STATELESS}`,
62314
+ "-e",
62315
+ `HINDSIGHT_API_RERANKER_LOCAL_BUCKET_BATCHING=${HINDSIGHT_DEFAULT_RERANKER_BUCKET_BATCHING}`,
62316
+ "-e",
62317
+ `HINDSIGHT_API_RERANKER_MAX_CANDIDATES=${HINDSIGHT_DEFAULT_RERANKER_MAX_CANDIDATES}`,
62318
+ "-e",
62319
+ `HINDSIGHT_API_RERANKER_LOCAL_MAX_CONCURRENT=${HINDSIGHT_DEFAULT_RERANKER_LOCAL_MAX_CONCURRENT}`,
62320
+ "-e",
62321
+ `HINDSIGHT_API_RECALL_MAX_CONCURRENT=${HINDSIGHT_DEFAULT_RECALL_MAX_CONCURRENT}`
62304
62322
  ];
62305
62323
  const args = [
62306
62324
  "run",
@@ -62309,6 +62327,10 @@ function startHindsight(ports) {
62309
62327
  "switchroom-hindsight",
62310
62328
  "--restart",
62311
62329
  "unless-stopped",
62330
+ `--memory=${HINDSIGHT_DEFAULT_MEM_LIMIT}`,
62331
+ `--memory-reservation=${HINDSIGHT_DEFAULT_MEM_RESERVATION}`,
62332
+ `--cpus=${HINDSIGHT_DEFAULT_CPUS}`,
62333
+ `--pids-limit=${HINDSIGHT_DEFAULT_PIDS_LIMIT}`,
62312
62334
  "-p",
62313
62335
  `127.0.0.1:${apiPort}:8888`,
62314
62336
  "-p",
@@ -62355,6 +62377,14 @@ function generateHindsightComposeSnippet() {
62355
62377
  " - HINDSIGHT_API_LLM_PROVIDER=claude-code",
62356
62378
  ` - HINDSIGHT_API_LLM_MODEL=${HINDSIGHT_DEFAULT_MODEL}`,
62357
62379
  ` - HINDSIGHT_API_MCP_STATELESS=${HINDSIGHT_DEFAULT_MCP_STATELESS}`,
62380
+ ` - HINDSIGHT_API_RERANKER_LOCAL_BUCKET_BATCHING=${HINDSIGHT_DEFAULT_RERANKER_BUCKET_BATCHING}`,
62381
+ ` - HINDSIGHT_API_RERANKER_MAX_CANDIDATES=${HINDSIGHT_DEFAULT_RERANKER_MAX_CANDIDATES}`,
62382
+ ` - HINDSIGHT_API_RERANKER_LOCAL_MAX_CONCURRENT=${HINDSIGHT_DEFAULT_RERANKER_LOCAL_MAX_CONCURRENT}`,
62383
+ ` - HINDSIGHT_API_RECALL_MAX_CONCURRENT=${HINDSIGHT_DEFAULT_RECALL_MAX_CONCURRENT}`,
62384
+ ` mem_limit: ${HINDSIGHT_DEFAULT_MEM_LIMIT}`,
62385
+ ` mem_reservation: ${HINDSIGHT_DEFAULT_MEM_RESERVATION}`,
62386
+ ` cpus: ${HINDSIGHT_DEFAULT_CPUS}`,
62387
+ ` pids_limit: ${HINDSIGHT_DEFAULT_PIDS_LIMIT}`,
62358
62388
  " volumes:",
62359
62389
  " - switchroom-hindsight-data:/home/hindsight/.pg0",
62360
62390
  ` - ${HINDSIGHT_BROKER_SOCK_VOLUME}:/run/switchroom/auth-broker`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "switchroom",
3
- "version": "0.13.20",
3
+ "version": "0.13.22",
4
4
  "description": "Run Claude Code 24/7 on your Claude Pro/Max subscription over Telegram. Open-source alternative to OpenClaw and NanoClaw — no API keys.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -207,14 +207,15 @@ export HINDSIGHT_AGENT_NAME="{{name}}"
207
207
  export HINDSIGHT_RECALL_MAX_MEMORIES={{hindsightRecallMaxMemories}}
208
208
  {{/if}}
209
209
  # Per-session recall cache (#424 phase 4.1). Identical (prompt, bank)
210
- # within a session reuses the prior recall result instead of round-
211
- # tripping to Hindsight. Defaults to 600s (10 min); operators can
212
- # override via memory.recall.cache_ttl_secs in switchroom.yaml.
213
- # Setting it to 0 disables caching for that agent.
210
+ # within a session reuses the prior recall result. v0.13.22: the
211
+ # unconditional default-600s export was dropped the 2026-05-24
212
+ # audit measured 0% hit rate across 430+ Telegram turns (cache key
213
+ # is `(session_id, prompt, bank, extra_banks)`; each Telegram inbound
214
+ # is unique). Operators who run Claude Code interactively (where
215
+ # prompt-repeat happens) can still opt in via memory.recall.cache_ttl_secs
216
+ # in switchroom.yaml. Setting it to 0 disables caching for that agent.
214
217
  {{#if (isNumber hindsightRecallCacheTtlSecs)}}
215
218
  export HINDSIGHT_RECALL_CACHE_TTL_SECS={{hindsightRecallCacheTtlSecs}}
216
- {{else}}
217
- export HINDSIGHT_RECALL_CACHE_TTL_SECS=600
218
219
  {{/if}}
219
220
  # Lexical-overlap relevance gate (#475). Drops memories whose Jaccard
220
221
  # overlap with the user's query is below this threshold (range 0.0–1.0).
@@ -23,11 +23,11 @@ The 👀→🤔→🔥→👍 status reaction and the typing indicator are *ambi
23
23
 
24
24
  **Follow-ups while a turn is in flight.** Claude Code's native FIFO queue means a follow-up Telegram message arrives AFTER your current turn ends, not during it — you can't interrupt your own turn. Every follow-up becomes the next prompt you see. The plugin enriches the `<channel>` meta so you can classify correctly:
25
25
 
26
- - `steering="true"` — prior turn was in progress and the user did NOT use `/queue`. Treat as a course-correction or addendum on the next action. Continue the original task, incorporating the new guidance.
27
- - `queued="true"` — the user typed `/queue ` or `/q ` (the prefix is stripped from the body you see). Treat as a new, independent task. Do NOT reference the in-flight work start fresh.
26
+ - `queued="true"` — DEFAULT for mid-turn follow-ups (no prefix). Treat as a new, independent task. Do NOT reference the in-flight work start fresh. Also fires when the user typed `/queue ` or `/q ` (legacy alias; the prefix is stripped from the body you see).
27
+ - `steering="true"` — the user typed `/steer ` or `/s ` (the prefix is stripped from the body you see). Treat as a course-correction or addendum on the in-flight work. Continue the original task, incorporating the new guidance.
28
28
  - `prior_turn_in_progress="true"`, `seconds_since_turn_start="N"`, `prior_assistant_preview="..."` — auxiliary context on the prior turn so you can decide which of the above applies when ambiguous. `prior_assistant_preview` is the first ~200 chars of your most recent reply in this chat, HTML tags stripped.
29
29
 
30
- If both `queued` and `steering` are somehow present, `queued` wins (explicit beats inferred). If `prior_turn_in_progress="true"` is set without either flag (shouldn't happen but defensive), treat the message as a follow-up related to your last reply.
30
+ If both `queued` and `steering` are somehow present, `steering` wins (explicit opt-in beats default). If `prior_turn_in_progress="true"` is set without either flag (shouldn't happen but defensive), treat the message as a follow-up related to your last reply.
31
31
 
32
32
  **Self-narrate the classification.** At the top of your reply for any `steering` or `queued` message, include a brief italic one-liner so the user can correct you — e.g. `_↪️ treating as steer on the prior task_` or `_📥 queued as a new task_`.
33
33
 
@@ -30563,7 +30563,7 @@ class OutboundDedupCache {
30563
30563
  constructor(opts = {}) {
30564
30564
  this.ttlMs = opts.ttlMs ?? DEFAULT_DEDUP_TTL_MS;
30565
30565
  }
30566
- record(chatId, threadId, text, now) {
30566
+ record(chatId, threadId, text, now, turnKey = null) {
30567
30567
  if (text.length < DEDUP_MIN_CONTENT_LEN)
30568
30568
  return;
30569
30569
  const key = makeKey(chatId, threadId);
@@ -30572,11 +30572,12 @@ class OutboundDedupCache {
30572
30572
  list.push({
30573
30573
  hash: normalizeForDedup(text),
30574
30574
  ts: now,
30575
- preview: text.slice(0, 80)
30575
+ preview: text.slice(0, 80),
30576
+ turnKey
30576
30577
  });
30577
30578
  this.entries.set(key, list);
30578
30579
  }
30579
- check(chatId, threadId, text, now) {
30580
+ check(chatId, threadId, text, now, turnKey = null) {
30580
30581
  if (text.length < DEDUP_MIN_CONTENT_LEN)
30581
30582
  return null;
30582
30583
  const key = makeKey(chatId, threadId);
@@ -30586,9 +30587,12 @@ class OutboundDedupCache {
30586
30587
  this.evict(list, now);
30587
30588
  const candidateHash = normalizeForDedup(text);
30588
30589
  for (const entry of list) {
30589
- if (entry.hash === candidateHash) {
30590
- return { matched: true, preview: entry.preview, ageMs: now - entry.ts };
30590
+ if (entry.hash !== candidateHash)
30591
+ continue;
30592
+ if (turnKey != null && entry.turnKey != null && entry.turnKey !== turnKey) {
30593
+ continue;
30591
30594
  }
30595
+ return { matched: true, preview: entry.preview, ageMs: now - entry.ts };
30592
30596
  }
30593
30597
  return null;
30594
30598
  }
@@ -40987,7 +40991,7 @@ function shouldShowHandoffLine() {
40987
40991
  return v.toLowerCase() !== "false";
40988
40992
  }
40989
40993
  function formatHandoffLine(topic, format) {
40990
- const prefix = "\u21a9\ufe0f Picked up where we left off \u2014 ";
40994
+ const prefix = "\u21a9\ufe0f Picked up where we left off, ";
40991
40995
  if (format === "html") {
40992
40996
  return `<i>${prefix}${escapeHtml6(topic)}</i>
40993
40997
 
@@ -41156,6 +41160,7 @@ function flushOnAgentDisconnect(deps) {
41156
41160
  activeDraftParseModes,
41157
41161
  clearActiveReactions: clearActiveReactions3,
41158
41162
  disposeProgressDriver,
41163
+ onDanglingTurnsSwept,
41159
41164
  log
41160
41165
  } = deps;
41161
41166
  if (agentName3 == null) {
@@ -41169,6 +41174,15 @@ function flushOnAgentDisconnect(deps) {
41169
41174
  activeTurnStartedAt.delete(key);
41170
41175
  }
41171
41176
  clearActiveReactions3();
41177
+ const danglingKeys = [...activeTurnStartedAt.keys()];
41178
+ if (danglingKeys.length > 0) {
41179
+ for (const k of danglingKeys) {
41180
+ activeTurnStartedAt.delete(k);
41181
+ activeReactionMsgIds.delete(k);
41182
+ }
41183
+ log(`telegram gateway: disconnect-flush swept ${danglingKeys.length} dangling turn key(s) ` + `post-bridge-death (controller loop missed \u2014 setDone raced disconnect)`);
41184
+ onDanglingTurnsSwept?.(danglingKeys);
41185
+ }
41172
41186
  disposeProgressDriver();
41173
41187
  for (const [key, stream] of activeDraftStreams.entries()) {
41174
41188
  if (!stream.isFinal())
@@ -44464,7 +44478,11 @@ function purgeStaleTurnsForChat(chatId, keys, purger) {
44464
44478
 
44465
44479
  // gateway/inbound-delivery-gate.ts
44466
44480
  function decideInboundDelivery(input) {
44467
- if (input.turnInFlight && !input.isSteering)
44481
+ if (input.isSteering)
44482
+ return "deliver";
44483
+ if (input.isInterrupt === true)
44484
+ return "deliver";
44485
+ if (input.turnInFlight)
44468
44486
  return "buffer-until-idle";
44469
44487
  return "deliver";
44470
44488
  }
@@ -46702,7 +46720,7 @@ function backfillJsonlAgentId(db2, jsonlPath, agentId, log) {
46702
46720
  db2.prepare("UPDATE subagents SET jsonl_agent_id = ? WHERE id = ?").run(agentId, candidate.id);
46703
46721
  log?.(`subagent-watcher: backfill linked ${agentId} \u2192 ${candidate.id}`);
46704
46722
  }
46705
- function readSubTail(entry, tail, now, onDescriptionUpdate, fs2, log, db2, parentStateDir, onUnstall) {
46723
+ function readSubTail(entry, tail, now, onDescriptionUpdate, fs2, log, db2, parentStateDir, onUnstall, onFileVanished) {
46706
46724
  try {
46707
46725
  const stat = fs2.statSync(entry.filePath);
46708
46726
  if (stat.size < tail.cursor) {
@@ -46807,6 +46825,12 @@ function readSubTail(entry, tail, now, onDescriptionUpdate, fs2, log, db2, paren
46807
46825
  }
46808
46826
  tail.hasEmittedStart = startState.hasEmittedStart;
46809
46827
  } catch (err) {
46828
+ const code = err.code;
46829
+ if (code === "ENOENT" || code === "EACCES") {
46830
+ log?.(`subagent-watcher: JSONL vanished for ${entry.agentId} (${code}) \u2014 deregistering`);
46831
+ onFileVanished?.(entry.agentId, code);
46832
+ return;
46833
+ }
46810
46834
  log?.(`subagent-watcher: read error ${entry.agentId}: ${err.message}`);
46811
46835
  }
46812
46836
  }
@@ -46913,7 +46937,7 @@ function startSubagentWatcher(config) {
46913
46937
  return;
46914
46938
  readSubTail(entry2, t, nowFn(), (desc) => {
46915
46939
  log?.(`subagent-watcher: description updated for ${agentId}: ${desc}`);
46916
- }, fs2, log, db2, parentStateDir, config.onUnstall);
46940
+ }, fs2, log, db2, parentStateDir, config.onUnstall, cleanupTerminalAgent);
46917
46941
  maybySendStateTransition(agentId);
46918
46942
  });
46919
46943
  } catch (err) {
@@ -47159,7 +47183,7 @@ function startSubagentWatcher(config) {
47159
47183
  continue;
47160
47184
  readSubTail(entry, tail, n, (desc) => {
47161
47185
  log?.(`subagent-watcher: description updated for ${agentId}: ${desc}`);
47162
- }, fs2, log, db2, parentStateDir, config.onUnstall);
47186
+ }, fs2, log, db2, parentStateDir, config.onUnstall, cleanupTerminalAgent);
47163
47187
  maybySendStateTransition(agentId);
47164
47188
  }
47165
47189
  checkStalls();
@@ -48291,10 +48315,10 @@ function sweepStaleTurnActiveMarker(stateDir, opts) {
48291
48315
  }
48292
48316
 
48293
48317
  // ../src/build-info.ts
48294
- var VERSION = "0.13.20";
48295
- var COMMIT_SHA = "9962efb4";
48296
- var COMMIT_DATE = "2026-05-23T08:29:36Z";
48297
- var LATEST_PR = 1684;
48318
+ var VERSION = "0.13.22";
48319
+ var COMMIT_SHA = "1706f857";
48320
+ var COMMIT_DATE = "2026-05-23T23:20:14Z";
48321
+ var LATEST_PR = 1700;
48298
48322
  var COMMITS_AHEAD_OF_TAG = 0;
48299
48323
 
48300
48324
  // gateway/boot-version.ts
@@ -50078,6 +50102,12 @@ startTimer({
50078
50102
  emitRuntimeMetric(event);
50079
50103
  },
50080
50104
  onFrameworkFallback: async (ctx) => {
50105
+ if (activeTurnStartedAt.get(ctx.key) == null && currentTurn == null) {
50106
+ process.stderr.write(`telegram gateway: silence-poke framework-fallback late-fire skipped \u2014 ` + `turn ended cleanly during silence window chat=${ctx.chatId} thread=${ctx.threadId ?? "-"} silence_ms=${ctx.silenceMs}
50107
+ `);
50108
+ endTurn(ctx.key);
50109
+ return;
50110
+ }
50081
50111
  let text = null;
50082
50112
  const upd = inFlightUpdate;
50083
50113
  if (upd != null) {
@@ -50344,6 +50374,13 @@ var ipcServer = createIpcServer({
50344
50374
  disposeProgressDriver: () => {
50345
50375
  progressDriver?.dispose?.({ preservePending: true });
50346
50376
  },
50377
+ onDanglingTurnsSwept: () => {
50378
+ if (currentTurn != null) {
50379
+ process.stderr.write(`telegram gateway: disconnect-flush nulled currentTurn (bridge died with turn in flight)
50380
+ `);
50381
+ currentTurn = null;
50382
+ }
50383
+ },
50347
50384
  log: (msg) => process.stderr.write(`${msg}
50348
50385
  `)
50349
50386
  });
@@ -50750,7 +50787,7 @@ async function executeReply(args) {
50750
50787
  `);
50751
50788
  {
50752
50789
  const replyThreadId = args.message_thread_id != null ? Number(args.message_thread_id) : undefined;
50753
- const dup = outboundDedup.check(chat_id, replyThreadId, text, Date.now());
50790
+ const dup = outboundDedup.check(chat_id, replyThreadId, text, Date.now(), currentTurn?.registryKey ?? null);
50754
50791
  if (dup != null) {
50755
50792
  process.stderr.write(`telegram gateway: reply: deduped (#546) chatId=${chat_id} ageMs=${dup.ageMs} preview=${JSON.stringify(dup.preview)}
50756
50793
  `);
@@ -50941,7 +50978,7 @@ ${url}`;
50941
50978
  })) {
50942
50979
  turn2.finalAnswerDelivered = true;
50943
50980
  }
50944
- outboundDedup.record(chat_id, threadId, decision.mergedText, Date.now());
50981
+ outboundDedup.record(chat_id, threadId, decision.mergedText, Date.now(), turn2?.registryKey ?? null);
50945
50982
  silentAnchorEditDone = true;
50946
50983
  } catch (err) {
50947
50984
  process.stderr.write(`telegram gateway: silent-reply auto-edit failed, falling back to fresh send: ${err instanceof Error ? err.message : String(err)}
@@ -51148,7 +51185,7 @@ ${url}`;
51148
51185
  process.stderr.write(`telegram channel: reply: finalized chatId=${chat_id} messageIds=[${sentIds.join(",")}] chunks=${chunks.length}
51149
51186
  `);
51150
51187
  if (sentIds.length > 0) {
51151
- outboundDedup.record(chat_id, threadId, text, Date.now());
51188
+ outboundDedup.record(chat_id, threadId, text, Date.now(), currentTurn?.registryKey ?? null);
51152
51189
  }
51153
51190
  return { content: [{ type: "text", text: result }] };
51154
51191
  }
@@ -51158,11 +51195,23 @@ async function executeStreamReply(args) {
51158
51195
  throw new Error("stream_reply: chat_id is required");
51159
51196
  if (args.text == null || args.text === "")
51160
51197
  throw new Error("stream_reply: text is required and cannot be empty");
51198
+ {
51199
+ const scrub = scrubVoice(args.text);
51200
+ if (scrub.replaced > 0) {
51201
+ args.text = scrub.scrubbed;
51202
+ emitRuntimeMetric({
51203
+ kind: "voice_scrub_applied",
51204
+ chatKey: statusKey(args.chat_id, args.message_thread_id != null ? Number(args.message_thread_id) : undefined),
51205
+ replaced: scrub.replaced,
51206
+ site: "stream_reply"
51207
+ });
51208
+ }
51209
+ }
51161
51210
  if (args.done === true) {
51162
51211
  const sChatId = args.chat_id;
51163
51212
  const sThreadId = args.message_thread_id != null ? Number(args.message_thread_id) : undefined;
51164
51213
  const sText = args.text;
51165
- const dup = outboundDedup.check(sChatId, sThreadId, sText, Date.now());
51214
+ const dup = outboundDedup.check(sChatId, sThreadId, sText, Date.now(), currentTurn?.registryKey ?? null);
51166
51215
  if (dup != null) {
51167
51216
  process.stderr.write(`telegram gateway: stream_reply: deduped (#546) chatId=${sChatId} ageMs=${dup.ageMs} preview=${JSON.stringify(dup.preview)}
51168
51217
  `);
@@ -51254,7 +51303,7 @@ async function executeStreamReply(args) {
51254
51303
  if (args.done === true && result.messageId != null) {
51255
51304
  const sChatId = args.chat_id;
51256
51305
  const sThreadId = args.message_thread_id != null ? Number(args.message_thread_id) : undefined;
51257
- outboundDedup.record(sChatId, sThreadId, args.text, Date.now());
51306
+ outboundDedup.record(sChatId, sThreadId, args.text, Date.now(), currentTurn?.registryKey ?? null);
51258
51307
  noteOutbound3(statusKey(sChatId, sThreadId), {
51259
51308
  messageId: result.messageId,
51260
51309
  text: args.text
@@ -52166,10 +52215,10 @@ function handleSessionEvent(ev) {
52166
52215
  }
52167
52216
  },
52168
52217
  checkDedup: (text) => {
52169
- return outboundDedup.check(turn.sessionChatId, turn.sessionThreadId, text, Date.now()) != null;
52218
+ return outboundDedup.check(turn.sessionChatId, turn.sessionThreadId, text, Date.now(), turn.registryKey ?? null) != null;
52170
52219
  },
52171
52220
  recordDedup: (text) => {
52172
- outboundDedup.record(turn.sessionChatId, turn.sessionThreadId, text, Date.now());
52221
+ outboundDedup.record(turn.sessionChatId, turn.sessionThreadId, text, Date.now(), turn.registryKey ?? null);
52173
52222
  },
52174
52223
  recordOutbound: ({ messageId, text }) => {
52175
52224
  if (!HISTORY_ENABLED)
@@ -52260,7 +52309,7 @@ function handleSessionEvent(ev) {
52260
52309
  streamFinalizedAsAnswer = true;
52261
52310
  turn.finalAnswerDelivered = true;
52262
52311
  try {
52263
- outboundDedup.record(turn.sessionChatId, turn.sessionThreadId, streamedFinalText, Date.now());
52312
+ outboundDedup.record(turn.sessionChatId, turn.sessionThreadId, streamedFinalText, Date.now(), turn.registryKey ?? null);
52264
52313
  } catch {}
52265
52314
  if (HISTORY_ENABLED) {
52266
52315
  try {
@@ -52360,10 +52409,22 @@ function handleSessionEvent(ev) {
52360
52409
  return;
52361
52410
  }
52362
52411
  if (flushDecision.kind === "flush") {
52363
- const capturedText = flushDecision.text;
52412
+ let capturedText = flushDecision.text;
52364
52413
  const backstopChatId = chatId;
52365
52414
  const backstopThreadId = threadId;
52366
52415
  const backstopCtrl = ctrl;
52416
+ {
52417
+ const scrub = scrubVoice(capturedText);
52418
+ if (scrub.replaced > 0) {
52419
+ capturedText = scrub.scrubbed;
52420
+ emitRuntimeMetric({
52421
+ kind: "voice_scrub_applied",
52422
+ chatKey: statusKey(backstopChatId, backstopThreadId),
52423
+ replaced: scrub.replaced,
52424
+ site: "turn_flush"
52425
+ });
52426
+ }
52427
+ }
52367
52428
  turn.finalAnswerDelivered = true;
52368
52429
  const cardTakeover = progressDriver?.takeOverCard({
52369
52430
  chatId: backstopChatId,
@@ -52455,7 +52516,7 @@ function handleSessionEvent(ev) {
52455
52516
  });
52456
52517
  } catch {}
52457
52518
  }
52458
- outboundDedup.record(backstopChatId, backstopThreadId, capturedText, Date.now());
52519
+ outboundDedup.record(backstopChatId, backstopThreadId, capturedText, Date.now(), currentTurn?.registryKey ?? null);
52459
52520
  if (backstopCtrl)
52460
52521
  backstopCtrl.setDone();
52461
52522
  if (backstopCardTurnKey != null) {
@@ -53345,7 +53406,8 @@ ${preBlock(write.output)}`;
53345
53406
  const selfAgent = process.env.SWITCHROOM_AGENT_NAME ?? "";
53346
53407
  if (decideInboundDelivery({
53347
53408
  turnInFlight: turnInFlightAtReceipt,
53348
- isSteering
53409
+ isSteering,
53410
+ isInterrupt: interrupt.isInterrupt
53349
53411
  }) === "buffer-until-idle") {
53350
53412
  pendingInboundBuffer.push(selfAgent, inboundMsg);
53351
53413
  process.stderr.write(`telegram gateway: inbound held mid-turn agent=${selfAgent} chat=${chat_id} msg=${msgId ?? "-"} \u2014 will flush on turn-complete
@@ -48,6 +48,18 @@ export interface DisconnectFlushDeps<Ctrl extends { setDone: () => void }, Strea
48
48
  /** Progress driver — disposed with `preservePending: true` for sub-agent JTBDs (#393). */
49
49
  disposeProgressDriver: () => void
50
50
 
51
+ /** Optional: called when the registered-agent disconnect found dangling
52
+ * `activeTurnStartedAt` entries the controller loop did not clear (i.e.
53
+ * `setDone()` already ran on the canonical reply path, leaving
54
+ * `activeStatusReactions` empty but `activeTurnStartedAt` populated).
55
+ * The gateway uses this to null its module-scope `currentTurn` — the
56
+ * bridge that owned that turn just died. Without this, the next
57
+ * inbound is "held mid-turn" against a ghost (the 2026-05-23 audit
58
+ * found ~14 such events / 3 days / 9 agents).
59
+ *
60
+ * No-op if no dangling keys are found. */
61
+ onDanglingTurnsSwept?: (purgedKeys: string[]) => void
62
+
51
63
  /** Logger — receives the one-line decision trace. */
52
64
  log: (msg: string) => void
53
65
  }
@@ -70,6 +82,7 @@ export function flushOnAgentDisconnect<
70
82
  activeDraftParseModes,
71
83
  clearActiveReactions,
72
84
  disposeProgressDriver,
85
+ onDanglingTurnsSwept,
73
86
  log,
74
87
  } = deps
75
88
 
@@ -91,6 +104,30 @@ export function flushOnAgentDisconnect<
91
104
  }
92
105
  clearActiveReactions()
93
106
 
107
+ // Defense-in-depth — sweep any `activeTurnStartedAt` keys the controller
108
+ // loop above did not touch. The bridge has crashed; any turn it owned is
109
+ // dead by definition, regardless of whether `activeStatusReactions`
110
+ // still tracks it. The race that motivates this: `setDone()` already
111
+ // fired on the canonical reply path (clearing the reaction controller)
112
+ // BUT the disconnect arrived BEFORE `purgeReactionTracking` ran the
113
+ // `activeTurnStartedAt.delete` line for that key. Without this sweep,
114
+ // the key orphans, and the next inbound is "held mid-turn" against
115
+ // a ghost — surfacing as the held-mid-turn / `currentTurn_nulled=true`
116
+ // wedge symptom documented in feedback_5min_restart_wedge memo and
117
+ // measured at ~14 events / 3 days / 9 agents (2026-05-23 audit).
118
+ const danglingKeys = [...activeTurnStartedAt.keys()]
119
+ if (danglingKeys.length > 0) {
120
+ for (const k of danglingKeys) {
121
+ activeTurnStartedAt.delete(k)
122
+ activeReactionMsgIds.delete(k)
123
+ }
124
+ log(
125
+ `telegram gateway: disconnect-flush swept ${danglingKeys.length} dangling turn key(s) ` +
126
+ `post-bridge-death (controller loop missed — setDone raced disconnect)`,
127
+ )
128
+ onDanglingTurnsSwept?.(danglingKeys)
129
+ }
130
+
94
131
  // Stop coalesce timers that could emit into a finalized draft stream, but
95
132
  // preserve chats with pendingCompletion=true — those have background
96
133
  // sub-agents that legitimately outlive the parent bridge disconnect. The