typeclaw 0.48.7 → 0.48.8

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.
Files changed (104) hide show
  1. package/auth.schema.json +15 -1
  2. package/package.json +1 -1
  3. package/secrets.schema.json +15 -1
  4. package/src/agent/guard-types.ts +25 -0
  5. package/src/agent/guards.ts +102 -0
  6. package/src/agent/index.ts +33 -3
  7. package/src/agent/multimodal/read-redirect.ts +8 -9
  8. package/src/agent/plugin-tools.ts +283 -148
  9. package/src/agent/provider-error.ts +6 -1
  10. package/src/agent/reload-tool.ts +12 -5
  11. package/src/agent/retry-same-ref.ts +95 -36
  12. package/src/agent/session-origin.ts +13 -1
  13. package/src/agent/system-prompt.ts +14 -3
  14. package/src/agent/todo/continuation-policy.ts +3 -4
  15. package/src/agent/tool-file-safety.ts +36 -13
  16. package/src/agent/tools/channel-reply.ts +39 -2
  17. package/src/agent/tools/channel-send.ts +45 -2
  18. package/src/agent/tools/post-github-review.ts +31 -13
  19. package/src/agent/tools/spawn-subagent.ts +15 -0
  20. package/src/agent/tools/webfetch/inline-style-visibility.ts +2 -2
  21. package/src/agent/tools/webfetch/strategies/readability.ts +109 -10
  22. package/src/agent/turn-runner.ts +23 -19
  23. package/src/bundled-plugins/backup/git-auth.ts +7 -4
  24. package/src/bundled-plugins/backup/subagents.ts +1 -1
  25. package/src/bundled-plugins/bun-hygiene/README.md +23 -20
  26. package/src/bundled-plugins/bun-hygiene/index.ts +1 -7
  27. package/src/bundled-plugins/bun-hygiene/policy.ts +111 -35
  28. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +44 -2
  29. package/src/bundled-plugins/github-cli-auth/gh-store.ts +733 -0
  30. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +25 -0
  31. package/src/bundled-plugins/github-cli-auth/git-command.ts +209 -31
  32. package/src/bundled-plugins/github-cli-auth/git-credential-env.ts +151 -0
  33. package/src/bundled-plugins/github-cli-auth/index.ts +236 -38
  34. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +5 -0
  35. package/src/bundled-plugins/guard/index.ts +2 -25
  36. package/src/bundled-plugins/guard/keys.ts +8 -0
  37. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +7 -8
  38. package/src/bundled-plugins/guard/policy.ts +1 -7
  39. package/src/bundled-plugins/security/policies/git-exfil.ts +22 -30
  40. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +2 -4
  41. package/src/bundled-plugins/security/policies/private-surface-read.ts +8 -6
  42. package/src/bundled-plugins/security/policies/secret-exfil-bash.ts +2 -5
  43. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +2 -4
  44. package/src/bundled-plugins/security/policies/session-search-secrets.ts +2 -4
  45. package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -4
  46. package/src/bundled-plugins/security/policy.ts +0 -8
  47. package/src/channels/adapters/discord-bot-slash-commands.ts +22 -0
  48. package/src/channels/adapters/discord-bot.ts +2 -1
  49. package/src/channels/adapters/discord-classify.ts +16 -4
  50. package/src/channels/adapters/discord.ts +20 -8
  51. package/src/channels/adapters/github/dedup.ts +37 -8
  52. package/src/channels/adapters/github/inbound.ts +241 -46
  53. package/src/channels/adapters/github/review-state.ts +13 -9
  54. package/src/channels/adapters/github/review-thread-resolver.ts +52 -20
  55. package/src/channels/adapters/slack-classify.ts +40 -5
  56. package/src/channels/adapters/slack.ts +3 -9
  57. package/src/channels/adapters/webex-bot-classify.ts +4 -33
  58. package/src/channels/adapters/webex-bot.ts +2 -4
  59. package/src/channels/adapters/webex-classify.ts +4 -33
  60. package/src/channels/adapters/webex-format.ts +36 -0
  61. package/src/channels/adapters/webex.ts +2 -4
  62. package/src/channels/continuation-willingness.ts +64 -39
  63. package/src/channels/github-rereview-guard.ts +20 -0
  64. package/src/channels/github-review-turn-ledger.ts +11 -1
  65. package/src/channels/github-review-verdict-coordinator.ts +475 -41
  66. package/src/channels/github-verdict-activity.ts +14 -5
  67. package/src/channels/persistence.ts +89 -5
  68. package/src/channels/router.ts +1187 -254
  69. package/src/channels/types.ts +21 -5
  70. package/src/cli/compose-stats.ts +6 -7
  71. package/src/cli/compose-status.ts +6 -7
  72. package/src/cli/compose-usage.ts +6 -7
  73. package/src/cli/stats.ts +6 -7
  74. package/src/cli/status.ts +7 -8
  75. package/src/cli/ui.ts +4 -4
  76. package/src/container/start.ts +41 -1
  77. package/src/cron/consumer.ts +30 -9
  78. package/src/cron/scheduler.ts +24 -9
  79. package/src/doctor/channel-checks.ts +64 -0
  80. package/src/doctor/report.ts +8 -8
  81. package/src/dreams/render.ts +2 -2
  82. package/src/init/dockerfile.ts +8 -1
  83. package/src/inspect/render.ts +2 -2
  84. package/src/path-safety/real-intended-path.ts +14 -1
  85. package/src/permissions/permissions.ts +10 -2
  86. package/src/permissions/resolve.ts +8 -2
  87. package/src/plugin/core-tool-names.ts +15 -0
  88. package/src/plugin/hooks.ts +37 -3
  89. package/src/plugin/registry.ts +7 -3
  90. package/src/run/index.ts +33 -7
  91. package/src/sandbox/build.ts +19 -3
  92. package/src/sandbox/policy.ts +1 -0
  93. package/src/secrets/export-github-cli-store.ts +158 -0
  94. package/src/secrets/index.ts +19 -1
  95. package/src/secrets/provision-github-cli-store.ts +322 -0
  96. package/src/secrets/schema.ts +13 -7
  97. package/src/secrets/storage.ts +30 -0
  98. package/src/shared/index.ts +2 -0
  99. package/src/shared/style-text.ts +13 -0
  100. package/src/skills/typeclaw-channel-github/SKILL.md +24 -12
  101. package/src/skills/typeclaw-config/SKILL.md +3 -1
  102. package/src/skills/typeclaw-github-contributing/SKILL.md +6 -2
  103. package/src/skills/typeclaw-permissions/SKILL.md +11 -22
  104. package/src/usage/report.ts +3 -3
@@ -1,7 +1,7 @@
1
1
  import { statSync } from 'node:fs'
2
2
  import { basename } from 'node:path'
3
3
 
4
- import type { AssistantMessage } from '@mariozechner/pi-ai'
4
+ import { createAssistantMessageEventStream, type AssistantMessage, type ToolResultMessage } from '@mariozechner/pi-ai'
5
5
  import { type SessionEntry, SessionManager } from '@mariozechner/pi-coding-agent'
6
6
 
7
7
  import { createSession, renderTurnRoleAnchor, renderTurnTimeAnchor, type AgentSession } from '@/agent'
@@ -53,7 +53,22 @@ import {
53
53
  } from './engagement'
54
54
  import { checkFalseReceipt } from './github-false-receipt'
55
55
  import { evaluateRereviewGuard } from './github-rereview-guard'
56
- import { resetReviewTurn, type ReviewOutputState } from './github-review-turn-ledger'
56
+ import { resetReviewTurn, type ReviewOutputState, type ReviewRoundOutcome } from './github-review-turn-ledger'
57
+ import {
58
+ canPromoteGithubReviewRoundTo,
59
+ completeGithubReviewRound,
60
+ forgetGithubReviewRound,
61
+ githubReviewRoundKey,
62
+ githubReviewRoundPersistence,
63
+ hasGithubReviewRoundDismissalAttempt,
64
+ isGithubReviewRoundComplete,
65
+ promoteGithubReviewRound,
66
+ registerGithubReviewRound,
67
+ restoreGithubReviewRound,
68
+ resetGithubReviewRoundCompletion,
69
+ resetGithubReviewRoundCompletionForPr,
70
+ validateGithubReviewRound,
71
+ } from './github-review-verdict-coordinator'
57
72
  import { renderPrVerdictStandDownReminder } from './github-verdict-activity'
