@qwen-code/channel-github 0.26.8 → 0.26.9-nightly.20261106.80fd7c3353

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,11 @@ 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.privateOnly === undefined ||
537
+ typeof record.privateOnly === 'boolean') &&
538
+ (record.lostSessionId === undefined ||
539
+ typeof record.lostSessionId === 'string'));
536
540
  }
537
541
  class FinalPublicationError extends Error {
538
542
  }
@@ -784,6 +788,14 @@ export class GithubChannel extends PollingChannelBase {
784
788
  * recovery keeps running.
785
789
  */
786
790
  watchReconcileBlocked = false;
791
+ /**
792
+ * The cause the blocking watch-guard row last named. The row is
793
+ * edge-triggered per CAUSE, not just per blocked window: a pending backlog
794
+ * that turns into an unreadable sidecar (or back) must re-journal, or the
795
+ * timeline keeps naming a remedy that no longer applies. Cleared on the
796
+ * recovery edge.
797
+ */
798
+ watchReconcileBlockedCause;
787
799
  /**
788
800
  * Consecutive binding-refresh failures since the last success. While no
789
801
  * snapshot has ever succeeded, the cold-start gate defers the comment lane,
@@ -795,6 +807,16 @@ export class GithubChannel extends PollingChannelBase {
795
807
  boundSnapshotFailureStreak = 0;
796
808
  prWatchState = { version: 1, entries: {} };
797
809
  prWatchStateLoaded = false;
810
+ /**
811
+ * Message keys that already have a durable dead-letter record, lazily
812
+ * loaded from the never-rotated dead-letter file on first use and kept
813
+ * current as this process appends. The file is the overflow retire's commit
814
+ * point: a head with a record is never re-appended — even across a restart,
815
+ * which empties this cache and reloads it from disk — and never delivered;
816
+ * the drain completes its retire instead. Watch keys are unique per
817
+ * episode, so a record can only match the same transition.
818
+ */
819
+ deadLetteredKeys;
798
820
  inboundRecoveryPending = true;
799
821
  recoverableInboundTasks = 0;
800
822
  /**
@@ -1434,13 +1456,30 @@ export class GithubChannel extends PollingChannelBase {
1434
1456
  if (this.prWatchEvents.size > 0) {
1435
1457
  try {
1436
1458
  await this.reconcilePendingWatch();
1459
+ const wasBlocked = this.watchReconcileBlocked;
1437
1460
  this.watchReconcileBlocked = false;
1461
+ this.watchReconcileBlockedCause = undefined;
1462
+ // The clearing edge is the recovery signal. A `poll` / `ok` row is
1463
+ // not: the base writes one after every poll that does not throw,
1464
+ // including every poll of a sustained outage, so it is present
1465
+ // throughout the degraded window and cannot mark its end.
1466
+ if (wasBlocked) {
1467
+ this.recordPollDegraded('watch_reconcile_recovered');
1468
+ }
1438
1469
  }
1439
1470
  catch (err) {
1440
1471
  // Recovery must not deliver accepted watch tasks while their pending
1441
1472
  // records are unreconciled (a later drain would deliver them again).
1442
1473
  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`);
1474
+ const message = sanitizeLogText(err instanceof Error ? err.message : String(err), 200);
1475
+ process.stderr.write(`[Channel:${this.name}] pending watch reconciliation failed, will retry next poll: ${message}\n`);
1476
+ // Edge-triggered per cause: this catch runs on EVERY poll while the
1477
+ // watch state stays unreadable, so a per-poll row would rotate the
1478
+ // journal — but a cause that CHANGES while blocked must re-journal.
1479
+ if (this.watchReconcileBlockedCause !== 'reconcile_failed') {
1480
+ this.recordPollDegraded('watch_reconcile_blocked', undefined, message);
1481
+ this.watchReconcileBlockedCause = 'reconcile_failed';
1482
+ }
1444
1483
  }
1445
1484
  }
1446
1485
  else {
@@ -1448,6 +1487,19 @@ export class GithubChannel extends PollingChannelBase {
1448
1487
  // still own their accepted tasks: recovery must not deliver and
1449
1488
  // remove a task that a later re-enabled drain would claim and
1450
1489
  // deliver again. Keep the guard until no watch pending remains.
1490
+ //
1491
+ // Classify the cause first. hasUnreconciledWatchPending() is fail-closed
1492
+ // on a read error, so an unreadable sidecar also blocks recovery — but
1493
+ // reporting that as a pending backlog names a remedy (re-enable
1494
+ // subscriptions) that cannot clear it. The gate below is unchanged.
1495
+ let watchStateError;
1496
+ try {
1497
+ this.loadPrWatchState();
1498
+ }
1499
+ catch (err) {
1500
+ watchStateError = sanitizeLogText(err instanceof Error ? err.message : String(err), 200);
1501
+ }
1502
+ const wasBlocked = this.watchReconcileBlocked;
1451
1503
  this.watchReconcileBlocked = this.hasUnreconciledWatchPending();
1452
1504
  if (this.watchReconcileBlocked) {
1453
1505
  // Park the legacy watch tasks as backpressure so they stop
@@ -1472,7 +1524,27 @@ export class GithubChannel extends PollingChannelBase {
1472
1524
  catch {
1473
1525
  // Task store unreadable/unwritable: fail closed, retry next poll.
1474
1526
  }
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`);
1527
+ 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`);
1528
+ // Edge-triggered per cause, for the same reason as the reconcile
1529
+ // failure above: this branch runs on every poll until an operator
1530
+ // re-enables watch, but a backlog that turns into a read error (or
1531
+ // back) must re-journal so the row never names a stale remedy.
1532
+ const cause = watchStateError ? 'read_error' : 'pending';
1533
+ if (this.watchReconcileBlockedCause !== cause) {
1534
+ if (watchStateError) {
1535
+ this.recordPollDegraded('watch_reconcile_blocked', undefined, watchStateError);
1536
+ }
1537
+ else {
1538
+ this.recordPollDegraded('watch_pending_unreconciled');
1539
+ }
1540
+ this.watchReconcileBlockedCause = cause;
1541
+ }
1542
+ }
1543
+ else {
1544
+ this.watchReconcileBlockedCause = undefined;
1545
+ if (wasBlocked) {
1546
+ this.recordPollDegraded('watch_reconcile_recovered');
1547
+ }
1476
1548
  }
1477
1549
  }
1478
1550
  // The watch pass runs before generic recovery so detection cannot race
@@ -1488,13 +1560,14 @@ export class GithubChannel extends PollingChannelBase {
1488
1560
  if (this.inboundRecoveryPending) {
1489
1561
  try {
1490
1562
  await this.recoverInboundTasks();
1563
+ // Clear only on success: the re-arm below reads an in-memory count
1564
+ // that a failed store read latched at 0, so clearing here would
1565
+ // promise a retry that never runs once the store is readable again.
1566
+ this.inboundRecoveryPending = false;
1491
1567
  }
1492
1568
  catch (err) {
1493
1569
  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
1570
  }
1495
- finally {
1496
- this.inboundRecoveryPending = false;
1497
- }
1498
1571
  }
1499
1572
  // Re-arm recovery before the cold-start gate: persisted tasks must keep
1500
1573
  // retrying even while the comment lane is deferred.
@@ -1529,7 +1602,12 @@ export class GithubChannel extends PollingChannelBase {
1529
1602
  this.coldEmptyPartialStreak < MAX_COLD_EMPTY_PARTIAL_POLLS) {
1530
1603
  if (this.coldEmptyPartialStreak === 1 ||
1531
1604
  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`);
1605
+ 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`);
1606
+ // This gate returns before the comment lane sets its poll detail, so
1607
+ // the degraded row is the ONLY journal trace of a stalled cold start.
1608
+ this.recordPollDegraded('bindings_cold_empty', {
1609
+ streak: this.coldEmptyPartialStreak,
1610
+ });
1533
1611
  }
1534
1612
  return;
1535
1613
  }
@@ -1802,6 +1880,12 @@ export class GithubChannel extends PollingChannelBase {
1802
1880
  async processCommentLane(ctx, onlyMentioned, directed = false) {
1803
1881
  const comments = await this.fetchNewComments(ctx);
1804
1882
  let dispatched = false;
1883
+ // Comments that only the bound path's mention waiver admits are private
1884
+ // deliveries the lane did not make before. They run after the rest of
1885
+ // the lane and the first-contact body, so their outcome (a gone session
1886
+ // evicted from the binding map, a deferral) cannot change how those are
1887
+ // handled.
1888
+ const waived = [];
1805
1889
  for (const comment of comments) {
1806
1890
  const key = comment.node_id || String(comment.id);
1807
1891
  const senderId = (comment.user?.login || 'unknown').toLowerCase();
@@ -1825,7 +1909,19 @@ export class GithubChannel extends PollingChannelBase {
1825
1909
  const hasMention = this.botUsername
1826
1910
  ? testBotMention(body, this.botUsername)
1827
1911
  : false;
1828
- if (onlyMentioned && !hasMention) {
1912
+ const text = this.botUsername
1913
+ ? stripBotMention(body, this.botUsername)
1914
+ : body;
1915
+ // A plain comment on a bound PR passes when the private path would
1916
+ // admit and deliver it: the preflight then only waives the mention
1917
+ // requirement. It is a conversation comment, not the thread's mention
1918
+ // or review request, so it resolves as a `comment` event.
1919
+ const mentionWaived = onlyMentioned &&
1920
+ !hasMention &&
1921
+ this.waivesBoundMention(ctx.chatId, senderId) &&
1922
+ this.admitsMessageRoute(text) &&
1923
+ this.resolveBoundTargets(ctx.chatId, ctx.issueNumber, 'comment', 'comment').targets.length > 0;
1924
+ if (onlyMentioned && !hasMention && !mentionWaived) {
1829
1925
  if (!this.journalOncePerWindow(`mention_required\0${key}`))
1830
1926
  continue;
1831
1927
  this.recordChannelEvent({
@@ -1854,7 +1950,7 @@ export class GithubChannel extends PollingChannelBase {
1854
1950
  chatId: ctx.chatId,
1855
1951
  threadId: ctx.threadId,
1856
1952
  messageId: String(comment.id),
1857
- text: this.botUsername ? stripBotMention(body, this.botUsername) : body,
1953
+ text,
1858
1954
  isGroup: true,
1859
1955
  // Never synthesize a mention into an unapproved pairing group: the
1860
1956
  // pairing step must keep dropping ambient comments, and a synthesized
@@ -1865,8 +1961,20 @@ export class GithubChannel extends PollingChannelBase {
1865
1961
  (this.config.groupPolicy !== 'pairing' ||
1866
1962
  this.groupGate.isGroupApproved(ctx.chatId))),
1867
1963
  isReplyToBot: false,
1868
- metadata: this.buildRouteMetadata(ctx),
1964
+ metadata: this.buildRouteMetadata(mentionWaived ? { ...ctx, reason: 'comment' } : ctx),
1869
1965
  };
1966
+ // Elsewhere the lane passes every comment, and the private path's
1967
+ // preflight waives the mention a group requirement would refuse.
1968
+ if (mentionWaived ||
1969
+ (!onlyMentioned &&
1970
+ !envelope.isMentioned &&
1971
+ this.resolveBoundTargets(ctx.chatId, ctx.issueNumber, ctx.reason, 'comment').targets.length > 0 &&
1972
+ this.waivesBoundMention(ctx.chatId, senderId) &&
1973
+ this.groupGate.check(envelope, { createPairingRequest: false })
1974
+ .reason === 'mention_required')) {
1975
+ waived.push({ envelope, key, privateOnly: mentionWaived });
1976
+ continue;
1977
+ }
1870
1978
  if (!(await this.dispatchEnvelope(envelope, ctx.issueNumber, {
1871
1979
  dispatchedComments: [key],
1872
1980
  }))) {
@@ -1887,8 +1995,18 @@ export class GithubChannel extends PollingChannelBase {
1887
1995
  this.recordDispatchedBody(`${ctx.chatId}|${ctx.threadId}`);
1888
1996
  }
1889
1997
  }
1890
- if (!dispatched && !ctx.lastReadAt) {
1891
- await this.tryFirstContactBody(ctx, onlyMentioned);
1998
+ try {
1999
+ if (!dispatched && !ctx.lastReadAt) {
2000
+ await this.tryFirstContactBody(ctx, onlyMentioned);
2001
+ }
2002
+ }
2003
+ finally {
2004
+ // A failing body read must not keep these from their sessions.
2005
+ for (const { envelope, key, privateOnly } of waived) {
2006
+ if (await this.dispatchEnvelope(envelope, ctx.issueNumber, { dispatchedComments: [key] }, privateOnly)) {
2007
+ this.recordDispatchedComment(key);
2008
+ }
2009
+ }
1892
2010
  }
1893
2011
  }
1894
2012
  async processDirectLane(ctx, reason) {
@@ -2227,7 +2345,7 @@ export class GithubChannel extends PollingChannelBase {
2227
2345
  }
2228
2346
  }
2229
2347
  }
2230
- async dispatchEnvelope(envelope, issueNumber, dedupe = {}) {
2348
+ async dispatchEnvelope(envelope, issueNumber, dedupe = {}, privateOnly = false) {
2231
2349
  // The publication audit is the durable consumption record for the
2232
2350
  // public path: a reply can land (audit `posted`), the task be removed,
2233
2351
  // and the cursor save still be lost (mark-read failure, crash). The
@@ -2286,7 +2404,7 @@ export class GithubChannel extends PollingChannelBase {
2286
2404
  kind: 'bound-session',
2287
2405
  sessionId: target.sessionId,
2288
2406
  ...(target.role ? { role: target.role } : {}),
2289
- }, first && targets.length > 1 ? targets : undefined));
2407
+ }, first && targets.length > 1 ? targets : undefined, privateOnly));
2290
2408
  first = false;
2291
2409
  }
2292
2410
  let settled = true;
@@ -2310,12 +2428,29 @@ export class GithubChannel extends PollingChannelBase {
2310
2428
  // incomplete evidence.
2311
2429
  this.applyTaskDedupe(dedupe);
2312
2430
  process.stderr.write(`[Channel:${this.name}] event ${envelope.messageId} matched no role's boundSessionActions; retiring without public fallback\n`);
2431
+ // Retired before any task was claimed, so there is no task row to
2432
+ // close: the skip is the event's only journal trace. The dedupe cursor
2433
+ // is still in memory here — the base saves it after pollOnce returns —
2434
+ // so this row is at-least-once: if that cursor write fails or the daemon
2435
+ // dies first, the notification re-lists and the same event may produce a
2436
+ // second identical skip row.
2437
+ this.recordChannelEvent({
2438
+ type: 'inbound',
2439
+ outcome: 'skipped',
2440
+ reason: 'no_role_matched',
2441
+ triggerKind: parseTriggerKind(envelope.metadata),
2442
+ repository: envelope.chatId,
2443
+ thread: envelope.threadId,
2444
+ number: issueNumber,
2445
+ messageId: envelope.messageId,
2446
+ actor: envelope.senderId,
2447
+ });
2313
2448
  return true;
2314
2449
  }
2315
- const task = this.claimInboundTask(envelope, issueNumber, dedupe);
2450
+ const task = this.claimInboundTask(envelope, issueNumber, dedupe, undefined, undefined, privateOnly);
2316
2451
  return this.runInboundTask(task);
2317
2452
  }
2318
- claimInboundTask(envelope, issueNumber, dedupe, delivery, fanout) {
2453
+ claimInboundTask(envelope, issueNumber, dedupe, delivery, fanout, privateOnly = false) {
2319
2454
  const existing = this.readInboundTasks().find((record) => record.source.chatId === envelope.chatId &&
2320
2455
  record.source.threadId === envelope.threadId &&
2321
2456
  record.source.messageId === envelope.messageId &&
@@ -2362,6 +2497,7 @@ export class GithubChannel extends PollingChannelBase {
2362
2497
  attempts: 0,
2363
2498
  ...(delivery ? { delivery } : {}),
2364
2499
  ...(fanout ? { fanout } : {}),
2500
+ ...(privateOnly ? { privateOnly: true } : {}),
2365
2501
  };
2366
2502
  this.updateInboundTasks((records) => [...records, task]);
2367
2503
  this.applyTaskDedupe(task.dedupe);
@@ -2431,6 +2567,9 @@ export class GithubChannel extends PollingChannelBase {
2431
2567
  // (private-only), so they share the no-charge running transition.
2432
2568
  this.transitionInboundTask(task.id, 'running', bound || isWatch ? {} : { attempts });
2433
2569
  let cancelled = false;
2570
+ // The public path journals its own acceptance and publication; only
2571
+ // bound delivery needs a verdict to name its terminal outcome.
2572
+ let boundResult = { kind: 'public' };
2434
2573
  try {
2435
2574
  // Watch events are private-only: route them by envelope identity, not
2436
2575
  // by the current delivery. A watch task whose delivery was cleared (a
@@ -2438,8 +2577,8 @@ export class GithubChannel extends PollingChannelBase {
2438
2577
  // target) must never fall through to the public channel path —
2439
2578
  // deliverToBoundSession retires a targetless watch event privately.
2440
2579
  if (bound || isWatch) {
2441
- const settled = await this.deliverToBoundSession(task, envelope);
2442
- if (!settled)
2580
+ boundResult = await this.deliverToBoundSession(task, envelope);
2581
+ if (boundResult.kind === 'deferred')
2443
2582
  return false;
2444
2583
  }
2445
2584
  else if (this.boundRoleAware &&
@@ -2452,6 +2591,9 @@ export class GithubChannel extends PollingChannelBase {
2452
2591
  this.retireBoundTask(task, 'event already delivered privately to another role; suppressing public duplicate');
2453
2592
  return true;
2454
2593
  }
2594
+ else if (task.privateOnly === true) {
2595
+ boundResult = this.retirePrivateOnly(task, envelope);
2596
+ }
2455
2597
  else {
2456
2598
  await this.handleInbound(envelope);
2457
2599
  }
@@ -2490,7 +2632,7 @@ export class GithubChannel extends PollingChannelBase {
2490
2632
  let posted = task.errorCommentPosted === true;
2491
2633
  // Bound-session delivery is private: a failure must not post a public
2492
2634
  // error comment. The fallback path clears delivery before retrying.
2493
- if (!posted && !stillBound) {
2635
+ if (!posted && !stillBound && task.privateOnly !== true) {
2494
2636
  posted = await this.postErrorComment(envelope.chatId, task.issueNumber, this.getInboundErrorSourceLabel(envelope));
2495
2637
  }
2496
2638
  // Queue full and temporarily-unavailable sessions/workspaces are
@@ -2552,9 +2694,19 @@ export class GithubChannel extends PollingChannelBase {
2552
2694
  // deduplicates, stable across task re-creation), but the mark still
2553
2695
  // retires the task without a needless round-trip.
2554
2696
  if (task.delivery?.kind === 'bound-session') {
2697
+ // Only a delivered or retired verdict reaches here with the delivery
2698
+ // still set — the public-fallback exits clear it. The verdict supplies
2699
+ // the journal's terminal word: without it a preflight-rejected event
2700
+ // would still end on `running`, indistinguishable from a delivery in
2701
+ // flight, because that exit consumes the task with its delivery set.
2702
+ const journal = boundResult.kind === 'delivered'
2703
+ ? { outcome: 'delivered' }
2704
+ : boundResult.kind === 'retired'
2705
+ ? { outcome: 'retired', reason: boundResult.reason }
2706
+ : undefined;
2555
2707
  this.transitionInboundTask(task.id, 'running', {
2556
2708
  deliveredAt: Date.now(),
2557
- });
2709
+ }, journal);
2558
2710
  // The slot mark must be durable BEFORE the accepted task is removed:
2559
2711
  // it is the only evidence connecting the acceptance to the original
2560
2712
  // fanout slot across retargeting. A write failure fails the poll
@@ -2575,6 +2727,13 @@ export class GithubChannel extends PollingChannelBase {
2575
2727
  // unrelated file's readability.
2576
2728
  this.privatelyRetiredInboundTaskIds.delete(task.id);
2577
2729
  this.removeInboundTask(task.id);
2730
+ // After the removal, like the dead-letter site: a throwing removal
2731
+ // leaves the task recoverable, and the journal must not claim a retire
2732
+ // that did not happen — the next poll would then write a second
2733
+ // terminal row with a different, false reason.
2734
+ if (boundResult.kind === 'retired') {
2735
+ this.recordBoundTaskEvent(task, 'retired', boundResult.reason, undefined, boundResult.sessionId);
2736
+ }
2578
2737
  return true;
2579
2738
  }
2580
2739
  if (this.hasPendingFinalDeliveryForTask(task)) {
@@ -2620,7 +2779,7 @@ export class GithubChannel extends PollingChannelBase {
2620
2779
  kind: 'bound-session',
2621
2780
  sessionId: target.sessionId,
2622
2781
  ...(target.role ? { role: target.role } : {}),
2623
- });
2782
+ }, undefined, task.privateOnly === true);
2624
2783
  }
2625
2784
  }
2626
2785
  const tasks = this.readInboundTasks().filter((task) => this.isRecoverableInboundTask(task));
@@ -2702,7 +2861,7 @@ export class GithubChannel extends PollingChannelBase {
2702
2861
  kind: 'bound-session',
2703
2862
  sessionId: target.sessionId,
2704
2863
  ...(target.role ? { role: target.role } : {}),
2705
- });
2864
+ }, undefined, task.privateOnly === true);
2706
2865
  }
2707
2866
  }
2708
2867
  else if (followed &&
@@ -2807,6 +2966,13 @@ export class GithubChannel extends PollingChannelBase {
2807
2966
  issueNumber: task.issueNumber,
2808
2967
  source: task.source,
2809
2968
  delivery: task.delivery,
2969
+ // A cleared delivery leaves the record without a target; name the
2970
+ // session the event lost so operator recovery knows where it was
2971
+ // bound. Only when the delivery is gone — a live delivery is the
2972
+ // authoritative target and an older lostSessionId would be stale.
2973
+ ...(task.delivery?.kind !== 'bound-session' && task.lostSessionId
2974
+ ? { lostSessionId: task.lostSessionId }
2975
+ : {}),
2810
2976
  reason,
2811
2977
  text: task.envelope?.text,
2812
2978
  };
@@ -2831,10 +2997,17 @@ export class GithubChannel extends PollingChannelBase {
2831
2997
  // — enough to forge extra log lines from untrusted event text.
2832
2998
  const payload = JSON.stringify(record);
2833
2999
  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`);
3000
+ // The task is kept, so this is a failure, not a retire. Only the write
3001
+ // error is journaled: `payload` carries the message body, which the
3002
+ // journal must never hold.
3003
+ this.recordBoundTaskEvent(task, 'failed', 'dead_letter_write_failed', sanitizeLogText(err instanceof Error ? err.message : String(err), 200));
2834
3004
  return;
2835
3005
  }
2836
3006
  process.stderr.write(`[Channel:${this.name}] bound event retired to dead-letter (${task.source.messageId}): ${reason}\n`);
2837
3007
  this.removeInboundTask(task.id);
3008
+ // After the removal: a throwing removal leaves the task recoverable, and
3009
+ // the journal must not claim a retire that did not happen.
3010
+ this.recordBoundTaskEvent(task, 'retired', 'dead_letter', reason);
2838
3011
  }
2839
3012
  hasPendingFinalDeliveryForTask(task) {
2840
3013
  return this.readPendingFinalDeliveries(true).some((record) => record.chatId === task.source.chatId &&
@@ -2904,22 +3077,61 @@ export class GithubChannel extends PollingChannelBase {
2904
3077
  }
2905
3078
  }
2906
3079
  }
2907
- transitionInboundTask(taskId, state, updates = {}) {
2908
- const records = this.updateInboundTasks((existing) => existing.map((record) => record.id === taskId
2909
- ? {
3080
+ transitionInboundTask(taskId, state, updates = {},
3081
+ /**
3082
+ * Overrides the journaled outcome without touching the persisted state.
3083
+ * The bound acceptance mark is persisted as `running` (there is no
3084
+ * `delivered` task state — the record is removed right after), but the
3085
+ * journal's last word for that event must be terminal, not in-flight.
3086
+ */
3087
+ journal) {
3088
+ // The exits that hand an event back to the public lane persist
3089
+ // `delivery: undefined`, and the record is re-read AFTER the update, so
3090
+ // the row would lose the session it is about. Remember the target the
3091
+ // task held going in: "which session lost this event" is the question
3092
+ // the private lane's attribution exists to answer.
3093
+ let previousSessionId;
3094
+ const records = this.updateInboundTasks((existing) => existing.map((record) => {
3095
+ if (record.id !== taskId)
3096
+ return record;
3097
+ if (record.delivery?.kind === 'bound-session') {
3098
+ previousSessionId = record.delivery.sessionId;
3099
+ }
3100
+ return {
2910
3101
  ...record,
2911
3102
  ...updates,
3103
+ // Persist the lost target, not just this row's attribution: the
3104
+ // gone-session fallback clears the delivery, and every later poll
3105
+ // re-enters the absence gate and finally the dead-letter with no
3106
+ // delivery left to read. Remembering it for one transition would
3107
+ // leave all of those rows — including the terminal one — unnamed.
3108
+ // Only an EXPLICIT clear counts; an update that merely omits the
3109
+ // key must not touch it.
3110
+ ...('delivery' in updates &&
3111
+ updates.delivery === undefined &&
3112
+ previousSessionId !== undefined
3113
+ ? { lostSessionId: previousSessionId }
3114
+ : {}),
2912
3115
  state,
2913
3116
  updatedAt: new Date().toISOString(),
2914
- }
2915
- : record));
3117
+ };
3118
+ }));
2916
3119
  const task = records.find((record) => record.id === taskId);
