@qwen-code/channel-github 0.26.8-nightly.20261105.7bd78683e6 → 0.26.9

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.
@@ -532,7 +532,9 @@ function isInboundTaskRecord(value) {
532
532
  (record.deferCount === undefined ||
533
533
  (Number.isSafeInteger(record.deferCount) && record.deferCount >= 0)) &&
534
534
  (record.backpressure === undefined ||
535
- typeof record.backpressure === 'boolean'));
535
+ typeof record.backpressure === 'boolean') &&
536
+ (record.lostSessionId === undefined ||
537
+ typeof record.lostSessionId === 'string'));
536
538
  }
537
539
  class FinalPublicationError extends Error {
538
540
  }
@@ -784,6 +786,14 @@ export class GithubChannel extends PollingChannelBase {
784
786
  * recovery keeps running.
785
787
  */
786
788
  watchReconcileBlocked = false;
789
+ /**
790
+ * The cause the blocking watch-guard row last named. The row is
791
+ * edge-triggered per CAUSE, not just per blocked window: a pending backlog
792
+ * that turns into an unreadable sidecar (or back) must re-journal, or the
793
+ * timeline keeps naming a remedy that no longer applies. Cleared on the
794
+ * recovery edge.
795
+ */
796
+ watchReconcileBlockedCause;
787
797
  /**
788
798
  * Consecutive binding-refresh failures since the last success. While no
789
799
  * snapshot has ever succeeded, the cold-start gate defers the comment lane,
@@ -795,6 +805,16 @@ export class GithubChannel extends PollingChannelBase {
795
805
  boundSnapshotFailureStreak = 0;
796
806
  prWatchState = { version: 1, entries: {} };
797
807
  prWatchStateLoaded = false;
808
+ /**
809
+ * Message keys that already have a durable dead-letter record, lazily
810
+ * loaded from the never-rotated dead-letter file on first use and kept
811
+ * current as this process appends. The file is the overflow retire's commit
812
+ * point: a head with a record is never re-appended — even across a restart,
813
+ * which empties this cache and reloads it from disk — and never delivered;
814
+ * the drain completes its retire instead. Watch keys are unique per
815
+ * episode, so a record can only match the same transition.
816
+ */
817
+ deadLetteredKeys;
798
818
  inboundRecoveryPending = true;
799
819
  recoverableInboundTasks = 0;
800
820
  /**
@@ -1434,13 +1454,30 @@ export class GithubChannel extends PollingChannelBase {
1434
1454
  if (this.prWatchEvents.size > 0) {
1435
1455
  try {
1436
1456
  await this.reconcilePendingWatch();
1457
+ const wasBlocked = this.watchReconcileBlocked;
1437
1458
  this.watchReconcileBlocked = false;
1459
+ this.watchReconcileBlockedCause = undefined;
1460
+ // The clearing edge is the recovery signal. A `poll` / `ok` row is
1461
+ // not: the base writes one after every poll that does not throw,
1462
+ // including every poll of a sustained outage, so it is present
1463
+ // throughout the degraded window and cannot mark its end.
1464
+ if (wasBlocked) {
1465
+ this.recordPollDegraded('watch_reconcile_recovered');
1466
+ }
1438
1467
  }
1439
1468
  catch (err) {
1440
1469
  // Recovery must not deliver accepted watch tasks while their pending
1441
1470
  // records are unreconciled (a later drain would deliver them again).
1442
1471
  this.watchReconcileBlocked = true;
1443
- process.stderr.write(`[Channel:${this.name}] pending watch reconciliation failed, will retry next poll: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
1472
+ const message = sanitizeLogText(err instanceof Error ? err.message : String(err), 200);
1473
+ process.stderr.write(`[Channel:${this.name}] pending watch reconciliation failed, will retry next poll: ${message}\n`);
1474
+ // Edge-triggered per cause: this catch runs on EVERY poll while the
1475
+ // watch state stays unreadable, so a per-poll row would rotate the
1476
+ // journal — but a cause that CHANGES while blocked must re-journal.
1477
+ if (this.watchReconcileBlockedCause !== 'reconcile_failed') {
1478
+ this.recordPollDegraded('watch_reconcile_blocked', undefined, message);
1479
+ this.watchReconcileBlockedCause = 'reconcile_failed';
1480
+ }
1444
1481
  }
1445
1482
  }
1446
1483
  else {
@@ -1448,6 +1485,19 @@ export class GithubChannel extends PollingChannelBase {
1448
1485
  // still own their accepted tasks: recovery must not deliver and
1449
1486
  // remove a task that a later re-enabled drain would claim and
1450
1487
  // deliver again. Keep the guard until no watch pending remains.
1488
+ //
1489
+ // Classify the cause first. hasUnreconciledWatchPending() is fail-closed
1490
+ // on a read error, so an unreadable sidecar also blocks recovery — but
1491
+ // reporting that as a pending backlog names a remedy (re-enable
1492
+ // subscriptions) that cannot clear it. The gate below is unchanged.
1493
+ let watchStateError;
1494
+ try {
1495
+ this.loadPrWatchState();
1496
+ }
1497
+ catch (err) {
1498
+ watchStateError = sanitizeLogText(err instanceof Error ? err.message : String(err), 200);
1499
+ }
1500
+ const wasBlocked = this.watchReconcileBlocked;
1451
1501
  this.watchReconcileBlocked = this.hasUnreconciledWatchPending();
1452
1502
  if (this.watchReconcileBlocked) {
1453
1503
  // Park the legacy watch tasks as backpressure so they stop
@@ -1472,7 +1522,27 @@ export class GithubChannel extends PollingChannelBase {
1472
1522
  catch {
1473
1523
  // Task store unreadable/unwritable: fail closed, retry next poll.
1474
1524
  }
1475
- process.stderr.write(`[Channel:${this.name}] watch subscriptions are disabled but pending watch events remain unreconciled; watch task recovery stays blocked until subscriptions are re-enabled and the pending events reconcile (legacy watch tasks parked as backpressure so the notification cursor keeps flowing)\n`);
1525
+ process.stderr.write(`[Channel:${this.name}] watch subscriptions are disabled but pending watch events remain unreconciled; watch task recovery stays blocked until subscriptions are re-enabled and the pending events reconcile (legacy watch tasks parked as backpressure so the notification cursor keeps flowing)${watchStateError ? ` — the watch state is also unreadable, which alone blocks recovery: ${watchStateError}` : ''}\n`);
1526
+ // Edge-triggered per cause, for the same reason as the reconcile
1527
+ // failure above: this branch runs on every poll until an operator
1528
+ // re-enables watch, but a backlog that turns into a read error (or
1529
+ // back) must re-journal so the row never names a stale remedy.
1530
+ const cause = watchStateError ? 'read_error' : 'pending';
1531
+ if (this.watchReconcileBlockedCause !== cause) {
1532
+ if (watchStateError) {
1533
+ this.recordPollDegraded('watch_reconcile_blocked', undefined, watchStateError);
1534
+ }
1535
+ else {
1536
+ this.recordPollDegraded('watch_pending_unreconciled');
1537
+ }
1538
+ this.watchReconcileBlockedCause = cause;
1539
+ }
1540
+ }
1541
+ else {
1542
+ this.watchReconcileBlockedCause = undefined;
1543
+ if (wasBlocked) {
1544
+ this.recordPollDegraded('watch_reconcile_recovered');
1545
+ }
1476
1546
  }
1477
1547
  }
1478
1548
  // The watch pass runs before generic recovery so detection cannot race
@@ -1530,7 +1600,12 @@ export class GithubChannel extends PollingChannelBase {
1530
1600
  this.coldEmptyPartialStreak < MAX_COLD_EMPTY_PARTIAL_POLLS) {
1531
1601
  if (this.coldEmptyPartialStreak === 1 ||
1532
1602
  this.coldEmptyPartialStreak % 10 === 0) {
1533
- process.stderr.write(`[Channel:${this.name}] binding snapshot is an empty partial (${this.coldEmptyPartialStreak}/${MAX_COLD_EMPTY_PARTIAL_POLLS} cold polls): the comment lane stays deferred until a complete or non-empty snapshot arrives, so no event is misrouted publicly.\n`);
1603
+ process.stderr.write(`[Channel:${this.name}] binding snapshot is an empty partial (${this.coldEmptyPartialStreak}/${MAX_COLD_EMPTY_PARTIAL_POLLS} cold binding scans): the comment lane stays deferred until a complete or non-empty snapshot arrives, so no event is misrouted publicly.\n`);
1604
+ // This gate returns before the comment lane sets its poll detail, so
1605
+ // the degraded row is the ONLY journal trace of a stalled cold start.
1606
+ this.recordPollDegraded('bindings_cold_empty', {
1607
+ streak: this.coldEmptyPartialStreak,
1608
+ });
1534
1609
  }
1535
1610
  return;
1536
1611
  }
@@ -2311,6 +2386,23 @@ export class GithubChannel extends PollingChannelBase {
2311
2386
  // incomplete evidence.
2312
2387
  this.applyTaskDedupe(dedupe);
2313
2388
  process.stderr.write(`[Channel:${this.name}] event ${envelope.messageId} matched no role's boundSessionActions; retiring without public fallback\n`);
2389
+ // Retired before any task was claimed, so there is no task row to
2390
+ // close: the skip is the event's only journal trace. The dedupe cursor
2391
+ // is still in memory here — the base saves it after pollOnce returns —
2392
+ // so this row is at-least-once: if that cursor write fails or the daemon
2393
+ // dies first, the notification re-lists and the same event may produce a
2394
+ // second identical skip row.
2395
+ this.recordChannelEvent({
2396
+ type: 'inbound',
2397
+ outcome: 'skipped',
2398
+ reason: 'no_role_matched',
2399
+ triggerKind: parseTriggerKind(envelope.metadata),
2400
+ repository: envelope.chatId,
2401
+ thread: envelope.threadId,
2402
+ number: issueNumber,
2403
+ messageId: envelope.messageId,
2404
+ actor: envelope.senderId,
2405
+ });
2314
2406
  return true;
2315
2407
  }
2316
2408
  const task = this.claimInboundTask(envelope, issueNumber, dedupe);
@@ -2432,6 +2524,9 @@ export class GithubChannel extends PollingChannelBase {
2432
2524
  // (private-only), so they share the no-charge running transition.
2433
2525
  this.transitionInboundTask(task.id, 'running', bound || isWatch ? {} : { attempts });
2434
2526
  let cancelled = false;
2527
+ // The public path journals its own acceptance and publication; only
2528
+ // bound delivery needs a verdict to name its terminal outcome.
2529
+ let boundResult = { kind: 'public' };
2435
2530
  try {
2436
2531
  // Watch events are private-only: route them by envelope identity, not
2437
2532
  // by the current delivery. A watch task whose delivery was cleared (a
@@ -2439,8 +2534,8 @@ export class GithubChannel extends PollingChannelBase {
2439
2534
  // target) must never fall through to the public channel path —
2440
2535
  // deliverToBoundSession retires a targetless watch event privately.
2441
2536
  if (bound || isWatch) {
2442
- const settled = await this.deliverToBoundSession(task, envelope);
2443
- if (!settled)
2537
+ boundResult = await this.deliverToBoundSession(task, envelope);
2538
+ if (boundResult.kind === 'deferred')
2444
2539
  return false;
2445
2540
  }
2446
2541
  else if (this.boundRoleAware &&
@@ -2553,9 +2648,19 @@ export class GithubChannel extends PollingChannelBase {
2553
2648
  // deduplicates, stable across task re-creation), but the mark still
2554
2649
  // retires the task without a needless round-trip.
2555
2650
  if (task.delivery?.kind === 'bound-session') {
2651
+ // Only a delivered or retired verdict reaches here with the delivery
2652
+ // still set — the public-fallback exits clear it. The verdict supplies
2653
+ // the journal's terminal word: without it a preflight-rejected event
2654
+ // would still end on `running`, indistinguishable from a delivery in
2655
+ // flight, because that exit consumes the task with its delivery set.
2656
+ const journal = boundResult.kind === 'delivered'
2657
+ ? { outcome: 'delivered' }
2658
+ : boundResult.kind === 'retired'
2659
+ ? { outcome: 'retired', reason: boundResult.reason }
2660
+ : undefined;
2556
2661
  this.transitionInboundTask(task.id, 'running', {
2557
2662
  deliveredAt: Date.now(),
2558
- });
2663
+ }, journal);
2559
2664
  // The slot mark must be durable BEFORE the accepted task is removed:
2560
2665
  // it is the only evidence connecting the acceptance to the original
2561
2666
  // fanout slot across retargeting. A write failure fails the poll
@@ -2576,6 +2681,13 @@ export class GithubChannel extends PollingChannelBase {
2576
2681
  // unrelated file's readability.
2577
2682
  this.privatelyRetiredInboundTaskIds.delete(task.id);
2578
2683
  this.removeInboundTask(task.id);
2684
+ // After the removal, like the dead-letter site: a throwing removal
2685
+ // leaves the task recoverable, and the journal must not claim a retire
2686
+ // that did not happen — the next poll would then write a second
2687
+ // terminal row with a different, false reason.
2688
+ if (boundResult.kind === 'retired') {
2689
+ this.recordBoundTaskEvent(task, 'retired', boundResult.reason, undefined, boundResult.sessionId);
2690
+ }
2579
2691
  return true;
2580
2692
  }
2581
2693
  if (this.hasPendingFinalDeliveryForTask(task)) {
@@ -2808,6 +2920,13 @@ export class GithubChannel extends PollingChannelBase {
2808
2920
  issueNumber: task.issueNumber,
2809
2921
  source: task.source,
2810
2922
  delivery: task.delivery,
2923
+ // A cleared delivery leaves the record without a target; name the
2924
+ // session the event lost so operator recovery knows where it was
2925
+ // bound. Only when the delivery is gone — a live delivery is the
2926
+ // authoritative target and an older lostSessionId would be stale.
2927
+ ...(task.delivery?.kind !== 'bound-session' && task.lostSessionId
2928
+ ? { lostSessionId: task.lostSessionId }
2929
+ : {}),
2811
2930
  reason,
2812
2931
  text: task.envelope?.text,
2813
2932
  };
@@ -2832,10 +2951,17 @@ export class GithubChannel extends PollingChannelBase {
2832
2951
  // — enough to forge extra log lines from untrusted event text.
2833
2952
  const payload = JSON.stringify(record);
2834
2953
  process.stderr.write(`[Channel:${this.name}] failed to write bound dead-letter (${task.source.messageId}): ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}; payload: ${sanitizeLogText(payload, payload.length)}\n`);
2954
+ // The task is kept, so this is a failure, not a retire. Only the write
2955
+ // error is journaled: `payload` carries the message body, which the
2956
+ // journal must never hold.
2957
+ this.recordBoundTaskEvent(task, 'failed', 'dead_letter_write_failed', sanitizeLogText(err instanceof Error ? err.message : String(err), 200));
2835
2958
  return;
2836
2959
  }
2837
2960
  process.stderr.write(`[Channel:${this.name}] bound event retired to dead-letter (${task.source.messageId}): ${reason}\n`);
2838
2961
  this.removeInboundTask(task.id);
2962
+ // After the removal: a throwing removal leaves the task recoverable, and
2963
+ // the journal must not claim a retire that did not happen.
2964
+ this.recordBoundTaskEvent(task, 'retired', 'dead_letter', reason);
2839
2965
  }
2840
2966
  hasPendingFinalDeliveryForTask(task) {
2841
2967
  return this.readPendingFinalDeliveries(true).some((record) => record.chatId === task.source.chatId &&
@@ -2905,22 +3031,61 @@ export class GithubChannel extends PollingChannelBase {
2905
3031
  }
2906
3032
  }
2907
3033
  }
2908
- transitionInboundTask(taskId, state, updates = {}) {
2909
- const records = this.updateInboundTasks((existing) => existing.map((record) => record.id === taskId
2910
- ? {
3034
+ transitionInboundTask(taskId, state, updates = {},
3035
+ /**
3036
+ * Overrides the journaled outcome without touching the persisted state.
3037
+ * The bound acceptance mark is persisted as `running` (there is no
3038
+ * `delivered` task state — the record is removed right after), but the
3039
+ * journal's last word for that event must be terminal, not in-flight.
3040
+ */
3041
+ journal) {
3042
+ // The exits that hand an event back to the public lane persist
3043
+ // `delivery: undefined`, and the record is re-read AFTER the update, so
3044
+ // the row would lose the session it is about. Remember the target the
3045
+ // task held going in: "which session lost this event" is the question
3046
+ // the private lane's attribution exists to answer.
3047
+ let previousSessionId;
3048
+ const records = this.updateInboundTasks((existing) => existing.map((record) => {
3049
+ if (record.id !== taskId)
3050
+ return record;
3051
+ if (record.delivery?.kind === 'bound-session') {
3052
+ previousSessionId = record.delivery.sessionId;
3053
+ }
3054
+ return {
2911
3055
  ...record,
2912
3056
  ...updates,
3057
+ // Persist the lost target, not just this row's attribution: the
3058
+ // gone-session fallback clears the delivery, and every later poll
3059
+ // re-enters the absence gate and finally the dead-letter with no
3060
+ // delivery left to read. Remembering it for one transition would
3061
+ // leave all of those rows — including the terminal one — unnamed.
3062
+ // Only an EXPLICIT clear counts; an update that merely omits the
3063
+ // key must not touch it.
3064
+ ...('delivery' in updates &&
3065
+ updates.delivery === undefined &&
3066
+ previousSessionId !== undefined
3067
+ ? { lostSessionId: previousSessionId }
3068
+ : {}),
2913
3069
  state,
2914
3070
  updatedAt: new Date().toISOString(),
2915
- }
2916
- : record));
3071
+ };
3072
+ }));
2917
3073
  const task = records.find((record) => record.id === taskId);