58
73
  import {
59
74
  MEMBERSHIP_COLD_FETCH_TIMEOUT_MS,
@@ -98,6 +113,7 @@ import type {
98
113
  GetMessageResult,
99
114
  HistoryCallback,
100
115
  InboundAttachment,
116
+ GithubReviewFollowupRound,
101
117
  InboundMessage,
102
118
  InboundReferenceContext,
103
119
  ListCallback,
@@ -214,12 +230,7 @@ export function disengageReactionEmojiFor(adapter: AdapterId): string {
214
230
  return DISENGAGE_REACTION_EMOJI_OVERRIDES[adapter] ?? DISENGAGE_REACTION_EMOJI
215
231
  }
216
232
 
217
- type SilentAckReason =
218
- | 'skip_response'
219
- | 'no_reply'
220
- | 'skip_response_text_leak'
221
- | 'github_review_output'
222
- | 'awaiting_background_child'
233
+ type SilentAckReason = 'github_review_output' | 'awaiting_background_child'
223
234
 
224
235
  // Wake nudge pushed into a resumed channel session at boot so drain() has a
225
236
  // non-empty batch and fires a turn. The substantive instruction the model acts
@@ -631,6 +642,12 @@ function defaultMeasureTranscriptBytes(path: string): number {
631
642
  // instead of awaiting the same dead promise forever.
632
643
  export const ENSURE_LIVE_TIMEOUT_MS = 30_000
633
644
 
645
+ const RELOAD_HANDOFF_RETENTION_MS = 15 * 60_000
646
+ const MAX_PENDING_RELOAD_HANDOFF_KEYS = 100
647
+ const MAX_PENDING_RELOAD_HANDOFF_ITEMS_PER_KEY = 1_000
648
+ const MAX_PENDING_RELOAD_HANDOFF_BYTES_PER_KEY = 8 * 1024 * 1024
649
+ const MAX_PENDING_RELOAD_HANDOFF_BYTES_TOTAL = 64 * 1024 * 1024
650
+
634
651
  // Thrown by ensureLive() when a teardown (roles reload or shutdown) raced
635
652
  // ahead of an in-flight creation. route() has no special handling — it
636
653
  // propagates to the adapter's outer catch, dropping this one inbound. The
@@ -752,6 +769,7 @@ type QueuedInbound = {
752
769
  // happened to dequeue it. Zero means "unknown" (the formatter omits the
753
770
  // prefix for those).
754
771
  ts: number
772
+ githubReviewRound?: GithubReviewFollowupRound
755
773
  }
756
774
 
757
775
  type ObservedInbound = {
@@ -782,6 +800,52 @@ type TimedAttachment = { ts: number; attachment: InboundAttachment }
782
800
 
783
801
  type ChannelAgentSession = AgentSession & { getAbortReason?: () => string | undefined }
784
802
 
803
+ // Provenance of a queued system reminder, which decides whether the
804
+ // reminder-only drain iteration it drives CONTINUES the current logical turn or
805
+ // OPENS a new one.
806
+ //
807
+ // `retry` — the router's own turn-recovery ladder asking the SAME logical turn
808
+ // to try again (empty-turn, tool-leak, stranded-tooluse, cold-start,
809
+ // empty-stop, willingness). Per-logical-turn attribution and the recovery
810
+ // budgets must survive these, or the ladder would refill its own budget and
811
+ // loop forever.
812
+ //
813
+ // `wakeup` — work injected from OUTSIDE the session's own turn machinery: a
814
+ // finished background subagent, a restart resume, a PR-verdict stand-down.
815
+ // These are a new episode that merely happens to arrive without a user
816
+ // message, so carrying the previous turn's attribution into them is wrong.
817
+ //
818
+ // The todo/idle continuation is deliberately `retry`, not `wakeup`: it is the
819
+ // same work episode continuing, and its turn must keep citing the durable work
820
+ // already completed.
821
+ //
822
+ // Provenance is per ENTRY rather than a single session-level flag because both
823
+ // kinds can coalesce into one iteration; a wakeup in the batch opens a new
824
+ // logical turn regardless of what else it rode in with. Matching on reminder
825
+ // TEXT was rejected: a wakeup body that happened to equal a nudge constant
826
+ // would silently misclassify, and every future enqueue site would inherit the
827
+ // default instead of being forced to choose.
828
+ type PendingSystemReminder = { text: string; kind: 'retry' | 'wakeup'; githubReviewRoundKey?: string }
829
+
830
+ type PendingReloadHandoff = {
831
+ key: ChannelKey
832
+ inbounds: QueuedInbound[]
833
+ observed: ObservedInbound[]
834
+ reminders: PendingSystemReminder[]
835
+ retainedAt: number
836
+ estimatedBytes: number
837
+ }
838
+
839
+ const retryReminder = (text: string): PendingSystemReminder => ({ text, kind: 'retry' })
840
+
841
+ const wakeupReminder = (text: string): PendingSystemReminder => ({ text, kind: 'wakeup' })
842
+
843
+ const githubReviewRoundWakeupReminder = (text: string, round: GithubReviewFollowupRound): PendingSystemReminder => ({
844
+ text,
845
+ kind: 'wakeup',
846
+ githubReviewRoundKey: githubReviewRoundKey(round),
847
+ })
848
+
785
849
  type LiveSession = {
786
850
  key: ChannelKey
787
851
  keyId: string
@@ -813,6 +877,10 @@ type LiveSession = {
813
877
  participants: ChannelParticipant[]
814
878
  resolvedNames: ResolvedChannelNames
815
879
  originRef: { current: SessionOrigin | undefined }
880
+ githubReviewRound: GithubReviewFollowupRound | null
881
+ // Round key of a close-out that arrived while the round was still pending
882
+ // completion. Replayed once the round completes; see replayPendingRoundCloseouts.
883
+ pendingGithubReviewRoundCloseout: string | null
816
884
  promptQueue: QueuedInbound[]
817
885
  contextBuffer: ObservedInbound[]
818
886
  // Attachments of the messages composing the in-flight turn. drain()
@@ -835,6 +903,12 @@ type LiveSession = {
835
903
  historyTimedAttachments: readonly TimedAttachment[]
836
904
  historyAttachments: InboundAttachment[]
837
905
  draining: boolean
906
+ // Every drain invocation still running, including the tail it executes after
907
+ // `draining` flips back to false. `drain()` deliberately no-ops while a drain
908
+ // owns the session, so a fire-and-forget `void drain(live)` is otherwise
909
+ // unobservable; this is the only handle a caller can await to know the turn
910
+ // actually landed. Entries remove themselves on settle.
911
+ activeDrains: Set<Promise<void>>
838
912
  debounceTimer: ReturnType<typeof setTimeout> | null
839
913
  typingTimer: ReturnType<typeof setInterval> | null
840
914
  typingStartedAt: number
@@ -871,14 +945,13 @@ type LiveSession = {
871
945
  // `currentTurnReactionRef` points at — last item of the drained batch) was
872
946
  // EXPLICITLY addressed to the bot: a DM, an @-mention/alias (`isBotMention`
873
947
  // folds plain-name matching in at the adapter classify layer), or a reply to
874
- // the bot's own message. Gates the PERSISTENT silent-ack :eyes: (see
875
- // `armSilentTurnAck`): a deliberate silence on a message aimed AT us earns a
876
- // courteous "seen, nothing to add" 👀, but staying quiet during ambient
877
- // human-to-human chatter (sticky observation, solo-human fallback) must leave
878
- // NO mark — otherwise a busy room accumulates stale 👀 on messages the bot
879
- // was never part of. Computed from the SAME message the reaction targets so
880
- // eligibility and target can never disagree. Reset with `currentTurnReactionRef`
881
- // in the drain finally; preserved across reminder-only iterations exactly like it.
948
+ // the bot's own message. Gates the PERSISTENT :eyes: for deferred background
949
+ // work (see `armSilentTurnAck`): an addressed request may retain a progress
950
+ // marker while a child runs, but ambient human-to-human chatter must leave no
951
+ // mark. Explicit NO_REPLY and skip_response turns never use this flag to add a
952
+ // reaction. Computed from the SAME message the reaction targets so eligibility
953
+ // and target cannot disagree. Reset with `currentTurnReactionRef` in the drain
954
+ // finally; preserved across reminder-only iterations exactly like it.
882
955
  currentTurnExplicitlyAddressed: boolean
883
956
  // Typing-status anchor of the inbound that triggered THIS turn (last item in
884
957
  // the drained batch, mirroring `currentTurnReactionRef`). Adapter-opaque ts
@@ -904,16 +977,12 @@ type LiveSession = {
904
977
  // discarded on silence (skip_response / empty / errored turns) so the bot never
905
978
  // leaves a reaction on a message it merely looked at (e.g. cron lookaround).
906
979
  pendingTurnReactions: ReactionRequest[]
907
- // Armed by `validateChannelTurn` on a DELIBERATE silent turn (skip_response or
908
- // an explicit NO_REPLY), stamped with `turnSeq` so a stale flag from a crashed
909
- // turn cannot leak into the next one. Read in drain's per-turn finally — AFTER
910
- // the transient engage :eyes: is dropped — to leave a PERSISTENT :eyes: on the
911
- // triggering message: "I saw this and intentionally chose not to reply." Null
912
- // on every non-deliberate outcome (a real reply, a model malfunction, a
913
- // plumbing leak, a retry, a synthetic turn). Firing after the engage-drop is
914
- // load-bearing: adapters that collapse a same-actor same-emoji reaction into
915
- // one toggle would otherwise have the engage-drop remove the only visible
916
- // :eyes:. See `reactOnSilentAck`.
980
+ // Armed when output landed outside the channel (a GitHub review) or was
981
+ // deliberately deferred to a background child. Explicit NO_REPLY and
982
+ // skip_response turns do not arm it: opting out must leave no reaction behind.
983
+ // Stamped with `turnSeq` so a stale flag from a crashed turn cannot leak into
984
+ // the next one. Fired after the transient engage :eyes: is dropped because
985
+ // adapters may collapse a same-actor same-emoji reaction into one toggle.
917
986
  silentAckTurn: { turnSeq: number; reason: SilentAckReason } | null
918
987
  // One silent-ack-:eyes:-add promise per PERSISTENT ack `reactOnSilentAck` has
919
988
  // planted on a trigger message, each resolving to its removable ref (or null).
@@ -922,16 +991,15 @@ type LiveSession = {
922
991
  // sees every in-flight add and awaits it before removing — storing only the
923
992
  // resolved ref raced (cleanup could snapshot an empty array, then a slow add
924
993
  // append its ref afterward, stranding the :eyes:). Cross-turn state on purpose:
925
- // a silent turn means "seen, not replying FOR NOW", and once the same sticky
926
- // conversation gets a genuine reply those marks read as stale/contradictory —
927
- // so they are retired on the next replied turn (see dropSilentAckReactions).
994
+ // the mark means output is external or deferred, and once the same sticky
995
+ // conversation gets a genuine reply it reads as stale — so it is retired on
996
+ // the next replied turn (see dropSilentAckReactions).
928
997
  // Conversation-scoped, NOT per-trigger-message: coalescing means the silent
929
998
  // turn's trigger (message N) and the eventual reply's trigger (message N+1)
930
999
  // routinely differ, so exact-message scoping would strand the mark. NOT reset
931
1000
  // in drain's outer per-turn finally. On teardown the entries are dropped
932
- // WITHOUT removing the reactions: a session that ends without ever replying
933
- // legitimately keeps its "seen, not replying" ack, unlike the transient
934
- // engage :eyes: which teardown must strip.
1001
+ // WITHOUT removing the reactions, unlike the transient engage :eyes: which
1002
+ // teardown must strip.
935
1003
  activeSilentAckReactions: Array<Promise<ReactionRef | null>>
936
1004
  // One add promise per willingness status posted by the agent, resolving to
937
1005
  // the removable reaction-instance ref. Cross-turn state on purpose: the
@@ -963,7 +1031,7 @@ type LiveSession = {
963
1031
  // every `drain()` iteration alongside the regular promptQueue batch;
964
1032
  // the drain loop's run condition checks BOTH queues so a system
965
1033
  // reminder alone is enough to trigger a turn.
966
- pendingSystemReminders: string[]
1034
+ pendingSystemReminders: PendingSystemReminder[]
967
1035
  // True only for the reminder-only iteration that consumed a willingness
968
1036
  // nudge. `willingnessNudges` persists across the logical turn, so it remains
969
1037
  // nonzero after a substantive result and would misclassify NO_REPLY from a
@@ -1063,13 +1131,20 @@ type LiveSession = {
1063
1131
  // user batch starts (batch.length > 0), NOT on the reminder-only iteration the
1064
1132
  // nudge itself queues — same anti-reloop discipline as the empty-turn budget.
1065
1133
  willingnessNudges: number
1066
- // Stashed by `installChannelReplyTerminalHook` just before it aborts the turn
1067
- // after a successful `channel_reply` that omitted `more_work_this_turn: true`. Read once
1134
+ // Stashed by `installChannelReplyTerminalHook` after a successful
1135
+ // `channel_reply` that omitted `more_work_this_turn: true`. Read once
1068
1136
  // by `validateChannelTurn` to decide the continuation nudge. `turnSeq`-stamped
1069
1137
  // (like `skippedTurn`/`skipLockedSendTurn`) so a stale record from an earlier
1070
1138
  // turn can never trigger a nudge on a later one. `null` when no such reply
1071
1139
  // ended this turn.
1072
- lastTerminalReplyAbort: { turnSeq: number; text: string } | null
1140
+ lastTerminalReplyCompletion: { turnSeq: number; text?: string; tokens: number } | null
1141
+ // Armed after a successful terminal reply. pi-agent-core invokes streamFn
1142
+ // again only after emitting every matching toolResult into its event queue;
1143
+ // the wrapper consumes this marker at that awaited provider boundary and
1144
+ // returns a local aborted response instead of calling the provider. Event
1145
+ // queue ordering then persists every toolResult before the synthetic aborted
1146
+ // assistant. Cleared on consumption, stop, or a fresh user turn.
1147
+ pendingTerminalReplyStop: { turnSeq: number; tokens: number } | null
1073
1148
  // Stamped by `installChannelReplyTerminalHook` when a successful `channel_reply`
1074
1149
  // set `more_work_this_turn: true` — the machine-readable "I'll keep working this turn"
1075
1150
  // promise. `validateChannelTurn` reads it to recover a turn that made that promise,
@@ -1292,6 +1367,7 @@ export type ExecuteCommandResult =
1292
1367
  // happened to be live, bypassing role gating entirely.
1293
1368
  export type ExecuteCommandOptions = {
1294
1369
  invokerId: string
1370
+ parentChat?: string
1295
1371
  }
1296
1372
 
1297
1373
  export type SendSource = 'tool' | 'system'
@@ -1487,9 +1563,21 @@ export type ChannelRouter = {
1487
1563
  injectPrVerdictActivity: (args: {
1488
1564
  workspace: string
1489
1565
  prNumber: number
1490
- verdict: 'APPROVE' | 'REQUEST_CHANGES'
1566
+ verdict: ReviewRoundOutcome
1491
1567
  sessionId: string
1492
1568
  }) => { kind: 'delivered'; count: number }
1569
+ completeGithubReviewRound?: (args: {
1570
+ workspace: string
1571
+ prNumber: number
1572
+ verdict: ReviewRoundOutcome
1573
+ sessionId: string
1574
+ }) => Promise<{ kind: 'completed' | 'no-round' }>
1575
+ finishGithubReviewRoundCloseout?: (args: {
1576
+ sessionId: string
1577
+ workspace: string
1578
+ prNumber: number
1579
+ thread: string | null
1580
+ }) => void
1493
1581
  noteGithubReviewOutput: (args: {
1494
1582
  sessionId: string
1495
1583
  workspace: string
@@ -1561,6 +1649,9 @@ export type ChannelRouter = {
1561
1649
  isTypingActive: (key: ChannelKey) => boolean
1562
1650
  stopTyping: (key: ChannelKey) => Promise<void>
1563
1651
  typingHeartbeatIntervalFor: (adapter: ChannelKey['adapter']) => number
1652
+ githubReviewRoundFor: (key: ChannelKey) => GithubReviewFollowupRound | null | undefined
1653
+ pendingReminderCount: (key: ChannelKey) => number | undefined
1654
+ creationTokenCount: () => number
1564
1655
  runIdleGc: () => Promise<void>
1565
1656
  // Returns the seeded author state on the live session matching
1566
1657
  // `key`, or undefined when no live session exists. Tests use this
@@ -1643,6 +1734,14 @@ export type CreateChannelRouterOptions = {
1643
1734
  // Test seam: override the ensureLive watchdog ceiling so the timeout path
1644
1735
  // is exercisable in <100ms instead of the 30s production default.
1645
1736
  ensureLiveTimeoutMs?: number
1737
+ // Test seam for expiring a failed reload handoff without waiting for the
1738
+ // production retention window.
1739
+ handoffRetryRetentionMs?: number
1740
+ // Test seam for exercising the per-key retry-buffer capacity without
1741
+ // manufacturing a production-sized batch.
1742
+ handoffRetryItemLimit?: number
1743
+ // Test seam for the retained payload-size guard.
1744
+ handoffRetryByteLimit?: number
1646
1745
  // Test seam: per-callback ceiling for channel name resolvers; mirrors the
1647
1746
  // ensureLive seam so timeout paths can be exercised quickly in tests.
1648
1747
  resolveChannelNamesTimeoutMs?: number
@@ -1760,6 +1859,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1760
1859
  const now = options.now ?? Date.now
1761
1860
  const measureTranscriptBytes = options.measureTranscriptBytes ?? defaultMeasureTranscriptBytes
1762
1861
  const ensureLiveTimeoutMs = options.ensureLiveTimeoutMs ?? ENSURE_LIVE_TIMEOUT_MS
1862
+ const handoffRetryRetentionMs = options.handoffRetryRetentionMs ?? RELOAD_HANDOFF_RETENTION_MS
1863
+ const handoffRetryItemLimit = options.handoffRetryItemLimit ?? MAX_PENDING_RELOAD_HANDOFF_ITEMS_PER_KEY
1864
+ const handoffRetryByteLimit = options.handoffRetryByteLimit ?? MAX_PENDING_RELOAD_HANDOFF_BYTES_PER_KEY
1763
1865
  const resolveChannelNamesTimeoutMs = options.resolveChannelNamesTimeoutMs ?? RESOLVE_CHANNEL_NAMES_TIMEOUT_MS
1764
1866
  const fetchHistoryTimeoutMs = options.fetchHistoryTimeoutMs ?? FETCH_HISTORY_TIMEOUT_MS
1765
1867
  const sessionIdleTimeoutMs = options.sessionIdleTimeoutMs ?? SESSION_IDLE_TIMEOUT_MS
@@ -1771,6 +1873,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1771
1873
  const newestRunningChildSubagentStartedAt = options.newestRunningChildSubagentStartedAt ?? (() => null)
1772
1874
  const liveSessions = new Map<string, LiveSession>()
1773
1875
  const creating = new Map<string, Promise<LiveSession>>()
1876
+ let nextCreationToken = 0
1877
+ const activeCreationAttempts = new Map<string, number>()
1878
+ // Unlike `creating`, this marker survives the watchdog cleanup. A timed-out
1879
+ // attempt can keep running after a retry claims the key, so only the latest
1880
+ // monotonic token may persist, install, or adopt queued handoff work.
1881
+ const latestCreationTokens = new Map<string, number>()
1882
+ // A deferred reload splices post-reload work off the stale session before it
1883
+ // recreates the successor. If that recreation times out, returning from the
1884
+ // handoff used to discard the only copy and produce the production symptom
1885
+ // "the agent stopped responding." Keep one ordered batch per channel key so
1886
+ // the next successful ensureLive adopts it before any newer inbound. Entries
1887
+ // expire and the key count is capped; crossing either bound reports the loss
1888
+ // to both logs and the channel instead of silently trimming user work.
1889
+ const pendingReloadHandoffs = new Map<string, PendingReloadHandoff>()
1774
1890
  // Restart-resume reservations, keyed by channelKeyId. Installed by
1775
1891
  // reserveRestartHandoff BEFORE channel adapters start receiving, so an
1776
1892
  // inbound that races the boot resume coalesces onto the reservation (via the
@@ -1913,6 +2029,34 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1913
2029
  await next
1914
2030
  }
1915
2031
 
2032
+ const persistGithubReviewRound = (live: LiveSession, round: GithubReviewFollowupRound | null): void => {
2033
+ if (mappings === null) return
2034
+ const idx = mappings.findIndex(
2035
+ (record) =>
2036
+ record.adapter === live.key.adapter &&
2037
+ record.workspace === live.key.workspace &&
2038
+ record.chat === live.key.chat &&
2039
+ (record.thread ?? null) === (live.key.thread ?? null),
2040
+ )
2041
+ if (idx < 0) return
2042
+ const record = mappings[idx]!
2043
+ if (round === null) {
2044
+ const { githubReviewRound: _removed, ...rest } = record
2045
+ void _removed
2046
+ mappings[idx] = rest
2047
+ } else {
2048
+ const state = githubReviewRoundPersistence(round)
2049
+ if (state === null) {
2050
+ const { githubReviewRound: _expired, ...rest } = record
2051
+ void _expired
2052
+ mappings[idx] = rest
2053
+ } else {
2054
+ mappings[idx] = { ...record, githubReviewRound: { ...round, ...state } }
2055
+ }
2056
+ }
2057
+ void persist()
2058
+ }
2059
+
1916
2060
  const createForChannel: CreateSessionForChannel =
1917
2061
  options.createSessionForChannel ??
1918
2062
  (async ({ key, existingSessionId, existingSessionFile, origin, originRef }) => {
@@ -2105,6 +2249,155 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2105
2249
  return true
2106
2250
  }
2107
2251
 
2252
+ const pendingReloadHandoffItemCount = (pending: PendingReloadHandoff): number =>
2253
+ pending.inbounds.length + pending.observed.length + pending.reminders.length
2254
+
2255
+ const estimateReloadHandoffBytes = (
2256
+ inbounds: QueuedInbound[],
2257
+ observed: ObservedInbound[],
2258
+ reminders: PendingSystemReminder[],
2259
+ ): number => {
2260
+ try {
2261
+ const serializableInbounds = inbounds.map(({ engageReaction: _engageReaction, ...inbound }) => inbound)
2262
+ return Buffer.byteLength(JSON.stringify({ inbounds: serializableInbounds, observed, reminders }), 'utf8')
2263
+ } catch {
2264
+ return Number.POSITIVE_INFINITY
2265
+ }
2266
+ }
2267
+
2268
+ const pendingReloadHandoffTotalBytes = (): number => {
2269
+ let total = 0
2270
+ for (const pending of pendingReloadHandoffs.values()) total += pending.estimatedBytes
2271
+ return total
2272
+ }
2273
+
2274
+ const reportDiscardedReloadHandoff = async (pending: PendingReloadHandoff, reason: string): Promise<void> => {
2275
+ const count = pendingReloadHandoffItemCount(pending)
2276
+ const recovery =
2277
+ "Re-send the affected messages. If provider credentials changed, run reload({ scope: 'providers' }); " +
2278
+ 'otherwise check the channel logs and retry after session creation is healthy.'
2279
+ logger.error(
2280
+ `[channels] ${channelKeyId(pending.key)}: reload handoff retention policy discarded ${count} queued item(s): ${reason}. ${recovery}`,
2281
+ )
2282
+ await dropPendingReloadHandoffEngageReactions(pending)
2283
+ const result = await send(
2284
+ {
2285
+ adapter: pending.key.adapter,
2286
+ workspace: pending.key.workspace,
2287
+ chat: pending.key.chat,
2288
+ thread: pending.key.thread,
2289
+ text: `⚠️ TypeClaw could not replay ${count} queued item(s) after reload: ${reason}. ${recovery}`,
2290
+ },
2291
+ { source: 'system', outputKind: 'meta' },
2292
+ ).catch((err) => {
2293
+ logger.error(`[channels] ${channelKeyId(pending.key)}: reload handoff loss notice threw: ${describeError(err)}`)
2294
+ return null
2295
+ })
2296
+ if (result !== null && !result.ok) {
2297
+ logger.error(`[channels] ${channelKeyId(pending.key)}: reload handoff loss notice failed: ${result.error}`)
2298
+ }
2299
+ }
2300
+
2301
+ const expirePendingReloadHandoffs = async (): Promise<void> => {
2302
+ const expired: Array<{ pending: PendingReloadHandoff; ageMs: number }> = []
2303
+ for (const [keyId, pending] of pendingReloadHandoffs) {
2304
+ const ageMs = now() - pending.retainedAt
2305
+ if (ageMs < handoffRetryRetentionMs) continue
2306
+ pendingReloadHandoffs.delete(keyId)
2307
+ expired.push({ pending, ageMs })
2308
+ }
2309
+ await Promise.all(
2310
+ expired.map(({ pending, ageMs }) =>
2311
+ reportDiscardedReloadHandoff(pending, `retention limit exceeded after ${ageMs}ms`),
2312
+ ),
2313
+ )
2314
+ }
2315
+
2316
+ const retainReloadHandoff = (
2317
+ key: ChannelKey,
2318
+ inbounds: QueuedInbound[],
2319
+ observed: ObservedInbound[],
2320
+ reminders: PendingSystemReminder[],
2321
+ ): boolean => {
2322
+ void expirePendingReloadHandoffs()
2323
+ const keyId = channelKeyId(key)
2324
+ const existing = pendingReloadHandoffs.get(keyId)
2325
+ if (existing !== undefined) {
2326
+ const incoming: PendingReloadHandoff = {
2327
+ key,
2328
+ inbounds,
2329
+ observed,
2330
+ reminders,
2331
+ retainedAt: now(),
2332
+ estimatedBytes: estimateReloadHandoffBytes(inbounds, observed, reminders),
2333
+ }
2334
+ if (pendingReloadHandoffItemCount(existing) + pendingReloadHandoffItemCount(incoming) > handoffRetryItemLimit) {
2335
+ void reportDiscardedReloadHandoff(incoming, `per-key item limit ${handoffRetryItemLimit} would be exceeded`)
2336
+ return false
2337
+ }
2338
+ if (existing.estimatedBytes + incoming.estimatedBytes > handoffRetryByteLimit) {
2339
+ void reportDiscardedReloadHandoff(incoming, `per-key byte limit ${handoffRetryByteLimit} would be exceeded`)
2340
+ return false
2341
+ }
2342
+ if (pendingReloadHandoffTotalBytes() + incoming.estimatedBytes > MAX_PENDING_RELOAD_HANDOFF_BYTES_TOTAL) {
2343
+ void reportDiscardedReloadHandoff(
2344
+ incoming,
2345
+ `global byte limit ${MAX_PENDING_RELOAD_HANDOFF_BYTES_TOTAL} would be exceeded`,
2346
+ )
2347
+ return false
2348
+ }
2349
+ existing.inbounds.push(...inbounds)
2350
+ existing.observed.push(...observed)
2351
+ existing.reminders.push(...reminders)
2352
+ existing.estimatedBytes += incoming.estimatedBytes
2353
+ return true
2354
+ }
2355
+ const pending: PendingReloadHandoff = {
2356
+ key,
2357
+ inbounds,
2358
+ observed,
2359
+ reminders,
2360
+ retainedAt: now(),
2361
+ estimatedBytes: estimateReloadHandoffBytes(inbounds, observed, reminders),
2362
+ }
2363
+ if (pendingReloadHandoffItemCount(pending) > handoffRetryItemLimit) {
2364
+ void reportDiscardedReloadHandoff(pending, `per-key item limit ${handoffRetryItemLimit} exceeded`)
2365
+ return false
2366
+ }
2367
+ if (pending.estimatedBytes > handoffRetryByteLimit) {
2368
+ void reportDiscardedReloadHandoff(pending, `per-key byte limit ${handoffRetryByteLimit} exceeded`)
2369
+ return false
2370
+ }
2371
+ if (pendingReloadHandoffTotalBytes() + pending.estimatedBytes > MAX_PENDING_RELOAD_HANDOFF_BYTES_TOTAL) {
2372
+ void reportDiscardedReloadHandoff(pending, `global byte limit ${MAX_PENDING_RELOAD_HANDOFF_BYTES_TOTAL} exceeded`)
2373
+ return false
2374
+ }
2375
+ if (pendingReloadHandoffs.size >= MAX_PENDING_RELOAD_HANDOFF_KEYS) {
2376
+ void reportDiscardedReloadHandoff(pending, `key limit ${MAX_PENDING_RELOAD_HANDOFF_KEYS} reached`)
2377
+ return false
2378
+ }
2379
+ pendingReloadHandoffs.set(keyId, pending)
2380
+ return true
2381
+ }
2382
+
2383
+ const adoptPendingReloadHandoff = (live: LiveSession): void => {
2384
+ const pending = pendingReloadHandoffs.get(live.keyId)
2385
+ if (pending === undefined) return
2386
+ const ageMs = now() - pending.retainedAt
2387
+ if (ageMs >= handoffRetryRetentionMs) {
2388
+ pendingReloadHandoffs.delete(live.keyId)
2389
+ void reportDiscardedReloadHandoff(pending, `retention limit exceeded after ${ageMs}ms`)
2390
+ return
2391
+ }
2392
+ // Delete before enqueueing: once ownership moves to the live queues, a
2393
+ // second ensureLive must not replay the same batch and double-deliver it.
2394
+ pendingReloadHandoffs.delete(live.keyId)
2395
+ live.promptQueue.push(...pending.inbounds)
2396
+ live.contextBuffer.push(...pending.observed)
2397
+ live.pendingSystemReminders.push(...pending.reminders)
2398
+ if ((pending.inbounds.length > 0 || pending.reminders.length > 0) && !live.draining) void drain(live)
2399
+ }
2400
+
2108
2401
  const ensureLive = async (
2109
2402
  key: ChannelKey,
2110
2403
  triggeringMessageId?: string,
@@ -2126,7 +2419,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2126
2419
  if (existing && !existing.destroyed) {
2127
2420
  // A resume that finds the key already live is a no-op for reopening: the
2128
2421
  // session is up, so just hand it back and let the caller enqueue the wake.
2129
- if (resumeTarget !== undefined) return existing
2422
+ if (resumeTarget !== undefined) {
2423
+ adoptPendingReloadHandoff(existing)
2424
+ return existing
2425
+ }
2130
2426
  // Rollover decision (soft TTL → cost-aware grace → hard cap) lives in
2131
2427
  // shouldRolloverLive, which also skips draining sessions so a mid-prompt
2132
2428
  // turn is never aborted by a follow-up's idle check (PR #359 incident).
@@ -2156,6 +2452,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2156
2452
  }
2157
2453
  }
2158
2454
  } else {
2455
+ adoptPendingReloadHandoff(existing)
2159
2456
  return existing
2160
2457
  }
2161
2458
  }
@@ -2164,8 +2461,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2164
2461
  if (inFlight) return inFlight
2165
2462
 
2166
2463
  const generation = liveGeneration
2464
+ const creationToken = ++nextCreationToken
2465
+ latestCreationTokens.set(keyId, creationToken)
2466
+ activeCreationAttempts.set(keyId, (activeCreationAttempts.get(keyId) ?? 0) + 1)
2467
+ const isLatestCreation = (): boolean => latestCreationTokens.get(keyId) === creationToken
2167
2468
 
2168
- const promise = (async () => {
2469
+ let promise!: Promise<LiveSession>
2470
+ promise = (async () => {
2169
2471
  await ensureLoaded()
2170
2472
  const record = mappings ? findRecord(mappings, key) : undefined
2171
2473
  let resolvedRecord = record
@@ -2190,6 +2492,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2190
2492
  thread: record.thread,
2191
2493
  participants: record.participants,
2192
2494
  lastInboundAt: 0,
2495
+ ...(record.githubReviewRound !== undefined ? { githubReviewRound: record.githubReviewRound } : {}),
2193
2496
  }
2194
2497
  if (mappings) {
2195
2498
  const idx = mappings.findIndex(
@@ -2220,6 +2523,28 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2220
2523
  lastInboundAt: now(),
2221
2524
  }
2222
2525
  }
2526
+ let restoredRound: GithubReviewFollowupRound | null = null
2527
+ let restoredRoundStatus: 'pending' | 'completed' | null = null
2528
+ if (resolvedRecord?.githubReviewRound !== undefined) {
2529
+ if (
2530
+ await validateGithubReviewRound(resolvedRecord.githubReviewRound, resolvedRecord.githubReviewRound.createdAt)
2531
+ ) {
2532
+ restoredRoundStatus = resolvedRecord.githubReviewRound.status
2533
+ restoredRound = restoreGithubReviewRound(
2534
+ resolvedRecord.githubReviewRound,
2535
+ restoredRoundStatus,
2536
+ resolvedRecord.githubReviewRound.attemptedCarriers,
2537
+ resolvedRecord.githubReviewRound.dismissalAttempted === true,
2538
+ resolvedRecord.githubReviewRound.requestChangesAttempted === true,
2539
+ resolvedRecord.githubReviewRound.createdAt,
2540
+ )
2541
+ } else {
2542
+ logger.info(
2543
+ `[channels] ${keyId}: dropped stale or expired persisted github review round pr=${resolvedRecord.githubReviewRound.workspace}#${resolvedRecord.githubReviewRound.prNumber}`,
2544
+ )
2545
+ }
2546
+ }
2547
+
2223
2548
  const phase = resolvedRecord?.sessionId === undefined ? 'cold-start' : 'rehydrate'
2224
2549
  logger.info(`[channels] ${keyId}: ensureLive begin (${phase})`)
2225
2550
  const participants = (resolvedRecord?.participants ?? []) as ChannelParticipant[]
@@ -2246,6 +2571,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2246
2571
  chat: key.chat,
2247
2572
  ...(resolvedNames.chatName !== undefined ? { chatName: resolvedNames.chatName } : {}),
2248
2573
  thread: key.thread,
2574
+ ...(restoredRound !== null ? { githubReviewRound: restoredRound } : {}),
2249
2575
  ...(room?.parentChat !== undefined ? { parentChat: room.parentChat } : {}),
2250
2576
  ...(room?.parentChatName !== undefined ? { parentChatName: room.parentChatName } : {}),
2251
2577
  ...(triggeringAuthorId !== undefined ? { lastInboundAuthorId: triggeringAuthorId } : {}),
@@ -2270,6 +2596,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2270
2596
  })
2271
2597
  logger.info(`[channels] ${keyId}: ensureLive session-created sessionId=${created.sessionId}`)
2272
2598
 
2599
+ // A watchdog timeout only releases callers; it cannot cancel the factory.
2600
+ // Check the durable per-key token before this late attempt can overwrite
2601
+ // the retry's mapping. The `creating` entry is intentionally insufficient:
2602
+ // both attempts may have removed their transient entries by now.
2603
+ if (!isLatestCreation()) {
2604
+ await created.dispose()
2605
+ throw new Error(`[channels] ${keyId}: superseded live session creation discarded`)
2606
+ }
2607
+
2273
2608
  const transcriptPath = created.getTranscriptPath?.()
2274
2609
  const persistedRecord: ChannelSessionRecord = {
2275
2610
  adapter: key.adapter,
@@ -2280,6 +2615,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2280
2615
  ...(transcriptPath ? { sessionFile: basename(transcriptPath) } : {}),
2281
2616
  lastInboundAt: now(),
2282
2617
  participants,
2618
+ ...(restoredRound !== null && restoredRoundStatus !== null
2619
+ ? (() => {
2620
+ const state = githubReviewRoundPersistence(restoredRound)
2621
+ return state === null ? {} : { githubReviewRound: { ...restoredRound, ...state } }
2622
+ })()
2623
+ : {}),
2283
2624
  }
2284
2625
  if (mappings) {
2285
2626
  const idx = mappings.findIndex(
@@ -2318,6 +2659,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2318
2659
  participants,
2319
2660
  resolvedNames,
2320
2661
  originRef,
2662
+ githubReviewRound: restoredRound,
2663
+ pendingGithubReviewRoundCloseout: null,
2321
2664
  promptQueue: [],
2322
2665
  pendingSystemReminders: [],
2323
2666
  willingnessReminderIteration: false,
@@ -2326,6 +2669,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2326
2669
  historyTimedAttachments: [],
2327
2670
  historyAttachments: [],
2328
2671
  draining: false,
2672
+ activeDrains: new Set(),
2329
2673
  debounceTimer: null,
2330
2674
  typingTimer: null,
2331
2675
  typingStartedAt: 0,
@@ -2374,7 +2718,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2374
2718
  toolLeakRetries: 0,
2375
2719
  emptyStopAfterToolWorkArmed: false,
2376
2720
  willingnessNudges: 0,
2377
- lastTerminalReplyAbort: null,
2721
+ lastTerminalReplyCompletion: null,
2722
+ pendingTerminalReplyStop: null,
2378
2723
  continueReplyTurn: null,
2379
2724
  abortReasonThisTurn: null,
2380
2725
  userStoppedTurnSeq: null,
@@ -2428,7 +2773,29 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2428
2773
  stampedAbort.reason === 'terminal_after_channel_reply'
2429
2774
  ? 'terminal-after-channel-reply'
2430
2775
  : undefined
2431
- if (stampedAbort?.turnSeq === live.turnSeq) live.abortReasonThisTurn = null
2776
+ // Keep the same-turn stamp through validateChannelTurn. Clearing it on
2777
+ // the aborted assistant event made the later stranded-toolUse retry log
2778
+ // `abort_reason=unknown`, even though this subscriber had just consumed
2779
+ // the exact internal reason. A fresh user batch clears the stamp, and
2780
+ // every reader also requires a matching turnSeq, so retaining it cannot
2781
+ // attribute a later turn to this abort.
2782
+ // AgentSession processes message events through one serial queue. By
2783
+ // the time this synthetic aborted message_end reaches the subscriber,
2784
+ // every preceding toolResult event has completed extension handling
2785
+ // and SessionManager persistence. Preserve the original assistant
2786
+ // usage rather than recording this local stream's zero-token envelope.
2787
+ const terminalCompletion = live.lastTerminalReplyCompletion
2788
+ if (termination !== undefined && terminalCompletion?.turnSeq === live.turnSeq) {
2789
+ enqueueTodoOutcomeWrite(live, {
2790
+ agentDir: options.agentDir,
2791
+ origin: buildLiveOrigin(live),
2792
+ turnId: live.sessionId,
2793
+ stopReason: usage.stopReason,
2794
+ termination,
2795
+ tokens: terminalCompletion.tokens,
2796
+ })
2797
+ return
2798
+ }
2432
2799
  const outcomeArgs = {
2433
2800
  agentDir: options.agentDir,
2434
2801
  origin: buildLiveOrigin(live),
@@ -2459,6 +2826,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2459
2826
  if (isColdStart) {
2460
2827
  // Install before the slow prefetch so a concurrent teardown/shutdown can
2461
2828
  // see and dispose this session during the network fetch.
2829
+ if (!isLatestCreation()) {
2830
+ await tearDownLive(live)
2831
+ throw new Error(`[channels] ${keyId}: superseded live session creation discarded`)
2832
+ }
2462
2833
  liveSessions.set(keyId, live)
2463
2834
  const adapterConfig = options.configForAdapter(key.adapter)
2464
2835
  // Overlap the disk mapping-write with the network history prefetch —
@@ -2482,6 +2853,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2482
2853
  // before installing — a failed persist must fail ensureLive without
2483
2854
  // leaving a warm session behind for later inbounds to reuse.
2484
2855
  await persistPromise
2856
+ if (!isLatestCreation()) {
2857
+ await tearDownLive(live)
2858
+ throw new Error(`[channels] ${keyId}: superseded live session creation discarded`)
2859
+ }
2485
2860
  liveSessions.set(keyId, live)
2486
2861
  }
2487
2862
 
@@ -2494,29 +2869,31 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2494
2869
  live.baseContextBytes = measureTranscriptBytes(transcriptPathForBase)
2495
2870
  }
2496
2871
 
2872
+ if (!isLatestCreation()) {
2873
+ await unwindInstalledLive(keyId, live)
2874
+ throw new Error(`[channels] ${keyId}: superseded live session creation discarded`)
2875
+ }
2876
+ adoptPendingReloadHandoff(live)
2497
2877
  logger.info(`[channels] ${keyId}: ensureLive done (${phase})`)
2498
2878
  return live
2499
- })()
2879
+ })().finally(() => {
2880
+ const remaining = (activeCreationAttempts.get(keyId) ?? 1) - 1
2881
+ if (remaining > 0) activeCreationAttempts.set(keyId, remaining)
2882
+ else {
2883
+ activeCreationAttempts.delete(keyId)
2884
+ latestCreationTokens.delete(keyId)
2885
+ }
2886
+ })
2500
2887
 
2501
2888
  creating.set(keyId, promise)
2502
2889
  try {
2503
2890
  return await raceWithTimeout(promise, ensureLiveTimeoutMs, `[channels] ${keyId} ensureLive`)
2504
2891
  } catch (err) {
2505
- // The orphaned `promise` may still settle eventually; that's OK because
2506
- // the only side effect it produces post-timeout is a `liveSessions.set`,
2507
- // which the next inbound's existence-check short-circuit at the top of
2508
- // ensureLive will treat as a usable warm session — strictly better than
2509
- // a permanent silent drop. The caller (route() in this file, ultimately
2510
- // the adapter's outer catch) sees the timeout error and logs it.
2892
+ // A timed-out creation may still settle, but the durable creation token
2893
+ // discards it if a later creation has claimed ownership of this key.
2511
2894
  logger.error(`[channels] ${keyId}: ensureLive failed: ${describeError(err)}`)
2512
2895
  throw err
2513
2896
  } finally {
2514
- // Owner-checked delete: only clear the in-flight marker if it still points
2515
- // at THIS promise. A watchdog timeout can orphan a slow creation whose
2516
- // `finally` runs while a later inbound has already installed its own
2517
- // `creating` entry for the same key; an unconditional delete would drop
2518
- // that newer entry and let a third inbound cold-start a duplicate session
2519
- // (observed: 3 concurrent sessions approving the same PR).
2520
2897
  if (creating.get(keyId) === promise) creating.delete(keyId)
2521
2898
  }
2522
2899
  }
@@ -2542,6 +2919,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2542
2919
  const result = await fetchHistory(live.key.adapter, {
2543
2920
  chat: live.key.chat,
2544
2921
  thread: live.key.thread,
2922
+ ...(live.githubReviewRound !== null ? { githubReviewRound: live.githubReviewRound } : {}),
2545
2923
  limit: requested,
2546
2924
  prefetch: true,
2547
2925
  })
@@ -2749,23 +3127,23 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2749
3127
  }
2750
3128
 
2751
3129
  // After a successful `channel_reply`, the model has delivered its user-facing
2752
- // response and the turn is semantically done. pi-agent-core's loop, however,
2753
- // unconditionally makes one more LLM call after any tool result (the
2754
- // "post-tool follow-up") to let multi-step tool chains continue. On a turn
2755
- // that ended with `channel_reply` there is nothing left to say, and Fireworks'
2756
- // kimi-k2p6-turbo degenerates that empty follow-up into a 32000-token
2757
- // repetition loop (see CHANNEL_MAX_OUTPUT_TOKENS). Aborting the run's signal
2758
- // from `afterToolCall` — which runs during tool execution, before the loop
2759
- // re-enters the LLM stream — makes the follow-up stream observe an already-
2760
- // aborted signal and return `stopReason: 'aborted'` without generating. This
2761
- // is the same `agent.abort()` lever the policy-denied-send cap uses; the
2762
- // tool's own result is already persisted, so the reply still lands.
3130
+ // response and the turn is semantically done. pi-agent-core otherwise makes
3131
+ // one more LLM call after the tool result (the "post-tool follow-up") so real
3132
+ // multi-step chains can continue. On a terminal reply there is nothing left
3133
+ // to say, and Fireworks' kimi-k2p6-turbo can degenerate that empty follow-up
3134
+ // into a 32000-token repetition loop (see CHANNEL_MAX_OUTPUT_TOKENS).
3135
+ // Suppress the provider only at its next stream boundary. agent-core reaches
3136
+ // that boundary after emitting every toolResult for the batch, and
3137
+ // AgentSession preserves the event order even when extensions delay
3138
+ // persistence. In the 2026-08-28 Discord incident, aborting from afterToolCall
3139
+ // left validation looking at the preceding result as
3140
+ // `stranded_toolUse_after_send` and opened a recovery turn after an
3141
+ // already-complete reply.
2763
3142
  //
2764
3143
  // Scope is deliberately narrow: only `channel_reply` (the current-chat user-
2765
3144
  // facing response), only on success, and only for channel sessions. Read-only
2766
3145
  // tools and `channel_send` must keep the follow-up so genuine multi-step turns
2767
- // continue. A prior non-typeclaw `afterToolCall` (none today) would be
2768
- // composed, not clobbered.
3146
+ // continue. A prior non-typeclaw `afterToolCall` (none today) is composed.
2769
3147
  //
2770
3148
  // `channel_reply({ more_work_this_turn: true })` is the explicit opt-out: a
2771
3149
  // mid-turn status reply ("working on it…") that the model follows with more
@@ -2801,12 +3179,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2801
3179
  live.continueReplyTurn = { turnSeq: live.turnSeq, sendCount: live.successfulChannelSends }
2802
3180
  }
2803
3181
  }
2804
- if (succeeded && !keepTurnAlive && agent.signal?.aborted !== true && live.userStoppedTurnSeq !== live.turnSeq) {
2805
- logger.info(`[channels] ${live.keyId} terminal_after_channel_reply`)
3182
+ if (succeeded && !keepTurnAlive && live.userStoppedTurnSeq !== live.turnSeq) {
3183
+ logger.info(
3184
+ `[channels] ${live.keyId} terminal_after_channel_reply site=terminal_after_channel_reply session=${live.sessionId} reason=terminal_after_channel_reply`,
3185
+ )
2806
3186
  const replyText = (context.toolCall.arguments as { text?: unknown } | undefined)?.text
2807
- live.lastTerminalReplyAbort = typeof replyText === 'string' ? { turnSeq: live.turnSeq, text: replyText } : null
2808
- live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason: 'terminal_after_channel_reply' }
2809
- agent.abort()
3187
+ live.lastTerminalReplyCompletion = {
3188
+ turnSeq: live.turnSeq,
3189
+ ...(typeof replyText === 'string' ? { text: replyText } : {}),
3190
+ tokens: context.assistantMessage.usage.totalTokens,
3191
+ }
3192
+ live.pendingTerminalReplyStop = {
3193
+ turnSeq: live.turnSeq,
3194
+ tokens: context.assistantMessage.usage.totalTokens,
3195
+ }
2810
3196
  }
2811
3197
  return result
2812
3198
  }
@@ -2823,13 +3209,48 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2823
3209
  const installChannelOutputCap = (live: LiveSession): void => {
2824
3210
  const { agent } = live.session
2825
3211
  const inner = agent.streamFn
2826
- agent.streamFn = (model, context, options) => {
2827
- let maxTokens = options?.maxTokens
3212
+ agent.streamFn = async (model, context, streamOptions) => {
3213
+ const pendingTerminalStop = live.pendingTerminalReplyStop
3214
+ if (pendingTerminalStop?.turnSeq === live.turnSeq && live.userStoppedTurnSeq !== pendingTerminalStop.turnSeq) {
3215
+ live.pendingTerminalReplyStop = null
3216
+ live.abortReasonThisTurn = {
3217
+ turnSeq: pendingTerminalStop.turnSeq,
3218
+ reason: 'terminal_after_channel_reply',
3219
+ }
3220
+ // This boundary runs only after agent-core has emitted all toolResults
3221
+ // for the batch. Return a local aborted assistant event instead of
3222
+ // entering the provider. Its later message_end is queued behind those
3223
+ // result events; that persistence-ordered subscriber records the
3224
+ // trusted outcome and original token usage.
3225
+ const message: AssistantMessage = {
3226
+ role: 'assistant',
3227
+ content: [],
3228
+ api: model.api,
3229
+ provider: model.provider,
3230
+ model: model.id,
3231
+ usage: {
3232
+ input: 0,
3233
+ output: 0,
3234
+ cacheRead: 0,
3235
+ cacheWrite: 0,
3236
+ totalTokens: 0,
3237
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
3238
+ },
3239
+ stopReason: 'aborted',
3240
+ errorMessage: 'terminal channel reply completed',
3241
+ timestamp: Date.now(),
3242
+ }
3243
+ const stream = createAssistantMessageEventStream()
3244
+ stream.push({ type: 'start', partial: message })
3245
+ stream.push({ type: 'error', reason: 'aborted', error: message })
3246
+ return stream
3247
+ }
3248
+ let maxTokens = streamOptions?.maxTokens
2828
3249
  if (maxTokens === undefined && live.nextPromptMaxTokens !== undefined) {
2829
3250
  maxTokens = live.nextPromptMaxTokens
2830
3251
  live.nextPromptMaxTokens = undefined
2831
3252
  }
2832
- return inner(model, context, { ...options, maxTokens: maxTokens ?? CHANNEL_MAX_OUTPUT_TOKENS })
3253
+ return await inner(model, context, { ...streamOptions, maxTokens: maxTokens ?? CHANNEL_MAX_OUTPUT_TOKENS })
2833
3254
  }
2834
3255
  }
2835
3256
 
@@ -2935,7 +3356,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2935
3356
  logger.info(`[channels] ${live.keyId}: dropping todo continuation reminder after user stop`)
2936
3357
  return
2937
3358
  }
2938
- live.pendingSystemReminders.push(text)
3359
+ // Self-continuation of the SAME work episode, not external injection:
3360
+ // `qualifyingWorkThisLogicalTurn` must survive it so a follow-up reply
3361
+ // can still cite the durable work this turn already did.
3362
+ live.pendingSystemReminders.push(retryReminder(text))
2939
3363
  },
2940
3364
  })
2941
3365
  } catch (err) {
@@ -3068,6 +3492,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3068
3492
  chat: live.key.chat,
3069
3493
  ...(live.resolvedNames.chatName !== undefined ? { chatName: live.resolvedNames.chatName } : {}),
3070
3494
  thread: live.key.thread,
3495
+ ...(live.githubReviewRound !== null ? { githubReviewRound: live.githubReviewRound } : {}),
3071
3496
  ...(live.room?.parentChat !== undefined ? { parentChat: live.room.parentChat } : {}),
3072
3497
  ...(live.room?.parentChatName !== undefined ? { parentChatName: live.room.parentChatName } : {}),
3073
3498
  ...(live.currentTurnAuthorId !== null ? { lastInboundAuthorId: live.currentTurnAuthorId } : {}),
@@ -3078,6 +3503,74 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3078
3503
  }
3079
3504
  }
3080
3505
 
3506
+ const failoverGithubReviewRound = async (live: LiveSession): Promise<void> => {
3507
+ const round = live.githubReviewRound
3508
+ if (round === null || isGithubReviewRoundComplete(round)) return
3509
+ if (hasGithubReviewRoundDismissalAttempt(round)) {
3510
+ const key = githubReviewRoundKey(round)
3511
+ for (const sibling of liveSessions.values()) {
3512
+ if (sibling.githubReviewRound !== null && githubReviewRoundKey(sibling.githubReviewRound) === key) {
3513
+ persistGithubReviewRound(sibling, sibling.githubReviewRound)
3514
+ }
3515
+ }
3516
+ return
3517
+ }
3518
+ const carrierIsLive = Array.from(liveSessions.values()).some(
3519
+ (candidate) =>
3520
+ !candidate.destroyed &&
3521
+ candidate.githubReviewRound !== null &&
3522
+ githubReviewRoundKey(candidate.githubReviewRound) === githubReviewRoundKey(round) &&
3523
+ candidate.key.thread === round.carrierThread,
3524
+ )
3525
+ if (round.carrierThread !== live.key.thread && carrierIsLive) return
3526
+
3527
+ const candidates = Array.from(liveSessions.values()).filter(
3528
+ (candidate) =>
3529
+ !candidate.destroyed &&
3530
+ candidate.githubReviewRound !== null &&
3531
+ githubReviewRoundKey(candidate.githubReviewRound) === githubReviewRoundKey(round) &&
3532
+ candidate.key.thread !== round.carrierThread,
3533
+ )
3534
+ const waiter = candidates
3535
+ .filter((candidate) => canPromoteGithubReviewRoundTo(round, candidate.key.thread))
3536
+ .sort((a, b) => a.keyId.localeCompare(b.keyId))[0]
3537
+ if (waiter === undefined) {
3538
+ const state = githubReviewRoundPersistence(round)
3539
+ if (candidates.length === 0) {
3540
+ logger.warn(
3541
+ `[channels] github review round failover found no live waiter pr=${round.workspace}#${round.prNumber} head=${round.headSha} carrier=${round.carrierThread ?? 'root'}; retry the review after the round expires`,
3542
+ )
3543
+ } else {
3544
+ logger.warn(
3545
+ `[channels] github review round exhausted all candidate carriers pr=${round.workspace}#${round.prNumber} head=${round.headSha} carrier=${round.carrierThread ?? 'root'} attempted=${(state?.attemptedCarriers ?? []).map((thread) => thread ?? 'root').join(',')}; retry the review after the round expires`,
3546
+ )
3547
+ }
3548
+ return
3549
+ }
3550
+
3551
+ const promoted = promoteGithubReviewRound(round, waiter.key.thread)
3552
+ if (promoted === null) return
3553
+ for (const sibling of liveSessions.values()) {
3554
+ if (
3555
+ sibling.githubReviewRound !== null &&
3556
+ githubReviewRoundKey(sibling.githubReviewRound) === githubReviewRoundKey(round)
3557
+ ) {
3558
+ sibling.githubReviewRound = promoted
3559
+ persistGithubReviewRound(sibling, promoted)
3560
+ }
3561
+ }
3562
+ waiter.pendingSystemReminders.push(
3563
+ githubReviewRoundWakeupReminder(
3564
+ `<system-reminder>\nThe designated sibling ended without a verified formal review verdict. ` +
3565
+ `You are now the carrier for PR #${round.prNumber} at ${round.headSha.slice(0, 7)}. ` +
3566
+ `Submit exactly one formal verdict for this follow-up round before closing out your thread.\n</system-reminder>`,
3567
+ promoted,
3568
+ ),
3569
+ )
3570
+ logger.info(`[channels] ${waiter.keyId}: github review round carrier promoted`)
3571
+ if (!waiter.draining) void drain(waiter)
3572
+ }
3573
+
3081
3574
  const enqueueTodoOutcomeWrite = (
3082
3575
  live: LiveSession,
3083
3576
  args: Parameters<typeof recordTurnOutcome>[0],
@@ -3114,7 +3607,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3114
3607
 
3115
3608
  const stopCurrentChannelTurn = async (live: LiveSession): Promise<void> => {
3116
3609
  live.userStoppedTurnSeq = live.turnSeq
3117
- live.lastTerminalReplyAbort = null
3610
+ live.lastTerminalReplyCompletion = null
3611
+ live.pendingTerminalReplyStop = null
3118
3612
  live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason: 'user_stop' }
3119
3613
  if (live.debounceTimer) clearTimeout(live.debounceTimer)
3120
3614
  live.debounceTimer = null
@@ -3132,7 +3626,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3132
3626
  await stopTypingHeartbeat(live)
3133
3627
  try {
3134
3628
  await live.session.abort()
3135
- logger.info(`[channels] ${live.keyId}: command /stop aborted current turn`)
3629
+ logger.info(
3630
+ `[channels] ${live.keyId}: command /stop aborted current turn site=user_stop session=${live.sessionId} reason=user_stop`,
3631
+ )
3136
3632
  } catch (err) {
3137
3633
  logger.warn(`[channels] ${live.keyId}: command /stop abort failed: ${describeError(err)}`)
3138
3634
  }
@@ -3222,8 +3718,50 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3222
3718
  }
3223
3719
  }
3224
3720
 
3225
- const drain = async (live: LiveSession): Promise<void> => {
3226
- if (live.draining || live.destroyed) return
3721
+ // Open a new logical turn for externally-injected work that arrived without a
3722
+ // user message. Deliberately a SUBSET of the fresh-batch reset above: only
3723
+ // state whose meaning is scoped to "the episode that just ended" is cleared.
3724
+ //
3725
+ // `promisedWorkOutstandingThisLogicalTurn` is the notable survivor. A
3726
+ // completion wakeup usually exists BECAUSE the agent promised a later result,
3727
+ // and that promise is exactly what makes a silent death user-visible harm —
3728
+ // clearing it here would re-open the hole this fix closes. It is cleared
3729
+ // authoritatively by a terminal send instead.
3730
+ //
3731
+ // Author identity is restored by the caller's existing reminder branch and
3732
+ // must not be reset: role resolution for the wakeup's own channel_reply
3733
+ // depends on it. `stagedFallbackCause` and the question signals also survive —
3734
+ // a wakeup can be the recovery opportunity a staged fallback was waiting for.
3735
+ //
3736
+ // `logicalTurnStartedAt` deliberately does NOT advance here. It exists solely
3737
+ // as the boundary `isAwaitingBackgroundChild` compares a child's `startedAt`
3738
+ // against, and advancing it would hide an older SIBLING child that is still
3739
+ // running: one child's completion wake would stop counting as "awaiting", and
3740
+ // the recovery ladder, todo continuation and staged fallback would all re-fire
3741
+ // while that sibling still works — exactly the duplicate-comment failure
3742
+ // f1f36462 fixed. The wake for A must stay silent while B runs; B's own
3743
+ // completion is what ends the wait.
3744
+ const beginWakeupTurn = (live: LiveSession): void => {
3745
+ live.pendingProviderError = null
3746
+ live.consecutiveSends.clear()
3747
+ live.lastSentText.clear()
3748
+ live.lastSendLeafId = null
3749
+ // Safe to refill precisely because retry nudges are `kind: 'retry'` and
3750
+ // never reach here: the ladder this wakeup turn may itself queue cannot
3751
+ // refill its own budget, so there is no unbounded loop.
3752
+ live.emptyTurnRetries = 0
3753
+ live.toolLeakRetries = 0
3754
+ live.emptyStopAfterToolWorkArmed = false
3755
+ live.willingnessNudges = 0
3756
+ live.abortReasonThisTurn = null
3757
+ live.userStoppedTurnSeq = null
3758
+ live.nextPromptMaxTokens = undefined
3759
+ live.githubReviewOutputTurn = null
3760
+ live.toolExecutionThisLogicalTurn = false
3761
+ live.qualifyingWorkThisLogicalTurn = false
3762
+ }
3763
+
3764
+ const runDrain = async (live: LiveSession): Promise<void> => {
3227
3765
  live.draining = true
3228
3766
  try {
3229
3767
  // `!live.pendingTeardown`: once a reload marks this draining session for
@@ -3250,8 +3788,27 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3250
3788
  const observed = live.contextBuffer.splice(0, live.contextBuffer.length)
3251
3789
  const reminders = live.pendingSystemReminders.splice(0, live.pendingSystemReminders.length)
3252
3790
  live.currentTurnAttachments = collectTurnAttachments(observed, batch)
3791
+ // A reminder-only iteration carrying externally-injected work opens a
3792
+ // NEW logical turn. Without this, the completed-subagent wakeup that
3793
+ // follows a turn which spawned it inherits that turn's
3794
+ // `toolExecutionThisLogicalTurn`, and a provider failure on the wakeup
3795
+ // is misread as "the turn already ran tools, so it wasn't silent" —
3796
+ // suppressing the notice for a prompt that ran no tool and produced
3797
+ // nothing. Observed in production as a review verdict lost with zero
3798
+ // user-visible signal. Retry nudges deliberately do NOT trip this: they
3799
+ // ARE the same logical turn retrying.
3800
+ const wakeupTurn = batch.length === 0 && reminders.some((r) => r.kind === 'wakeup')
3801
+ // Gated on `!wakeupTurn` because a willingness nudge can coalesce into the
3802
+ // same iteration as a wakeup. The wakeup wins the boundary and clears the
3803
+ // nudge budget, so the willingness bookkeeping now describes a superseded
3804
+ // turn — and a legitimate NO_REPLY from the wake (a PR stand-down, say)
3805
+ // would otherwise post a bogus `no_reply_after_willingness_nudge`
3806
+ // fallback. Same defect the branch that reads this flag already guards
3807
+ // against for later unrelated reminders.
3253
3808
  live.willingnessReminderIteration =
3254
- batch.length === 0 && reminders.some((r) => r === WILLINGNESS_NUDGE || r === SEND_WILLINGNESS_NUDGE)
3809
+ !wakeupTurn &&
3810
+ batch.length === 0 &&
3811
+ reminders.some((r) => r.text === WILLINGNESS_NUDGE || r.text === SEND_WILLINGNESS_NUDGE)
3255
3812
 
3256
3813
  if (batch.length > 0) {
3257
3814
  // A fresh user batch starts a NEW logical turn. Drop any provider
@@ -3268,6 +3825,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3268
3825
  live.currentTurnAuthorIds = new Set(batch.map((m) => m.authorId))
3269
3826
  live.currentTurnReactionRef = batch[batch.length - 1]!.reactionRef ?? null
3270
3827
  const trigger = batch[batch.length - 1]!
3828
+ if (trigger.githubReviewRound !== undefined) {
3829
+ live.githubReviewRound = registerGithubReviewRound(trigger.githubReviewRound)
3830
+ }
3271
3831
  live.currentTurnExplicitlyAddressed =
3272
3832
  trigger.isDm || trigger.isBotMention || trigger.replyToBotMessageId !== null
3273
3833
  live.currentTurnTypingThread = batch[batch.length - 1]!.typingThread ?? null
@@ -3300,6 +3860,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3300
3860
  live.stagedFallbackCause = null
3301
3861
  }
3302
3862
  live.abortReasonThisTurn = null
3863
+ live.pendingTerminalReplyStop = null
3303
3864
  live.userStoppedTurnSeq = null
3304
3865
  live.nextPromptMaxTokens = undefined
3305
3866
  // Cleared with the retry budgets (NOT beside resetReviewTurn below) so a
@@ -3328,6 +3889,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3328
3889
  } else {
3329
3890
  live.currentTurnEngageReactions = []
3330
3891
  }
3892
+ // After the author-identity restore above, which a wakeup turn still needs.
3893
+ if (wakeupTurn) beginWakeupTurn(live)
3331
3894
 
3332
3895
  // Update the live origin holder so this turn's tool.before events
3333
3896
  // carry the current actor's id, and resolve the live role from it for
@@ -3343,10 +3906,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3343
3906
  adapter: live.key.adapter,
3344
3907
  loopGuardActive: live.loopGuardActive,
3345
3908
  groupChatNudge: live.multiHumanGroup,
3346
- systemReminders: reminders,
3909
+ systemReminders: reminders.map((r) => r.text),
3347
3910
  role: liveRole,
3348
3911
  })
3349
3912
 
3913
+ const repairedToolCalls = repairDanglingToolUseBranch(live.session, now())
3914
+ if (repairedToolCalls.length > 0) {
3915
+ logger.warn(
3916
+ `[channels] ${live.keyId} branch_repair=missing_tool_result session=${live.sessionId} ` +
3917
+ `count=${repairedToolCalls.length} tools=${repairedToolCalls.join(',')}`,
3918
+ )
3919
+ }
3920
+
3350
3921
  // Bracketing logs around the LLM call so a hung prompt() is
3351
3922
  // diagnosable from logs alone (we see prompting without prompted).
3352
3923
  // text length is a proxy for "did we send something at all".
@@ -3472,15 +4043,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3472
4043
  // (observe-after-engage). Leaving it only on the reply path stranded the
3473
4044
  // ack permanently on messages the agent looked at but never answered.
3474
4045
  const dropDone = dropEngageReactions(live, engageAddPromises)
3475
- // A DELIBERATE silent turn (skip_response / NO_REPLY) leaves a
3476
- // PERSISTENT :eyes: acking "seen, intentionally not replying". On a
3477
- // typing-less adapter it reuses the same message/emoji/actor as the
3478
- // transient engage :eyes:, and adapters that collapse that into one
3479
- // toggle would let a still-in-flight engage removal strip the ack — so
3480
- // the silent path AWAITS every engage removal reaching the adapter
3481
- // before adding the persistent one. Only silent turns pay that wait:
3482
- // normal/reply turns keep the engage drop fire-and-forget (`void`), so
3483
- // turn-end never blocks on the reaction API off the silent path.
4046
+ // A turn whose output landed outside the channel or was deferred to a
4047
+ // background child leaves a persistent :eyes:. On a typing-less adapter
4048
+ // it reuses the transient engage reaction's message/emoji/actor, so wait
4049
+ // for that removal to reach the adapter before adding the persistent one.
3484
4050
  if (live.silentAckTurn?.turnSeq === live.turnSeq) await dropDone
3485
4051
  else void dropDone
3486
4052
  reactOnSilentAck(live)
@@ -3530,6 +4096,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3530
4096
  if (!isAwaitingBackgroundChild(live, 'staged-fallback')) {
3531
4097
  await resolveStagedFallback(live)
3532
4098
  }
4099
+ const logicalTurnStillOpen =
4100
+ live.pendingSystemReminders.length > 0 ||
4101
+ live.stagedFallbackCause !== null ||
4102
+ live.promisedWorkOutstandingThisLogicalTurn
4103
+ if (!logicalTurnStillOpen) await failoverGithubReviewRound(live)
3533
4104
  live.lastTurnAuthorIds = new Set(live.currentTurnAuthorIds)
3534
4105
  if (live.currentTurnAuthorId !== null) {
3535
4106
  live.lastTurnAuthorId = live.currentTurnAuthorId
@@ -3567,9 +4138,47 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3567
4138
  const carriedInbounds = live.promptQueue.splice(0, live.promptQueue.length)
3568
4139
  const carriedObserved = live.contextBuffer.splice(0, live.contextBuffer.length)
3569
4140
  const carriedReminders = live.pendingSystemReminders.splice(0, live.pendingSystemReminders.length)
4141
+ const hasCarriedWork = carriedInbounds.length > 0 || carriedObserved.length > 0 || carriedReminders.length > 0
4142
+ const retained =
4143
+ hasCarriedWork && retainReloadHandoff(live.key, carriedInbounds, carriedObserved, carriedReminders)
3570
4144
  liveSessions.delete(live.keyId)
3571
4145
  await tearDownLive(live)
3572
- await handOffToSuccessor(live.key, carriedInbounds, carriedObserved, carriedReminders)
4146
+ if (retained) await handOffToSuccessor(live.key)
4147
+ }
4148
+ }
4149
+
4150
+ // No-op while a drain already owns the session: that loop re-checks both
4151
+ // queues every iteration, so work landing behind it is picked up without a
4152
+ // second concurrent drain. Registers the running invocation on `activeDrains`
4153
+ // so `settleDrains` can await a turn started fire-and-forget.
4154
+ const drain = (live: LiveSession): Promise<void> => {
4155
+ if (live.draining || live.destroyed) return Promise.resolve()
4156
+ const running = runDrain(live)
4157
+ // Attaching this handler marks `running` handled, so a drain-tail throw can
4158
+ // no longer reach the runtime's unhandled-rejection reporter — every
4159
+ // production call site is `void drain(live)` and catches nothing. Log it
4160
+ // here so the failure stays visible rather than disappearing into the
4161
+ // tracking. The settlement copy must still RESOLVE: `settleDrains` waits on
4162
+ // unrelated turns too, and one failed drain must not reject a waiter that
4163
+ // has nothing to do with it. Callers keep `running`, so an awaiting caller
4164
+ // still sees the original rejection.
4165
+ const settled = running.then(
4166
+ () => undefined,
4167
+ (err: unknown) => {
4168
+ logger.error(`[channels] ${live.keyId}: drain failed: ${describeError(err)}`)
4169
+ },
4170
+ )
4171
+ live.activeDrains.add(settled)
4172
+ void settled.then(() => live.activeDrains.delete(settled))
4173
+ return running
4174
+ }
4175
+
4176
+ // Resolves once no drain is running. Loops because a drain's post-`draining`
4177
+ // tail can start a rival, and because work queued during one turn opens the
4178
+ // next; a snapshot `Promise.all` would return with that successor in flight.
4179
+ const settleDrains = async (live: LiveSession): Promise<void> => {
4180
+ while (live.activeDrains.size > 0) {
4181
+ await Promise.all(live.activeDrains)
3573
4182
  }
3574
4183
  }
3575
4184
 
@@ -3579,33 +4188,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3579
4188
  // were enqueued while draining), so they are transplanted straight onto the
3580
4189
  // fresh session's queues rather than re-routed through route() — re-routing
3581
4190
  // would re-run the claim/command/permission gates and re-derive engagement
3582
- // from a lossy QueuedInbound projection. Best-effort: a recreate failure logs
3583
- // and drops the batch rather than throwing out of the predecessor's drain.
3584
- const handOffToSuccessor = async (
3585
- key: ChannelKey,
3586
- inbounds: QueuedInbound[],
3587
- observed: ObservedInbound[],
3588
- reminders: string[],
3589
- ): Promise<void> => {
3590
- // Observed context alone is carried too: observe() can buffer post-reload
3591
- // messages onto contextBuffer with no queued prompt, and dropping them would
3592
- // lose the successor's "recent context". Only skip when nothing at all was
3593
- // carried.
3594
- if (inbounds.length === 0 && reminders.length === 0 && observed.length === 0) return
3595
- let successor: LiveSession
4191
+ // from a lossy QueuedInbound projection. The batch is retained BEFORE the
4192
+ // recreate attempt so a timeout leaves it available to the next successful
4193
+ // ensureLive rather than dropping the user's messages at the handoff seam.
4194
+ const handOffToSuccessor = async (key: ChannelKey): Promise<void> => {
3596
4195
  try {
3597
- successor = await ensureLive(key)
4196
+ await ensureLive(key)
3598
4197
  } catch (err) {
3599
- logger.warn(`[channels] ${channelKeyId(key)}: successor recreate after reload failed: ${describeError(err)}`)
3600
- return
4198
+ logger.warn(
4199
+ `[channels] ${channelKeyId(key)}: successor recreate after reload failed; queued work retained for the next successful session: ${describeError(err)}`,
4200
+ )
3601
4201
  }
3602
- if (successor.destroyed) return
3603
- successor.promptQueue.push(...inbounds)
3604
- successor.contextBuffer.push(...observed)
3605
- successor.pendingSystemReminders.push(...reminders)
3606
- // Observed-only context is NOT a turn trigger — it waits on contextBuffer for
3607
- // a real inbound. Drain only when there is actual work (a prompt or reminder).
3608
- if ((inbounds.length > 0 || reminders.length > 0) && !successor.draining) void drain(successor)
3609
4202
  }
3610
4203
 
3611
4204
  const scheduleDebouncedDrain = (live: LiveSession): void => {
@@ -3911,6 +4504,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3911
4504
  workspace: event.workspace,
3912
4505
  chat: event.chat,
3913
4506
  thread: event.thread,
4507
+ ...(event.room?.parentChat !== undefined ? { parentChat: event.room.parentChat } : {}),
3914
4508
  lastInboundAuthorId: event.authorId,
3915
4509
  })
3916
4510
 
@@ -4014,9 +4608,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4014
4608
  replyToBotMessageId: event.replyToBotMessageId,
4015
4609
  isDm: event.isDm,
4016
4610
  ...(event.typingThread !== undefined ? { typingThread: event.typingThread } : {}),
4611
+ ...(event.githubReviewRound !== undefined ? { githubReviewRound: event.githubReviewRound } : {}),
4017
4612
  receivedAt: now(),
4018
4613
  ts: event.ts,
4019
4614
  })