2917
3120
  if (!task)
2918
3121
  return;
2919
3122
  const envelope = task.envelope;
3123
+ // Read the delivery from the UPDATED record: a retarget or a gone
3124
+ // fallback clears it mid-run, and the journal row must name the
3125
+ // session the transition actually refers to. A cleared delivery falls
3126
+ // back to the target this transition lost, so the row still names it.
3127
+ const identity = this.boundJournalIdentity(task.delivery);
3128
+ const sessionId = identity.sessionId ?? previousSessionId ?? task.lostSessionId;
3129
+ const sessionWorkspaceCwd = identity.sessionWorkspaceCwd ??
3130
+ (sessionId ? this.sessionWorkspaceFor(sessionId) : undefined);
2920
3131
  this.recordChannelEvent({
2921
3132
  type: 'task',
2922
- outcome: state,
3133
+ outcome: journal?.outcome ?? state,
3134
+ ...(journal?.reason ? { reason: journal.reason } : {}),
2923
3135
  ...(envelope
2924
3136
  ? {
2925
3137
  triggerKind: parseTriggerKind(envelope.metadata),
@@ -2930,16 +3142,47 @@ export class GithubChannel extends PollingChannelBase {
2930
3142
  thread: task.source.threadId,
2931
3143
  number: task.issueNumber,
2932
3144
  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),
3145
+ ...(sessionId ? { sessionId } : {}),
3146
+ ...(sessionWorkspaceCwd ? { sessionWorkspaceCwd } : {}),
2937
3147
  ...(updates.attempts !== undefined
2938
3148
  ? { detail: { attempts: updates.attempts } }
2939
3149
  : {}),
2940
3150
  ...(updates.error ? { error: updates.error } : {}),
2941
3151
  });
2942
3152
  }
3153
+ /**
3154
+ * Journals a terminal decision about a bound event that never reached a
3155
+ * session: a private retire or a dead-letter. Identifiers only — the
3156
+ * dead-letter record's `text` (the message body) must never be copied here.
3157
+ * `sessionId` names the target the event lost when the delivery was already
3158
+ * cleared from the record.
3159
+ */
3160
+ recordBoundTaskEvent(task, outcome, reason, error, sessionId) {
3161
+ const envelope = task.envelope;
3162
+ const target = sessionId ??
3163
+ (task.delivery?.kind === 'bound-session'
3164
+ ? task.delivery.sessionId
3165
+ : task.lostSessionId);
3166
+ const workspaceCwd = target ? this.sessionWorkspaceFor(target) : undefined;
3167
+ this.recordChannelEvent({
3168
+ type: 'task',
3169
+ outcome,
3170
+ reason,
3171
+ ...(envelope
3172
+ ? {
3173
+ triggerKind: parseTriggerKind(envelope.metadata),
3174
+ actor: envelope.senderId,
3175
+ }
3176
+ : {}),
3177
+ repository: task.source.chatId,
3178
+ thread: task.source.threadId,
3179
+ number: task.issueNumber,
3180
+ messageId: task.source.messageId,
3181
+ ...(target ? { sessionId: target } : {}),
3182
+ ...(workspaceCwd ? { sessionWorkspaceCwd: workspaceCwd } : {}),
3183
+ ...(error ? { error } : {}),
3184
+ });
3185
+ }
2943
3186
  /**
2944
3187
  * Session identity for journal rows about a bound delivery, so the events
2945
3188
  * page can link the row to the session that received the event. The
@@ -2956,9 +3199,93 @@ export class GithubChannel extends PollingChannelBase {
2956
3199
  ...(workspaceCwd ? { sessionWorkspaceCwd: workspaceCwd } : {}),
2957
3200
  };
2958
3201
  }
3202
+ /**
3203
+ * The workspace a bound session lives in, from the latest binding list, so
3204
+ * a journal row's Open-session button reaches a session in ANOTHER
3205
+ * workspace instead of falling back to the Channel's own (the daemon would
3206
+ * answer 404). Undefined when the session is not currently listed.
3207
+ */
3208
+ sessionWorkspaceFor(sessionId) {
3209
+ return this.lastBindings.find((binding) => binding.sessionId === sessionId)
3210
+ ?.workspaceCwd;
3211
+ }
3212
+ /**
3213
+ * Whether a message key already has a durable dead-letter record. Loads the
3214
+ * never-rotated file's keys once, then serves from the cache this process
3215
+ * keeps current on append. A read failure yields an empty cache: nothing is
3216
+ * known to be dead-lettered, so the caller appends (a possible duplicate is
3217
+ * benign) rather than silently skipping the exhaustion surface.
3218
+ */
3219
+ isDeadLettered(messageKey) {
3220
+ if (this.deadLetteredKeys === undefined) {
3221
+ const keys = new Set();
3222
+ try {
3223
+ const raw = readFileSync(this.channelFilePath('github-bound-deadletter.jsonl'), 'utf-8');
3224
+ for (const line of raw.split('\n')) {
3225
+ if (!line)
3226
+ continue;
3227
+ try {
3228
+ const rec = JSON.parse(line);
3229
+ if (typeof rec.source?.messageId === 'string') {
3230
+ keys.add(rec.source.messageId);
3231
+ }
3232
+ }
3233
+ catch {
3234
+ // A malformed line names no key; skip it.
3235
+ }
3236
+ }
3237
+ }
3238
+ catch {
3239
+ // No file yet, or unreadable: nothing known to be dead-lettered.
3240
+ }
3241
+ this.deadLetteredKeys = keys;
3242
+ }
3243
+ return this.deadLetteredKeys.has(messageKey);
3244
+ }
3245
+ /**
3246
+ * The overflow retire's journal trace, written only after the retire is
3247
+ * durable. Identifiers only — the dead-letter record's `text` (the body)
3248
+ * must never be copied here. Carries the frozen target and its workspace so
3249
+ * the row links to the session the event lost, even in another workspace.
3250
+ */
3251
+ recordWatchOverflowSkip(pending) {
3252
+ const sessionId = pending.delivery?.kind === 'bound-session'
3253
+ ? pending.delivery.sessionId
3254
+ : undefined;
3255
+ const workspaceCwd = sessionId
3256
+ ? this.sessionWorkspaceFor(sessionId)
3257
+ : undefined;
3258
+ this.recordChannelEvent({
3259
+ type: 'inbound',
3260
+ outcome: 'skipped',
3261
+ reason: 'watch_pending_overflow',
3262
+ repository: pending.envelope.chatId,
3263
+ thread: pending.envelope.threadId,
3264
+ number: pending.issueNumber,
3265
+ messageId: pending.key,
3266
+ ...(sessionId ? { sessionId } : {}),
3267
+ ...(workspaceCwd ? { sessionWorkspaceCwd: workspaceCwd } : {}),
3268
+ });
3269
+ }
2959
3270
  removeInboundTask(taskId) {
2960
3271
  this.updateInboundTasks((records) => records.filter((record) => record.id !== taskId));
2961
3272
  }
3273
+ /**
3274
+ * Journals a degraded dependency the poll loop itself survived: the poll
3275
+ * still reports `ok`, so without this row a binding scan that stalls every
3276
+ * notification is invisible in the timeline. Emitted only where the
3277
+ * adapter already throttles its stderr line (or on a state edge), so a
3278
+ * permanent outage cannot rotate the useful rows out of the journal.
3279
+ */
3280
+ recordPollDegraded(reason, detail, error) {
3281
+ this.recordChannelEvent({
3282
+ type: 'poll',
3283
+ outcome: 'degraded',
3284
+ reason,
3285
+ ...(detail ? { detail } : {}),
3286
+ ...(error ? { error } : {}),
3287
+ });
3288
+ }
2962
3289
  updateInboundTasks(update) {
2963
3290
  try {
2964
3291
  const records = update(this.readInboundTasks());
@@ -3284,6 +3611,10 @@ export class GithubChannel extends PollingChannelBase {
3284
3611
  }
3285
3612
  }
3286
3613
  }
3614
+ // Sessions the routing map still routes to besides the ones this scan
3615
+ // listed. Under a partial answer retention keeps unlisted sessions, so
3616
+ // the scan's own row count alone can be 0 while the map is not.
3617
+ let retainedSessionCount = 0;
3287
3618
  if (snapshot.partial) {
3288
3619
  // An incomplete enumeration is not an absence: keep every known
3289
3620
  // binding the partial answer failed to list, so private delivery
@@ -3307,6 +3638,7 @@ export class GithubChannel extends PollingChannelBase {
3307
3638
  .sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''))
3308
3639
  .slice(0, MAX_PARTIAL_RETAINED)
3309
3640
  : retained;
3641
+ retainedSessionCount = retainedCapped.length;
3310
3642
  if (retainedCapped.length < retained.length) {
3311
3643
  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
3644
  }
@@ -3338,7 +3670,10 @@ export class GithubChannel extends PollingChannelBase {
3338
3670
  if (snapshot.partial && map.size === 0 && !this.boundSnapshotTrusted) {
3339
3671
  this.coldEmptyPartialStreak += 1;
3340
3672
  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`);
3673
+ 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`);
3674
+ this.recordPollDegraded('bindings_cold_empty', {
3675
+ streak: this.coldEmptyPartialStreak,
3676
+ });
3342
3677
  }
3343
3678
  }
