@qwen-code/channel-github 0.26.8 → 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
@@ -1488,13 +1558,14 @@ export class GithubChannel extends PollingChannelBase {
1488
1558
  if (this.inboundRecoveryPending) {
1489
1559
  try {
1490
1560
  await this.recoverInboundTasks();
1561
+ // Clear only on success: the re-arm below reads an in-memory count
1562
+ // that a failed store read latched at 0, so clearing here would
1563
+ // promise a retry that never runs once the store is readable again.
1564
+ this.inboundRecoveryPending = false;
1491
1565
  }
1492
1566
  catch (err) {
1493
1567
  process.stderr.write(`[Channel:${this.name}] inbound task recovery failed, will retry next poll: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
1494
1568
  }
1495
- finally {
1496
- this.inboundRecoveryPending = false;
1497
- }
1498
1569
  }
1499
1570
  // Re-arm recovery before the cold-start gate: persisted tasks must keep
1500
1571
  // retrying even while the comment lane is deferred.
@@ -1529,7 +1600,12 @@ export class GithubChannel extends PollingChannelBase {
1529
1600
  this.coldEmptyPartialStreak < MAX_COLD_EMPTY_PARTIAL_POLLS) {
1530
1601
  if (this.coldEmptyPartialStreak === 1 ||
1531
1602
  this.coldEmptyPartialStreak % 10 === 0) {
1532
- 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
+ });
1533
1609
  }
1534
1610
  return;
1535
1611
  }
@@ -2310,6 +2386,23 @@ export class GithubChannel extends PollingChannelBase {
2310
2386
  // incomplete evidence.
2311
2387
  this.applyTaskDedupe(dedupe);
2312
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
+ });
2313
2406
  return true;
2314
2407
  }
2315
2408
  const task = this.claimInboundTask(envelope, issueNumber, dedupe);
@@ -2431,6 +2524,9 @@ export class GithubChannel extends PollingChannelBase {
2431
2524
  // (private-only), so they share the no-charge running transition.
2432
2525
  this.transitionInboundTask(task.id, 'running', bound || isWatch ? {} : { attempts });
2433
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' };
2434
2530
  try {
2435
2531
  // Watch events are private-only: route them by envelope identity, not
2436
2532
  // by the current delivery. A watch task whose delivery was cleared (a
@@ -2438,8 +2534,8 @@ export class GithubChannel extends PollingChannelBase {
2438
2534
  // target) must never fall through to the public channel path —
2439
2535
  // deliverToBoundSession retires a targetless watch event privately.
2440
2536
  if (bound || isWatch) {
2441
- const settled = await this.deliverToBoundSession(task, envelope);
2442
- if (!settled)
2537
+ boundResult = await this.deliverToBoundSession(task, envelope);
2538
+ if (boundResult.kind === 'deferred')
2443
2539
  return false;
2444
2540
  }
2445
2541
  else if (this.boundRoleAware &&
@@ -2552,9 +2648,19 @@ export class GithubChannel extends PollingChannelBase {
2552
2648
  // deduplicates, stable across task re-creation), but the mark still
2553
2649
  // retires the task without a needless round-trip.
2554
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;
2555
2661
  this.transitionInboundTask(task.id, 'running', {
2556
2662
  deliveredAt: Date.now(),
2557
- });
2663
+ }, journal);
2558
2664
  // The slot mark must be durable BEFORE the accepted task is removed:
2559
2665
  // it is the only evidence connecting the acceptance to the original
2560
2666
  // fanout slot across retargeting. A write failure fails the poll
@@ -2575,6 +2681,13 @@ export class GithubChannel extends PollingChannelBase {
2575
2681
  // unrelated file's readability.
2576
2682
  this.privatelyRetiredInboundTaskIds.delete(task.id);
2577
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
+ }
2578
2691
  return true;
2579
2692
  }
2580
2693
  if (this.hasPendingFinalDeliveryForTask(task)) {
@@ -2807,6 +2920,13 @@ export class GithubChannel extends PollingChannelBase {
2807
2920
  issueNumber: task.issueNumber,
2808
2921
  source: task.source,
2809
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
+ : {}),
2810
2930
  reason,
2811
2931
  text: task.envelope?.text,
2812
2932
  };
@@ -2831,10 +2951,17 @@ export class GithubChannel extends PollingChannelBase {
2831
2951
  // — enough to forge extra log lines from untrusted event text.
2832
2952
  const payload = JSON.stringify(record);
2833
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));
2834
2958
  return;
2835
2959
  }
2836
2960
  process.stderr.write(`[Channel:${this.name}] bound event retired to dead-letter (${task.source.messageId}): ${reason}\n`);
2837
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);
2838
2965
  }
2839
2966
  hasPendingFinalDeliveryForTask(task) {
2840
2967
  return this.readPendingFinalDeliveries(true).some((record) => record.chatId === task.source.chatId &&
@@ -2904,22 +3031,61 @@ export class GithubChannel extends PollingChannelBase {
2904
3031
  }
2905
3032
  }
2906
3033
  }
2907
- transitionInboundTask(taskId, state, updates = {}) {
2908
- const records = this.updateInboundTasks((existing) => existing.map((record) => record.id === taskId
2909
- ? {
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 {
2910
3055
  ...record,
2911
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
+ : {}),
2912
3069
  state,
2913
3070
  updatedAt: new Date().toISOString(),
2914
- }
2915
- : record));
3071
+ };
3072
+ }));
2916
3073
  const task = records.find((record) => record.id === taskId);
2917
3074
  if (!task)
2918
3075
  return;
2919
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);
2920
3085
  this.recordChannelEvent({
2921
3086
  type: 'task',
2922
- outcome: state,
3087
+ outcome: journal?.outcome ?? state,
3088
+ ...(journal?.reason ? { reason: journal.reason } : {}),
2923
3089
  ...(envelope
2924
3090
  ? {
2925
3091
  triggerKind: parseTriggerKind(envelope.metadata),
@@ -2930,16 +3096,47 @@ export class GithubChannel extends PollingChannelBase {
2930
3096
  thread: task.source.threadId,
2931
3097
  number: task.issueNumber,
2932
3098
  messageId: task.source.messageId,
2933
- // Read the delivery from the UPDATED record: a retarget or a gone
2934
- // fallback clears it mid-run, and the journal row must name the
2935
- // session the transition actually refers to.
2936
- ...this.boundJournalIdentity(task.delivery),
3099
+ ...(sessionId ? { sessionId } : {}),
3100
+ ...(sessionWorkspaceCwd ? { sessionWorkspaceCwd } : {}),
2937
3101
  ...(updates.attempts !== undefined
2938
3102
  ? { detail: { attempts: updates.attempts } }
2939
3103
  : {}),
2940
3104
  ...(updates.error ? { error: updates.error } : {}),
2941
3105
  });
2942
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
+ }
2943
3140
  /**
2944
3141
  * Session identity for journal rows about a bound delivery, so the events
2945
3142
  * page can link the row to the session that received the event. The
@@ -2956,9 +3153,93 @@ export class GithubChannel extends PollingChannelBase {
2956
3153
  ...(workspaceCwd ? { sessionWorkspaceCwd: workspaceCwd } : {}),
2957
3154
  };
2958
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
+ }
2959
3224
  removeInboundTask(taskId) {
2960
3225
  this.updateInboundTasks((records) => records.filter((record) => record.id !== taskId));
2961
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
+ }
2962
3243
  updateInboundTasks(update) {
2963
3244
  try {
2964
3245
  const records = update(this.readInboundTasks());
@@ -3284,6 +3565,10 @@ export class GithubChannel extends PollingChannelBase {
3284
3565
  }
3285
3566
  }
3286
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;
3287
3572
  if (snapshot.partial) {
3288
3573
  // An incomplete enumeration is not an absence: keep every known
3289
3574
  // binding the partial answer failed to list, so private delivery
@@ -3307,6 +3592,7 @@ export class GithubChannel extends PollingChannelBase {
3307
3592
  .sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''))
3308
3593
  .slice(0, MAX_PARTIAL_RETAINED)
3309
3594
  : retained;
3595
+ retainedSessionCount = retainedCapped.length;
3310
3596
  if (retainedCapped.length < retained.length) {
3311
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`);
3312
3598
  }
@@ -3338,7 +3624,10 @@ export class GithubChannel extends PollingChannelBase {
3338
3624
  if (snapshot.partial && map.size === 0 && !this.boundSnapshotTrusted) {
3339
3625
  this.coldEmptyPartialStreak += 1;
3340
3626
  if (this.coldEmptyPartialStreak === MAX_COLD_EMPTY_PARTIAL_POLLS) {
3341
- 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
+ });
3342
3631
  }
3343
3632
  }
3344
3633
  else {
@@ -3355,11 +3644,23 @@ export class GithubChannel extends PollingChannelBase {
3355
3644
  if ((snapshot.bindings.length > 0 || map.size > 0) &&
3356
3645
  (this.partialSnapshotStreak === 10 ||
3357
3646
  this.partialSnapshotStreak % 60 === 0)) {
3358
- 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 &&
3359
3656
  map.size === 0 &&
3360
3657
  this.coldEmptyPartialStreak < MAX_COLD_EMPTY_PARTIAL_POLLS
3361
- ? `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.`
3362
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
+ });
3363
3664
  }
3364
3665
  }