4615
+ if (event.githubReviewRound !== undefined) {
4616
+ live.githubReviewRound = registerGithubReviewRound(event.githubReviewRound)
4617
+ persistGithubReviewRound(live, live.githubReviewRound)
4618
+ }
4020
4619
  // Make the typing anchor live BEFORE startTypingHeartbeat fires (route()
4021
4620
  // starts the heartbeat right after enqueue, ahead of drain). drain() later
4022
4621
  // refreshes it to the last inbound of a coalesced batch.
@@ -4177,7 +4776,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4177
4776
  // its persistent :eyes: is added strictly AFTER the transient one is removed
4178
4777
  // (see reactOnSilentAck). Fire-and-forget callers just `void` the result.
4179
4778
  const dropEngageReactions = (live: LiveSession, addPromises: Array<Promise<ReactionRef | null>>): Promise<void> => {
4180
- return Promise.all(addPromises.map((addPromise) => dropOneEngageReaction(live, addPromise))).then(() => undefined)
4779
+ return Promise.all(addPromises.map((addPromise) => dropOneEngageReaction(live.key, addPromise))).then(
4780
+ () => undefined,
4781
+ )
4181
4782
  }
4182
4783
 
4183
4784
  // Only the LAST engaging inbound of a coalesced batch should carry the eager