3344
3679
  else {
@@ -3355,11 +3690,23 @@ export class GithubChannel extends PollingChannelBase {
3355
3690
  if ((snapshot.bindings.length > 0 || map.size > 0) &&
3356
3691
  (this.partialSnapshotStreak === 10 ||
3357
3692
  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 &&
3693
+ // The routing map is keyed per PR, so its size counts bound PRs,
3694
+ // not sessions: one session following two PRs would be reported as
3695
+ // two. Count session rows instead — the ones this scan listed plus
3696
+ // the ones retention keeps routing to. Reporting only the listed
3697
+ // rows would say "0 sessions listed" for a draining workspace whose
3698
+ // retained sessions are still receiving deliveries, and hand the
3699
+ // operator a page-cap diagnosis for a state that is not a page cap.
3700
+ const listedSessions = snapshot.bindings.length + retainedSessionCount;
3701
+ 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
3702
  map.size === 0 &&
3360
3703
  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.`
3704
+ ? `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
3705
  : '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`);
3706
+ this.recordPollDegraded('bindings_partial', {
3707
+ streak: this.partialSnapshotStreak,
3708
+ sessions: listedSessions,
3709
+ });
3363
3710
  }
3364
3711
  }
3365
3712
  else {
@@ -3390,9 +3737,12 @@ export class GithubChannel extends PollingChannelBase {
3390
3737
  this.coldEmptyPartialStreak += 1;
3391
3738
  this.coldEmptyFailurePolls += 1;
3392
3739
  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
3740
+ process.stderr.write(`[Channel:${this.name}] binding snapshot has been an empty partial for ${this.coldEmptyPartialStreak} consecutive binding scans: ${this.boundSnapshotSeen
3394
3741
  ? 'opening the comment lane. Unmatched PR events will defer (and dead-letter after the backpressure horizon) until a complete snapshot establishes absence.'
3395
3742
  : 'the comment lane stays closed until a snapshot succeeds; every notification, issue events included, remains stalled.'} ${this.coldEmptyCapCause()}\n`);
3743
+ this.recordPollDegraded('bindings_cold_empty', {
3744
+ streak: this.coldEmptyPartialStreak,
3745
+ });
3396
3746
  }
3397
3747
  // Surface the stall distinctly and actionably, throttled so a
3398
3748
  // transient outage does not spam; the misleading "keeping previous
@@ -3402,6 +3752,7 @@ export class GithubChannel extends PollingChannelBase {
3402
3752
  if (this.boundSnapshotFailureStreak === 1 ||
3403
3753
  this.boundSnapshotFailureStreak % 10 === 0) {
3404
3754
  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`);
3755
+ this.recordPollDegraded('bindings_unreachable', { streak: this.boundSnapshotFailureStreak }, detail);
3405
3756
  }
3406
3757
  }
3407
3758
  else {
@@ -3592,6 +3943,26 @@ export class GithubChannel extends PollingChannelBase {
3592
3943
  task.source.threadId === envelope.threadId &&
3593
3944
  task.source.messageId === envelope.messageId);
3594
3945
  }
3946
+ /**
3947
+ * A comment that only the bound path's mention waiver admitted never takes
3948
+ * the channel path: with no bound session left it is retired privately.
3949
+ * The retire row names the session it lost: `sessionId` when the caller
3950
+ * knows it, else the delivery the task still held.
3951
+ */
3952
+ retirePrivateOnly(task, envelope, sessionId) {
3953
+ process.stderr.write(`[Channel:${this.name}] bound event ${envelope.messageId} has no bound session left and has no mention for a public reply; retiring without public fallback\n`);
3954
+ // Read before markPrivatelyRetired clears the delivery.
3955
+ const lost = sessionId ??
3956
+ (task.delivery?.kind === 'bound-session'
3957
+ ? task.delivery.sessionId
3958
+ : undefined);
3959
+ this.markPrivatelyRetired(task);
3960
+ return {
3961
+ kind: 'retired',
3962
+ reason: 'private_only_no_target',
3963
+ ...(lost ? { sessionId: lost } : {}),
3964
+ };
3965
+ }
3595
3966
  /**
3596
3967
  * Persist a terminal private retirement BEFORE the routing identity is
3597
3968
  * cleared or the task removed: if the removal then fails (EIO), restart
@@ -3818,6 +4189,25 @@ export class GithubChannel extends PollingChannelBase {
3818
4189
  }
3819
4190
  this.lastBindings = this.lastBindings.filter((binding) => binding.sessionId !== sessionId);
3820
4191
  }
4192
+ /**
4193
+ * Whether a plain comment by this sender reaches a bound session without
4194
+ * the repository's mention requirement. That requirement keeps ambient
4195
+ * chatter out of public replies and is no authorization boundary, so the
4196
+ * private path can drop it — but only for senders the repository lists:
4197
+ * with open senders every drive-by or bot comment would become a turn of
4198
+ * the session. Callers check that the PR is bound.
4199
+ */
4200
+ waivesBoundMention(chatId, senderId) {
4201
+ const target = { isGroup: true, chatId };
4202
+ const sender = senderId.toLowerCase();
4203
+ return (
4204
+ // A bound session usually acts on GitHub as an operator's account, so
4205
+ // without a mention its own comments would come back to it as turns.
4206
+ !(this.config.operators ?? []).some((operator) => operator.toLowerCase() === sender) &&
4207
+ this.groupGate.admits(chatId) &&
4208
+ this.groupSendersFor(target) === 'allowlist' &&
4209
+ this.senderGateFor(target).isAllowed(senderId));
4210
+ }
3821
4211
  buildBoundSessionPrompt(envelope, role, laneClass) {
3822
4212
  // The first metadata line is the `Type: … | Title: … | URL: …` identity
3823
4213
  // built by buildMetadata; the publication instructions that follow it in
@@ -3893,17 +4283,25 @@ export class GithubChannel extends PollingChannelBase {
3893
4283
  // target they are logged and retired, never fallen back publicly.
3894
4284
  if (isWatch) {
3895
4285
  process.stderr.write(`[Channel:${this.name}] watch event ${envelope.messageId} has no bound delivery target; retiring without public fallback\n`);
3896
- return true;
4286
+ return { kind: 'retired', reason: 'watch_no_target' };
3897
4287
  }
3898
4288
  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).
4289
+ // Defensive: a sibling role already accepted this event privately, so
4290
+ // a targetless retry must not answer it publicly (durable delivery
4291
+ // ring). Unreachable in practice — boundRoleAware requires
4292
+ // boundSessionActions, which the constructor clears in standalone
4293
+ // mode, and a bound delivery implies a live boundSessions handle — so
4294
+ // this reason is NOT part of the published vocabulary. Kept as a guard
4295
+ // against a future call path that clears the delivery mid-run.
3901
4296
  process.stderr.write(`[Channel:${this.name}] event ${envelope.messageId} already delivered privately to another role; retiring without public fallback\n`);
3902
4297
  this.markPrivatelyRetired(task);
3903
- return true;
4298
+ return { kind: 'retired', reason: 'already_delivered_other_role' };
4299
+ }
4300
+ if (task.privateOnly === true) {
4301
+ return this.retirePrivateOnly(task, envelope);
3904
4302
  }
3905
4303
  await this.handleInbound(envelope);
3906
- return true;
4304
+ return { kind: 'public' };
3907
4305
  }
3908
4306
  // The target was frozen at claim/detection time. Re-validate it against
3909
4307
  // the latest COMPLETE snapshot: a live rebind must not keep delivering
@@ -3929,7 +4327,11 @@ export class GithubChannel extends PollingChannelBase {
3929
4327
  // their public fallback contract is handled by the gone path below.
3930
4328
  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
4329
  this.markPrivatelyRetired(task);
3932
- return true;
4330
+ return {
4331
+ kind: 'retired',
4332
+ reason: isWatch ? 'watch_no_candidate' : 'bound_no_candidate',
4333
+ sessionId: delivery.sessionId,
4334
+ };
3933
4335
  }
3934
4336
  }
3935
4337
  // The channel path runs the group/sender/pairing gates inside
@@ -3938,14 +4340,19 @@ export class GithubChannel extends PollingChannelBase {
3938
4340
  // included). Watch events have no human sender — they are operator
3939
4341
  // opt-in state changes — and are exempt.
3940
4342
  if (!isWatch) {
3941
- const preflight = this.preflightInbound(envelope);
4343
+ // A first-contact body is the PR's own description, not a comment
4344
+ // for the session: it keeps the mention requirement.
4345
+ const preflight = this.preflightInbound(envelope, {
4346
+ waiveGroupMention: !envelope.messageId?.startsWith('issue-body-') &&
4347
+ this.waivesBoundMention(envelope.chatId, envelope.senderId),
4348
+ });
3942
4349
  const admitted = typeof preflight === 'boolean' ? preflight : await preflight;
3943
4350
  if (!admitted) {
3944
4351
  // 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.
4352
+ // message routes); a rejection retires the event without delivering
4353
+ // it, so surface it instead of consuming it silently.
3947
4354
  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;
4355
+ return { kind: 'retired', reason: 'preflight_rejected' };
3949
4356
  }
3950
4357
  }
3951
4358
  const prompt = this.buildBoundSessionPrompt(envelope, delivery.role, this.boundLaneClass(task.dedupe));
@@ -3989,18 +4396,23 @@ export class GithubChannel extends PollingChannelBase {
3989
4396
  // loop by the finite follower count even if a stale snapshot keeps
3990
4397
  // re-listing dead sessions.
3991
4398
  const goneSessions = new Set([delivery.sessionId]);
4399
+ // The local `delivery` is the FIRST follower; the loop walks past it.
4400
+ // The terminal row must name the last one tried, or the operator opens
4401
+ // the workspace of a session evicted a step earlier.
4402
+ let lastTarget = delivery;
3992
4403
  const roleFilter = this.boundRoleAware
3993
4404
  ? { role: delivery.role }
3994
4405
  : undefined;
3995
4406
  let next = this.resolveBoundDeliveryExcluding(envelope.chatId, task.issueNumber, goneSessions, roleFilter);
3996
4407
  while (next) {
4408
+ lastTarget = next;
3997
4409
  this.transitionInboundTask(task.id, 'running', { delivery: next });
3998
4410
  task.delivery = next;
3999
4411
  try {
4000
4412
  // Same event key: a different session's ring has never seen it.
4001
4413
  await boundSessions.deliverPrompt(next.sessionId, prompt, idempotencyKey);
4002
4414
  this.recordBoundDelivered(envelope, next.sessionId);
4003
- return true;
4415
+ return { kind: 'delivered' };
4004
4416
  }
4005
4417
  catch (retryErr) {
4006
4418
  if (!(retryErr instanceof BoundSessionGoneError))
@@ -4021,7 +4433,11 @@ export class GithubChannel extends PollingChannelBase {
4021
4433
  process.stderr.write(`[Channel:${this.name}] watch event ${envelope.messageId} lost its bound session; retiring without public fallback\n`);
4022
4434
  this.transitionInboundTask(task.id, 'running', { delivery: undefined });
4023
4435
  task.delivery = undefined;
4024
- return true;
4436
+ return {
4437
+ kind: 'retired',
4438
+ reason: 'watch_session_gone',
4439
+ sessionId: lastTarget.sessionId,
4440
+ };
4025
4441
  }
4026
4442
  // Role-aware fan-out: a partially delivered event never ALSO goes
4027
4443
  // public. While any role still follows the PR, the event is (or will
@@ -4033,7 +4449,11 @@ export class GithubChannel extends PollingChannelBase {
4033
4449
  this.boundEventAlreadyDelivered(envelope))) {
4034
4450
  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
4451
  this.markPrivatelyRetired(task);
4036
- return true;
4452
+ return {
4453
+ kind: 'retired',
4454
+ reason: 'siblings_still_follow',
4455
+ sessionId: lastTarget.sessionId,
4456
+ };
4037
4457
  }
4038
4458
  // Comment events keep today's contract: fall back to the normal
4039
4459
  // channel path so the event is not lost — but only when absence is
@@ -4042,14 +4462,31 @@ export class GithubChannel extends PollingChannelBase {
4042
4462
  // the public reply would be irreversible: defer as backpressure
4043
4463
  // (delivery cleared so recovery re-resolves without a doomed POST)
4044
4464
  // 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.
4465
+ // The `deferred` verdict tells runInboundTask the task was deferred
4466
+ // HERE: its success path must not retire the record as delivered.
4047
4467
  if (this.lastBindingsPartial || this.boundRefreshFailed) {
4048
4468
  const deferCount = (task.deferCount ?? 0) + 1;
4049
- task.delivery = undefined;
4469
+ // Attribution only, mirroring the store's lostSessionId: the horizon
4470
+ // retire below reads the IN-MEMORY task, which the store persistence
4471
+ // in transitionInboundTask never touches. Without this the terminal
4472
+ // row and the dead-letter record would file the event under the
4473
+ // Channel with no victim when the horizon is reached in the same run
4474
+ // that still held the target.
4475
+ task.lostSessionId = lastTarget.sessionId;
4050
4476
  if (deferCount >= MAX_BOUND_DEFERRALS) {
4051
- this.retireBoundTask(task, `gone fallback deferred ${deferCount} times; binding snapshot never completed`);
4052
- return false;
4477
+ // The dead-letter names the lost session through lostSessionId,
4478
+ // not the delivery; if retiring fails, the task is still a bound
4479
+ // one and its failure stays private (no public error comment).
4480
+ const target = task.delivery;
4481
+ task.delivery = undefined;
4482
+ try {
4483
+ this.retireBoundTask(task, `gone fallback deferred ${deferCount} times; binding snapshot never completed`);
4484
+ }
4485
+ catch (err) {
4486
+ task.delivery = target;
4487
+ throw err;
4488
+ }
4489
+ return { kind: 'deferred' };
4053
4490
  }
4054
4491
  this.transitionInboundTask(task.id, 'failed', {
4055
4492
  delivery: undefined,
@@ -4058,13 +4495,20 @@ export class GithubChannel extends PollingChannelBase {
4058
4495
  deferCount,
4059
4496
  backpressure: true,
4060
4497
  });
4061
- return false;
4498
+ // Cleared only once saved: if the save fails, the task is still a
4499
+ // bound one, so the failure stays private (no public error comment).
4500
+ task.delivery = undefined;
4501
+ return { kind: 'deferred' };
4502
+ }
4503
+ if (task.privateOnly === true) {
4504
+ return this.retirePrivateOnly(task, envelope, lastTarget.sessionId);
4062
4505
  }
4063
4506
  this.transitionInboundTask(task.id, 'running', { delivery: undefined });
4064
4507
  task.delivery = undefined;
4065
4508
  await this.handleInbound(envelope);
4509
+ return { kind: 'public' };
4066
4510
  }
4067
- return true;
4511
+ return { kind: 'delivered' };
4068
4512
  }
4069
4513
  prWatchStatePath() {
4070
4514
  return this.channelFilePath('github-pr-watch.json');
@@ -4498,6 +4942,9 @@ export class GithubChannel extends PollingChannelBase {
4498
4942
  // independent subscriptions. Comment events still dedupe across
4499
4943
  // instances via their stable GitHub ids.
4500
4944
  const detectedAt = Date.now();
4945
+ // Overflow retires sliced during this pass; their skip rows are journalled
4946
+ // only after the end-of-pass save commits the baseline and queue together.
4947
+ const overflowRetires = [];
4501
4948
  for (const event of events) {
4502
4949
  // ci_failure dedupes per head SHA: once per head even when the
4503
4950
  // aggregate flaps back to success and fails again. The other three
@@ -4560,35 +5007,50 @@ export class GithubChannel extends PollingChannelBase {
4560
5007
  });
4561
5008
  if (next.pending.length > MAX_PENDING_WATCH_PER_ENTRY) {
4562
5009
  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`);
5010
+ if (!this.isDeadLettered(oldest.key)) {
5011
+ const record = {
5012
+ retiredAt: new Date().toISOString(),
5013
+ issueNumber: oldest.issueNumber,
5014
+ source: {
5015
+ chatId,
5016
+ threadId: `pr:${number}`,
5017
+ messageId: oldest.key,
5018
+ },
5019
+ delivery: oldest.delivery,
5020
+ reason: `watch pending queue overflow (cap ${MAX_PENDING_WATCH_PER_ENTRY}); oldest event retired undelivered`,
5021
+ text: oldest.envelope.text,
5022
+ };
5023
+ try {
5024
+ const path = this.channelFilePath('github-bound-deadletter.jsonl');
5025
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
5026
+ appendFileSync(path, `${JSON.stringify(record)}\n`, {
5027
+ encoding: 'utf-8',
5028
+ mode: 0o600,
5029
+ });
5030
+ this.deadLetteredKeys.add(oldest.key);
5031
+ }
5032
+ catch (err) {
5033
+ // The exhaustion surface cannot be written: keep the event queued
5034
+ // (over cap) and retry the overflow on the next detection instead
5035
+ // of dropping it. The body has nowhere else to go, so dump it to
5036
+ // stderr — sanitized without truncation, like retireBoundTask.
5037
+ const payload = JSON.stringify(record);
5038
+ 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`);
5039
+ }
4584
5040
  }
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`);
5041
+ if (this.isDeadLettered(oldest.key)) {
5042
+ // The dead-letter record is the retire's commit point. Slice in
5043
+ // memory ONLY: the end-of-pass save below commits the advanced
5044
+ // baseline and the full queue in one write. A mid-pass save here
5045
+ // would persist the baseline before this pass's later events are
5046
+ // queued, so a crash would never re-derive them. The skip row is
5047
+ // journalled after that save, never before; if the save throws, the
5048
+ // drain completes the retire next poll (the head is dead-lettered,
5049
+ // so it is never delivered).
5050
+ next.pending = next.pending.slice(1);
5051
+ this.prWatchState.entries[key] = next;
5052
+ overflowRetires.push(oldest);
5053
+ 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
5054
  }
4593
5055
  }
4594
5056
  if (event.type === 'ci_failure' && headSha !== undefined) {
@@ -4600,6 +5062,12 @@ export class GithubChannel extends PollingChannelBase {
4600
5062
  // either finds the pending event (drained next poll) or the claimed
4601
5063
  // task (recovery), never a consumed transition with nothing to retry.
4602
5064
  this.savePrWatchState();
5065
+ // The overflow retires are durable only now. Journal their skip rows after
5066
+ // the save: a throwing save leaves no claim for an event still queued on
5067
+ // disk, and the drain completes the retire next poll instead.
5068
+ for (const retired of overflowRetires) {
5069
+ this.recordWatchOverflowSkip(retired);
5070
+ }
4603
5071
  await this.drainPendingWatch(key, next);
4604
5072
  }
4605
5073
  /**
@@ -4632,6 +5100,25 @@ export class GithubChannel extends PollingChannelBase {
4632
5100
  return;
4633
5101
  while (entry.pending && entry.pending.length > 0) {
4634
5102
  const pending = entry.pending[0];
5103
+ if (this.isDeadLettered(pending.key)) {
5104
+ // This head already carries a durable "retired undelivered" record
5105
+ // (an overflow whose end-of-pass save failed, or a crash before it).
5106
+ // Complete the retire instead of delivering: a delivered event must
5107
+ // never also stand in the dead-letter file as retired undelivered.
5108
+ const pendingBefore = entry.pending;
5109
+ entry.pending = entry.pending.slice(1);
5110
+ this.prWatchState.entries[key] = entry;
5111
+ try {
5112
+ this.savePrWatchState();
5113
+ }
5114
+ catch (err) {
5115
+ entry.pending = pendingBefore;
5116
+ this.prWatchState.entries[key] = entry;
5117
+ throw err;
5118
+ }
5119
+ this.recordWatchOverflowSkip(pending);
5120
+ continue;
5121
+ }
4635
5122
  // Re-validate the frozen recipient against the latest COMPLETE
4636
5123
  // snapshot: a live rebind must not misdeliver to the old session. On
4637
5124
  // a partial/failed scan the persisted target stands (fail-closed).
@@ -4648,9 +5135,48 @@ export class GithubChannel extends PollingChannelBase {
4648
5135
  }
4649
5136
  else {
4650
5137
  process.stderr.write(`[Channel:${this.name}] watch event ${pending.key} has no bound candidate left; retiring without public fallback\n`);
5138
+ const pendingBefore = entry.pending;
4651
5139
  entry.pending = entry.pending.slice(1);
4652
5140
  this.prWatchState.entries[key] = entry;
4653
- this.savePrWatchState();
5141
+ try {
5142
+ this.savePrWatchState();
5143
+ }
5144
+ catch (err) {
5145
+ // The slice already mutated the loaded state, and a failed save
5146
+ // does not clear prWatchStateLoaded — without this rollback the
5147
+ // next poll skips the entry and the end-of-pass save persists the
5148
+ // truncation, losing the event with no trace at all. Mirrors the
5149
+ // claim path's rollback below.
5150
+ entry.pending = pendingBefore;
5151
+ this.prWatchState.entries[key] = entry;
5152
+ throw err;
5153
+ }
5154
+ // Retired before any task was claimed, so there is no task row to
5155
+ // close: the skip is the event's only journal trace. After the
5156
+ // durable save — the rollback above keeps the event queued when the
5157
+ // save throws, and the journal must not claim a retire that did not
5158
+ // happen.
5159
+ const lostTarget = pending.delivery?.kind === 'bound-session'
5160
+ ? pending.delivery.sessionId
5161
+ : undefined;
5162
+ const lostWorkspace = lostTarget
5163
+ ? this.sessionWorkspaceFor(lostTarget)
5164
+ : undefined;
5165
+ this.recordChannelEvent({
5166
+ type: 'inbound',
5167
+ outcome: 'skipped',
5168
+ reason: 'watch_no_candidate',
5169
+ repository: pending.envelope.chatId,
5170
+ thread: pending.envelope.threadId,
5171
+ number: pending.issueNumber,
5172
+ messageId: pending.key,
5173
+ // The frozen target is in hand; this retire writes no dead-letter
5174
+ // record (only the overflow retire does), so the skip row is the
5175
+ // event's only trace — without the target it cannot say whether
5176
+ // the retired event ever belonged to a session.
5177
+ ...(lostTarget ? { sessionId: lostTarget } : {}),
5178
+ ...(lostWorkspace ? { sessionWorkspaceCwd: lostWorkspace } : {}),
5179
+ });
4654
5180
  continue;
4655
5181
  }
4656
5182
  }
@@ -4710,6 +5236,24 @@ export class GithubChannel extends PollingChannelBase {
4710
5236
  async drainPendingWatchRoleAware(key, entry) {
4711
5237
  while (entry.pending && entry.pending.length > 0) {
4712
5238
  const pending = entry.pending[0];
5239
+ if (this.isDeadLettered(pending.key)) {
5240
+ // A dead-lettered head is committed to retire; complete it rather than
5241
+ // deliver, so no event is both delivered and filed as retired
5242
+ // undelivered. Mirrors the legacy drain's guard.
5243
+ const pendingBefore = entry.pending;
5244
+ entry.pending = entry.pending.slice(1);
5245
+ this.prWatchState.entries[key] = entry;
5246
+ try {
5247
+ this.savePrWatchState();
5248
+ }
5249
+ catch (err) {
5250
+ entry.pending = pendingBefore;
5251
+ this.prWatchState.entries[key] = entry;
5252
+ throw err;
5253
+ }
5254
+ this.recordWatchOverflowSkip(pending);
5255
+ continue;
5256
+ }
4713
5257
  const { targets } = this.resolveBoundTargets(pending.envelope.chatId, pending.issueNumber, this.boundEventClass(pending.envelope));
4714
5258
  if (targets.length === 0) {
4715
5259
  // An incomplete enumeration is not an absence: defer instead of