3365
3666
  else {
@@ -3390,9 +3691,12 @@ export class GithubChannel extends PollingChannelBase {
3390
3691
  this.coldEmptyPartialStreak += 1;
3391
3692
  this.coldEmptyFailurePolls += 1;
3392
3693
  if (this.coldEmptyPartialStreak === MAX_COLD_EMPTY_PARTIAL_POLLS) {
3393
- 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
3394
3695
  ? 'opening the comment lane. Unmatched PR events will defer (and dead-letter after the backpressure horizon) until a complete snapshot establishes absence.'
3395
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
+ });
3396
3700
  }
3397
3701
  // Surface the stall distinctly and actionably, throttled so a
3398
3702
  // transient outage does not spam; the misleading "keeping previous
@@ -3402,6 +3706,7 @@ export class GithubChannel extends PollingChannelBase {
3402
3706
  if (this.boundSnapshotFailureStreak === 1 ||
3403
3707
  this.boundSnapshotFailureStreak % 10 === 0) {
3404
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);
3405
3710
  }
3406
3711
  }
3407
3712
  else {
@@ -3893,17 +4198,22 @@ export class GithubChannel extends PollingChannelBase {
3893
4198
  // target they are logged and retired, never fallen back publicly.
3894
4199
  if (isWatch) {
3895
4200
  process.stderr.write(`[Channel:${this.name}] watch event ${envelope.messageId} has no bound delivery target; retiring without public fallback\n`);
3896
- return true;
4201
+ return { kind: 'retired', reason: 'watch_no_target' };
3897
4202
  }
3898
4203
  if (this.boundRoleAware && this.boundEventAlreadyDelivered(envelope)) {
3899
- // A sibling role already accepted this event privately; a targetless
3900
- // 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.
3901
4211
  process.stderr.write(`[Channel:${this.name}] event ${envelope.messageId} already delivered privately to another role; retiring without public fallback\n`);
3902
4212
  this.markPrivatelyRetired(task);
3903
- return true;
4213
+ return { kind: 'retired', reason: 'already_delivered_other_role' };
3904
4214
  }
3905
4215
  await this.handleInbound(envelope);
3906
- return true;
4216
+ return { kind: 'public' };
3907
4217
  }
3908
4218
  // The target was frozen at claim/detection time. Re-validate it against
3909
4219
  // the latest COMPLETE snapshot: a live rebind must not keep delivering
@@ -3929,7 +4239,11 @@ export class GithubChannel extends PollingChannelBase {
3929
4239
  // their public fallback contract is handled by the gone path below.
3930
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`);
3931
4241
  this.markPrivatelyRetired(task);
3932
- return true;
4242
+ return {
4243
+ kind: 'retired',
4244
+ reason: isWatch ? 'watch_no_candidate' : 'bound_no_candidate',
4245
+ sessionId: delivery.sessionId,
4246
+ };
3933
4247
  }
3934
4248
  }
3935
4249
  // The channel path runs the group/sender/pairing gates inside
@@ -3942,10 +4256,10 @@ export class GithubChannel extends PollingChannelBase {
3942
4256
  const admitted = typeof preflight === 'boolean' ? preflight : await preflight;
3943
4257
  if (!admitted) {
3944
4258
  // The bound path inherits the channel gates (sender allowlist,
3945
- // message routes); a rejection retires the event as delivered, so
3946
- // 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.
3947
4261
  process.stderr.write(`[Channel:${this.name}] bound event ${envelope.messageId} rejected by the channel preflight (sender/route gates); retiring without delivery\n`);
3948
- return true;
4262
+ return { kind: 'retired', reason: 'preflight_rejected' };
3949
4263
  }
3950
4264
  }
3951
4265
  const prompt = this.buildBoundSessionPrompt(envelope, delivery.role, this.boundLaneClass(task.dedupe));
@@ -3989,18 +4303,23 @@ export class GithubChannel extends PollingChannelBase {
3989
4303
  // loop by the finite follower count even if a stale snapshot keeps
3990
4304
  // re-listing dead sessions.
3991
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;
3992
4310
  const roleFilter = this.boundRoleAware
3993
4311
  ? { role: delivery.role }
3994
4312
  : undefined;
3995
4313
  let next = this.resolveBoundDeliveryExcluding(envelope.chatId, task.issueNumber, goneSessions, roleFilter);
3996
4314
  while (next) {
4315
+ lastTarget = next;
3997
4316
  this.transitionInboundTask(task.id, 'running', { delivery: next });
3998
4317
  task.delivery = next;
3999
4318
  try {
4000
4319
  // Same event key: a different session's ring has never seen it.
4001
4320
  await boundSessions.deliverPrompt(next.sessionId, prompt, idempotencyKey);
4002
4321
  this.recordBoundDelivered(envelope, next.sessionId);
4003
- return true;
4322
+ return { kind: 'delivered' };
4004
4323
  }
4005
4324
  catch (retryErr) {
4006
4325
  if (!(retryErr instanceof BoundSessionGoneError))
@@ -4021,7 +4340,11 @@ export class GithubChannel extends PollingChannelBase {
4021
4340
  process.stderr.write(`[Channel:${this.name}] watch event ${envelope.messageId} lost its bound session; retiring without public fallback\n`);
4022
4341
  this.transitionInboundTask(task.id, 'running', { delivery: undefined });
4023
4342
  task.delivery = undefined;
4024
- return true;
4343
+ return {
4344
+ kind: 'retired',
4345
+ reason: 'watch_session_gone',
4346
+ sessionId: lastTarget.sessionId,
4347
+ };
4025
4348
  }
4026
4349
  // Role-aware fan-out: a partially delivered event never ALSO goes
4027
4350
  // public. While any role still follows the PR, the event is (or will
@@ -4033,7 +4356,11 @@ export class GithubChannel extends PollingChannelBase {
4033
4356
  this.boundEventAlreadyDelivered(envelope))) {
4034
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`);
4035
4358
  this.markPrivatelyRetired(task);
4036
- return true;
4359
+ return {
4360
+ kind: 'retired',
4361
+ reason: 'siblings_still_follow',
4362
+ sessionId: lastTarget.sessionId,
4363
+ };
4037
4364
  }