@@ -4192,29 +4793,35 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4192
4793
  void dropEngageReactions(live, addPromises)
4193
4794
  }
4194
4795
 
4195
- const dropOneEngageReaction = (live: LiveSession, addPromise: Promise<ReactionRef | null>): Promise<void> => {
4796
+ const dropPendingReloadHandoffEngageReactions = (pending: PendingReloadHandoff): Promise<void> => {
4797
+ const addPromises = pending.inbounds.flatMap((item) =>
4798
+ item.engageReaction !== undefined ? [item.engageReaction] : [],
4799
+ )
4800
+ for (const item of pending.inbounds) delete item.engageReaction
4801
+ return Promise.all(addPromises.map((addPromise) => dropOneEngageReaction(pending.key, addPromise))).then(
4802
+ () => undefined,
4803
+ )
4804
+ }
4805
+
4806
+ const dropOneEngageReaction = (key: ChannelKey, addPromise: Promise<ReactionRef | null>): Promise<void> => {
4196
4807
  return addPromise
4197
4808
  .then((reactionRef) => {
4198
4809
  if (reactionRef === null) return undefined
4199
4810
  return removeReaction({
4200
- adapter: live.key.adapter,
4201
- workspace: live.key.workspace,
4202
- chat: live.key.chat,
4203
- thread: live.key.thread,
4811
+ adapter: key.adapter,
4812
+ workspace: key.workspace,
4813
+ chat: key.chat,
4814
+ thread: key.thread,
4204
4815
  reactionRef,
4205
4816
  })
4206
4817
  })
4207
4818
  .then((result) => {
4208
4819
  if (result && !result.ok && result.code !== 'unsupported' && result.code !== 'not-found') {
4209
- logger.info(
4210
- `[channels] engage-unreact failed adapter=${live.key.adapter} chat=${live.key.chat}: ${result.error}`,
4211
- )
4820
+ logger.info(`[channels] engage-unreact failed adapter=${key.adapter} chat=${key.chat}: ${result.error}`)
4212
4821
  }
4213
4822
  })
4214
4823
  .catch((err) => {
4215
- logger.info(
4216
- `[channels] engage-unreact threw adapter=${live.key.adapter} chat=${live.key.chat}: ${describeError(err)}`,
4217
- )
4824
+ logger.info(`[channels] engage-unreact threw adapter=${key.adapter} chat=${key.chat}: ${describeError(err)}`)
4218
4825
  })
4219
4826
  }
4220
4827
 
@@ -4657,6 +5264,35 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4657
5264
  accountingTarget.thread === (msg.thread ?? null)
4658
5265
  const keyId = channelKeyId(accountingTarget)
4659
5266
  const live = liveSessions.get(keyId)
5267
+ // Credit sticky where the reply was PUBLISHED, not where it was accounted.
5268
+ // The two diverge when a caller answers from one sub-surface but publishes
5269
+ // to another in the same room — `postDuplicateRequestChangesComment` sends
5270
+ // with `thread: null` while passing the review-thread session as
5271
+ // `accountingTarget`. An inbound is keyed from its OWN tuple, so the human's
5272
+ // follow-up consumes the root key and finds nothing: the reply was observed
5273
+ // and silently dropped.
5274
+ //
5275
+ // Delivery-only, not both. A dual grant cannot be undone atomically —
5276
+ // `clearSticky` clears one key, so `channel_disengage` on the originating
5277
+ // thread would strand the root credit. It also buys nothing here: GitHub
5278
+ // review-comment inbounds set `suppressSticky`, so they never reach the
5279
+ // sticky gate and engage via `replyToBotMessageId` instead.
5280
+ //
5281
+ // Same adapter/workspace/chat only. `targets` are authors of the ACCOUNTING
5282
+ // turn and author ids are namespaced per adapter, so redirecting a genuine
5283
+ // cross-channel send would credit ids that cannot appear in that room.
5284
+ const stickyGrantKeyId =
5285
+ !deliveryMatchesAccounting &&
5286
+ accountingTarget.adapter === msg.adapter &&
5287
+ accountingTarget.workspace === msg.workspace &&
5288
+ accountingTarget.chat === msg.chat
5289
+ ? channelKeyId({
5290
+ adapter: msg.adapter,
5291
+ workspace: msg.workspace,
5292
+ chat: msg.chat,
5293
+ thread: msg.thread ?? null,
5294
+ })
5295
+ : keyId
4660
5296
  const sendKey = consecutiveSendKey(accountingTarget.chat, accountingTarget.thread)
4661
5297
  // Tool-source sends consume the captured quote candidate exactly
4662
5298
  // once per turn — the intervening-observed check runs HERE against
@@ -4722,7 +5358,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4722
5358
  const count = (live.policyDeniedToolSendsThisTurn.get(sendKey) ?? 0) + 1
4723
5359
  live.policyDeniedToolSendsThisTurn.set(sendKey, count)
4724
5360
  if (count >= MAX_POLICY_DENIED_CHANNEL_SENDS_PER_TURN) {
4725
- logger.warn(`[channels] ${live.keyId}: aborting turn — ${count} policy-denied channel sends (last: ${code})`)
5361
+ logger.warn(
5362
+ `[channels] ${live.keyId}: aborting turn — ${count} policy-denied channel sends (last: ${code}) site=policy_denied_send_cap session=${live.sessionId} reason=policy_denied:${code}`,
5363
+ )
4726
5364
  live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason: `policy_denied:${code}` }
4727
5365
  if (live.session.agent.signal?.aborted !== true) live.session.agent.abort()
4728
5366
  }