2918
3074
  if (!task)
2919
3075
  return;
2920
3076
  const envelope = task.envelope;
3077
+ // Read the delivery from the UPDATED record: a retarget or a gone
3078
+ // fallback clears it mid-run, and the journal row must name the
3079
+ // session the transition actually refers to. A cleared delivery falls
3080
+ // back to the target this transition lost, so the row still names it.
3081
+ const identity = this.boundJournalIdentity(task.delivery);
3082
+ const sessionId = identity.sessionId ?? previousSessionId ?? task.lostSessionId;
3083
+ const sessionWorkspaceCwd = identity.sessionWorkspaceCwd ??
3084
+ (sessionId ? this.sessionWorkspaceFor(sessionId) : undefined);
2921
3085
  this.recordChannelEvent({
2922
3086
  type: 'task',
2923
- outcome: state,
3087
+ outcome: journal?.outcome ?? state,
3088
+ ...(journal?.reason ? { reason: journal.reason } : {}),
2924
3089
  ...(envelope
2925
3090
  ? {
2926
3091
  triggerKind: parseTriggerKind(envelope.metadata),
@@ -2931,16 +3096,47 @@ export class GithubChannel extends PollingChannelBase {
2931
3096
  thread: task.source.threadId,
2932
3097
  number: task.issueNumber,
2933
3098
  messageId: task.source.messageId,
2934
- // Read the delivery from the UPDATED record: a retarget or a gone
2935
- // fallback clears it mid-run, and the journal row must name the
2936
- // session the transition actually refers to.
2937
- ...this.boundJournalIdentity(task.delivery),
3099
+ ...(sessionId ? { sessionId } : {}),
3100
+ ...(sessionWorkspaceCwd ? { sessionWorkspaceCwd } : {}),
2938
3101
  ...(updates.attempts !== undefined
2939
3102
  ? { detail: { attempts: updates.attempts } }
2940
3103
  : {}),
2941
3104
  ...(updates.error ? { error: updates.error } : {}),
2942
3105
  });
2943
3106
  }
3107
+ /**
3108
+ * Journals a terminal decision about a bound event that never reached a
3109
+ * session: a private retire or a dead-letter. Identifiers only — the
3110
+ * dead-letter record's `text` (the message body) must never be copied here.
3111
+ * `sessionId` names the target the event lost when the delivery was already
3112
+ * cleared from the record.
3113
+ */
3114
+ recordBoundTaskEvent(task, outcome, reason, error, sessionId) {
3115
+ const envelope = task.envelope;
3116
+ const target = sessionId ??
3117
+ (task.delivery?.kind === 'bound-session'
3118
+ ? task.delivery.sessionId
3119
+ : task.lostSessionId);
3120
+ const workspaceCwd = target ? this.sessionWorkspaceFor(target) : undefined;
3121
+ this.recordChannelEvent({
3122
+ type: 'task',
3123
+ outcome,
3124
+ reason,
3125
+ ...(envelope
3126
+ ? {
3127
+ triggerKind: parseTriggerKind(envelope.metadata),
3128
+ actor: envelope.senderId,
3129
+ }
3130
+ : {}),
3131
+ repository: task.source.chatId,
3132
+ thread: task.source.threadId,
3133
+ number: task.issueNumber,
3134
+ messageId: task.source.messageId,
3135
+ ...(target ? { sessionId: target } : {}),
3136
+ ...(workspaceCwd ? { sessionWorkspaceCwd: workspaceCwd } : {}),
3137
+ ...(error ? { error } : {}),
3138
+ });
3139
+ }
2944
3140
  /**
2945
3141
  * Session identity for journal rows about a bound delivery, so the events
2946
3142
  * page can link the row to the session that received the event. The
@@ -2957,9 +3153,93 @@ export class GithubChannel extends PollingChannelBase {
2957
3153
  ...(workspaceCwd ? { sessionWorkspaceCwd: workspaceCwd } : {}),
2958
3154
  };
2959
3155
  }
3156
+ /**
3157
+ * The workspace a bound session lives in, from the latest binding list, so
3158
+ * a journal row's Open-session button reaches a session in ANOTHER
3159
+ * workspace instead of falling back to the Channel's own (the daemon would
3160
+ * answer 404). Undefined when the session is not currently listed.
3161
+ */
3162
+ sessionWorkspaceFor(sessionId) {
3163
+ return this.lastBindings.find((binding) => binding.sessionId === sessionId)
3164
+ ?.workspaceCwd;
3165
+ }
3166
+ /**
3167
+ * Whether a message key already has a durable dead-letter record. Loads the
3168
+ * never-rotated file's keys once, then serves from the cache this process
3169
+ * keeps current on append. A read failure yields an empty cache: nothing is
3170
+ * known to be dead-lettered, so the caller appends (a possible duplicate is
3171
+ * benign) rather than silently skipping the exhaustion surface.
3172
+ */
3173
+ isDeadLettered(messageKey) {
3174
+ if (this.deadLetteredKeys === undefined) {
3175
+ const keys = new Set();
3176
+ try {
3177
+ const raw = readFileSync(this.channelFilePath('github-bound-deadletter.jsonl'), 'utf-8');
3178
+ for (const line of raw.split('\n')) {
3179
+ if (!line)
3180
+ continue;
3181
+ try {
3182
+ const rec = JSON.parse(line);
3183
+ if (typeof rec.source?.messageId === 'string') {
3184
+ keys.add(rec.source.messageId);
3185
+ }
3186
+ }
3187
+ catch {
3188
+ // A malformed line names no key; skip it.
3189
+ }
3190
+ }
3191
+ }
3192
+ catch {
3193
+ // No file yet, or unreadable: nothing known to be dead-lettered.
3194
+ }
3195
+ this.deadLetteredKeys = keys;
3196
+ }
3197
+ return this.deadLetteredKeys.has(messageKey);
3198
+ }
3199
+ /**
3200
+ * The overflow retire's journal trace, written only after the retire is
3201
+ * durable. Identifiers only — the dead-letter record's `text` (the body)
3202
+ * must never be copied here. Carries the frozen target and its workspace so
3203
+ * the row links to the session the event lost, even in another workspace.
3204
+ */
3205
+ recordWatchOverflowSkip(pending) {
3206
+ const sessionId = pending.delivery?.kind === 'bound-session'
3207
+ ? pending.delivery.sessionId
3208
+ : undefined;
3209
+ const workspaceCwd = sessionId
3210
+ ? this.sessionWorkspaceFor(sessionId)
3211
+ : undefined;
3212
+ this.recordChannelEvent({
3213
+ type: 'inbound',
3214
+ outcome: 'skipped',
3215
+ reason: 'watch_pending_overflow',
3216
+ repository: pending.envelope.chatId,
3217
+ thread: pending.envelope.threadId,
3218
+ number: pending.issueNumber,
3219
+ messageId: pending.key,
3220
+ ...(sessionId ? { sessionId } : {}),
3221
+ ...(workspaceCwd ? { sessionWorkspaceCwd: workspaceCwd } : {}),
3222
+ });
3223
+ }
2960
3224
  removeInboundTask(taskId) {
2961
3225
  this.updateInboundTasks((records) => records.filter((record) => record.id !== taskId));
2962
3226
  }
3227
+ /**
3228
+ * Journals a degraded dependency the poll loop itself survived: the poll
3229
+ * still reports `ok`, so without this row a binding scan that stalls every
3230
+ * notification is invisible in the timeline. Emitted only where the
3231
+ * adapter already throttles its stderr line (or on a state edge), so a
3232
+ * permanent outage cannot rotate the useful rows out of the journal.
3233
+ */
3234
+ recordPollDegraded(reason, detail, error) {
3235
+ this.recordChannelEvent({
3236
+ type: 'poll',
3237
+ outcome: 'degraded',
3238
+ reason,
3239
+ ...(detail ? { detail } : {}),
3240
+ ...(error ? { error } : {}),
3241
+ });
3242
+ }
2963
3243
  updateInboundTasks(update) {
2964
3244
  try {
2965
3245
  const records = update(this.readInboundTasks());
@@ -3285,6 +3565,10 @@ export class GithubChannel extends PollingChannelBase {
3285
3565
  }
3286
3566
  }
3287
3567
  }
3568
+ // Sessions the routing map still routes to besides the ones this scan
3569
+ // listed. Under a partial answer retention keeps unlisted sessions, so
3570
+ // the scan's own row count alone can be 0 while the map is not.
3571
+ let retainedSessionCount = 0;
3288
3572
  if (snapshot.partial) {
3289
3573
  // An incomplete enumeration is not an absence: keep every known
3290
3574
  // binding the partial answer failed to list, so private delivery
@@ -3308,6 +3592,7 @@ export class GithubChannel extends PollingChannelBase {
3308
3592
  .sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''))
3309
3593
  .slice(0, MAX_PARTIAL_RETAINED)
3310
3594
  : retained;
3595
+ retainedSessionCount = retainedCapped.length;
3311
3596
  if (retainedCapped.length < retained.length) {
3312
3597
  process.stderr.write(`[Channel:${this.name}] binding retention cap exceeded under a partial snapshot: dropped ${retained.length - retainedCapped.length} oldest unlisted sessions (keeping ${MAX_PARTIAL_RETAINED}); their unmatched events defer until a complete snapshot establishes absence\n`);
3313
3598
  }
@@ -3339,7 +3624,10 @@ export class GithubChannel extends PollingChannelBase {
3339
3624
  if (snapshot.partial && map.size === 0 && !this.boundSnapshotTrusted) {
3340
3625
  this.coldEmptyPartialStreak += 1;
3341
3626
  if (this.coldEmptyPartialStreak === MAX_COLD_EMPTY_PARTIAL_POLLS) {
3342
- process.stderr.write(`[Channel:${this.name}] binding snapshot has been an empty partial for ${this.coldEmptyPartialStreak} consecutive polls: opening the comment lane. Unmatched PR events will defer (and dead-letter after the backpressure horizon) until a complete snapshot establishes absence. ${this.coldEmptyCapCause()}\n`);
3627
+ process.stderr.write(`[Channel:${this.name}] binding snapshot has been an empty partial for ${this.coldEmptyPartialStreak} consecutive binding scans: opening the comment lane. Unmatched PR events will defer (and dead-letter after the backpressure horizon) until a complete snapshot establishes absence. ${this.coldEmptyCapCause()}\n`);
3628
+ this.recordPollDegraded('bindings_cold_empty', {
3629
+ streak: this.coldEmptyPartialStreak,
3630
+ });
3343
3631
  }
3344
3632
  }
3345
3633
  else {
@@ -3356,11 +3644,23 @@ export class GithubChannel extends PollingChannelBase {
3356
3644
  if ((snapshot.bindings.length > 0 || map.size > 0) &&
3357
3645
  (this.partialSnapshotStreak === 10 ||
3358
3646
  this.partialSnapshotStreak % 60 === 0)) {
3359
- process.stderr.write(`[Channel:${this.name}] binding snapshot has been partial for ${this.partialSnapshotStreak} consecutive polls (${snapshot.bindings.length} sessions listed): the daemon could not read every PR sidecar, transcript or live session list, or a registered workspace has no runtime. ${!this.boundSnapshotTrusted &&
3647
+ // The routing map is keyed per PR, so its size counts bound PRs,
3648
+ // not sessions: one session following two PRs would be reported as
3649
+ // two. Count session rows instead — the ones this scan listed plus
3650
+ // the ones retention keeps routing to. Reporting only the listed
3651
+ // rows would say "0 sessions listed" for a draining workspace whose
3652
+ // retained sessions are still receiving deliveries, and hand the
3653
+ // operator a page-cap diagnosis for a state that is not a page cap.
3654
+ const listedSessions = snapshot.bindings.length + retainedSessionCount;
3655
+ process.stderr.write(`[Channel:${this.name}] binding snapshot has been partial for ${this.partialSnapshotStreak} consecutive binding scans (${listedSessions} sessions listed): the daemon could not read every PR sidecar, transcript or live session list, or a registered workspace has no runtime. ${!this.boundSnapshotTrusted &&
3360
3656
  map.size === 0 &&
3361
3657
  this.coldEmptyPartialStreak < MAX_COLD_EMPTY_PARTIAL_POLLS
3362
- ? `The comment lane is still deferred (${this.coldEmptyPartialStreak}/${MAX_COLD_EMPTY_PARTIAL_POLLS} cold polls), so PR and issue events are both stalled.`
3658
+ ? `The comment lane is still deferred (${this.coldEmptyPartialStreak}/${MAX_COLD_EMPTY_PARTIAL_POLLS} cold binding scans), so PR and issue events are both stalled.`
3363
3659
  : 'Unmatched PR events defer to the dead-letter horizon instead of the channel (issue events are unaffected).'} Check the daemon's stderr for the failing workspace, and its \`PR bindings scan\` lines for the session it could not read.\n`);
3660
+ this.recordPollDegraded('bindings_partial', {
3661
+ streak: this.partialSnapshotStreak,
3662
+ sessions: listedSessions,
3663
+ });
3364
3664
  }
3365
3665
  }
3366
3666
  else {
@@ -3391,9 +3691,12 @@ export class GithubChannel extends PollingChannelBase {
3391
3691
  this.coldEmptyPartialStreak += 1;
3392
3692
  this.coldEmptyFailurePolls += 1;
3393
3693
  if (this.coldEmptyPartialStreak === MAX_COLD_EMPTY_PARTIAL_POLLS) {
3394
- process.stderr.write(`[Channel:${this.name}] binding snapshot has been an empty partial for ${this.coldEmptyPartialStreak} consecutive polls: ${this.boundSnapshotSeen
3694
+ process.stderr.write(`[Channel:${this.name}] binding snapshot has been an empty partial for ${this.coldEmptyPartialStreak} consecutive binding scans: ${this.boundSnapshotSeen
3395
3695
  ? 'opening the comment lane. Unmatched PR events will defer (and dead-letter after the backpressure horizon) until a complete snapshot establishes absence.'
3396
3696
  : 'the comment lane stays closed until a snapshot succeeds; every notification, issue events included, remains stalled.'} ${this.coldEmptyCapCause()}\n`);
3697
+ this.recordPollDegraded('bindings_cold_empty', {
3698
+ streak: this.coldEmptyPartialStreak,
3699
+ });
3397
3700
  }
3398
3701
  // Surface the stall distinctly and actionably, throttled so a
3399
3702
  // transient outage does not spam; the misleading "keeping previous
@@ -3403,6 +3706,7 @@ export class GithubChannel extends PollingChannelBase {
3403
3706
  if (this.boundSnapshotFailureStreak === 1 ||
3404
3707
  this.boundSnapshotFailureStreak % 10 === 0) {
3405
3708
  process.stderr.write(`[Channel:${this.name}] binding snapshot has never succeeded (${this.boundSnapshotFailureStreak} consecutive failures): the comment lane is deferred and ALL notifications are stalled. Verify GET /sessions/pr-bindings is reachable and the worker credentials are valid: ${detail}\n`);
3709
+ this.recordPollDegraded('bindings_unreachable', { streak: this.boundSnapshotFailureStreak }, detail);
3406
3710
  }
3407
3711
  }
3408
3712
  else {
@@ -3894,17 +4198,22 @@ export class GithubChannel extends PollingChannelBase {
3894
4198
  // target they are logged and retired, never fallen back publicly.
3895
4199
  if (isWatch) {
3896
4200
  process.stderr.write(`[Channel:${this.name}] watch event ${envelope.messageId} has no bound delivery target; retiring without public fallback\n`);
3897
- return true;
4201
+ return { kind: 'retired', reason: 'watch_no_target' };
3898
4202
  }
3899
4203
  if (this.boundRoleAware && this.boundEventAlreadyDelivered(envelope)) {
3900
- // A sibling role already accepted this event privately; a targetless
3901
- // retry must not answer it publicly (durable delivery ring).
4204
+ // Defensive: a sibling role already accepted this event privately, so
4205
+ // a targetless retry must not answer it publicly (durable delivery
4206
+ // ring). Unreachable in practice — boundRoleAware requires
4207
+ // boundSessionActions, which the constructor clears in standalone
4208
+ // mode, and a bound delivery implies a live boundSessions handle — so
4209
+ // this reason is NOT part of the published vocabulary. Kept as a guard
4210
+ // against a future call path that clears the delivery mid-run.
3902
4211
  process.stderr.write(`[Channel:${this.name}] event ${envelope.messageId} already delivered privately to another role; retiring without public fallback\n`);
3903
4212
  this.markPrivatelyRetired(task);
3904
- return true;
4213
+ return { kind: 'retired', reason: 'already_delivered_other_role' };
3905
4214
  }
3906
4215
  await this.handleInbound(envelope);
3907
- return true;
4216
+ return { kind: 'public' };
3908
4217
  }
3909
4218
  // The target was frozen at claim/detection time. Re-validate it against
3910
4219
  // the latest COMPLETE snapshot: a live rebind must not keep delivering
@@ -3930,7 +4239,11 @@ export class GithubChannel extends PollingChannelBase {
3930
4239
  // their public fallback contract is handled by the gone path below.
3931
4240
  process.stderr.write(`[Channel:${this.name}] ${isWatch ? 'watch' : 'bound'} event ${envelope.messageId} has no bound candidate left for its role; retiring without public fallback\n`);
3932
4241
  this.markPrivatelyRetired(task);
3933
- return true;
4242
+ return {
4243
+ kind: 'retired',
4244
+ reason: isWatch ? 'watch_no_candidate' : 'bound_no_candidate',
4245
+ sessionId: delivery.sessionId,
4246
+ };
3934
4247
  }
3935
4248
  }
3936
4249
  // The channel path runs the group/sender/pairing gates inside
@@ -3943,10 +4256,10 @@ export class GithubChannel extends PollingChannelBase {
3943
4256
  const admitted = typeof preflight === 'boolean' ? preflight : await preflight;
3944
4257
  if (!admitted) {
3945
4258
  // The bound path inherits the channel gates (sender allowlist,
3946
- // message routes); a rejection retires the event as delivered, so
3947
- // surface it instead of consuming it silently.
4259
+ // message routes); a rejection retires the event without delivering
4260
+ // it, so surface it instead of consuming it silently.
3948
4261
  process.stderr.write(`[Channel:${this.name}] bound event ${envelope.messageId} rejected by the channel preflight (sender/route gates); retiring without delivery\n`);
3949
- return true;
4262
+ return { kind: 'retired', reason: 'preflight_rejected' };
3950
4263
  }
3951
4264
  }
3952
4265
  const prompt = this.buildBoundSessionPrompt(envelope, delivery.role, this.boundLaneClass(task.dedupe));
@@ -3990,18 +4303,23 @@ export class GithubChannel extends PollingChannelBase {
3990
4303
  // loop by the finite follower count even if a stale snapshot keeps
3991
4304
  // re-listing dead sessions.
3992
4305
  const goneSessions = new Set([delivery.sessionId]);
4306
+ // The local `delivery` is the FIRST follower; the loop walks past it.
4307
+ // The terminal row must name the last one tried, or the operator opens
4308
+ // the workspace of a session evicted a step earlier.
4309
+ let lastTarget = delivery;
3993
4310
  const roleFilter = this.boundRoleAware
3994
4311
  ? { role: delivery.role }
3995
4312
  : undefined;
3996
4313
  let next = this.resolveBoundDeliveryExcluding(envelope.chatId, task.issueNumber, goneSessions, roleFilter);
3997
4314
  while (next) {
4315
+ lastTarget = next;
3998
4316
  this.transitionInboundTask(task.id, 'running', { delivery: next });
3999
4317
  task.delivery = next;
4000
4318
  try {
4001
4319
  // Same event key: a different session's ring has never seen it.
4002
4320
  await boundSessions.deliverPrompt(next.sessionId, prompt, idempotencyKey);
4003
4321
  this.recordBoundDelivered(envelope, next.sessionId);
4004
- return true;
4322
+ return { kind: 'delivered' };
4005
4323
  }
4006
4324
  catch (retryErr) {
4007
4325
  if (!(retryErr instanceof BoundSessionGoneError))
@@ -4022,7 +4340,11 @@ export class GithubChannel extends PollingChannelBase {
4022
4340
  process.stderr.write(`[Channel:${this.name}] watch event ${envelope.messageId} lost its bound session; retiring without public fallback\n`);
4023
4341
  this.transitionInboundTask(task.id, 'running', { delivery: undefined });
4024
4342
  task.delivery = undefined;
4025
- return true;
4343
+ return {
4344
+ kind: 'retired',
4345
+ reason: 'watch_session_gone',
4346
+ sessionId: lastTarget.sessionId,
4347
+ };
4026
4348
  }
4027
4349
  // Role-aware fan-out: a partially delivered event never ALSO goes
4028
4350
  // public. While any role still follows the PR, the event is (or will
@@ -4034,7 +4356,11 @@ export class GithubChannel extends PollingChannelBase {
4034
4356
  this.boundEventAlreadyDelivered(envelope))) {
4035
4357
  process.stderr.write(`[Channel:${this.name}] bound event ${envelope.messageId} lost its role's session but other roles still follow the PR or already received it; retiring without public fallback\n`);
4036
4358
  this.markPrivatelyRetired(task);
4037
- return true;
4359
+ return {
4360
+ kind: 'retired',
4361
+ reason: 'siblings_still_follow',
4362
+ sessionId: lastTarget.sessionId,
4363
+ };
4038
4364
  }
4039
4365
  // Comment events keep today's contract: fall back to the normal
4040
4366
  // channel path so the event is not lost — but only when absence is
@@ -4043,14 +4369,21 @@ export class GithubChannel extends PollingChannelBase {
4043
4369
  // the public reply would be irreversible: defer as backpressure
4044
4370
  // (delivery cleared so recovery re-resolves without a doomed POST)
4045
4371
  // until a complete snapshot lands, same rule as unmatched claims.
4046
- // The false return tells runInboundTask the task was deferred HERE:
4047
- // its success path must not retire the record as delivered.
4372
+ // The `deferred` verdict tells runInboundTask the task was deferred
4373
+ // HERE: its success path must not retire the record as delivered.
4048
4374
  if (this.lastBindingsPartial || this.boundRefreshFailed) {
4049
4375
  const deferCount = (task.deferCount ?? 0) + 1;
4376
+ // Attribution only, mirroring the store's lostSessionId: the horizon
4377
+ // retire below reads the IN-MEMORY task, which the store persistence
4378
+ // in transitionInboundTask never touches. Without this the terminal
4379
+ // row and the dead-letter record would file the event under the
4380
+ // Channel with no victim when the horizon is reached in the same run
4381
+ // that still held the target.
4382
+ task.lostSessionId = lastTarget.sessionId;
4050
4383
  task.delivery = undefined;
4051
4384
  if (deferCount >= MAX_BOUND_DEFERRALS) {
4052
4385
  this.retireBoundTask(task, `gone fallback deferred ${deferCount} times; binding snapshot never completed`);
4053
- return false;
4386
+ return { kind: 'deferred' };
4054
4387
  }
4055
4388
  this.transitionInboundTask(task.id, 'failed', {
4056
4389
  delivery: undefined,
@@ -4059,13 +4392,14 @@ export class GithubChannel extends PollingChannelBase {
4059
4392
  deferCount,
4060
4393
  backpressure: true,
4061
4394
  });
4062
- return false;
4395
+ return { kind: 'deferred' };
4063
4396
  }
4064
4397
  this.transitionInboundTask(task.id, 'running', { delivery: undefined });
4065
4398
  task.delivery = undefined;
4066
4399
  await this.handleInbound(envelope);
4400
+ return { kind: 'public' };
4067
4401
  }
4068
- return true;
4402
+ return { kind: 'delivered' };
4069
4403
  }
4070
4404
  prWatchStatePath() {
4071
4405
  return this.channelFilePath('github-pr-watch.json');
@@ -4499,6 +4833,9 @@ export class GithubChannel extends PollingChannelBase {
4499
4833
  // independent subscriptions. Comment events still dedupe across
4500
4834
  // instances via their stable GitHub ids.
4501
4835
  const detectedAt = Date.now();
4836
+ // Overflow retires sliced during this pass; their skip rows are journalled
4837
+ // only after the end-of-pass save commits the baseline and queue together.
4838
+ const overflowRetires = [];
4502
4839
  for (const event of events) {
4503
4840
  // ci_failure dedupes per head SHA: once per head even when the
4504
4841
  // aggregate flaps back to success and fails again. The other three
@@ -4561,35 +4898,50 @@ export class GithubChannel extends PollingChannelBase {
4561
4898
  });
4562
4899
  if (next.pending.length > MAX_PENDING_WATCH_PER_ENTRY) {
4563
4900
  const oldest = next.pending[0];
4564
- const record = {
4565
- retiredAt: new Date().toISOString(),
4566
- issueNumber: oldest.issueNumber,
4567
- source: {
4568
- chatId,
4569
- threadId: `pr:${number}`,
4570
- messageId: oldest.key,
4571
- },
4572
- delivery: oldest.delivery,
4573
- reason: `watch pending queue overflow (cap ${MAX_PENDING_WATCH_PER_ENTRY}); oldest event retired undelivered`,
4574
- text: oldest.envelope.text,
4575
- };
4576
- try {
4577
- const path = this.channelFilePath('github-bound-deadletter.jsonl');
4578
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
4579
- appendFileSync(path, `${JSON.stringify(record)}\n`, {
4580
- encoding: 'utf-8',
4581
- mode: 0o600,
4582
- });
4583
- next.pending.shift();
4584
- process.stderr.write(`[Channel:${this.name}] watch pending overflow for ${key}: retired ${oldest.key} to dead-letter (cap ${MAX_PENDING_WATCH_PER_ENTRY})\n`);
4901
+ if (!this.isDeadLettered(oldest.key)) {
4902
+ const record = {
4903
+ retiredAt: new Date().toISOString(),
4904
+ issueNumber: oldest.issueNumber,
4905
+ source: {
4906
+ chatId,
4907
+ threadId: `pr:${number}`,
4908
+ messageId: oldest.key,
4909
+ },
4910
+ delivery: oldest.delivery,
4911
+ reason: `watch pending queue overflow (cap ${MAX_PENDING_WATCH_PER_ENTRY}); oldest event retired undelivered`,
4912
+ text: oldest.envelope.text,
4913
+ };
4914
+ try {
4915
+ const path = this.channelFilePath('github-bound-deadletter.jsonl');
4916
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
4917
+ appendFileSync(path, `${JSON.stringify(record)}\n`, {
4918
+ encoding: 'utf-8',
4919
+ mode: 0o600,
4920
+ });
4921
+ this.deadLetteredKeys.add(oldest.key);
4922
+ }
4923
+ catch (err) {
4924
+ // The exhaustion surface cannot be written: keep the event queued
4925
+ // (over cap) and retry the overflow on the next detection instead
4926
+ // of dropping it. The body has nowhere else to go, so dump it to
4927
+ // stderr — sanitized without truncation, like retireBoundTask.
4928
+ const payload = JSON.stringify(record);
4929
+ process.stderr.write(`[Channel:${this.name}] failed to write watch pending overflow dead-letter (${oldest.key}): ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}; payload: ${sanitizeLogText(payload, payload.length)}\n`);
4930
+ }
4585
4931
  }
4586
- catch (err) {
4587
- // Same fail-safe as retireBoundTask: if the exhaustion surface
4588
- // cannot be written, keep the event queued (over cap) and retry
4589
- // the overflow on the next detection instead of dropping it.
4590
- // Sanitized without truncation, like the retireBoundTask dump.
4591
- const payload = JSON.stringify(record);
4592
- process.stderr.write(`[Channel:${this.name}] failed to write watch pending overflow dead-letter (${oldest.key}): ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}; payload: ${sanitizeLogText(payload, payload.length)}\n`);
4932
+ if (this.isDeadLettered(oldest.key)) {
4933
+ // The dead-letter record is the retire's commit point. Slice in
4934
+ // memory ONLY: the end-of-pass save below commits the advanced
4935
+ // baseline and the full queue in one write. A mid-pass save here
4936
+ // would persist the baseline before this pass's later events are
4937
+ // queued, so a crash would never re-derive them. The skip row is
4938
+ // journalled after that save, never before; if the save throws, the
4939
+ // drain completes the retire next poll (the head is dead-lettered,
4940
+ // so it is never delivered).
4941
+ next.pending = next.pending.slice(1);
4942
+ this.prWatchState.entries[key] = next;
4943
+ overflowRetires.push(oldest);
4944
+ process.stderr.write(`[Channel:${this.name}] watch pending overflow for ${key}: retired ${oldest.key} to dead-letter (cap ${MAX_PENDING_WATCH_PER_ENTRY})\n`);
4593
4945
  }
4594
4946
  }
4595
4947
  if (event.type === 'ci_failure' && headSha !== undefined) {
@@ -4601,6 +4953,12 @@ export class GithubChannel extends PollingChannelBase {
4601
4953
  // either finds the pending event (drained next poll) or the claimed
4602
4954
  // task (recovery), never a consumed transition with nothing to retry.
4603
4955
  this.savePrWatchState();
4956
+ // The overflow retires are durable only now. Journal their skip rows after
4957
+ // the save: a throwing save leaves no claim for an event still queued on
4958
+ // disk, and the drain completes the retire next poll instead.
4959
+ for (const retired of overflowRetires) {
4960
+ this.recordWatchOverflowSkip(retired);
4961
+ }
4604
4962
  await this.drainPendingWatch(key, next);
4605
4963
  }
4606
4964
  /**
@@ -4633,6 +4991,25 @@ export class GithubChannel extends PollingChannelBase {
4633
4991
  return;
4634
4992
  while (entry.pending && entry.pending.length > 0) {
4635
4993
  const pending = entry.pending[0];
4994
+ if (this.isDeadLettered(pending.key)) {
4995
+ // This head already carries a durable "retired undelivered" record
4996
+ // (an overflow whose end-of-pass save failed, or a crash before it).
4997
+ // Complete the retire instead of delivering: a delivered event must
4998
+ // never also stand in the dead-letter file as retired undelivered.
4999
+ const pendingBefore = entry.pending;
5000
+ entry.pending = entry.pending.slice(1);
5001
+ this.prWatchState.entries[key] = entry;
5002
+ try {
5003
+ this.savePrWatchState();
5004
+ }
5005
+ catch (err) {
5006
+ entry.pending = pendingBefore;
5007
+ this.prWatchState.entries[key] = entry;
5008
+ throw err;
5009
+ }
5010
+ this.recordWatchOverflowSkip(pending);
5011
+ continue;
5012
+ }
4636
5013
  // Re-validate the frozen recipient against the latest COMPLETE
4637
5014
  // snapshot: a live rebind must not misdeliver to the old session. On
4638
5015
  // a partial/failed scan the persisted target stands (fail-closed).
@@ -4649,9 +5026,48 @@ export class GithubChannel extends PollingChannelBase {
4649
5026
  }
4650
5027
  else {
4651
5028
  process.stderr.write(`[Channel:${this.name}] watch event ${pending.key} has no bound candidate left; retiring without public fallback\n`);
5029
+ const pendingBefore = entry.pending;
4652
5030
  entry.pending = entry.pending.slice(1);
4653
5031
  this.prWatchState.entries[key] = entry;
4654
- this.savePrWatchState();
5032
+ try {
5033
+ this.savePrWatchState();
5034
+ }
5035
+ catch (err) {
5036
+ // The slice already mutated the loaded state, and a failed save
5037
+ // does not clear prWatchStateLoaded — without this rollback the
5038
+ // next poll skips the entry and the end-of-pass save persists the
5039
+ // truncation, losing the event with no trace at all. Mirrors the
5040
+ // claim path's rollback below.
5041
+ entry.pending = pendingBefore;
5042
+ this.prWatchState.entries[key] = entry;
5043
+ throw err;
5044
+ }
5045
+ // Retired before any task was claimed, so there is no task row to
5046
+ // close: the skip is the event's only journal trace. After the
5047
+ // durable save — the rollback above keeps the event queued when the
5048
+ // save throws, and the journal must not claim a retire that did not
5049
+ // happen.
5050
+ const lostTarget = pending.delivery?.kind === 'bound-session'
5051
+ ? pending.delivery.sessionId
5052
+ : undefined;
5053
+ const lostWorkspace = lostTarget
5054
+ ? this.sessionWorkspaceFor(lostTarget)
5055
+ : undefined;
5056
+ this.recordChannelEvent({
5057
+ type: 'inbound',
5058
+ outcome: 'skipped',
5059
+ reason: 'watch_no_candidate',
5060
+ repository: pending.envelope.chatId,
5061
+ thread: pending.envelope.threadId,
5062
+ number: pending.issueNumber,
5063
+ messageId: pending.key,
5064
+ // The frozen target is in hand; this retire writes no dead-letter
5065
+ // record (only the overflow retire does), so the skip row is the
5066
+ // event's only trace — without the target it cannot say whether
5067
+ // the retired event ever belonged to a session.
5068
+ ...(lostTarget ? { sessionId: lostTarget } : {}),
5069
+ ...(lostWorkspace ? { sessionWorkspaceCwd: lostWorkspace } : {}),
5070
+ });
4655
5071
  continue;
4656
5072
  }
4657
5073
  }
@@ -4711,6 +5127,24 @@ export class GithubChannel extends PollingChannelBase {
4711
5127
  async drainPendingWatchRoleAware(key, entry) {
4712
5128
  while (entry.pending && entry.pending.length > 0) {
4713
5129
  const pending = entry.pending[0];
5130
+ if (this.isDeadLettered(pending.key)) {
5131
+ // A dead-lettered head is committed to retire; complete it rather than
5132
+ // deliver, so no event is both delivered and filed as retired
5133
+ // undelivered. Mirrors the legacy drain's guard.
5134
+ const pendingBefore = entry.pending;
5135
+ entry.pending = entry.pending.slice(1);
5136
+ this.prWatchState.entries[key] = entry;
5137
+ try {
5138
+ this.savePrWatchState();
5139
+ }
5140
+ catch (err) {
5141
+ entry.pending = pendingBefore;
5142
+ this.prWatchState.entries[key] = entry;
5143
+ throw err;
5144
+ }
5145
+ this.recordWatchOverflowSkip(pending);
5146
+ continue;
5147
+ }
4714
5148
  const { targets } = this.resolveBoundTargets(pending.envelope.chatId, pending.issueNumber, this.boundEventClass(pending.envelope));
4715
5149
  if (targets.length === 0) {
4716
5150
  // An incomplete enumeration is not an absence: defer instead of