4038
4365
  // Comment events keep today's contract: fall back to the normal
4039
4366
  // channel path so the event is not lost — but only when absence is
@@ -4042,14 +4369,21 @@ export class GithubChannel extends PollingChannelBase {
4042
4369
  // the public reply would be irreversible: defer as backpressure
4043
4370
  // (delivery cleared so recovery re-resolves without a doomed POST)
4044
4371
  // until a complete snapshot lands, same rule as unmatched claims.
4045
- // The false return tells runInboundTask the task was deferred HERE:
4046
- // 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.
4047
4374
  if (this.lastBindingsPartial || this.boundRefreshFailed) {
4048
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;
4049
4383
  task.delivery = undefined;
4050
4384
  if (deferCount >= MAX_BOUND_DEFERRALS) {
4051
4385
  this.retireBoundTask(task, `gone fallback deferred ${deferCount} times; binding snapshot never completed`);
4052
- return false;
4386
+ return { kind: 'deferred' };
4053
4387
  }
4054
4388
  this.transitionInboundTask(task.id, 'failed', {
4055
4389
  delivery: undefined,
@@ -4058,13 +4392,14 @@ export class GithubChannel extends PollingChannelBase {
4058
4392
  deferCount,
4059
4393
  backpressure: true,
4060
4394
  });
4061
- return false;
4395
+ return { kind: 'deferred' };
4062
4396
  }
4063
4397
  this.transitionInboundTask(task.id, 'running', { delivery: undefined });
4064
4398
  task.delivery = undefined;
4065
4399
  await this.handleInbound(envelope);
4400
+ return { kind: 'public' };
4066
4401
  }
4067
- return true;
4402
+ return { kind: 'delivered' };
4068
4403
  }