@@ -4867,7 +5505,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4867
5505
  }
4868
5506
  }
4869
5507
  if (targets.size > 0) {
4870
- grantStickyForReplyTargets(stickyLedger, keyId, Array.from(targets), adapterConfig.engagement, now())
5508
+ grantStickyForReplyTargets(
5509
+ stickyLedger,
5510
+ stickyGrantKeyId,
5511
+ Array.from(targets),
5512
+ adapterConfig.engagement,
5513
+ now(),
5514
+ )
4871
5515
  }
4872
5516
  }
4873
5517
  const turnCount = live.consecutiveSends.get(sendKey) ?? 0
@@ -4887,24 +5531,64 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4887
5531
  }
4888
5532
  }
4889
5533
 
4890
- // The turn ended via the terminal-reply abort. If that reply promised to keep
5534
+ // The turn ended via terminal channel_reply completion. If that reply promised to keep
4891
5535
  // working but omitted `more_work_this_turn: true`, queue ONE reminder-only re-prompt so
4892
- // the model gets a second chance to actually do it. The abort already fired
4893
- // (safe default preserved); this only adds an optional nudge. Bounded by
5536
+ // the model gets a second chance to actually do it. The tool batch already
5537
+ // terminated (safe default preserved); this only adds an optional nudge. Bounded by
4894
5538
  // MAX_WILLINGNESS_NUDGES and gated on `promptQueue` being empty so a real
4895
5539
  // inbound that coalesced into this turn is never answered with a stale nudge.
4896
5540
  const maybeNudgeContinuationWillingness = (live: LiveSession): void => {
4897
- const record = live.lastTerminalReplyAbort
4898
- live.lastTerminalReplyAbort = null
5541
+ const record = live.lastTerminalReplyCompletion
5542
+ live.lastTerminalReplyCompletion = null
4899
5543
  if (record === null || record.turnSeq !== live.turnSeq) return
4900
5544
  if (live.willingnessNudges >= MAX_WILLINGNESS_NUDGES) return
4901
5545
  if (live.promptQueue.length > 0) return
5546
+ if (record.text === undefined) return
4902
5547
  if (!detectContinuationWillingness(record.text)) return
4903
5548
  live.willingnessNudges++
4904
5549
  logger.info(
4905
5550
  `[channels] ${live.keyId} willingness_nudge attempt=${live.willingnessNudges}/${MAX_WILLINGNESS_NUDGES}`,
4906
5551
  )
4907
- live.pendingSystemReminders.push(WILLINGNESS_NUDGE)
5552
+ live.pendingSystemReminders.push(retryReminder(WILLINGNESS_NUDGE))
5553
+ }
5554
+
5555
+ const armRetainedOutputAckIfEligible = (
5556
+ live: LiveSession,
5557
+ successfulSendsBeforePrompt: number,
5558
+ explicitlySkipped: boolean,
5559
+ ): boolean => {
5560
+ // A formal GitHub review is user-facing output delivered outside the channel.
5561
+ // Preserve its acknowledgement even when the model closes the turn through
5562
+ // skip_response after publishing the review.
5563
+ if (
5564
+ live.githubReviewOutputTurn === live.turnSeq &&
5565
+ live.successfulChannelSends === successfulSendsBeforePrompt &&
5566
+ live.currentTurnAuthorId !== null
5567
+ ) {
5568
+ logger.info(`[channels] ${live.keyId} empty_turn_suppressed cause=github_review_output_this_turn`)
5569
+ armSilentTurnAck(live, 'github_review_output')
5570
+ return true
5571
+ }
5572
+
5573
+ // An active child means delivery is deferred rather than dropped. Normally a
5574
+ // completed prose leaf still goes through reply recovery, but skip_response is
5575
+ // authoritative: its prose is intentionally discarded, while the progress
5576
+ // acknowledgement must remain until the child reports back.
5577
+ const awaitLeaf = recoverableAssistantText(live.session)
5578
+ const awaitLeafIsUnfinishedToolUse = awaitLeaf?.source === 'mid-turn' || awaitLeaf?.source === 'pre-tool'
5579
+ if (
5580
+ live.currentTurnAuthorId !== null &&
5581
+ (explicitlySkipped ||
5582
+ awaitLeaf === null ||
5583
+ awaitLeafIsUnfinishedToolUse ||
5584
+ endsWithNoReplySignal(awaitLeaf.text)) &&
5585
+ isAwaitingBackgroundChild(live, 'empty_turn_recovery')
5586
+ ) {
5587
+ logger.info(`[channels] ${live.keyId} empty_turn_suppressed cause=awaiting_background_child`)
5588
+ armSilentTurnAck(live, 'awaiting_background_child')
5589
+ return true
5590
+ }
5591
+ return false
4908
5592
  }
4909
5593
 
4910
5594
  const validateChannelTurn = async (live: LiveSession, successfulSendsBeforePrompt: number): Promise<void> => {
@@ -4924,8 +5608,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4924
5608
  if (live.skippedTurn !== null && live.skippedTurn.turnSeq === live.turnSeq && !skipContested) {
4925
5609
  const { reason } = live.skippedTurn
4926
5610
  live.skippedTurn = null
5611
+ armRetainedOutputAckIfEligible(live, successfulSendsBeforePrompt, true)
4927
5612
  logger.info(`[channels] ${live.keyId} skipped_by_tool reason=${JSON.stringify(reason)}`)
4928
- armSilentTurnAck(live, 'skip_response')
4929
5613
  void dropContinuationReactions(live)
4930
5614
  return
4931
5615
  }
@@ -4939,49 +5623,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4939
5623
  live.stagedFallbackCause = { cause, sendCountAtStage: live.successfulChannelSends }
4940
5624
  }
4941
5625
 
4942
- // A formal GitHub review already landed this logical turn (APPROVE /
4943
- // REQUEST_CHANGES / COMMENT, stamped via noteGithubReviewOutput). That review IS
4944
- // the turn's user-facing output — it just went through the GitHub review API, not
4945
- // channel_reply/channel_send, so `successfulChannelSends` never moved. An empty
4946
- // completion afterward is the agent legitimately having nothing more to say, NOT
4947
- // a dead turn: skip the empty-turn retries AND the "I got stuck" fallback and
4948
- // treat it as silent completion. Gated on no channel send this turn so a turn
4949
- // that ALSO replied in-channel still runs the normal reply-recovery below.
4950
- if (
4951
- live.githubReviewOutputTurn === live.turnSeq &&
4952
- live.successfulChannelSends === successfulSendsBeforePrompt &&
4953
- live.currentTurnAuthorId !== null
4954
- ) {
4955
- logger.info(`[channels] ${live.keyId} empty_turn_suppressed cause=github_review_output_this_turn`)
4956
- armSilentTurnAck(live, 'github_review_output')
4957
- return
4958
- }
4959
-
4960
- // A background child spawned by this session is still running, and the turn
4961
- // produced no user-facing output. That is `spawn_subagent`'s contract being
4962
- // honored ("you will receive a system-reminder when it completes"), not the
4963
- // empty-completion degeneration every branch below exists to repair — so the
4964
- // recovery ladder must not manufacture the status prose the model
4965
- // deliberately withheld. Each nudge re-enters with the child STILL running,
4966
- // so the budgets stack (MAX_EMPTY_TURN_RETRIES + MAX_WILLINGNESS_NUDGES) into
4967
- // several "still working…" messages for one request; on GitHub, where a
4968
- // channel reply IS a public PR comment, that shipped as duplicate review
4969
- // acknowledgements. The completion reminder re-wakes this session with the
4970
- // real result, so silence here is delivery deferred, not delivery dropped.
4971
- // Bounded by the same stuck-child backstop as GC/rollover: a wedged child
4972
- // stops pinning and the normal ladder resumes. A leaf carrying real text is
4973
- // deliberately NOT covered — recovering an answer the model already wrote is
4974
- // still correct while a child runs.
4975
5626
  const awaitLeaf = recoverableAssistantText(live.session)
4976
- if (
4977
- live.currentTurnAuthorId !== null &&
4978
- (awaitLeaf === null || endsWithNoReplySignal(awaitLeaf.text)) &&
4979
- isAwaitingBackgroundChild(live, 'empty_turn_recovery')
4980
- ) {
4981
- logger.info(`[channels] ${live.keyId} empty_turn_suppressed cause=awaiting_background_child`)
4982
- armSilentTurnAck(live, 'awaiting_background_child')
4983
- return
4984
- }
5627
+ if (armRetainedOutputAckIfEligible(live, successfulSendsBeforePrompt, false)) return
4985
5628
 
4986
5629
  // Suppress a leaked tool call (never post the plumbing) and, while budget
4987
5630
  // remains, push a self-correction reminder so the same logical turn
@@ -4995,7 +5638,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4995
5638
  `[channels] ${live.keyId}: suppressed plain_text_tool_call_leak (nudge ` +
4996
5639
  `attempt=${live.toolLeakRetries}/${MAX_TOOL_LEAK_RETRIES}) text_len=${leakedText.length}`,
4997
5640
  )
4998
- live.pendingSystemReminders.push(TOOL_CALL_LEAK_NUDGE)
5641
+ live.pendingSystemReminders.push(retryReminder(TOOL_CALL_LEAK_NUDGE))
4999
5642
  return
5000
5643
  }
5001
5644
  logger.warn(
@@ -5004,6 +5647,49 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5004
5647
  )
5005
5648
  }
5006
5649
 
5650
+ const retryStrandedToolUse = async (cause: string, exhaustedCause: string): Promise<void> => {
5651
+ if (live.emptyTurnRetries < MAX_EMPTY_TURN_RETRIES) {
5652
+ live.emptyTurnRetries++
5653
+ const routerAbortReason =
5654
+ live.abortReasonThisTurn !== null && live.abortReasonThisTurn.turnSeq === live.turnSeq
5655
+ ? live.abortReasonThisTurn.reason
5656
+ : undefined
5657
+ const agentAbortReason =
5658
+ live.session.agent.signal?.aborted === true ? live.session.getAbortReason?.() : undefined
5659
+ const abortReason = routerAbortReason ?? agentAbortReason ?? 'unknown'
5660
+ logger.warn(
5661
+ `[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
5662
+ `cause=${cause} abort_reason=${abortReason}`,
5663
+ )
5664
+ live.pendingSystemReminders.push(retryReminder(STRANDED_TOOLUSE_CONTINUATION_NUDGE))
5665
+ return
5666
+ }
5667
+ await postEmptyTurnFallback(live, exhaustedCause)
5668
+ }
5669
+
5670
+ // A real asker who received nothing cannot distinguish unfinished tool-use
5671
+ // narration from a completed answer. Posting that scratchpad can falsely
5672
+ // claim completion in the wrong language or before the tool result is
5673
+ // interpreted; treating it as deliberate silence strands the asker instead.
5674
+ // Keep both textless and text-bearing unfinished shapes on the established
5675
+ // bounded continuation ladder, while explicit NO_REPLY, queued fresh input,
5676
+ // observation-only turns, and every earlier delivery-deferred guard retain
5677
+ // their narrower silence contracts.
5678
+ const unfinishedToolUse = awaitLeaf
5679
+ const unfinishedToolUseWithoutReply =
5680
+ unfinishedToolUse !== null &&
5681
+ (unfinishedToolUse.source === 'mid-turn' || unfinishedToolUse.source === 'pre-tool') &&
5682
+ (unfinishedToolUse.text.trim() === '' || !endsWithNoReplySignal(unfinishedToolUse.text))
5683
+ if (
5684
+ unfinishedToolUseWithoutReply &&
5685
+ live.successfulChannelSends === successfulSendsBeforePrompt &&
5686
+ live.currentTurnAuthorId !== null &&
5687
+ live.promptQueue.length === 0
5688
+ ) {
5689
+ await retryStrandedToolUse('stranded_toolUse_without_send', 'stranded_toolUse_without_send_retries_exhausted')
5690
+ return
5691
+ }
5692
+
5007
5693
  // A send landed this turn, but the model may have posted a `more_work_this_turn: true`
5008
5694
  // progress reply, kept working, then ENDED with its final answer as plain
5009
5695
  // prose — never calling a channel tool again. The terminal-reply abort fires
@@ -5015,6 +5701,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5015
5701
  // the send is narration the model emitted with/before the reply that already
5016
5702
  // landed — suppress it, as before.
5017
5703
  if (live.successfulChannelSends > successfulSendsBeforePrompt) {
5704
+ const terminalReplyCompletedThisTurn = live.lastTerminalReplyCompletion?.turnSeq === live.turnSeq
5018
5705
  maybeNudgeContinuationWillingness(live)
5019
5706
 
5020
5707
  // A `channel_reply({ more_work_this_turn: true })` progress ack landed this turn (the
@@ -5051,7 +5738,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5051
5738
  `[channels] ${live.keyId} send_willingness_nudge attempt=${live.willingnessNudges}/${MAX_WILLINGNESS_NUDGES} ` +
5052
5739
  `cause=empty_stop_after_continue_reply`,
5053
5740
  )
5054
- live.pendingSystemReminders.push(SEND_WILLINGNESS_NUDGE)
5741
+ live.pendingSystemReminders.push(retryReminder(SEND_WILLINGNESS_NUDGE))
5055
5742
  } else {
5056
5743
  stageEmptyTurnFallback('empty_stop_after_continue_reply_nudges_exhausted')
5057
5744
  }
@@ -5062,7 +5749,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5062
5749
  // then an EMPTY `stop` leaf: the model computed the answer in its reasoning
5063
5750
  // / tool results but never sent it (the Kimi/Fireworks empty-completion
5064
5751
  // flake). `maybeNudgeContinuationWillingness` above can't catch this — it
5065
- // reads `lastTerminalReplyAbort`, which only a `channel_reply` sets;
5752
+ // reads `lastTerminalReplyCompletion`, which only a `channel_reply` sets;
5066
5753
  // `channel_send` keeps the turn alive and stamps nothing. And the
5067
5754
  // stranded-toolUse retry below requires `source !== 'leaf'`, but an empty
5068
5755
  // `stop` leaf recovers as `source: 'leaf'`, so this shape would otherwise
@@ -5087,13 +5774,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5087
5774
  `[channels] ${live.keyId} send_willingness_nudge attempt=${live.willingnessNudges}/${MAX_WILLINGNESS_NUDGES} ` +
5088
5775
  `cause=empty_stop_after_send_ack`,
5089
5776
  )
5090
- live.pendingSystemReminders.push(SEND_WILLINGNESS_NUDGE)
5777
+ live.pendingSystemReminders.push(retryReminder(SEND_WILLINGNESS_NUDGE))
5091
5778
  } else {
5092
5779
  stageEmptyTurnFallback('empty_stop_after_send_ack_nudges_exhausted')
5093
5780
  }
5094
5781
  return
5095
5782
  }
5096
5783
 
5784
+ // A terminal channel_reply now ends the SDK tool batch with
5785
+ // ToolResult.terminate after its matching result is persisted. The leaf
5786
+ // therefore has the same toolResult-under-toolUse shape as genuinely
5787
+ // stranded post-status work, but this turn already delivered its final
5788
+ // answer and explicitly terminated. The 2026-08-28 Discord incident
5789
+ // crossed this distinction: validation re-prompted the completed turn as
5790
+ // `stranded_toolUse_after_send`, then subsequent inbounds accumulated on
5791
+ // the failed recovery branch. Keep willingness nudges queued above, but do
5792
+ // not send terminal completion through stranded-work recovery.
5793
+ if (terminalReplyCompletedThisTurn) return
5794
+
5097
5795
  const trailing = recoverableAssistantText(live.session)
5098
5796
  if (trailing === null || trailing.source !== 'leaf') {
5099
5797
  // A `more_work_this_turn: true` status reply landed, then the turn stranded on an
@@ -5111,29 +5809,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5111
5809
  // that accompanied the already-landed reply); only the no-prose strand
5112
5810
  // gets a retry-or-fallback.
5113
5811
  if (leafIsStrandedToolUse(live.session) && live.currentTurnAuthorId !== null) {
5114
- if (live.emptyTurnRetries < MAX_EMPTY_TURN_RETRIES) {
5115
- live.emptyTurnRetries++
5116
- const routerAbortReason =
5117
- live.abortReasonThisTurn !== null && live.abortReasonThisTurn.turnSeq === live.turnSeq
5118
- ? live.abortReasonThisTurn.reason
5119
- : undefined
5120
- const agentAbortReason =
5121
- live.session.agent.signal?.aborted === true ? live.session.getAbortReason?.() : undefined
5122
- const abortReason = routerAbortReason ?? agentAbortReason ?? 'unknown'
5123
- logger.warn(
5124
- `[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
5125
- `cause=stranded_toolUse_after_send abort_reason=${abortReason}`,
5126
- )
5127
- live.pendingSystemReminders.push(STRANDED_TOOLUSE_CONTINUATION_NUDGE)
5128
- } else {
5129
- await postEmptyTurnFallback(live, 'stranded_toolUse_retries_exhausted')
5130
- }
5812
+ await retryStrandedToolUse('stranded_toolUse_after_send', 'stranded_toolUse_retries_exhausted')
5131
5813
  }
5132
5814
  return
5133
5815
  }