4069
4404
  prWatchStatePath() {
4070
4405
  return this.channelFilePath('github-pr-watch.json');
@@ -4498,6 +4833,9 @@ export class GithubChannel extends PollingChannelBase {
4498
4833
  // independent subscriptions. Comment events still dedupe across
4499
4834
  // instances via their stable GitHub ids.
4500
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 = [];
4501
4839
  for (const event of events) {
4502
4840
  // ci_failure dedupes per head SHA: once per head even when the
4503
4841
  // aggregate flaps back to success and fails again. The other three
@@ -4560,35 +4898,50 @@ export class GithubChannel extends PollingChannelBase {
4560
4898
  });
4561
4899
  if (next.pending.length > MAX_PENDING_WATCH_PER_ENTRY) {
4562
4900
  const oldest = next.pending[0];
4563
- const record = {
4564
- retiredAt: new Date().toISOString(),
4565
- issueNumber: oldest.issueNumber,
4566
- source: {
4567
- chatId,
4568
- threadId: `pr:${number}`,
4569
- messageId: oldest.key,
4570
- },
4571
- delivery: oldest.delivery,
4572
- reason: `watch pending queue overflow (cap ${MAX_PENDING_WATCH_PER_ENTRY}); oldest event retired undelivered`,
4573
- text: oldest.envelope.text,
4574
- };
4575
- try {
4576
- const path = this.channelFilePath('github-bound-deadletter.jsonl');
4577
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
4578
- appendFileSync(path, `${JSON.stringify(record)}\n`, {
4579
- encoding: 'utf-8',
4580
- mode: 0o600,
4581
- });
4582
- next.pending.shift();
4583
- 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
+ }
4584
4931
  }
4585
- catch (err) {
4586
- // Same fail-safe as retireBoundTask: if the exhaustion surface
4587
- // cannot be written, keep the event queued (over cap) and retry
4588
- // the overflow on the next detection instead of dropping it.
4589
- // Sanitized without truncation, like the retireBoundTask dump.
4590
- const payload = JSON.stringify(record);
4591
- 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`);
4592
4945
  }
4593
4946
  }
4594
4947
  if (event.type === 'ci_failure' && headSha !== undefined) {
@@ -4600,6 +4953,12 @@ export class GithubChannel extends PollingChannelBase {
4600
4953
  // either finds the pending event (drained next poll) or the claimed
4601
4954
  // task (recovery), never a consumed transition with nothing to retry.
4602
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
+ }
4603
4962
  await this.drainPendingWatch(key, next);
4604
4963
  }
4605
4964
  /**
@@ -4632,6 +4991,25 @@ export class GithubChannel extends PollingChannelBase {
4632
4991
  return;
4633
4992
  while (entry.pending && entry.pending.length > 0) {
4634
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
+ }
4635
5013
  // Re-validate the frozen recipient against the latest COMPLETE
4636
5014
  // snapshot: a live rebind must not misdeliver to the old session. On
4637
5015
  // a partial/failed scan the persisted target stands (fail-closed).
@@ -4648,9 +5026,48 @@ export class GithubChannel extends PollingChannelBase {
4648
5026
  }
4649
5027
  else {
4650
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;
4651
5030
  entry.pending = entry.pending.slice(1);
4652
5031
  this.prWatchState.entries[key] = entry;
4653
- 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
+ });
4654
5071
  continue;
4655
5072
  }
4656
5073
  }
@@ -4710,6 +5127,24 @@ export class GithubChannel extends PollingChannelBase {
4710
5127
  async drainPendingWatchRoleAware(key, entry) {
4711
5128
  while (entry.pending && entry.pending.length > 0) {
4712
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
+ }
4713
5148
  const { targets } = this.resolveBoundTargets(pending.envelope.chatId, pending.issueNumber, this.boundEventClass(pending.envelope));
4714
5149
  if (targets.length === 0) {
4715
5150
  // An incomplete enumeration is not an absence: defer instead of