5134
5816
  if (live.session.sessionManager.getLeafEntry()?.id === live.lastSendLeafId) return
5135
5817
  }
5136
5818
 
5819
+ if (unfinishedToolUseWithoutReply) {
5820
+ logger.info(`[channels] ${live.keyId} empty_turn_suppressed cause=unfinished_toolUse_continuation_ineligible`)
5821
+ return
5822
+ }
5823
+
5137
5824
  let candidate = recoverableAssistantText(live.session)
5138
5825
  // A `length` leaf is recovered ONLY when stripping leaked `<think>…</think>`
5139
5826
  // spans actually removed something AND leaves a postable reply. The removal
@@ -5239,7 +5926,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5239
5926
  `[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
5240
5927
  `max_tokens=${live.nextPromptMaxTokens ?? CHANNEL_MAX_OUTPUT_TOKENS}`,
5241
5928
  )
5242
- live.pendingSystemReminders.push(EMPTY_TURN_RETRY_NUDGE)
5929
+ live.pendingSystemReminders.push(retryReminder(EMPTY_TURN_RETRY_NUDGE))
5243
5930
  return
5244
5931
  }
5245
5932
  await postEmptyTurnFallback(live, attemptedSendThisTurn ? 'send_thrash' : 'retries_exhausted')
@@ -5274,7 +5961,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5274
5961
  `[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
5275
5962
  `cause=cold_start_solo_bare_empty`,
5276
5963
  )
5277
- live.pendingSystemReminders.push(COLD_START_REPLY_NUDGE)
5964
+ live.pendingSystemReminders.push(retryReminder(COLD_START_REPLY_NUDGE))
5278
5965
  return
5279
5966
  }
5280
5967
  await postEmptyTurnFallback(live, 'cold_start_solo_bare_empty_retries_exhausted')
@@ -5310,7 +5997,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5310
5997
  `[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
5311
5998
  `cause=empty_stop_after_tool_work`,
5312
5999
  )
5313
- live.pendingSystemReminders.push(EMPTY_STOP_AFTER_TOOL_WORK_NUDGE)
6000
+ live.pendingSystemReminders.push(retryReminder(EMPTY_STOP_AFTER_TOOL_WORK_NUDGE))
5314
6001
  return
5315
6002
  }
5316
6003
  await postEmptyTurnFallback(live, 'empty_stop_after_tool_work_retries_exhausted')
@@ -5331,7 +6018,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5331
6018
  }
5332
6019
  const leakedReasoning = !isNoReplySignal(assistantText)
5333
6020
  logger.info(`[channels] ${live.keyId} no_reply${leakedReasoning ? ' (with_leaked_reasoning)' : ''}`)
5334
- armSilentTurnAck(live, 'no_reply')
5335
6021
  void dropContinuationReactions(live)
5336
6022
  return
5337
6023
  }
@@ -5377,7 +6063,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5377
6063
  logger.warn(
5378
6064
  `[channels] ${live.keyId}: suppressed plain_text_tool_call_leak (silent) text_len=${assistantText.length}`,
5379
6065
  )
5380
- armSilentTurnAck(live, 'skip_response_text_leak')
5381
6066
  return
5382
6067
  }
5383
6068
  if (plainTextToolCallKind === 'suppress-warn') {
@@ -5413,21 +6098,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5413
6098
  assistantText = extracted
5414
6099
  }
5415
6100
 
5416
- // `source` distinguishes the three recovery shapes for log triage:
6101
+ // `source` distinguishes the completed recovery shapes for log triage:
5417
6102
  // - 'leaf': the assistant message IS the leaf with stopReason 'stop'
5418
6103
  // (existing behavior; model ended its turn with text but forgot to
5419
6104
  // call channel_reply).
5420
- // - 'mid-turn': the assistant message IS the leaf with stopReason
5421
- // 'toolUse'; the model narrated a reply, committed to a tool plan, and
5422
- // the turn ended before a follow-up that would have called a channel
5423
- // tool was persisted. The narration is the only user-facing text.
5424
- // - 'pre-tool': the leaf is a toolResult (or other non-assistant entry)
5425
- // and the assistant message lives upstream in the branch. This is the
5426
- // Kimi-on-Fireworks `kimi-k2p6-turbo` failure mode where the post-tool
5427
- // follow-up LLM call never produced a persisted assistant message, so
5428
- // the model's pre-tool commentary is the only user-facing text we have.
5429
- // Recovering it means the user gets *something* — strictly better than
5430
- // the historical silent drop.
6105
+ // - 'length-leaf': the assistant message hit the output cap, leaked
6106
+ // reasoning was stripped, and a complete-looking answer survived.
6107
+ // Unfinished 'mid-turn' / 'pre-tool' prose never reaches this egress: the
6108
+ // terminal gate above either continues an eligible turn or preserves the
6109
+ // silence contract that made continuation ineligible.
5431
6110
  // Egress-level GitHub review guards. The false-receipt and re-review
5432
6111
  // stranding guards live inside the channel_reply / channel_send tool
5433
6112
  // handlers, but recovery surfaces trailing assistant prose through a
@@ -5574,8 +6253,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5574
6253
  live.unsubTodoOutcome?.()
5575
6254
  live.unsubTodoOutcome = null
5576
6255
  await stopTypingHeartbeat(live)
6256
+ // Captured before the abort call: `draining` flips false in drain()'s own
6257
+ // finally once the turn it was guarding ends, so reading it here is the
6258
+ // only reliable signal that this teardown cut off a turn actually in
6259
+ // flight rather than an already-idle session.
6260
+ const abortedInFlightTurn = live.draining
5577
6261
  try {
5578
6262
  await live.session.abort()
6263
+ if (abortedInFlightTurn) {
6264
+ logger.warn(`[channels] ${live.keyId} abort site=teardown session=${live.sessionId} reason=teardown`)
6265
+ }
5579
6266
  } catch (err) {
5580
6267
  logger.warn(`[channels] abort failed for ${live.keyId}: ${describeError(err)}`)
5581
6268
  }
@@ -5595,6 +6282,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5595
6282
  }
5596
6283
 
5597
6284
  const runIdleGc = async (): Promise<void> => {
6285
+ await expirePendingReloadHandoffs()
5598
6286
  const t = now()
5599
6287
  const victims: LiveSession[] = []
5600
6288
  for (const live of liveSessions.values()) {
@@ -5629,6 +6317,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5629
6317
  if (gcTimer) clearInterval(gcTimer)
5630
6318
  gcTimer = null
5631
6319
  liveGeneration++
6320
+ const pendingHandoffs = Array.from(pendingReloadHandoffs.values())
6321
+ pendingReloadHandoffs.clear()
6322
+ for (const pending of pendingHandoffs) {
6323
+ await reportDiscardedReloadHandoff(pending, 'router stopped before replay could complete')
6324
+ }
5632
6325
  const all = Array.from(liveSessions.values())
5633
6326
  liveSessions.clear()
5634
6327
  for (const live of all) {
@@ -5690,6 +6383,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5690
6383
  )
5691
6384
  await live.session
5692
6385
  .abort()
6386
+ .then(() => {
6387
+ logger.warn(
6388
+ `[channels] ${live.keyId} abort site=graceful_restart session=${live.sessionId} reason=graceful_restart`,
6389
+ )
6390
+ })
5693
6391
  .catch((err) => logger.error(`[channels] graceful-restart abort failed: ${describeError(err)}`))
5694
6392
  }
5695
6393
  }
@@ -5865,7 +6563,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5865
6563
  // either way. Still skip the generic synthetic wake.
5866
6564
  if (reservation.sawInbound) {
5867
6565
  if (handoff.interruptedSubagents !== undefined && handoff.interruptedSubagents.length > 0) {
5868
- live.pendingSystemReminders.push(buildInterruptedSubagentNotice(handoff.interruptedSubagents))
6566
+ live.pendingSystemReminders.push(
6567
+ wakeupReminder(buildInterruptedSubagentNotice(handoff.interruptedSubagents)),
6568
+ )
5869
6569
  logger.info(
5870
6570
  `[channels] ${keyId}: restart-resume coalesced with a real inbound; delivering interrupted-subagent notice`,
5871
6571
  )
@@ -5886,7 +6586,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5886
6586
  logger.error(`[channels] ${keyId}: restart-resume clear abort suppression failed: ${describeError(err)}`),
5887
6587
  )
5888
6588
 
5889
- live.pendingSystemReminders.push(buildRestartResumeWakeReminder(handoff.interruptedSubagents))
6589
+ live.pendingSystemReminders.push(wakeupReminder(buildRestartResumeWakeReminder(handoff.interruptedSubagents)))
5890
6590
  logger.info(`[channels] ${keyId}: restart-resume waking session ${live.sessionId}`)
5891
6591
  void drain(live)
5892
6592
  },
@@ -5932,6 +6632,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5932
6632
  workspace: key.workspace,
5933
6633
  chat: key.chat,
5934
6634
  thread: key.thread,
6635
+ ...(options.parentChat !== undefined ? { parentChat: options.parentChat } : {}),
5935
6636
  lastInboundAuthorId: options.invokerId,
5936
6637
  }
5937
6638
  if (!permissions.has(partial, requiredPermission)) {
@@ -5947,9 +6648,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5947
6648
  if (resolved.kind === 'ambiguous') {
5948
6649
  return { kind: 'ambiguous', matchCount: resolved.count }
5949
6650
  }
5950
- // A resolved session that isn't actually running has nothing for /stop to
5951
- // cancel; report it as no-live-session so bystander agents stay silent.
5952
- if (lowered === 'stop' && !hasStoppableWork(resolved.session)) {
6651
+ // Slack broadcasts slash commands to every installed app, so an idle
6652
+ // fallback/observe-only session must stay silent instead of claiming it
6653
+ // stopped work. Discord interactions are delivered only to the selected
6654
+ // application, and its exact channel key is authoritative even between
6655
+ // prompts. In the 2026-08-28 incident, one exact Discord session consumed
6656
+ // 14 messages into a no-assistant-output branch; each prompt ended in
6657
+ // ~53ms, so /stop landed while `draining`, queues, and reminders were all
6658
+ // empty and incorrectly reported no-live-session. Always pass that exact
6659
+ // session to stopCurrentChannelTurn so the user's escape hatch remains.
6660
+ const exactDiscordSession = key.adapter === 'discord-bot' && resolved.session.keyId === channelKeyId(key)
6661
+ if (lowered === 'stop' && !exactDiscordSession && !hasStoppableWork(resolved.session)) {
5953
6662
  return { kind: 'no-live-session' }
5954
6663
  }
5955
6664
  live = resolved.session
@@ -5994,7 +6703,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5994
6703
  channel: true,
5995
6704
  adapter,
5996
6705
  })
5997
- live.pendingSystemReminders.push(text)
6706
+ live.pendingSystemReminders.push(wakeupReminder(text))
5998
6707
  // The reminder tells the agent to fetch this result now; clear the
5999
6708
  // subagent_output window so an earlier premature-polling streak can't
6000
6709
  // hard-block that legitimate fetch.
@@ -6048,7 +6757,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6048
6757
  const injectPrVerdictActivity = (args: {
6049
6758
  workspace: string
6050
6759
  prNumber: number
6051
- verdict: 'APPROVE' | 'REQUEST_CHANGES'
6760
+ verdict: ReviewRoundOutcome
6052
6761
  sessionId: string
6053
6762
  }): { kind: 'delivered'; count: number } => {
6054
6763
  const chat = `pr:${args.prNumber}`
@@ -6061,7 +6770,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6061
6770
  // stand down from its own legitimate review.
6062
6771
  if (live.sessionId === args.sessionId) continue
6063
6772
  const text = renderPrVerdictStandDownReminder({ prNumber: args.prNumber, verdict: args.verdict })
6064
- live.pendingSystemReminders.push(text)
6773
+ live.pendingSystemReminders.push(wakeupReminder(text))
6065
6774
  logger.info(`[channels] ${live.keyId}: pr-verdict stand-down queued pr=${chat} verdict=${args.verdict}`)
6066
6775
  if (!live.draining) void drain(live)
6067
6776
  count++
@@ -6069,6 +6778,162 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6069
6778
  return { kind: 'delivered', count }
6070
6779
  }
6071
6780
 
6781
+ const completeRoundForVerifiedVerdict = async (args: {
6782
+ workspace: string
6783
+ prNumber: number
6784
+ verdict: ReviewRoundOutcome
6785
+ sessionId: string
6786
+ }): Promise<{ kind: 'completed' | 'no-round' }> => {
6787
+ const chat = `pr:${args.prNumber}`
6788
+ const publisher = Array.from(liveSessions.values()).find(
6789
+ (live) =>
6790
+ !live.destroyed &&
6791
+ live.sessionId === args.sessionId &&
6792
+ live.key.adapter === 'github' &&
6793
+ live.key.workspace === args.workspace &&
6794
+ live.key.chat === chat &&
6795
+ live.githubReviewRound !== null,
6796
+ )
6797
+ const persistedPublisher = mappings?.find(
6798
+ (record) =>
6799
+ record.sessionId === args.sessionId &&
6800
+ record.adapter === 'github' &&
6801
+ record.workspace === args.workspace &&
6802
+ record.chat === chat &&
6803
+ record.githubReviewRound !== undefined,
6804
+ )
6805
+ const round = publisher?.githubReviewRound ?? persistedPublisher?.githubReviewRound
6806
+ if (round === null || round === undefined) {
6807
+ const resetRound = resetGithubReviewRoundCompletionForPr(args.workspace, args.prNumber)
6808
+ if (resetRound !== null) persistMatchingGithubReviewRound(resetRound)
6809
+ logger.warn(
6810
+ `[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: no publisher session with round state session=${args.sessionId}`,
6811
+ )
6812
+ return { kind: 'no-round' }
6813
+ }
6814
+
6815
+ const activeRound = registerGithubReviewRound(round)
6816
+ if (activeRound === null) {
6817
+ logger.warn(
6818
+ `[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: round expired`,
6819
+ )
6820
+ return { kind: 'no-round' }
6821
+ }
6822
+ const publisherThread = publisher?.key.thread ?? persistedPublisher?.thread ?? null
6823
+ if (activeRound.carrierThread !== publisherThread) {
6824
+ resetGithubReviewRoundCompletion(activeRound)
6825
+ persistMatchingGithubReviewRound(activeRound)
6826
+ logger.warn(
6827
+ `[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: publisher thread=${publisherThread ?? 'root'} is not carrier=${activeRound.carrierThread ?? 'root'}`,
6828
+ )
6829
+ return { kind: 'no-round' }
6830
+ }
6831
+ if (!(await validateGithubReviewRound(activeRound))) {
6832
+ resetGithubReviewRoundCompletion(activeRound)
6833
+ persistMatchingGithubReviewRound(activeRound)
6834
+ logger.warn(
6835
+ `[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: head mismatch or unavailable expected=${activeRound.headSha}`,
6836
+ )
6837
+ return { kind: 'no-round' }
6838
+ }
6839
+ completeGithubReviewRound(activeRound)
6840
+ const key = githubReviewRoundKey(round)
6841
+ for (const live of liveSessions.values()) {
6842
+ if (live.githubReviewRound === null || githubReviewRoundKey(live.githubReviewRound) !== key) continue
6843
+ live.pendingSystemReminders = live.pendingSystemReminders.filter(
6844
+ (reminder) => reminder.githubReviewRoundKey !== key,
6845
+ )
6846
+ live.githubReviewRound = activeRound
6847
+ }
6848
+ persistMatchingGithubReviewRound(activeRound)
6849
+ replayPendingRoundCloseouts(activeRound)
6850
+ logger.info(`[channels] github review round completed pr=${chat} verdict=${args.verdict}`)
6851
+ return { kind: 'completed' }
6852
+ }
6853
+
6854
+ // Round state must reach every session carrying the round, not only the ones
6855
+ // currently live. An idle-GC'd or not-yet-reopened sibling keeps its persisted
6856
+ // `pending` record, and reopening it restores that stale status over the
6857
+ // completed one, re-arming failover and permitting a second blocking review.
6858
+ const persistMatchingGithubReviewRound = (round: GithubReviewFollowupRound): void => {
6859
+ if (mappings === null) return
6860
+ const key = githubReviewRoundKey(round)
6861
+ const state = githubReviewRoundPersistence(round)
6862
+ let changed = false
6863
+ for (const [idx, record] of mappings.entries()) {
6864
+ if (record.githubReviewRound === undefined) continue
6865
+ if (githubReviewRoundKey(record.githubReviewRound) !== key) continue
6866
+ if (state === null) {
6867
+ const { githubReviewRound: _expired, ...rest } = record
6868
+ void _expired
6869
+ mappings[idx] = rest
6870
+ } else {
6871
+ mappings[idx] = { ...record, githubReviewRound: { ...round, ...state } }
6872
+ }
6873
+ changed = true
6874
+ }
6875
+ if (changed) void persist()
6876
+ }
6877
+
6878
+ // A close-out can land while completion is still awaiting head validation, so
6879
+ // `finishGithubReviewRoundCloseout` sees a pending round and returns without
6880
+ // clearing. Nothing else retries it, which would strand round metadata on the
6881
+ // session and reject its later verdicts — so the close-out is recorded and
6882
+ // replayed here once the round actually completes.
6883
+ const replayPendingRoundCloseouts = (round: GithubReviewFollowupRound): void => {
6884
+ const key = githubReviewRoundKey(round)
6885
+ for (const live of liveSessions.values()) {
6886
+ if (live.pendingGithubReviewRoundCloseout !== key) continue
6887
+ live.pendingGithubReviewRoundCloseout = null
6888
+ finishGithubReviewRoundCloseout({
6889
+ sessionId: live.sessionId,
6890
+ workspace: live.key.workspace,
6891
+ prNumber: Number(live.key.chat.slice('pr:'.length)),
6892
+ thread: live.key.thread ?? null,
6893
+ })
6894
+ }
6895
+ }
6896
+
6897
+ const finishGithubReviewRoundCloseout = (args: {
6898
+ sessionId: string
6899
+ workspace: string
6900
+ prNumber: number
6901
+ thread: string | null
6902
+ }): void => {
6903
+ const chat = `pr:${args.prNumber}`
6904
+ const live = Array.from(liveSessions.values()).find(
6905
+ (candidate) =>
6906
+ !candidate.destroyed &&
6907
+ candidate.sessionId === args.sessionId &&
6908
+ candidate.key.adapter === 'github' &&
6909
+ candidate.key.workspace === args.workspace &&
6910
+ candidate.key.chat === chat &&
6911
+ candidate.key.thread === args.thread,
6912
+ )
6913
+ if (live?.githubReviewRound === null || live?.githubReviewRound === undefined) return
6914
+ const round = live.githubReviewRound
6915
+ if (!isGithubReviewRoundComplete(round)) {
6916
+ live.pendingGithubReviewRoundCloseout = githubReviewRoundKey(round)
6917
+ return
6918
+ }
6919
+ live.pendingGithubReviewRoundCloseout = null
6920
+ live.githubReviewRound = null
6921
+ persistGithubReviewRound(live, null)
6922
+ const stillReferenced =
6923
+ Array.from(liveSessions.values()).some(
6924
+ (candidate) =>
6925
+ candidate.githubReviewRound !== null &&
6926
+ githubReviewRoundKey(candidate.githubReviewRound) === githubReviewRoundKey(round),
6927
+ ) ||
6928
+ (mappings?.some(
6929
+ (record) =>
6930
+ record.githubReviewRound !== undefined &&
6931
+ githubReviewRoundKey(record.githubReviewRound) === githubReviewRoundKey(round),
6932
+ ) ??
6933
+ false)
6934
+ if (!stillReferenced) forgetGithubReviewRound(round)
6935
+ }
6936
+
6072
6937
  // Stamp the review-output flag on the session that just landed a formal GitHub
6073
6938
  // review this turn. Matched by sessionId (the recorder records the exact
6074
6939
  // event.sessionId), and confirmed to be the right github PR live session so a
@@ -6161,11 +7026,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6161
7026
  }
6162
7027
 
6163
7028
  const armSilentTurnAck = (live: LiveSession, reason: SilentAckReason): void => {
6164
- // A GitHub review IS its own emoji-shaped output, so it always earns the
6165
- // 👀; every other deliberate silence earns one ONLY when the triggering
6166
- // message was addressed to the bot. Staying quiet in ambient chatter leaves
6167
- // no mark, so a busy room never accumulates stale 👀 on messages the bot
6168
- // was never part of.
7029
+ // A GitHub review is user-facing output, so it always earns the 👀; deferred
7030
+ // background work earns one only when the triggering message addressed the
7031
+ // bot. Ambient chatter stays unmarked.
6169
7032
  const eligible =
6170
7033
  reason === 'github_review_output' ? live.key.adapter === 'github' : live.currentTurnExplicitlyAddressed
6171
7034
  if (!eligible) return
@@ -6205,8 +7068,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6205
7068
  }
6206
7069
 
6207
7070
  // Retire every persistent silent-ack :eyes: outstanding in this live session
6208
- // once the agent posts a genuine reply — the "seen, not replying" mark is now
6209
- // contradicted. Snapshot-and-clear the promise array BEFORE awaiting, so a
7071
+ // once the agent posts a genuine reply. Snapshot-and-clear the promise array
7072
+ // BEFORE awaiting, so a
6210
7073
  // concurrent later silent turn appending a fresh add is never swept by this
6211
7074
  // in-flight cleanup. Each entry is AWAITED to its resolved ref before removal,
6212
7075
  // so an add still in flight when the reply lands is still retired. Failures are
@@ -6361,6 +7224,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6361
7224
  getSelfAliases: computeSelfAliases,
6362
7225
  injectSubagentCompletionReminder,
6363
7226
  injectPrVerdictActivity,
7227
+ completeGithubReviewRound: completeRoundForVerifiedVerdict,
7228
+ finishGithubReviewRoundCloseout,
6364
7229
  noteGithubReviewOutput,
6365
7230
  markTurnSkipped,
6366
7231
  clearSticky,
@@ -6372,15 +7237,39 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6372
7237
  writeInterruptedSubagentHandoff,
6373
7238
  liveCount: () => liveSessions.size,
6374
7239
  __testing: {
7240
+ githubReviewRoundFor: (key: ChannelKey) => liveSessions.get(channelKeyId(key))?.githubReviewRound,
7241
+ pendingReminderCount: (key: ChannelKey) => liveSessions.get(channelKeyId(key))?.pendingSystemReminders.length,
7242
+ creationTokenCount: () => latestCreationTokens.size,
6375
7243
  flushDebounce: async (key: ChannelKey) => {
6376
- const live = liveSessions.get(channelKeyId(key))
7244
+ const keyId = channelKeyId(key)
7245
+ let live = liveSessions.get(keyId)
6377
7246
  if (!live) return
6378
7247
  if (live.debounceTimer) {
6379
7248
  clearTimeout(live.debounceTimer)
6380
7249
  live.debounceTimer = null
6381
7250
  }
6382
7251
  live.firstUnprocessedAt = 0
6383
- await drain(live)
7252
+ // Settle a drain that is ALREADY in flight before starting our own, then
7253
+ // again after. `drain()` no-ops while one owns the session, so a
7254
+ // fire-and-forget `void drain(live)` raised elsewhere — the restart-resume
7255
+ // lost-work notice, a promoted review carrier, a subagent-completion wake —
7256
+ // would still be mid-turn when this returned, and the caller would assert
7257
+ // on a prompt that has not landed. Same defect shape as the `persist()`
7258
+ // race below: this seam has to mean "settled", not "started".
7259
+ //
7260
+ // Re-resolved by key each round because settling is not a property of one
7261
+ // object: a deferred reload teardown drops this session mid-drain and
7262
+ // `handOffToSuccessor` replays the carried work onto a REPLACEMENT live
7263
+ // session with its own `activeDrains`. Watching only the session captured
7264
+ // at entry would return with the successor's prompt still in flight.
7265
+ for (;;) {
7266
+ await settleDrains(live)
7267
+ await drain(live)
7268
+ await settleDrains(live)
7269
+ const current = liveSessions.get(keyId)
7270
+ if (current === undefined || current === live) break
7271
+ live = current
7272
+ }
6384
7273
  // Settle the fire-and-forget `void persist()` from scheduleDebouncedDrain
6385
7274
  // (the lastInboundAt write). Draining alone doesn't await that promise, so
6386
7275
  // a test reading sessions.json right after would race the disk write — the
@@ -6445,7 +7334,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6445
7334
  injectContinuationReminder: (key: ChannelKey, text: string): void => {
6446
7335
  const live = liveSessions.get(channelKeyId(key))
6447
7336
  if (!live) return
6448
- live.pendingSystemReminders.push(text)
7337
+ live.pendingSystemReminders.push(retryReminder(text))
6449
7338
  },
6450
7339
  enqueueUserInbound: (key: ChannelKey, event: InboundMessage): void => {
6451
7340
  const live = liveSessions.get(channelKeyId(key))
@@ -7229,27 +8118,19 @@ async function raceWithTimeout<T>(work: Promise<T>, ms: number, label: string):
7229
8118
  // Observed against claude on a channel turn that fell silent (2026-06-12).
7230
8119
  //
7231
8120
  // - source: 'mid-turn'
7232
- // The leaf IS an assistant message with `stopReason === 'toolUse'` that
7233
- // carries visible text. The model narrated a user-facing reply ("on it,
7234
- // bumping to 16x now") AND committed to a tool plan in the same message,
7235
- // but the turn ended before any follow-up assistant message that would
7236
- // have called `channel_reply` was persisted — the upstream pi-agent-core
7237
- // loop's post-tool follow-up never landed, or the run was aborted
7238
- // mid-loop. The model treated its visible prose as ambient narration; in
7239
- // a channel session that prose is dead text. Recovers it so the user gets
7240
- // the reply the model thought it had already given. Observed against
7241
- // Fireworks' `kimi-k2p6-turbo` on KakaoTalk: the agent posted speed-change
7242
- // status as narration, kept taking screenshots, and the user saw nothing.
7243
- // This is the leaf-is-assistant twin of the 'pre-tool' shape below.
8121
+ // The leaf IS an assistant message with `stopReason === 'toolUse'`. Its
8122
+ // visible text, if any, is unfinished narration rather than a trustworthy
8123
+ // answer because the planned tool work never reached a follow-up assistant
8124
+ // message. The caller uses this source to enter bounded continuation rather
8125
+ // than publishing the narration.
7244
8126
  //
7245
8127
  // - source: 'pre-tool'
7246
8128
  // The leaf is a `toolResult` and the immediately-prior assistant message
7247
8129
  // has `stopReason === 'toolUse'` (it called the tool that produced this
7248
8130
  // toolResult). The upstream pi-agent-core loop SHOULD have made a
7249
8131
  // follow-up LLM call after the tool returned, but that call either never
7250
- // happened or produced no persisted message. Recovers the assistant's
7251
- // pre-tool commentary so the user gets *something* — observed against
7252
- // Fireworks' `accounts/fireworks/routers/kimi-k2p6-turbo` on 2026-05-26.
8132
+ // happened or produced no persisted message. The caller treats the
8133
+ // assistant's commentary as unfinished and enters bounded continuation.
7253
8134
  //
7254
8135
  // Returns null when no recovery is appropriate:
7255
8136
  // - No leaf, no messages in branch, branch is malformed
@@ -7272,9 +8153,8 @@ function recoverableAssistantText(
7272
8153
  if (leaf.message.stopReason === 'stop') {
7273
8154
  return { text: visibleAssistantText(leaf.message), source: 'leaf' }
7274
8155
  }
7275
- // The model committed to a tool plan but its visible prose never reached
7276
- // the channel and no follow-up message that would have called a channel
7277
- // tool was persisted. Recover the stranded prose.
8156
+ // Preserve the unfinished shape for the caller's continuation ladder; its
8157
+ // prose is not a final answer and must not be published directly.
7278
8158
  if (leaf.message.stopReason === 'toolUse') {
7279
8159
  return { text: visibleAssistantText(leaf.message), source: 'mid-turn' }
7280
8160
  }
@@ -7305,7 +8185,9 @@ function recoverableAssistantText(
7305
8185
  if (!parent) return null
7306
8186
  if (parent.type === 'message') {
7307
8187
  if (parent.message.role === 'assistant') {
7308
- return { text: visibleAssistantText(parent.message), source: 'pre-tool' }
8188
+ return parent.message.stopReason === 'toolUse'
8189
+ ? { text: visibleAssistantText(parent.message), source: 'pre-tool' }
8190
+ : null
7309
8191
  }
7310
8192
  if (parent.message.role === 'user') return null
7311
8193
  }
@@ -7364,6 +8246,57 @@ function leafIsStrandedToolUse(session: AgentSession): boolean {
7364
8246
  return false
7365
8247
  }
7366
8248
 
8249
+ // Permanently close a trailing tool batch whose assistant toolUse has one or
8250
+ // more missing results. PR #1386 could recognize this shape and re-prompt, but
8251
+ // the 2026-08-28 Discord fingerprint showed the poisoned branch rejecting each
8252
+ // retry in ~53ms before provider generation: 15 user entries accumulated with
8253
+ // no assistant entry until idle rollover. Append-only error results preserve
8254
+ // the full conversation and any completed sibling results while making both
8255
+ // the live Agent state and persisted SessionManager branch valid again.
8256
+ function repairDanglingToolUseBranch(session: AgentSession, timestamp: number): string[] {
8257
+ const branch = session.sessionManager.getBranch?.()
8258
+ if (!branch) return []
8259
+ const messages = branch.filter(
8260
+ (entry): entry is Extract<SessionEntry, { type: 'message' }> => entry.type === 'message',
8261
+ )
8262
+ if (messages.length === 0) return []
8263
+
8264
+ const completed = new Set<string>()
8265
+ let index = messages.length - 1
8266
+ while (index >= 0) {
8267
+ const message = messages[index]!.message
8268
+ if (message.role !== 'toolResult') break
8269
+ completed.add(message.toolCallId)
8270
+ index--
8271
+ }
8272
+
8273
+ const assistantEntry = messages[index]
8274
+ if (!assistantEntry || assistantEntry.message.role !== 'assistant') return []
8275
+ if (assistantEntry.message.stopReason !== 'toolUse') return []
8276
+ const missing = assistantEntry.message.content.filter(
8277
+ (block): block is Extract<(typeof assistantEntry.message.content)[number], { type: 'toolCall' }> =>
8278
+ block.type === 'toolCall' && !completed.has(block.id),
8279
+ )
8280
+ if (missing.length === 0) return []
8281
+
8282
+ const repairedMessages: ToolResultMessage[] = missing.map((toolCall) => ({
8283
+ role: 'toolResult',
8284
+ toolCallId: toolCall.id,
8285
+ toolName: toolCall.name,
8286
+ content: [
8287
+ {
8288
+ type: 'text',
8289
+ text: 'Tool execution was interrupted before its result was recorded. Continue from the preserved conversation without assuming the tool succeeded.',
8290
+ },
8291
+ ],
8292
+ isError: true,
8293
+ timestamp,
8294
+ }))
8295
+ for (const message of repairedMessages) session.sessionManager.appendMessage(message)
8296
+ session.agent.state.messages = [...session.agent.state.messages, ...repairedMessages]
8297
+ return missing.map((toolCall) => toolCall.name)
8298
+ }
8299
+
7367
8300
  // The turn-end leaf is a FRESH empty `stop` — an assistant message with no visible
7368
8301
  // text and no tool call, distinct from the leaf in place at the last successful
7369
8302
  // send. "Fresh" (`!== lastSendLeafId`) is what separates a post-send degeneration