@qwen-code/channel-github 0.27.3 → 0.27.4-nightly.20261116.eb3a599ef3

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.
@@ -246,10 +246,9 @@ export function validateRepoFilterConfig(config, channelName) {
246
246
  return undefined;
247
247
  }
248
248
  /**
249
- * The prWatchEvents vocabulary, shared by the config validator, the watch
250
- * emit path, and the management UI's option list (built from this constant
251
- * in index.ts) so the three cannot drift apart (R2-18). Lowercase: the
252
- * editor and normalizePrWatchEvents both lowercase before matching.
249
+ * The prWatchEvents vocabulary, shared by the deprecated alias's option list
250
+ * (built from this constant in index.ts) and the bound-action validator, so
251
+ * the management UI cannot drift from the key vocabulary (R2-18). Lowercase.
253
252
  */
254
253
  export const PR_WATCH_EVENTS = [
255
254
  'ci_failure',
@@ -300,55 +299,14 @@ const BOUND_ACTION_VOCABULARY = {
300
299
  : PR_NOTIFICATION_REASONS.includes(event),
301
300
  eventClassDescription: 'an event class (watch:<type> or a notification reason)',
302
301
  };
303
- /**
304
- * Default open-PR watch fan-out per poll (~1 pulls.get per watched PR plus
305
- * conditional Checks fetches; terminal-pending bindings drain in an
306
- * additional slice of up to 20% outside this budget). Operators with more
307
- * open bindings raise `prWatchLimit` (and `pollInterval`) deliberately;
308
- * the watch pass already fails fast on rate limits, so an over-budget
309
- * configuration degrades instead of hammering the API. Exported for the
310
- * descriptor so the form bound and the effective bound cannot drift.
311
- */
312
- export const DEFAULT_PR_WATCH_LIMIT = 30;
313
- /** Hard ceiling for the configurable watch fan-out. */
314
- export const MAX_PR_WATCH_LIMIT = 500;
315
302
  /**
316
303
  * Requests held back for the interactive notification lane. When the last
317
304
  * known REST budget is at or below this, the watch pass is skipped for the
318
305
  * poll so a human mention is not starved by background PR polling. ~4% of a
319
306
  * 5,000/hour classic-PAT budget: enough for several polls of mention traffic
320
- * while barely trimming a healthy watch. Operators on other scales (GitHub
321
- * Enterprise, finer-grained tokens) set prWatchBudgetReserve explicitly.
322
- */
323
- export const DEFAULT_PR_WATCH_BUDGET_RESERVE = 200;
324
- /** Hard ceiling for the configurable watch budget reserve. */
325
- export const MAX_PR_WATCH_BUDGET_RESERVE = 5000;
326
- /**
327
- * After a head change, checks register asynchronously (queued or self-hosted
328
- * runners can take minutes). Within this window an empty CI aggregate
329
- * ('none') is treated as unsettled and re-checked every poll.
307
+ * while barely trimming a healthy comment watch.
330
308
  */
331
- const CI_NONE_GRACE_MS = 10 * 60 * 1000;
332
- /**
333
- * Settled heads are re-checked on this period even when nothing observable
334
- * advances: PR updated_at does NOT bump on check re-runs (verified against
335
- * the live API), and CI can appear long after the grace window on a manual
336
- * workflow_dispatch. Without a periodic re-check a settled head that turns
337
- * red later would be missed forever. Cost: at most 2 extra calls per watched
338
- * PR per interval (30 PRs x 2 x 6/hour = 360/hour on top of the 1800/hour
339
- * steady state, well under the 5000/hour token budget).
340
- */
341
- const CI_RECHECK_INTERVAL_MS = 10 * 60 * 1000;
342
- /**
343
- * Pending aggregates re-check on this period, NOT every poll: a workflow
344
- * queued for environment approval or an offline runner can stay pending for
345
- * hours, and an unbounded per-poll re-fetch turns the settled-head cost
346
- * model into ~3,600 CI calls/hour at the watch cap — over the 5,000/hour
347
- * PAT budget once pulls.get is counted, starving the notification lane.
348
- * Must stay above the poll interval (60s) to actually bound the fan-out;
349
- * pending still settles within one period of the real transition.
350
- */
351
- const CI_PENDING_RECHECK_INTERVAL_MS = 5 * 60 * 1000;
309
+ const PR_WATCH_BUDGET_RESERVE = 200;
352
310
  /**
353
311
  * Bound PR comment watch re-check period. Comments are fetched when the PR's
354
312
  * updated_at advances OR this interval elapses, so a settled PR still hears
@@ -356,6 +314,14 @@ const CI_PENDING_RECHECK_INTERVAL_MS = 5 * 60 * 1000;
356
314
  * bound PR. Above the 60s poll interval to bound the fan-out at the watch cap.
357
315
  */
358
316
  const COMMENT_RECHECK_INTERVAL_MS = 2 * 60 * 1000;
317
+ /**
318
+ * Minimum downtime gap before the first watch pass after startup digests the
319
+ * comment backlog instead of delivering one prompt per comment. The effective
320
+ * threshold scales with the poll interval (5 intervals) so a long-interval
321
+ * channel does not digest every poll; a sustained API outage counts as a gap
322
+ * because failed polls do not save the cursor heartbeat.
323
+ */
324
+ const STARTUP_DIGEST_MIN_GAP_MS = 10 * 60 * 1000;
359
325
  /**
360
326
  * Pass-wide budget on watched comments, shared by every watched PR in a single
361
327
  * watch pass (not a per-PR cap): commentSince survives a restart, so after a
@@ -366,6 +332,17 @@ const COMMENT_RECHECK_INTERVAL_MS = 2 * 60 * 1000;
366
332
  * processed comment so the tail drains over subsequent passes, never dropped.
367
333
  */
368
334
  const MAX_WATCH_COMMENTS_PER_PASS = 20;
335
+ /**
336
+ * Bound on consecutive PERMANENT digest retirements (a preflight rejection
337
+ * returns settled with no delivery). A retired digest is re-listed and retried
338
+ * — the route/sender gate may be fixed — but not forever: without a bound a
339
+ * permanently-rejected digest holds its cursor and spends the pass-wide watch
340
+ * budget every poll for the process lifetime with zero prompts. At this bound
341
+ * the backlog is consumed with a visible journal trace instead. Transient
342
+ * deferrals (settled === false) do not count toward it and keep the fail-closed
343
+ * hold.
344
+ */
345
+ const MAX_DIGEST_RETIREMENT_RETRIES = 3;
369
346
  /**
370
347
  * Backpressure horizon for bound-session delivery: queue-full and
371
348
  * temporarily-unavailable conditions defer without consuming the failure
@@ -390,33 +367,18 @@ const MAX_BOUND_DEFERRALS = 240;
390
367
  const MAX_COLD_EMPTY_PARTIAL_POLLS = 30;
391
368
  /**
392
369
  * Retention bound under a PERMANENT partial snapshot: prune never runs while
393
- * the binding answer is incomplete, so unlisted sessions and unbound PR
394
- * entries would otherwise accumulate for the daemon's whole uptime (same
395
- * cap discipline as the worker's wake cache). Oldest-first eviction,
396
- * surfaced on stderr; watch-entry eviction additionally protects retained
397
- * bindings and in-flight tasks, and an evicted entry's PR has no delivery
398
- * target — a later rebind re-baselines silently like any first observation,
399
- * so eviction bounds memory without losing a deliverable event.
370
+ * the binding answer is incomplete, so unlisted PR entries would otherwise
371
+ * accumulate for the daemon's whole uptime. Oldest-first eviction, surfaced
372
+ * on stderr; an evicted entry has no retained binding, so a later rebind
373
+ * re-baselines it silently.
400
374
  */
401
375
  const MAX_PARTIAL_RETAINED = 1024;
402
- /**
403
- * Per-entry pending queue bound. A persistently failing claim (task store
404
- * unreadable/unwritable) keeps every detected transition queued; without a
405
- * cap the entry is also exempt from retention eviction, and the watch file
406
- * would grow without bound. Overflow retires the OLDEST queued event to the
407
- * private dead-letter (surfaced, never silent); a failed dead-letter write
408
- * keeps the event queued and retries the overflow next detection.
409
- */
410
- const MAX_PENDING_WATCH_PER_ENTRY = 64;
411
- const MAX_REPORTED_FAILED_CHECKS = 5;
412
- const MAX_FIRED_KEYS = 64;
413
376
  /**
414
377
  * Shape check for a persisted watch entry. The container check alone lets a
415
- * legal-JSON malformed value (e.g. `null`) through, and
416
- * `reconcilePendingWatch` dereferences every entry — one bad entry would
417
- * throw each poll and starve the API-independent drain of the entries after
418
- * it. A malformed entry is dropped (healthy entries survive) rather than
419
- * resetting the whole file.
378
+ * legal-JSON malformed value (e.g. `null`) through, and the comment pass
379
+ * dereferences every entry — one bad entry would throw each poll and starve
380
+ * the entries after it. A malformed entry is dropped (healthy entries
381
+ * survive) rather than resetting the whole file.
420
382
  */
421
383
  function isPrWatchEntryShape(value) {
422
384
  if (value === null || typeof value !== 'object' || Array.isArray(value)) {
@@ -425,38 +387,18 @@ function isPrWatchEntryShape(value) {
425
387
  const entry = value;
426
388
  const stringOrUndef = (v) => v === undefined || typeof v === 'string';
427
389
  const numberOrUndef = (v) => v === undefined || typeof v === 'number';
428
- // The envelope and delivery must satisfy the SAME validators the task
429
- // store applies at claim time: a shape-valid envelope missing chatId
430
- // would throw in prBindingKey and abort the whole reconcile loop
431
- // (starving the healthy entries queued behind it), and a partial
432
- // envelope would be claimed verbatim, rejected by isInboundTaskRecord on
433
- // the next read, and wedge the task file until an operator deletes it.
434
- const isPending = (item) => item !== null &&
435
- typeof item === 'object' &&
436
- typeof item.key === 'string' &&
437
- typeof item.issueNumber === 'number' &&
438
- item.envelope !== undefined &&
439
- isInboundEnvelope(item.envelope) &&
440
- (item.delivery === undefined ||
441
- isBoundDeliveryShape(item.delivery));
442
- return (stringOrUndef(entry.headSha) &&
443
- stringOrUndef(entry.ci) &&
444
- stringOrUndef(entry.mergeableState) &&
445
- stringOrUndef(entry.prState) &&
446
- stringOrUndef(entry.title) &&
447
- stringOrUndef(entry.prUpdatedAt) &&
448
- numberOrUndef(entry.headObservedAt) &&
449
- numberOrUndef(entry.lastCiFetchAt) &&
450
- numberOrUndef(entry.seq) &&
451
- stringOrUndef(entry.ciFiredSha) &&
390
+ return (stringOrUndef(entry.title) &&
452
391
  stringOrUndef(entry.commentBaseline) &&
453
392
  stringOrUndef(entry.commentSince) &&
454
393
  numberOrUndef(entry.commentLastFetchAt) &&
455
- (entry.pending === undefined ||
456
- (Array.isArray(entry.pending) && entry.pending.every(isPending))) &&
457
- (entry.fired === undefined ||
458
- (Array.isArray(entry.fired) &&
459
- entry.fired.every((k) => typeof k === 'string'))));
394
+ (entry.digestPending === undefined ||
395
+ typeof entry.digestPending === 'boolean') &&
396
+ (entry.digestSizeArmed === undefined ||
397
+ typeof entry.digestSizeArmed === 'boolean') &&
398
+ (entry.digestRendered === undefined ||
399
+ (Array.isArray(entry.digestRendered) &&
400
+ entry.digestRendered.every((k) => typeof k === 'string'))) &&
401
+ numberOrUndef(entry.digestRetiredCount));
460
402
  }
461
403
  /**
462
404
  * Parse and validate boundSessionActions into the lookup map connect() and
@@ -478,29 +420,33 @@ function normalizeBoundSessionActions(config, channelName) {
478
420
  }
479
421
  return validateBoundActionEntries(entries, source, BOUND_ACTION_VOCABULARY);
480
422
  }
481
- function normalizePrWatchEvents(config, channelName) {
482
- if (config.prWatchEvents === undefined)
483
- return new Set();
484
- if (!Array.isArray(config.prWatchEvents)) {
485
- throw new Error(`prWatchEvents for channel ${channelName} must be an array of event names.`);
486
- }
487
- const events = new Set();
488
- for (const value of config.prWatchEvents) {
489
- if (typeof value !== 'string') {
490
- throw new Error(`prWatchEvents entries for channel ${channelName} must be strings.`);
491
- }
492
- const event = value.trim().toLowerCase();
493
- if (!event)
494
- continue;
495
- if (!KNOWN_PR_WATCH_EVENTS.has(event)) {
496
- throw new Error(`Unrecognized prWatchEvents value for channel ${channelName}: ${value}`);
497
- }
498
- events.add(event);
499
- }
500
- if (events.size > 0 && config.deliverToBoundSessions !== true) {
501
- throw new Error(`prWatchEvents for channel ${channelName} requires deliverToBoundSessions: true.`);
423
+ /**
424
+ * Whether the channel still uses any of the four deprecated state-watch keys:
425
+ * `prWatchEvents`, a `watch:*` key in `boundSessionActions`, `prWatchLimit`
426
+ * or `prWatchBudgetReserve`. The first two are accepted for one minor release
427
+ * and read by the daemon as a per-host alias while `serve.sessionPrWatch` and
428
+ * its events environment override are both unset; the two limit knobs are
429
+ * ignored, and the pass uses its built-in budget.
430
+ */
431
+ function usesDeprecatedPrWatchSurface(config) {
432
+ if (config.prWatchEvents !== undefined)
433
+ return true;
434
+ if (config.prWatchLimit !== undefined)
435
+ return true;
436
+ if (config.prWatchBudgetReserve !== undefined)
437
+ return true;
438
+ const actions = config.boundSessionActions;
439
+ if (actions === null ||
440
+ typeof actions !== 'object' ||
441
+ Array.isArray(actions)) {
442
+ return false;
502
443
  }
503
- return events;
444
+ return Object.keys(actions).some((key) => {
445
+ if (key.startsWith('watch:'))
446
+ return true;
447
+ const colon = key.indexOf(':');
448
+ return colon !== -1 && key.slice(colon + 1).startsWith('watch:');
449
+ });
504
450
  }
505
451
  /**
506
452
  * Shared validation for the plugin descriptor (returns the message) and
@@ -512,10 +458,6 @@ export function validateBoundSessionConfig(config, channelName) {
512
458
  typeof config.deliverToBoundSessions !== 'boolean') {
513
459
  return `[Channel:${channelName}] deliverToBoundSessions must be a boolean.`;
514
460
  }
515
- if (config.prWatchLimit !== undefined &&
516
- config.deliverToBoundSessions !== true) {
517
- return `prWatchLimit for channel ${channelName} requires deliverToBoundSessions: true.`;
518
- }
519
461
  if (config.requireBoundWatch !== undefined &&
520
462
  typeof config.requireBoundWatch !== 'boolean') {
521
463
  return `[Channel:${channelName}] requireBoundWatch must be a boolean.`;
@@ -531,28 +473,7 @@ export function validateBoundSessionConfig(config, channelName) {
531
473
  // No deliverToBoundSessions dependency: prCommentWatch is default-on, so the
532
474
  // editor emits it even for channels without bound delivery. It is inert there
533
475
  // (the watch is gated on deliverToBoundSessions at runtime), not an error.
534
- if (config.prWatchBudgetReserve !== undefined &&
535
- config.deliverToBoundSessions !== true) {
536
- return `prWatchBudgetReserve for channel ${channelName} requires deliverToBoundSessions: true.`;
537
- }
538
- // The descriptor now declares minimum: 0, so the editor refuses a negative
539
- // the operator types. This check still guards everything else: a hand-edited
540
- // settings.json or a daemon API call, and a stored negative the editor
541
- // re-sends unchanged under its descriptor-level tolerance. The getter would
542
- // silently fall back to the default for a negative, letting a saved value
543
- // mean something other than it says.
544
- // Positive fractions stay legal: the getter rounds them UP, which is the
545
- // documented behaviour, not a silent fallback.
546
- if (config.prWatchBudgetReserve !== undefined) {
547
- const reserve = config.prWatchBudgetReserve;
548
- if (typeof reserve !== 'number' ||
549
- !Number.isFinite(reserve) ||
550
- reserve < 0) {
551
- return `prWatchBudgetReserve for channel ${channelName} must be a non-negative number.`;
552
- }
553
- }
554
476
  try {
555
- normalizePrWatchEvents(config, channelName);
556
477
  normalizeBoundSessionActions(config, channelName);
557
478
  }
558
479
  catch (err) {
@@ -719,16 +640,11 @@ const BOUND_DELIVERY_COPY = {
719
640
  commentTruncated: (count) => `comment truncated: ${count} more characters`,
720
641
  newCommentLead: (author) => `New comment by @${author}:`,
721
642
  newInlineReviewCommentLead: (author) => `New inline review comment by @${author}:`,
643
+ offlineCommentsLead: (count) => `Offline backlog: ${count} new comment(s) on the PR since the last successful poll:`,
644
+ commentBacklogLead: (count) => `Comment backlog: ${count} new comment(s) on this PR:`,
645
+ offlineOmittedNotice: (count) => `${count} comment(s) omitted from this digest to fit the prompt budget; they will follow in further digests`,
722
646
  reviewRequestedInstruction: 'Return a formal review summary with verified actionable findings, or a concise no-blocker result.',
723
647
  assignInstruction: 'Triage this issue and respond with the next action.',
724
- headChange: (fromSha, toSha) => `New commits pushed: head moved from ${fromSha} to ${toSha}.`,
725
- ciFailure: (headSha) => `CI failed on head ${headSha}.`,
726
- failedChecks: (names, namesIncomplete) => ` Failed checks: ${names}${namesIncomplete
727
- ? ' (list may be incomplete: later check pages were not read)'
728
- : ''}.`,
729
- mergeConflict: 'Merge conflicts detected (mergeable_state: dirty).',
730
- prMerged: 'The PR was merged.',
731
- prClosed: 'The PR was closed without merging.',
732
648
  },
733
649
  zh: {
734
650
  provenance: (channelName) => `由 "${channelName}" GitHub channel 投递,因为本会话绑定了下面的 PR。`,
@@ -738,14 +654,11 @@ const BOUND_DELIVERY_COPY = {
738
654
  commentTruncated: (count) => `评论已截断:省略了 ${count} 个字符`,
739
655
  newCommentLead: (author) => `@${author} 的新评论:`,
740
656
  newInlineReviewCommentLead: (author) => `@${author} 的新行内评审评论:`,
657
+ offlineCommentsLead: (count) => `离线积压:自上次成功轮询以来 PR 新增 ${count} 条评论:`,
658
+ commentBacklogLead: (count) => `评论积压:本 PR 新增 ${count} 条评论:`,
659
+ offlineOmittedNotice: (count) => `本摘要因篇幅省略了 ${count} 条评论,将分批摘要补投`,
741
660
  reviewRequestedInstruction: '请给出正式的评审总结,包含经核实的可操作发现;若没有阻塞问题,给出简洁的无阻塞结论。',
742
661
  assignInstruction: '请分诊该 issue 并给出下一步行动。',
743
- headChange: (fromSha, toSha) => `有新提交推送:head 从 ${fromSha} 变为 ${toSha}。`,
744
- ciFailure: (headSha) => `head ${headSha} 的 CI 失败。`,
745
- failedChecks: (names, namesIncomplete) => `失败的检查:${names}${namesIncomplete ? '(列表可能不完整:未读取后续检查分页)' : ''}。`,
746
- mergeConflict: '检测到合并冲突(mergeable_state: dirty)。',
747
- prMerged: 'PR 已合并。',
748
- prClosed: 'PR 已关闭,未合并。',
749
662
  },
750
663
  };
751
664
  function isNoReplySentinel(text) {
@@ -756,19 +669,11 @@ function isNoReplySentinel(text) {
756
669
  /** GitHub's wording for a secondary (abuse) rate limit. */
757
670
  const SECONDARY_RATE_LIMIT_MESSAGE = /secondary rate limit|abuse detection/i;
758
671
  /**
759
- * Cap on cached conditional responses, sized from the fan-out it has to
760
- * serve: up to MAX_PR_WATCH_LIMIT open PRs, a terminal-drain slice on top,
761
- * and the notifications pages. A cap below the sweep does not degrade
762
- * proportionally — each miss evicts the entry the sweep is about to read, so
763
- * every read of every later pass misses and the saving is exactly zero for
764
- * the high-fan-out deployments this is meant to help. Derived from the watch
765
- * limit so the two cannot drift apart.
766
- *
767
- * A moved notifications `since` cursor still mints new keys, so the map is
768
- * bounded and evicts least-recently-used first; an evicted URL simply pays
769
- * for one full 200 again.
672
+ * Cap on cached conditional responses. 1,000 is the former watch fan-out
673
+ * ceiling doubled; the state watch is gone, but the cache still serves the
674
+ * notification pages and the comment watch's list reads.
770
675
  */
771
- export const CONDITIONAL_CACHE_MAX_ENTRIES = MAX_PR_WATCH_LIMIT * 2;
676
+ export const CONDITIONAL_CACHE_MAX_ENTRIES = 1000;
772
677
  /**
773
678
  * Bodies above this size are not cached, so a pathologically large page
774
679
  * cannot pin memory. Sized against the entry cap above to keep the retention
@@ -999,7 +904,6 @@ export class GithubChannel extends PollingChannelBase {
999
904
  * with deliverToBoundSessions; `prCommentWatch: false` disables it.
1000
905
  */
1001
906
  prCommentWatchEnabled = true;
1002
- prWatchEvents = new Set();
1003
907
  /**
1004
908
  * Operator instruction templates keyed by the closed bound-action
1005
909
  * vocabulary. Non-empty switches routing to role-aware fan-out (one
@@ -1016,9 +920,20 @@ export class GithubChannel extends PollingChannelBase {
1016
920
  boundDeliveredOrder = [];
1017
921
  /**
1018
922
  * An unreadable ring cannot prove a negative: fail CLOSED for the public
1019
- * fallback (suppress it) rather than risk an irreversible duplicate.
923
+ * fallback (suppress it) rather than risk an irreversible duplicate. This
924
+ * verdict is NEVER cleared by a repair: the keys lost with the file stay
925
+ * unknown, so the suppression callers must keep failing closed for them.
1020
926
  */
1021
927
  boundDeliveredUnreadable = false;
928
+ /**
929
+ * A successful ring write after a startup-unreadable ring. Lets the digest
930
+ * prove its OWN acceptance from the freshly written key without clearing
931
+ * boundDeliveredUnreadable (which would convert the lost history from
932
+ * "unknown" to "not delivered" and open the public-duplicate window for
933
+ * every pre-corruption event). Suppression stays fail-closed; only the
934
+ * digest's delivered check consults this latch.
935
+ */
936
+ boundDeliveredRepaired = false;
1022
937
  /**
1023
938
  * Tasks retired privately during the current runInboundTask call (role
1024
939
  * lost its match, siblings already delivered, ring suppression). Their
@@ -1039,6 +954,14 @@ export class GithubChannel extends PollingChannelBase {
1039
954
  * gated on this (a partial answer is not an absence).
1040
955
  */
1041
956
  boundSnapshotTrusted = false;
957
+ /**
958
+ * One-shot flag set when a downtime gap is detected; it arms the per-entry
959
+ * digestPending flags and clears as soon as it has armed them, so a skipped,
960
+ * aborted or untrusted pass cannot re-arm an entry an earlier pass already
961
+ * drained. The per-entry flags carry the digest for individual PRs across
962
+ * errors, cap exclusion, and restarts.
963
+ */
964
+ startupDigestPending = false;
1042
965
  /**
1043
966
  * False until ANY binding snapshot succeeds (complete or partial). The
1044
967
  * cold-start comment-lane gate uses this, not boundSnapshotTrusted: the
@@ -1112,23 +1035,6 @@ export class GithubChannel extends PollingChannelBase {
1112
1035
  gateGraceClear(key) {
1113
1036
  this.gateDeferredOnce.delete(key);
1114
1037
  }
1115
- /**
1116
- * True while the most recent pending-watch reconciliation FAILED (e.g.
1117
- * the watch file is unreadable). Generic recovery must then leave watch
1118
- * tasks alone: delivering and removing an accepted watch task without
1119
- * reconciling its on-disk pending record would let a later drain claim
1120
- * and deliver the same transition a second time. Unrelated comment
1121
- * recovery keeps running.
1122
- */
1123
- watchReconcileBlocked = false;
1124
- /**
1125
- * The cause the blocking watch-guard row last named. The row is
1126
- * edge-triggered per CAUSE, not just per blocked window: a pending backlog
1127
- * that turns into an unreadable sidecar (or back) must re-journal, or the
1128
- * timeline keeps naming a remedy that no longer applies. Cleared on the
1129
- * recovery edge.
1130
- */
1131
- watchReconcileBlockedCause;
1132
1038
  /**
1133
1039
  * Last REST budget seen on a SUCCESSFUL response, recorded by the request
1134
1040
  * hook regardless of the call's return shape. Undefined until the first
@@ -1145,9 +1051,9 @@ export class GithubChannel extends PollingChannelBase {
1145
1051
  lastRateLimitResetAt;
1146
1052
  /**
1147
1053
  * Whether the watch pass is currently skipped for low budget. Edge-triggered
1148
- * journaling (the watchReconcileBlockedCause pattern): a permanent low-budget
1149
- * condition journalled once on the edge, not every poll, so it cannot rotate
1150
- * the useful rows out of the timeline. Cleared on the recovery edge.
1054
+ * journaling: a permanent low-budget condition is journalled once on the
1055
+ * edge, not every poll, so it cannot rotate the useful rows out of the
1056
+ * timeline. Cleared on the recovery edge.
1151
1057
  */
1152
1058
  watchBudgetLow = false;
1153
1059
  /**
@@ -1187,16 +1093,6 @@ export class GithubChannel extends PollingChannelBase {
1187
1093
  boundSnapshotFailureStreak = 0;
1188
1094
  prWatchState = { version: 1, entries: {} };
1189
1095
  prWatchStateLoaded = false;
1190
- /**
1191
- * Message keys that already have a durable dead-letter record, lazily
1192
- * loaded from the never-rotated dead-letter file on first use and kept
1193
- * current as this process appends. The file is the overflow retire's commit
1194
- * point: a head with a record is never re-appended — even across a restart,
1195
- * which empties this cache and reloads it from disk — and never delivered;
1196
- * the drain completes its retire instead. Watch keys are unique per
1197
- * episode, so a record can only match the same transition.
1198
- */
1199
- deadLetteredKeys;
1200
1096
  inboundRecoveryPending = true;
1201
1097
  recoverableInboundTasks = 0;
1202
1098
  /**
@@ -1297,6 +1193,11 @@ export class GithubChannel extends PollingChannelBase {
1297
1193
  Number.isNaN(new Date(base.metaFloor).getTime()))) {
1298
1194
  delete base.metaFloor;
1299
1195
  }
1196
+ if (base.lastPollAt !== undefined &&
1197
+ (typeof base.lastPollAt !== 'string' ||
1198
+ Number.isNaN(new Date(base.lastPollAt).getTime()))) {
1199
+ delete base.lastPollAt;
1200
+ }
1300
1201
  for (const field of [
1301
1202
  'dispatchedBodies',
1302
1203
  'dispatchedComments',
@@ -1363,11 +1264,13 @@ export class GithubChannel extends PollingChannelBase {
1363
1264
  if (boundConfigError) {
1364
1265
  throw new Error(boundConfigError);
1365
1266
  }
1366
- this.prWatchEvents = normalizePrWatchEvents(cfg, this.name);
1367
1267
  this.boundSessionActions = normalizeBoundSessionActions(cfg, this.name);
1368
1268
  this.deliverToBoundSessions = cfg.deliverToBoundSessions === true;
1369
1269
  this.requireBoundWatch = cfg.requireBoundWatch === true;
1370
1270
  this.prCommentWatchEnabled = cfg.prCommentWatch !== false;
1271
+ if (usesDeprecatedPrWatchSurface(cfg)) {
1272
+ process.stderr.write(`[Channel:${this.name}] warning: prWatchEvents, the watch:* keys of boundSessionActions, prWatchLimit and prWatchBudgetReserve are deprecated; this channel no longer detects PR state transitions. Configure serve.sessionPrWatch in the daemon's settings instead. The watch keys are read as a per-host alias for one minor release; the two limit knobs are ignored and the pass uses its built-in budget.\n`);
1273
+ }
1371
1274
  if (this.deliverToBoundSessions) {
1372
1275
  this.loadBoundDeliveredRing();
1373
1276
  }
@@ -1375,7 +1278,6 @@ export class GithubChannel extends PollingChannelBase {
1375
1278
  process.stderr.write(`[Channel:${this.name}] warning: deliverToBoundSessions requires a daemon-managed channel; ignoring (standalone mode).\n`);
1376
1279
  this.deliverToBoundSessions = false;
1377
1280
  this.requireBoundWatch = false;
1378
- this.prWatchEvents = new Set();
1379
1281
  this.boundSessionActions = new Map();
1380
1282
  }
1381
1283
  const baseUrl = cfg.baseUrl || 'https://api.github.com';
@@ -1454,6 +1356,7 @@ export class GithubChannel extends PollingChannelBase {
1454
1356
  this.config.operators = this.config.operators.map((u) => u.toLowerCase());
1455
1357
  }
1456
1358
  this.migrateLegacyPublicationState();
1359
+ this.retireLegacyPrWatchState();
1457
1360
  this.inboundPersistenceBlocked = false;
1458
1361
  this.inboundRecoveryPending = true;
1459
1362
  // A reconnect starts a fresh runner generation; any runner left over
@@ -2026,122 +1929,64 @@ export class GithubChannel extends PollingChannelBase {
2026
1929
  });
2027
1930
  }
2028
1931
  async pollOnce() {
1932
+ await this.runPollOnce();
1933
+ // Heartbeat stamped only on a SUCCESSFUL poll (the base class saves the
1934
+ // cursor after this resolves): failed polls leave it stale, so an
1935
+ // in-process outage grows the gap and is detected when polls recover.
1936
+ this.cursor.lastPollAt = new Date().toISOString();
1937
+ }
1938
+ async runPollOnce() {
2029
1939
  this.inboundPersistenceBlocked = false;
2030
1940
  this.notificationRetryPending = false;
2031
1941
  this.publicationAuditBlocked = false;
2032
1942
  this.publicationAuditKeysCache = undefined;
2033
- if (this.deliverToBoundSessions) {
2034
- await this.refreshBoundSessions();
2035
- }
2036
- // Reconcile durable pending watch events BEFORE generic recovery and
2037
- // independently of the live API pass: a crash between claim and the
2038
- // pending->fired save leaves both records on disk, and if recovery ran
2039
- // first it would deliver and remove the task, then a later drain would
2040
- // claim and deliver the same transition again. Draining needs no GitHub
2041
- // calls, so a failing or rate-limited binding fetch must not starve it —
2042
- // drain's own re-validation fails closed (keeps the frozen target) when
2043
- // the snapshot is partial or the refresh failed.
2044
- if (this.prWatchEvents.size > 0) {
2045
- try {
2046
- await this.reconcilePendingWatch();
2047
- const wasBlocked = this.watchReconcileBlocked;
2048
- this.watchReconcileBlocked = false;
2049
- this.watchReconcileBlockedCause = undefined;
2050
- // The clearing edge is the recovery signal. A `poll` / `ok` row is
2051
- // not: the base writes one after every poll that does not throw,
2052
- // including every poll of a sustained outage, so it is present
2053
- // throughout the degraded window and cannot mark its end.
2054
- if (wasBlocked) {
2055
- this.recordPollDegraded('watch_reconcile_recovered');
2056
- }
2057
- }
2058
- catch (err) {
2059
- // Recovery must not deliver accepted watch tasks while their pending
2060
- // records are unreconciled (a later drain would deliver them again).
2061
- this.watchReconcileBlocked = true;
2062
- const message = sanitizeLogText(err instanceof Error ? err.message : String(err), 200);
2063
- process.stderr.write(`[Channel:${this.name}] pending watch reconciliation failed, will retry next poll: ${message}\n`);
2064
- // Edge-triggered per cause: this catch runs on EVERY poll while the
2065
- // watch state stays unreadable, so a per-poll row would rotate the
2066
- // journal — but a cause that CHANGES while blocked must re-journal.
2067
- if (this.watchReconcileBlockedCause !== 'reconcile_failed') {
2068
- this.recordPollDegraded('watch_reconcile_blocked', undefined, message);
2069
- this.watchReconcileBlockedCause = 'reconcile_failed';
2070
- }
2071
- }
2072
- }
2073
- else {
2074
- // Subscriptions are off, but unreconciled pending records on disk
2075
- // still own their accepted tasks: recovery must not deliver and
2076
- // remove a task that a later re-enabled drain would claim and
2077
- // deliver again. Keep the guard until no watch pending remains.
2078
- //
2079
- // Classify the cause first. hasUnreconciledWatchPending() is fail-closed
2080
- // on a read error, so an unreadable sidecar also blocks recovery — but
2081
- // reporting that as a pending backlog names a remedy (re-enable
2082
- // subscriptions) that cannot clear it. The gate below is unchanged.
2083
- let watchStateError;
2084
- try {
2085
- this.loadPrWatchState();
2086
- }
2087
- catch (err) {
2088
- watchStateError = sanitizeLogText(err instanceof Error ? err.message : String(err), 200);
2089
- }
2090
- const wasBlocked = this.watchReconcileBlocked;
2091
- this.watchReconcileBlocked = this.hasUnreconciledWatchPending();
2092
- if (this.watchReconcileBlocked) {
2093
- // Park the legacy watch tasks as backpressure so they stop
2094
- // blocking the SHARED notification cursor: watch delivery is off,
2095
- // the reconcile guard still skips them in recovery, and comment
2096
- // events must not stall channel-wide until an operator re-enables
2097
- // watch. Re-enabling drains the pendings and re-resolves them.
1943
+ // Downtime-gap detection on EVERY poll: a pure local comparison against
1944
+ // the last successful heartbeat. A healthy poll re-stamps it, so this
1945
+ // cannot fire in steady state; a restart OR an in-process outage whose
1946
+ // failed polls skipped the cursor save both grow the gap past the
1947
+ // threshold. The threshold scales with the poll interval so a
1948
+ // long-interval channel does not digest every poll.
1949
+ const lastPollAt = this.cursor.lastPollAt;
1950
+ if (lastPollAt !== undefined) {
1951
+ const gapMs = Date.now() - Date.parse(lastPollAt);
1952
+ const thresholdMs = Math.max(STARTUP_DIGEST_MIN_GAP_MS, 5 * this.pollInterval);
1953
+ if (gapMs > thresholdMs &&
1954
+ !this.startupDigestPending &&
1955
+ this.deliverToBoundSessions &&
1956
+ this.prCommentWatchEnabled) {
1957
+ this.startupDigestPending = true;
1958
+ // Persist the arm immediately: this poll's comment watch may be
1959
+ // skipped (failed binding refresh), and a restart before a trusted
1960
+ // pass must still find the arm and digest the backlog instead of
1961
+ // flooding one prompt per comment.
2098
1962
  try {
2099
- for (const task of this.readInboundTasks()) {
2100
- if (this.isRecoverableInboundTask(task) &&
2101
- task.backpressure !== true &&
2102
- task.envelope?.messageId?.startsWith('watch:') === true) {
2103
- this.transitionInboundTask(task.id, 'failed', {
2104
- error: 'watch subscriptions disabled; parked until re-enabled',
2105
- attempts: task.attempts ?? 0,
2106
- deferCount: task.deferCount ?? 0,
2107
- backpressure: true,
2108
- });
2109
- }
1963
+ this.loadPrWatchState();
1964
+ for (const entry of Object.values(this.prWatchState.entries)) {
1965
+ entry.digestPending = true;
1966
+ // A genuine gap is the current origin: reset any stale size-arm
1967
+ // origin so an outage that interrupts a size-armed drain still
1968
+ // reports the offline lead rather than the neutral one.
1969
+ entry.digestSizeArmed = false;
2110
1970
  }
1971
+ this.savePrWatchState();
2111
1972
  }
2112
- catch {
2113
- // Task store unreadable/unwritable: fail closed, retry next poll.
2114
- }
2115
- 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`);
2116
- // Edge-triggered per cause, for the same reason as the reconcile
2117
- // failure above: this branch runs on every poll until an operator
2118
- // re-enables watch, but a backlog that turns into a read error (or
2119
- // back) must re-journal so the row never names a stale remedy.
2120
- const cause = watchStateError ? 'read_error' : 'pending';
2121
- if (this.watchReconcileBlockedCause !== cause) {
2122
- if (watchStateError) {
2123
- this.recordPollDegraded('watch_reconcile_blocked', undefined, watchStateError);
2124
- }
2125
- else {
2126
- this.recordPollDegraded('watch_pending_unreconciled');
2127
- }
2128
- this.watchReconcileBlockedCause = cause;
2129
- }
2130
- }
2131
- else {
2132
- this.watchReconcileBlockedCause = undefined;
2133
- if (wasBlocked) {
2134
- this.recordPollDegraded('watch_reconcile_recovered');
1973
+ catch (err) {
1974
+ // Watch state unreadable or the arm write failed: the in-memory flag
1975
+ // still arms the next successful pass. Surface it so a persisted-arm
1976
+ // write failure is not swallowed silently.
1977
+ process.stderr.write(`[Channel:${this.name}] could not persist the downtime-gap digest arm (the in-memory flag still arms the next pass): ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
2135
1978
  }
1979
+ process.stderr.write(`[Channel:${this.name}] downtime gap detected (${Math.round(gapMs / 1000)}s since the last successful poll); each bound PR's comment backlog digests into one prompt\n`);
2136
1980
  }
2137
1981
  }
2138
- // The watch pass runs before generic recovery so detection cannot race
2139
- // recovery over the same task; pending events were already reconciled.
2140
- // The comment watch is independent of the state-event subscription, so an
2141
- // empty prWatchEvents still runs the pass while comment watching is on.
1982
+ if (this.deliverToBoundSessions) {
1983
+ await this.refreshBoundSessions();
1984
+ }
1985
+ // The comment watch runs before generic recovery so a slow fetch cannot
1986
+ // race the tasks its own deliveries create. It is default-on with bound
1987
+ // delivery and independent of the retired state subscription.
2142
1988
  const commentWatchActive = this.deliverToBoundSessions && this.prCommentWatchEnabled;
2143
- if ((this.prWatchEvents.size > 0 || commentWatchActive) &&
2144
- !this.boundRefreshFailed) {
1989
+ if (commentWatchActive && !this.boundRefreshFailed) {
2145
1990
  // Protect the interactive notification lane: the watch runs first and
2146
1991
  // is best-effort edge-triggered detection, so when the last known REST
2147
1992
  // budget is at or below the reserve, skip the pass this poll rather
@@ -2175,6 +2020,36 @@ export class GithubChannel extends PollingChannelBase {
2175
2020
  // recovers during this window still owes its recovery row.
2176
2021
  this.watchBudgetLow = false;
2177
2022
  this.closeWatchBudgetEpisode();
2023
+ if (!commentWatchActive) {
2024
+ // Comment watching is OFF (not merely skipped this poll): a persisted
2025
+ // digest arm must not survive a disabled restart and later digest the
2026
+ // comments accumulated while it was off. This is the observable site —
2027
+ // runPrStateWatch is never called while disabled. The design promises
2028
+ // per-comment delivery for comments accumulated while watching is off.
2029
+ // A transient boundRefreshFailed skip keeps the arm (the backlog is real).
2030
+ try {
2031
+ this.loadPrWatchState();
2032
+ let cleared = false;
2033
+ for (const entry of Object.values(this.prWatchState.entries)) {
2034
+ if (entry.digestPending === true) {
2035
+ entry.digestPending = false;
2036
+ entry.digestSizeArmed = false;
2037
+ // Keep the rendered frontier: it dedupes already-DELIVERED
2038
+ // members while commentSince stays held. Clearing it here would
2039
+ // let ring-evicted rendered keys re-list and re-deliver on
2040
+ // re-enable. It clears through the consumption paths instead.
2041
+ entry.digestRetiredCount = 0;
2042
+ cleared = true;
2043
+ }
2044
+ }
2045
+ if (cleared)
2046
+ this.savePrWatchState();
2047
+ }
2048
+ catch {
2049
+ // Watch state unreadable: nothing to clear, and the arm cannot be
2050
+ // consumed while watching is off anyway.
2051
+ }
2052
+ }
2178
2053
  }
2179
2054
  if (this.inboundRecoveryPending) {
2180
2055
  try {
@@ -3321,28 +3196,16 @@ export class GithubChannel extends PollingChannelBase {
3321
3196
  record.source.messageId === envelope.messageId &&
3322
3197
  // Fan-out claims one task per (event, target): the target is part
3323
3198
  // of the task identity, while source.messageId stays the pure
3324
- // event key (watch prefix, audit key, and dedupe all ride it).
3199
+ // event key (audit key and dedupe ride it).
3325
3200
  record.delivery?.sessionId === delivery?.sessionId);
3326
3201
  if (existing) {
3327
- // A terminal failed/cancelled record must not swallow the same key's
3328
- // surviving pending event (a crash can leave the pending queue and a
3329
- // terminal attempt of one episode): replace it with a fresh task.
3330
- // reply_pending is NOT terminal — a public reply is still awaiting
3331
- // publication, and replacing it would double-publish.
3332
- const terminal = existing.state === 'cancelled' ||
3333
- (existing.state === 'failed' &&
3334
- (existing.attempts ?? 0) >= MAX_INBOUND_TASK_ATTEMPTS);
3335
- // Only watch episode keys legitimately recur. Comment/event/issue-body
3336
- // keys are stable identifiers that never re-fire: a terminal record
3337
- // there is a permanent dedupe barrier. Replacing it would revive a
3338
- // cancelled comment (public reply to a silenced comment) or duplicate
3339
- // a failed one after a crash leaves the cursor behind the cancel.
3340
- const recurrible = existing.source.messageId?.startsWith('watch:') === true;
3341
- if (!terminal || !recurrible) {
3342
- this.applyTaskDedupe(existing.dedupe);
3343
- return existing;
3344
- }
3345
- this.removeInboundTask(existing.id);
3202
+ // Comment/event/issue-body keys are stable identifiers that never
3203
+ // re-fire: any existing record is a permanent dedupe barrier. Replacing
3204
+ // it would revive a cancelled comment (public reply to a silenced
3205
+ // comment) or duplicate a failed one after a crash leaves the cursor
3206
+ // behind the cancel.
3207
+ this.applyTaskDedupe(existing.dedupe);
3208
+ return existing;
3346
3209
  }
3347
3210
  const now = new Date().toISOString();
3348
3211
  const task = {
@@ -3493,9 +3356,7 @@ export class GithubChannel extends PollingChannelBase {
3493
3356
  if (!envelope)
3494
3357
  return false;
3495
3358
  const bound = task.delivery?.kind === 'bound-session';
3496
- const isWatch = envelope.messageId?.startsWith('watch:') === true;
3497
3359
  if (bound ||
3498
- isWatch ||
3499
3360
  !this.deliverToBoundSessions ||
3500
3361
  envelope.threadId?.startsWith('pr:') !== true) {
3501
3362
  return false;
@@ -3525,7 +3386,6 @@ export class GithubChannel extends PollingChannelBase {
3525
3386
  if (!envelope)
3526
3387
  return true;
3527
3388
  const bound = task.delivery?.kind === 'bound-session';
3528
- const isWatch = envelope.messageId?.startsWith('watch:') === true;
3529
3389
  // Absence from the map authorizes the irreversible public path ONLY
3530
3390
  // on a current complete, successful snapshot. A partial answer cannot
3531
3391
  // prove absence for a PR even when every OBSERVED binder is listed and
@@ -3549,20 +3409,14 @@ export class GithubChannel extends PollingChannelBase {
3549
3409
  // increment. The backpressure rollback is a second write, and a crash
3550
3410
  // between the two would leak one budget per cycle until the event is
3551
3411
  // silently dropped. Recovery charges the interrupted attempt instead,
3552
- // which keeps crash loops terminating. Watch events are bound-path too
3553
- // (private-only), so they share the no-charge running transition.
3554
- this.transitionInboundTask(task.id, 'running', bound || isWatch ? {} : { attempts });
3412
+ // which keeps crash loops terminating.
3413
+ this.transitionInboundTask(task.id, 'running', bound ? {} : { attempts });
3555
3414
  let cancelled = false;
3556
3415
  // The public path journals its own acceptance and publication; only
3557
3416
  // bound delivery needs a verdict to name its terminal outcome.
3558
3417
  let boundResult = { kind: 'public' };
3559
3418
  try {
3560
- // Watch events are private-only: route them by envelope identity, not
3561
- // by the current delivery. A watch task whose delivery was cleared (a
3562
- // gone session, or a crash/removal failure that left it running with no
3563
- // target) must never fall through to the public channel path —
3564
- // deliverToBoundSession retires a targetless watch event privately.
3565
- if (bound || isWatch) {
3419
+ if (bound) {
3566
3420
  boundResult = await this.deliverToBoundSession(task, envelope);
3567
3421
  if (boundResult.kind === 'deferred')
3568
3422
  return false;
@@ -3714,14 +3568,12 @@ export class GithubChannel extends PollingChannelBase {
3714
3568
  this.removeInboundTask(task.id);
3715
3569
  return true;
3716
3570
  }
3717
- if (isWatch || this.privatelyRetiredInboundTaskIds.has(task.id)) {
3718
- // A watch task reaches here only after a private retire cleared its
3719
- // delivery (gone session, no target left); a role-aware comment task
3720
- // after a private retire (role lost its match, siblings already
3721
- // delivered). Neither published anything, so they can have no pending
3722
- // final delivery: reading the public reply lane's store here would
3723
- // wedge the retired task — and with it the shared cursor — on an
3724
- // unrelated file's readability.
3571
+ if (this.privatelyRetiredInboundTaskIds.has(task.id)) {
3572
+ // A role-aware comment task reaches here after a private retire (role
3573
+ // lost its match, siblings already delivered). It published nothing, so
3574
+ // it can have no pending final delivery: reading the public reply lane's
3575
+ // store here would wedge the retired task — and with it the shared
3576
+ // cursor — on an unrelated file's readability.
3725
3577
  this.privatelyRetiredInboundTaskIds.delete(task.id);
3726
3578
  this.removeInboundTask(task.id);
3727
3579
  // After the removal, like the dead-letter site: a throwing removal
@@ -3813,16 +3665,14 @@ export class GithubChannel extends PollingChannelBase {
3813
3665
  // in-flight entry is a genuine crash and must still be recovered.
3814
3666
  if (this.publicTasksInFlight.has(task.id))
3815
3667
  continue;
3816
- this.applyTaskDedupe(task.dedupe);
3817
- if (this.watchReconcileBlocked &&
3818
- task.envelope.messageId?.startsWith('watch:') === true) {
3819
- // Reconciliation itself failed (e.g. the watch file is unreadable):
3820
- // delivering and removing this accepted task now would leave its
3821
- // on-disk pending record for a later drain to claim and deliver a
3822
- // second time. Keep it queued for the reconcile pass; unrelated
3823
- // comment recovery continues below.
3668
+ if (task.envelope.messageId?.startsWith('watch:') === true) {
3669
+ // The adapter's state watch is retired. A task left behind by a
3670
+ // failed retirement must never be replayed; its dead-letter record is
3671
+ // the only intended trace. A failed write keeps it for the next pass.
3672
+ this.retireBoundTask(task, 'the adapter PR state watch was retired; the transition is not replayed');
3824
3673
  continue;
3825
3674
  }
3675
+ this.applyTaskDedupe(task.dedupe);
3826
3676
  if (task.deliveredAt !== undefined) {
3827
3677
  // The daemon accepted this prompt before the crash; re-injecting
3828
3678
  // would deliver the same event twice. Retire without replay — but
@@ -3963,13 +3813,8 @@ export class GithubChannel extends PollingChannelBase {
3963
3813
  * deferral horizon, and must not freeze mark-as-read for every unrelated
3964
3814
  * PR the channel follows. This covers both bound deliveries and the
3965
3815
  * targetless deferrals an incomplete binding snapshot produces (no
3966
- * delivery yet, same durable retry). Watch tasks are excluded while
3967
- * reconcile is blocked: recovery skips them and the drain cannot run, so
3968
- * they cannot make progress — and watch events are detected from PR
3969
- * state, not notifications, so holding the cursor for them only stalls
3970
- * unrelated comment traffic until the watch sidecar recovers. Once
3971
- * reconcile succeeds they count again, and their retry budgets guarantee
3972
- * they settle instead of freezing the cursor forever.
3816
+ * delivery yet, same durable retry). Every entry here settles through its
3817
+ * own retry budget, so it cannot freeze the cursor forever.
3973
3818
  */
3974
3819
  hasCursorBlockingTasks() {
3975
3820
  return this.readInboundTasks().some((task) => this.isCursorBlockingTask(task));
@@ -3992,10 +3837,13 @@ export class GithubChannel extends PollingChannelBase {
3992
3837
  return this.pollStartHeldThreads.has(`${chatId}|${threadId}`);
3993
3838
  }
3994
3839
  isCursorBlockingTask(task) {
3840
+ // A retired `watch:` task that the dead-letter write keeps retrying is
3841
+ // never replayed, so it must not freeze the shared notification cursor:
3842
+ // with the dead-letter path unwritable, holding it would stop
3843
+ // markNotificationsAsRead for the daemon's lifetime.
3995
3844
  return (this.isRecoverableInboundTask(task) &&
3996
3845
  task.backpressure !== true &&
3997
- !(this.watchReconcileBlocked &&
3998
- task.envelope?.messageId?.startsWith('watch:') === true));
3846
+ task.envelope?.messageId?.startsWith('watch:') !== true);
3999
3847
  }
4000
3848
  /** Whether one of the thread's own tasks holds the cursor, as last seen. */
4001
3849
  threadTaskHoldsCursor(chatId, threadId) {
@@ -4261,64 +4109,6 @@ export class GithubChannel extends PollingChannelBase {
4261
4109
  return this.lastBindings.find((binding) => binding.sessionId === sessionId)
4262
4110
  ?.workspaceCwd;
4263
4111
  }
4264
- /**
4265
- * Whether a message key already has a durable dead-letter record. Loads the
4266
- * never-rotated file's keys once, then serves from the cache this process
4267
- * keeps current on append. A read failure yields an empty cache: nothing is
4268
- * known to be dead-lettered, so the caller appends (a possible duplicate is
4269
- * benign) rather than silently skipping the exhaustion surface.
4270
- */
4271
- isDeadLettered(messageKey) {
4272
- if (this.deadLetteredKeys === undefined) {
4273
- const keys = new Set();
4274
- try {
4275
- const raw = readFileSync(this.channelFilePath('github-bound-deadletter.jsonl'), 'utf-8');
4276
- for (const line of raw.split('\n')) {
4277
- if (!line)
4278
- continue;
4279
- try {
4280
- const rec = JSON.parse(line);
4281
- if (typeof rec.source?.messageId === 'string') {
4282
- keys.add(rec.source.messageId);
4283
- }
4284
- }
4285
- catch {
4286
- // A malformed line names no key; skip it.
4287
- }
4288
- }
4289
- }
4290
- catch {
4291
- // No file yet, or unreadable: nothing known to be dead-lettered.
4292
- }
4293
- this.deadLetteredKeys = keys;
4294
- }
4295
- return this.deadLetteredKeys.has(messageKey);
4296
- }
4297
- /**
4298
- * The overflow retire's journal trace, written only after the retire is
4299
- * durable. Identifiers only — the dead-letter record's `text` (the body)
4300
- * must never be copied here. Carries the frozen target and its workspace so
4301
- * the row links to the session the event lost, even in another workspace.
4302
- */
4303
- recordWatchOverflowSkip(pending) {
4304
- const sessionId = pending.delivery?.kind === 'bound-session'
4305
- ? pending.delivery.sessionId
4306
- : undefined;
4307
- const workspaceCwd = sessionId
4308
- ? this.sessionWorkspaceFor(sessionId)
4309
- : undefined;
4310
- this.recordChannelEvent({
4311
- type: 'inbound',
4312
- outcome: 'skipped',
4313
- reason: 'watch_pending_overflow',
4314
- repository: pending.envelope.chatId,
4315
- thread: pending.envelope.threadId,
4316
- number: pending.issueNumber,
4317
- messageId: pending.key,
4318
- ...(sessionId ? { sessionId } : {}),
4319
- ...(workspaceCwd ? { sessionWorkspaceCwd: workspaceCwd } : {}),
4320
- });
4321
- }
4322
4112
  removeInboundTask(taskId) {
4323
4113
  this.updateInboundTasks((records) => records.filter((record) => record.id !== taskId));
4324
4114
  }
@@ -4427,12 +4217,7 @@ export class GithubChannel extends PollingChannelBase {
4427
4217
  * covers a wrong estimate or a secondary limit.
4428
4218
  */
4429
4219
  watchBudgetExhausted() {
4430
- const reserve = this.prWatchBudgetReserve;
4431
- // A reserve of 0 disables the gate outright. Without this, a remaining
4432
- // of 0 would still satisfy `0 <= 0` and skip the watch the operator
4433
- // explicitly opted out of protecting.
4434
- if (reserve === 0)
4435
- return false;
4220
+ const reserve = PR_WATCH_BUDGET_RESERVE;
4436
4221
  if (this.lastRateLimitRemaining === undefined)
4437
4222
  return false;
4438
4223
  if (this.lastRateLimitResetAt !== undefined &&
@@ -4453,9 +4238,9 @@ export class GithubChannel extends PollingChannelBase {
4453
4238
  this.watchBudgetLow = true;
4454
4239
  this.recordPollDegraded('watch_budget_low', {
4455
4240
  remaining: this.lastRateLimitRemaining ?? 0,
4456
- reserve: this.prWatchBudgetReserve,
4241
+ reserve: PR_WATCH_BUDGET_RESERVE,
4457
4242
  });
4458
- process.stderr.write(`[Channel:${this.name}] PR state watch skipped: REST budget ${this.lastRateLimitRemaining} at or below reserve ${this.prWatchBudgetReserve}; preserving budget for the notification lane\n`);
4243
+ process.stderr.write(`[Channel:${this.name}] PR watch skipped: REST budget ${this.lastRateLimitRemaining} at or below reserve ${PR_WATCH_BUDGET_RESERVE}; preserving budget for the notification lane\n`);
4459
4244
  }
4460
4245
  /**
4461
4246
  * Close the episode once the budget is no longer exhausted. A still-low
@@ -5155,19 +4940,11 @@ export class GithubChannel extends PollingChannelBase {
5155
4940
  return followers;
5156
4941
  }
5157
4942
  /**
5158
- * The event class a bound delivery resolves templates against: the watch
5159
- * type from the durable message id (authoritative — the metadata Event
5160
- * line is display, not identity), else the notification trigger reason.
5161
- * An envelope with neither has no class and resolves through `default`.
4943
+ * The event class a bound delivery resolves templates against: the
4944
+ * notification trigger reason. An envelope with none has no class and
4945
+ * resolves through `default`.
5162
4946
  */
5163
4947
  boundEventClass(envelope) {
5164
- const messageId = envelope.messageId ?? '';
5165
- if (messageId.startsWith('watch:')) {
5166
- const type = messageId.slice('watch:'.length).split(':')[0];
5167
- if (type && KNOWN_PR_WATCH_EVENTS.has(type))
5168
- return `watch:${type}`;
5169
- return undefined;
5170
- }
5171
4948
  return parseTriggerKind(envelope.metadata);
5172
4949
  }
5173
4950
  /**
@@ -5175,7 +4952,7 @@ export class GithubChannel extends PollingChannelBase {
5175
4952
  * aggregate, identified by their dispatchedComments dedupe) fall back to
5176
4953
  * `comment` after the thread's notification reason, so a `fix:comment`
5177
4954
  * template catches a comment delivered under `mention`/`subscribed`/
5178
- * `author` too. Watch and direct-event lanes have no lane fallback.
4955
+ * `author` too. A direct-event lane has no lane fallback.
5179
4956
  */
5180
4957
  boundLaneClass(dedupe) {
5181
4958
  return dedupe?.dispatchedComments !== undefined ? 'comment' : undefined;
@@ -5334,6 +5111,13 @@ export class GithubChannel extends PollingChannelBase {
5334
5111
  const path = this.channelFilePath('github-bound-delivered.json');
5335
5112
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
5336
5113
  writeFileSync(path, `${JSON.stringify({ keys: this.boundDeliveredOrder })}\n`, { encoding: 'utf-8', mode: 0o600 });
5114
+ // A successful write repairs the ring for the digest's own acceptance
5115
+ // check: latch the repair so the digest can prove its freshly written
5116
+ // key. Do NOT clear boundDeliveredUnreadable — the keys lost with the
5117
+ // file stay unknown, and the public-duplicate suppression callers must
5118
+ // keep failing closed for them (clearing it would open an irreversible
5119
+ // public-reply window for every pre-corruption event).
5120
+ this.boundDeliveredRepaired = true;
5337
5121
  }
5338
5122
  catch (err) {
5339
5123
  process.stderr.write(`[Channel:${this.name}] failed to persist bound-delivered ring (in-memory suppression still active): ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
@@ -5564,16 +5348,7 @@ export class GithubChannel extends PollingChannelBase {
5564
5348
  async deliverToBoundSession(task, envelope) {
5565
5349
  const boundSessions = this.boundSessions;
5566
5350
  let delivery = task.delivery;
5567
- const isWatch = envelope.messageId?.startsWith('watch:') === true;
5568
5351
  if (!boundSessions || delivery?.kind !== 'bound-session') {
5569
- // Watch events are operator-facing machine state with no public path:
5570
- // a channel session's reply would publish the internal prompt text on
5571
- // the PR. They are only ever delivered privately; without a bound
5572
- // target they are logged and retired, never fallen back publicly.
5573
- if (isWatch) {
5574
- process.stderr.write(`[Channel:${this.name}] watch event ${envelope.messageId} has no bound delivery target; retiring without public fallback\n`);
5575
- return { kind: 'retired', reason: 'watch_no_target' };
5576
- }
5577
5352
  if (this.boundRoleAware && this.boundEventAlreadyDelivered(envelope)) {
5578
5353
  // Defensive: a sibling role already accepted this event privately, so
5579
5354
  // a targetless retry must not answer it publicly (durable delivery
@@ -5618,27 +5393,25 @@ export class GithubChannel extends PollingChannelBase {
5618
5393
  delivery = current;
5619
5394
  }
5620
5395
  else if (!current &&
5621
- (isWatch ||
5622
- this.boundRoleAware ||
5396
+ (this.boundRoleAware ||
5623
5397
  this.frozenTargetGateExcluded(delivery, envelope.chatId, task.issueNumber))) {
5624
5398
  // On a complete snapshot with no candidate left for the task's role,
5625
- // retire privately. Watch events are private-only by contract; a
5626
- // role-aware COMMENT whose role lost its match (the binding's role
5627
- // changed, or the operator removed the template) must not keep
5628
- // injecting the obsolete role's instruction into the frozen session
5629
- // either. Under the watch gate a legacy comment retires too, but
5630
- // ONLY when the gate excluded the FROZEN TARGET itself (it stopped
5631
- // watching between claim and delivery). The decision is about the
5632
- // target, not the follower set: an exempt fix/untyped target, a
5399
+ // retire privately. A role-aware COMMENT whose role lost its match
5400
+ // (the binding's role changed, or the operator removed the template)
5401
+ // must not keep injecting the obsolete role's instruction into the
5402
+ // frozen session. Under the watch gate a legacy comment retires too,
5403
+ // but ONLY when the gate excluded the FROZEN TARGET itself (it
5404
+ // stopped watching between claim and delivery). The decision is about
5405
+ // the target, not the follower set: an exempt fix/untyped target, a
5633
5406
  // merely author-excluded winner, or a REMOVED binding all keep the
5634
5407
  // legacy contract — the frozen target stands and the gone path below
5635
5408
  // owns the fallback — so the gate never changes behavior for the
5636
5409
  // fix/untyped sessions it exempts.
5637
- 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`);
5410
+ process.stderr.write(`[Channel:${this.name}] bound event ${envelope.messageId} has no bound candidate left for its role; retiring without public fallback\n`);
5638
5411
  this.markPrivatelyRetired(task);
5639
5412
  return {
5640
5413
  kind: 'retired',
5641
- reason: isWatch ? 'watch_no_candidate' : 'bound_no_candidate',
5414
+ reason: 'bound_no_candidate',
5642
5415
  sessionId: delivery.sessionId,
5643
5416
  };
5644
5417
  }
@@ -5646,29 +5419,26 @@ export class GithubChannel extends PollingChannelBase {
5646
5419
  // The channel path runs the group/sender/pairing gates inside
5647
5420
  // handleInbound → preflightInbound; bound delivery bypasses
5648
5421
  // handleInbound, so run the same preflight here (pairing side effects
5649
- // included). Watch events have no human sender — they are operator
5650
- // opt-in state changes — and are exempt.
5651
- if (!isWatch) {
5652
- // A first-contact body is the PR's own description, not a comment
5653
- // for the session: it keeps the mention requirement.
5654
- const preflight = this.preflightInbound(envelope, {
5655
- waiveGroupMention: !envelope.messageId?.startsWith('issue-body-') &&
5656
- this.waivesBoundMention(envelope.chatId, envelope.senderId),
5657
- // The comment watch delivers the channel account's own comments (the
5658
- // notification lanes filter that login out, so this can only be the
5659
- // watch). The sender allowlist guidance excludes that account, which
5660
- // would otherwise retire every watched comment as preflight_rejected.
5661
- waiveGroupSender: this.botUsername != null &&
5662
- envelope.senderId === this.botUsername.toLowerCase(),
5663
- });
5664
- const admitted = typeof preflight === 'boolean' ? preflight : await preflight;
5665
- if (!admitted) {
5666
- // The bound path inherits the channel gates (sender allowlist,
5667
- // message routes); a rejection retires the event without delivering
5668
- // it, so surface it instead of consuming it silently.
5669
- process.stderr.write(`[Channel:${this.name}] bound event ${envelope.messageId} rejected by the channel preflight (sender/route gates); retiring without delivery\n`);
5670
- return { kind: 'retired', reason: 'preflight_rejected' };
5671
- }
5422
+ // included).
5423
+ // A first-contact body is the PR's own description, not a comment
5424
+ // for the session: it keeps the mention requirement.
5425
+ const preflight = this.preflightInbound(envelope, {
5426
+ waiveGroupMention: !envelope.messageId?.startsWith('issue-body-') &&
5427
+ this.waivesBoundMention(envelope.chatId, envelope.senderId),
5428
+ // The comment watch delivers the channel account's own comments (the
5429
+ // notification lanes filter that login out, so this can only be the
5430
+ // watch). The sender allowlist guidance excludes that account, which
5431
+ // would otherwise retire every watched comment as preflight_rejected.
5432
+ waiveGroupSender: this.botUsername != null &&
5433
+ envelope.senderId === this.botUsername.toLowerCase(),
5434
+ });
5435
+ const admitted = typeof preflight === 'boolean' ? preflight : await preflight;
5436
+ if (!admitted) {
5437
+ // The bound path inherits the channel gates (sender allowlist,
5438
+ // message routes); a rejection retires the event without delivering
5439
+ // it, so surface it instead of consuming it silently.
5440
+ process.stderr.write(`[Channel:${this.name}] bound event ${envelope.messageId} rejected by the channel preflight (sender/route gates); retiring without delivery\n`);
5441
+ return { kind: 'retired', reason: 'preflight_rejected' };
5672
5442
  }
5673
5443
  const prompt = this.buildBoundSessionPrompt(envelope, delivery.role, this.boundLaneClass(task.dedupe), task.boundText);
5674
5444
  // The idempotency identity is the EVENT (chat + source message), not the
@@ -5755,19 +5525,6 @@ export class GithubChannel extends PollingChannelBase {
5755
5525
  next = this.resolveBoundDeliveryExcluding(envelope.chatId, task.issueNumber, goneSessions, roleFilter);
5756
5526
  }
5757
5527
  }
5758
- if (isWatch) {
5759
- // Private-only: no public fallback for watch events (a channel
5760
- // session would publish the operator-facing prompt as a PR comment
5761
- // and re-gate it through the sender allowlist). Log and retire.
5762
- process.stderr.write(`[Channel:${this.name}] watch event ${envelope.messageId} lost its bound session; retiring without public fallback\n`);
5763
- this.transitionInboundTask(task.id, 'running', { delivery: undefined });
5764
- task.delivery = undefined;
5765
- return {
5766
- kind: 'retired',
5767
- reason: 'watch_session_gone',
5768
- sessionId: lastTarget.sessionId,
5769
- };
5770
- }
5771
5528
  // Role-aware fan-out: a partially delivered event never ALSO goes
5772
5529
  // public. While any role still follows the PR, the event is (or will
5773
5530
  // be) delivered privately through that role's own task; a public
@@ -5849,6 +5606,79 @@ export class GithubChannel extends PollingChannelBase {
5849
5606
  }
5850
5607
  return { kind: 'delivered' };
5851
5608
  }
5609
+ /**
5610
+ * One-time retirement of the adapter's persisted state watch. The watch
5611
+ * file stays (the comment cursors and the last title live in it), but the
5612
+ * transition baseline and queue are stripped, and persisted `watch:`
5613
+ * tasks are retired privately rather than replayed. A sentinel makes the
5614
+ * count a once-only line and lets a failed retirement retry instead of
5615
+ * being skipped.
5616
+ */
5617
+ retireLegacyPrWatchState() {
5618
+ const sentinel = this.channelFilePath('github-pr-watch-retired');
5619
+ if (existsSync(sentinel))
5620
+ return;
5621
+ try {
5622
+ // Tasks first: a failure here must not lose the count, which is only
5623
+ // observable while the state file still holds the queue.
5624
+ const tasks = this.readInboundTasks().filter((task) => task.envelope?.messageId?.startsWith('watch:') === true);
5625
+ for (const task of tasks) {
5626
+ this.retireBoundTask(task, 'the adapter PR state watch was retired; the transition is not replayed');
5627
+ }
5628
+ const remaining = this.readInboundTasks().some((task) => task.envelope?.messageId?.startsWith('watch:') === true);
5629
+ if (remaining) {
5630
+ process.stderr.write(`[Channel:${this.name}] PR state watch retirement could not retire every persisted watch task; will retry on the next connect\n`);
5631
+ return;
5632
+ }
5633
+ this.loadPrWatchState();
5634
+ let undelivered = 0;
5635
+ const entries = {};
5636
+ for (const [key, entry] of Object.entries(this.prWatchState.entries)) {
5637
+ // The retired watch wrote fields this type no longer declares; read
5638
+ // only the queue length once, before stripping the entry.
5639
+ const legacy = entry;
5640
+ undelivered += Array.isArray(legacy.pending)
5641
+ ? legacy.pending.length
5642
+ : 0;
5643
+ const kept = {};
5644
+ if (entry.title !== undefined)
5645
+ kept.title = entry.title;
5646
+ if (entry.commentBaseline !== undefined) {
5647
+ kept.commentBaseline = entry.commentBaseline;
5648
+ }
5649
+ if (entry.commentSince !== undefined) {
5650
+ kept.commentSince = entry.commentSince;
5651
+ }
5652
+ if (entry.commentLastFetchAt !== undefined) {
5653
+ kept.commentLastFetchAt = entry.commentLastFetchAt;
5654
+ }
5655
+ entries[key] = kept;
5656
+ }
5657
+ this.prWatchState = { version: 1, entries };
5658
+ // A fresh install has no file: do not create one just to write the
5659
+ // emptied state.
5660
+ if (existsSync(this.prWatchStatePath())) {
5661
+ this.savePrWatchState();
5662
+ }
5663
+ process.stderr.write(`[Channel:${this.name}] PR state watch retired: ${undelivered} undelivered transition${undelivered === 1 ? '' : 's'} dropped (not replayed); comment cursors and the last observed title preserved\n`);
5664
+ mkdirSync(dirname(sentinel), { recursive: true, mode: 0o700 });
5665
+ writeFileSync(sentinel, '', { mode: 0o600 });
5666
+ }
5667
+ catch (err) {
5668
+ // Leave the sentinel unwritten so the next connect retries. Reload the
5669
+ // file then: a failed save leaves the on-disk state intact.
5670
+ this.prWatchStateLoaded = false;
5671
+ process.stderr.write(`[Channel:${this.name}] PR state watch retirement failed, will retry on the next connect: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
5672
+ }
5673
+ finally {
5674
+ // The pass must read the file it will maintain, whether or not a file
5675
+ // existed before this retirement.
5676
+ if (existsSync(sentinel)) {
5677
+ this.prWatchState = { version: 1, entries: {} };
5678
+ this.prWatchStateLoaded = false;
5679
+ }
5680
+ }
5681
+ }
5852
5682
  prWatchStatePath() {
5853
5683
  return this.channelFilePath('github-pr-watch.json');
5854
5684
  }
@@ -5914,37 +5744,6 @@ export class GithubChannel extends PollingChannelBase {
5914
5744
  }
5915
5745
  this.prWatchStateLoaded = true;
5916
5746
  }
5917
- /**
5918
- * Whether any persisted watch entry still holds pending events. Keeps
5919
- * recovery blocked while watch subscriptions are disabled: an accepted
5920
- * task whose pending record is unreconciled must not be delivered and
5921
- * removed ahead of a later re-enabled drain. Fail-closed on read errors.
5922
- */
5923
- hasUnreconciledWatchPending() {
5924
- try {
5925
- this.loadPrWatchState();
5926
- }
5927
- catch {
5928
- return true;
5929
- }
5930
- return Object.values(this.prWatchState.entries).some((entry) => (entry.pending?.length ?? 0) > 0);
5931
- }
5932
- /**
5933
- * PR keys whose earlier watch transition still has a recoverable inbound
5934
- * task. Undefined when the task store cannot be read: the caller must
5935
- * not prune or evict watch memory it cannot cross-check (fail-closed).
5936
- */
5937
- survivingWatchPrKeys() {
5938
- try {
5939
- return new Set(this.readInboundTasks()
5940
- .filter((task) => this.isRecoverableInboundTask(task) &&
5941
- task.envelope?.messageId?.startsWith('watch:') === true)
5942
- .map((task) => this.prBindingKey(task.source.chatId, task.issueNumber)));
5943
- }
5944
- catch {
5945
- return undefined;
5946
- }
5947
- }
5948
5747
  savePrWatchState() {
5949
5748
  // Never overwrite on-disk state with memory that failed to load: a
5950
5749
  // transient read error must not destroy pending events / fired rings.
@@ -5979,72 +5778,20 @@ export class GithubChannel extends PollingChannelBase {
5979
5778
  }
5980
5779
  }
5981
5780
  /**
5982
- * Drain durable pending watch events independently of the live API pass
5983
- * and BEFORE generic recovery. Needs no GitHub calls: a failing or
5984
- * rate-limited watch pass must not starve already-detected events, and
5985
- * recovery must not deliver-and-remove a task that a later drain would
5986
- * re-claim (crash between the claim and the pending->fired save leaves
5987
- * both records on disk).
5988
- */
5989
- async reconcilePendingWatch() {
5990
- if (!this.boundSessions || this.prWatchEvents.size === 0)
5991
- return;
5992
- this.loadPrWatchState();
5993
- for (const [key, entry] of Object.entries(this.prWatchState.entries)) {
5994
- if (!entry.pending?.length)
5995
- continue;
5996
- await this.drainPendingWatch(key, entry);
5997
- }
5998
- }
5999
- /**
6000
- * Open-PR watch fan-out per poll (terminal-pending bindings drain in an
6001
- * additional slice outside it). Clamped like pollInterval: unset or
6002
- * invalid keeps the default; a fractional count rounds up so the
6003
- * configured budget is never silently smaller than requested.
6004
- */
6005
- get prWatchLimit() {
6006
- const configured = this.config.prWatchLimit;
6007
- if (typeof configured === 'number' &&
6008
- Number.isFinite(configured) &&
6009
- configured > 0) {
6010
- return Math.min(Math.max(Math.ceil(configured), 1), MAX_PR_WATCH_LIMIT);
6011
- }
6012
- return DEFAULT_PR_WATCH_LIMIT;
6013
- }
6014
- /**
6015
- * Requests reserved for the notification lane: at or below this remaining
6016
- * budget the watch pass yields. Clamped like prWatchLimit; a configured 0
6017
- * is honoured (disables the gate) so an operator can opt out, while unset
6018
- * or invalid keeps the default. Rounds up so the reserve is never silently
6019
- * smaller than requested.
6020
- */
6021
- get prWatchBudgetReserve() {
6022
- const configured = this.config
6023
- .prWatchBudgetReserve;
6024
- if (typeof configured === 'number' &&
6025
- Number.isFinite(configured) &&
6026
- configured >= 0) {
6027
- return Math.min(Math.ceil(configured), MAX_PR_WATCH_BUDGET_RESERVE);
6028
- }
6029
- return DEFAULT_PR_WATCH_BUDGET_RESERVE;
6030
- }
6031
- /**
6032
- * Edge-triggered state watch over the PRs bound to live sessions. Runs
6033
- * inside the existing poll loop; detection is API-level and costs no model
6034
- * tokens until a real transition fires.
5781
+ * The comment-watch pass over the PRs bound to live sessions. Runs inside
5782
+ * the existing poll loop. The state-transition watch that used to share
5783
+ * this pass moved to the daemon (master §7), so an empty state
5784
+ * subscription no longer skips it: only the comment subscription and the
5785
+ * bound-session handle decide.
6035
5786
  */
6036
5787
  async runPrStateWatch() {
6037
- // The comment watch is default-on with deliverToBoundSessions and is
6038
- // independent of the state-event subscription, so an empty prWatchEvents
6039
- // must not skip the pass while comment watching is enabled.
6040
- const commentWatchActive = this.deliverToBoundSessions && this.prCommentWatchEnabled;
6041
5788
  if (!this.boundSessions ||
6042
- (this.prWatchEvents.size === 0 && !commentWatchActive)) {
5789
+ !this.deliverToBoundSessions ||
5790
+ !this.prCommentWatchEnabled) {
6043
5791
  return;
6044
5792
  }
6045
5793
  this.loadPrWatchState();
6046
5794
  const candidates = new Map();
6047
- const active = new Map();
6048
5795
  for (const summary of this.lastBindings) {
6049
5796
  if (summary.sourceType === 'channel')
6050
5797
  continue;
@@ -6052,169 +5799,105 @@ export class GithubChannel extends PollingChannelBase {
6052
5799
  const identity = this.parsePrBindingUrl(pr.url);
6053
5800
  if (!identity || identity.number !== pr.number)
6054
5801
  continue;
5802
+ // A merged or closed binding has no new comments to fetch, but it
5803
+ // still belongs to the snapshot: the entry is the only home of the
5804
+ // comment cursor and the title, and the prune below deletes every key
5805
+ // the snapshot does not claim. Skipping the fetch, not the candidate,
5806
+ // keeps a reopen from re-baselining past the merged window.
5807
+ const terminal = pr.state === 'merged' || pr.state === 'closed';
6055
5808
  const key = this.prBindingKey(identity.chatId, identity.number);
6056
5809
  const updatedAt = summary.updatedAt ?? '';
6057
5810
  const existing = candidates.get(key);
6058
- if (!existing || updatedAt > existing.updatedAt) {
5811
+ if (!existing) {
6059
5812
  candidates.set(key, {
6060
5813
  chatId: identity.chatId,
6061
5814
  number: identity.number,
6062
5815
  updatedAt,
5816
+ terminal,
6063
5817
  });
6064
5818
  }
6065
- // The independent binding refresh can record merged/closed before
6066
- // this poll observes the transition. Keep such PRs polled until the
6067
- // terminal transition has actually been observed (prState 'closed'),
6068
- // so state_change is never skipped. Once observed, the terminal
6069
- // MARKER is retained (no polling) for as long as the binding lists
6070
- // the PR: pruning it here would re-add the closed PR as a first
6071
- // observation on the next poll (query oscillation) and lose the
6072
- // terminal record. Binding retention and active polling are
6073
- // separate concerns. A comment-only channel subscribes no state
6074
- // event, so there is no state_change to observe and watchOnePr (the
6075
- // only prState writer) never runs: drain on the binding's terminal
6076
- // state alone, else merged/closed bindings would be comment-fetched
6077
- // forever. A reopened binding flips back to open and resumes.
6078
- if ((pr.state === 'merged' || pr.state === 'closed') &&
6079
- (this.prWatchState.entries[key]?.prState === 'closed' ||
6080
- this.prWatchEvents.size === 0)) {
6081
- continue;
6082
- }
6083
- const existingActive = active.get(key);
6084
- if (!existingActive || updatedAt > existingActive.updatedAt) {
6085
- active.set(key, {
6086
- chatId: identity.chatId,
6087
- number: identity.number,
6088
- updatedAt,
6089
- // Tiering only — observation stays API-authoritative. A binding
6090
- // still saying open while the watch already observed closed must
6091
- // not hold an open-tier slot (stale registry, e.g. refresh
6092
- // disabled); a genuinely reopened PR gets one leftover-budget
6093
- // observation and returns to the open tier, self-correcting.
6094
- terminal: pr.state === 'merged' ||
6095
- pr.state === 'closed' ||
6096
- this.prWatchState.entries[key]?.prState === 'closed',
6097
- });
5819
+ else {
5820
+ // Any open binding wins: its session still follows the PR, so the
5821
+ // fetch stays on even when another summary already reads terminal.
5822
+ if (!terminal)
5823
+ existing.terminal = false;
5824
+ if (updatedAt > existing.updatedAt)
5825
+ existing.updatedAt = updatedAt;
6098
5826
  }
6099
5827
  }
6100
5828
  }
6101
- // Prune only against a complete snapshot: a partial answer (workspace
6102
- // failure, unreadable sidecar or missing runtime) must not destroy
6103
- // the edge-triggered memory of PRs it failed to list. Prune against the
6104
- // full candidate set, not the capped watch set, so PRs rotating out of
6105
- // the cap keep their baseline. Never delete an entry that still holds
6106
- // undelivered pending events (a failed claim keeps its queue) OR whose
6107
- // earlier transition still has a surviving inbound task: keep the
6108
- // baseline and ciFiredSha pin while the old transition is in flight so
6109
- // a rebind does not re-fire the same red head.
5829
+ // Prune only against a complete snapshot: a partial answer must not
5830
+ // destroy cursors for PRs it failed to list.
6110
5831
  if (!this.lastBindingsPartial) {
6111
- // Undefined = task store unreadable: skip pruning entirely this poll
6112
- // (fail-closed, same convention as the persistence-blocked cursor).
6113
- const survivingWatchPrs = this.survivingWatchPrKeys();
6114
- if (survivingWatchPrs !== undefined) {
6115
- for (const key of Object.keys(this.prWatchState.entries)) {
6116
- if (candidates.has(key))
6117
- continue;
6118
- if (this.prWatchState.entries[key]?.pending?.length)
6119
- continue;
6120
- if (survivingWatchPrs.has(key))
6121
- continue;
5832
+ for (const key of Object.keys(this.prWatchState.entries)) {
5833
+ if (!candidates.has(key))
6122
5834
  delete this.prWatchState.entries[key];
6123
- }
6124
5835
  }
6125
5836
  }
6126
- // The prune above never runs under a permanent partial; cap the entry
6127
- // map so an unscannable workspace cannot grow it without bound. Evict
6128
- // only the oldest IDLE entries that no retained binding still claims
6129
- // and no in-flight watch task still owns — the same protections as the
6130
- // complete-snapshot prune. An evicted entry belongs to a PR with no
6131
- // delivery target: a later rebind re-baselines silently like any first
6132
- // observation, so eviction bounds memory without losing a deliverable
6133
- // event. Surfaced on stderr, never silent.
5837
+ // Cap the entry map so an unscannable workspace cannot grow it without
5838
+ // bound. Evict only idle entries no retained binding still claims; an
5839
+ // evicted entry re-baselines silently on a later rebind. Surfaced on
5840
+ // stderr, never silent.
6134
5841
  const entryKeys = Object.keys(this.prWatchState.entries);
6135
5842
  if (entryKeys.length > MAX_PARTIAL_RETAINED) {
6136
- const survivingWatchPrs = this.survivingWatchPrKeys();
6137
- if (survivingWatchPrs !== undefined) {
6138
- const evictable = entryKeys
6139
- .filter((key) => !this.prWatchState.entries[key]?.pending?.length &&
6140
- !candidates.has(key) &&
6141
- !survivingWatchPrs.has(key))
6142
- .sort((a, b) => (this.prWatchState.entries[a]?.headObservedAt ?? 0) -
6143
- (this.prWatchState.entries[b]?.headObservedAt ?? 0));
6144
- const evictCount = Math.min(evictable.length, entryKeys.length - MAX_PARTIAL_RETAINED);
6145
- for (let i = 0; i < evictCount; i++) {
6146
- delete this.prWatchState.entries[evictable[i]];
6147
- }
6148
- if (evictCount > 0) {
6149
- process.stderr.write(`[Channel:${this.name}] PR watch entry cap exceeded: evicted ${evictCount} idle entries (oldest first) to bound memory under a partial binding snapshot\n`);
6150
- }
5843
+ const evictable = entryKeys
5844
+ .filter((key) => !candidates.has(key))
5845
+ .sort((a, b) => (this.prWatchState.entries[a]?.commentLastFetchAt ?? 0) -
5846
+ (this.prWatchState.entries[b]?.commentLastFetchAt ?? 0));
5847
+ const evictCount = Math.min(evictable.length, entryKeys.length - MAX_PARTIAL_RETAINED);
5848
+ for (let i = 0; i < evictCount; i++) {
5849
+ delete this.prWatchState.entries[evictable[i]];
5850
+ }
5851
+ if (evictCount > 0) {
5852
+ process.stderr.write(`[Channel:${this.name}] PR watch entry cap exceeded: evicted ${evictCount} idle entries (oldest first) to bound memory under a partial binding snapshot\n`);
6151
5853
  }
6152
- }
6153
- // Open bindings take the FULL watch budget: a merged or closed PR that
6154
- // the watch has not observed yet must never crowd a live PR out of it,
6155
- // even when open bindings fill the limit. Terminal-pending bindings
6156
- // drain in an ADDITIONAL slice outside the open budget (20% of the
6157
- // limit, at least one, plus any leftover open budget): without it they
6158
- // would never receive their one terminal observation when open PRs
6159
- // fill the limit, and the active set would grow with every merge. The
6160
- // extra slice costs at most ceil(limit*0.2) additional pulls.get per
6161
- // poll while a backlog drains; each drained binding leaves the active
6162
- // set for good, so the fan-out returns to the open budget once the
6163
- // backlog clears.
6164
- const limit = this.prWatchLimit;
6165
- const byRecency = (a, b) => b[1].updatedAt.localeCompare(a[1].updatedAt);
6166
- const openEntries = [...active.entries()]
6167
- .filter(([, candidate]) => !candidate.terminal)
6168
- .sort(byRecency);
6169
- const terminalEntries = [...active.entries()]
6170
- .filter(([, candidate]) => candidate.terminal)
6171
- .sort(byRecency);
6172
- const terminalReserved = terminalEntries.length > 0
6173
- ? Math.min(terminalEntries.length, Math.max(1, Math.ceil(limit * 0.2)))
6174
- : 0;
6175
- const watched = openEntries.slice(0, limit);
6176
- const terminalSlots = Math.max(terminalReserved, limit - watched.length);
6177
- watched.push(...terminalEntries.slice(0, Math.min(terminalEntries.length, terminalSlots)));
6178
- if (watched.length < active.size) {
6179
- // The cap deterministically excludes the oldest bindings every poll.
6180
- // Surface it (dead-letter principle: surfaced, never silently
6181
- // consumed) so an operator knows some bound PRs are not watched this
6182
- // pass.
6183
- const watchedKeys = new Set(watched.map(([key]) => key));
6184
- const excluded = [...active.keys()].filter((key) => !watchedKeys.has(key));
6185
- process.stderr.write(`[Channel:${this.name}] PR watch cap exceeded: watching ${watched.length}/${active.size} bound PRs (open first, most recent; open limit ${limit}); not watched: ${excluded.join(', ')}\n`);
6186
5854
  }
6187
5855
  // One burst budget for the whole pass: after an outage every watched PR
6188
5856
  // can be due at once, and a per-PR cap would claim up to cap × watched-PR
6189
5857
  // durable tasks in a single poll. PRs that find it spent keep their cursor
6190
5858
  // and resume next pass.
5859
+ // Arm the digest on EVERY persisted entry — not just this snapshot's
5860
+ // active keys: a degraded (empty/partial) first poll must still arm the
5861
+ // entries on disk, so a restart before a complete snapshot finds the arm
5862
+ // and digests the backlog instead of flooding per comment. Entries
5863
+ // outside the watch-cap slice keep their arm until watched. The one-shot
5864
+ // clears HERE, once it has armed: the per-entry flags (persisted below)
5865
+ // carry the digest across per-PR errors, cap exclusion, untrusted
5866
+ // snapshots, and restarts. Keeping the global flag alive across aborted
5867
+ // passes would re-arm entries an earlier pass already drained, so a later
5868
+ // single fresh comment would digest under an outage lead that never
5869
+ // happened.
5870
+ if (this.startupDigestPending) {
5871
+ for (const entry of Object.values(this.prWatchState.entries)) {
5872
+ entry.digestPending = true;
5873
+ entry.digestSizeArmed = false;
5874
+ }
5875
+ this.startupDigestPending = false;
5876
+ }
6191
5877
  const commentBudget = { remaining: MAX_WATCH_COMMENTS_PER_PASS };
6192
- for (const [key, candidate] of watched) {
5878
+ for (const [key, candidate] of candidates) {
5879
+ if (candidate.terminal)
5880
+ continue;
6193
5881
  // Yield at the spend site, not only at the poll boundary: one pass can
6194
5882
  // issue several requests per watched PR, so a pass entered just above
6195
5883
  // the reserve would otherwise spend the whole reserve before the
6196
- // notification lane runs. Break (not return) so the baseline observed
6197
- // so far still reaches savePrWatchState below.
5884
+ // notification lane runs. Break (not return) so the cursors observed
5885
+ // so far still reach savePrWatchState below.
6198
5886
  if (this.watchBudgetExhausted()) {
6199
5887
  this.noteWatchBudgetLow();
6200
5888
  break;
6201
5889
  }
6202
5890
  try {
6203
- // The state observation costs a pulls.get per watched PR per poll; skip
6204
- // it when no state event is subscribed so a comment-only channel does
6205
- // not pay for transitions it never emits.
6206
- if (this.prWatchEvents.size > 0) {
6207
- await this.watchOnePr(key, candidate.chatId, candidate.number);
6208
- }
6209
5891
  // Additive comment watch: isolates its own failures so a comment
6210
- // fetch problem never skips the state transitions above.
6211
- await this.watchPrComments(key, candidate.chatId, candidate.number, commentBudget);
5892
+ // fetch problem never skips the next PR.
5893
+ await this.watchPrComments(key, candidate.chatId, candidate.number, commentBudget, this.prWatchState.entries[key]?.digestPending === true);
6212
5894
  }
6213
5895
  catch (err) {
6214
5896
  if (isWatchPassAbortError(err)) {
6215
5897
  // Shared credential/rate-limit failure: abort the rest of the
6216
5898
  // pass instead of issuing one doomed request per watched PR.
6217
- // Later polls retry the full set once the condition clears.
5899
+ // Later polls retry the full set once the condition clears. The
5900
+ // per-entry arms persisted below carry the digest across the abort.
6218
5901
  process.stderr.write(`[Channel:${this.name}] PR watch pass aborted at ${key} (credential/rate limit); the remaining watched PRs skip this poll: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
6219
5902
  break;
6220
5903
  }
@@ -6223,305 +5906,6 @@ export class GithubChannel extends PollingChannelBase {
6223
5906
  }
6224
5907
  this.savePrWatchState();
6225
5908
  }
6226
- async watchOnePr(key, chatId, number) {
6227
- const copy = BOUND_DELIVERY_COPY[this.locale];
6228
- const [owner, repo] = chatId.split('/');
6229
- // Rate-limited watch calls fail fast instead of sleeping out the reset
6230
- // window: the watch pass runs before notification processing, and a
6231
- // blocking cooldown here would pin the whole notification lane (the
6232
- // design promises notifications are unaffected by watch rate limiting).
6233
- const { data: pr } = await this.githubApi(() => this.octokit.rest.pulls.get({
6234
- owner,
6235
- repo,
6236
- pull_number: number,
6237
- }), `pulls.get(watch ${key})`, 3, (err) => !isWatchFailFastError(err));
6238
- const entry = this.prWatchState.entries[key] ?? {};
6239
- const firstObservation = entry.headSha === undefined && entry.prState === undefined;
6240
- const headSha = pr.head?.sha;
6241
- const headChanged = headSha !== undefined &&
6242
- entry.headSha !== undefined &&
6243
- headSha !== entry.headSha;
6244
- const events = [];
6245
- if (headChanged && this.prWatchEvents.has('head_change')) {
6246
- events.push({
6247
- type: 'head_change',
6248
- summary: copy.headChange(entry.headSha, headSha),
6249
- });
6250
- }
6251
- // Check fetches are conditional and gated on the ci_failure subscription
6252
- // (the other three events come from pulls.get fields alone). A
6253
- // steady-state green PR costs one pulls.get per poll. A new head always
6254
- // re-checks; a pending aggregate re-checks on the
6255
- // CI_PENDING_RECHECK_INTERVAL_MS period until it settles; an advanced
6256
- // updated_at re-checks a settled head. updated_at is NOT a reliable
6257
- // re-run signal (GitHub does not bump it on check activity), so settled
6258
- // heads — including 'none' past the grace window — also re-check on the
6259
- // CI_RECHECK_INTERVAL_MS period to catch re-runs that turn red and CI
6260
- // that appears late (manual workflow_dispatch).
6261
- const prUpdatedAt = typeof pr.updated_at === 'string' ? pr.updated_at : undefined;
6262
- let ciResult;
6263
- let ciFetchAttempted = false;
6264
- if (headSha &&
6265
- this.prWatchEvents.has('ci_failure') &&
6266
- (headChanged ||
6267
- ((entry.ci === undefined || entry.ci === 'pending') &&
6268
- (entry.lastCiFetchAt === undefined ||
6269
- Date.now() - entry.lastCiFetchAt >=
6270
- CI_PENDING_RECHECK_INTERVAL_MS)) ||
6271
- (prUpdatedAt !== undefined && prUpdatedAt !== entry.prUpdatedAt) ||
6272
- (entry.ci === 'none' &&
6273
- entry.headObservedAt !== undefined &&
6274
- Date.now() - entry.headObservedAt < CI_NONE_GRACE_MS) ||
6275
- (entry.lastCiFetchAt !== undefined &&
6276
- Date.now() - entry.lastCiFetchAt >= CI_RECHECK_INTERVAL_MS))) {
6277
- ciFetchAttempted = true;
6278
- try {
6279
- ciResult = await this.fetchCiAggregate(owner, repo, headSha);
6280
- }
6281
- catch (err) {
6282
- // CI is a conditional refinement of the pulls.get baseline, not a
6283
- // dependency of it: a persistent Checks-endpoint failure (a classic
6284
- // PAT without Checks permission, an enterprise policy) must not
6285
- // suppress merge_conflict / state_change, whose data already arrived
6286
- // in pulls.get. Leave ciResult undefined so entry.ci is preserved
6287
- // (writing 'none' would re-fire ci_failure when the endpoint heals).
6288
- // The attempt still advances lastCiFetchAt below: without it, a
6289
- // persistent failure would leave the interval conditions true every
6290
- // poll and degrade to one doomed request per PR per poll.
6291
- process.stderr.write(`[Channel:${this.name}] CI fetch failed for ${key}, continuing without CI state this poll: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
6292
- }
6293
- }
6294
- const ci = ciResult?.aggregate;
6295
- const prevCiForThisHead = headChanged ? undefined : entry.ci;
6296
- if (!firstObservation &&
6297
- ci === 'failure' &&
6298
- prevCiForThisHead !== 'failure' &&
6299
- this.prWatchEvents.has('ci_failure')) {
6300
- const failedChecks = ciResult && ciResult.failedChecks.length > 0
6301
- ? copy.failedChecks(ciResult.failedChecks.join(', '), ciResult.namesIncomplete)
6302
- : '';
6303
- events.push({
6304
- type: 'ci_failure',
6305
- // ciResult is assigned only inside the headSha-guarded fetch block,
6306
- // so ci === 'failure' proves headSha is defined.
6307
- summary: `${copy.ciFailure(headSha)}${failedChecks}`,
6308
- });
6309
- }
6310
- // mergeable === null means GitHub is still computing; never overwrite
6311
- // the last known state with it.
6312
- const mergeableState = pr.mergeable !== null && typeof pr.mergeable_state === 'string'
6313
- ? pr.mergeable_state
6314
- : undefined;
6315
- if (!firstObservation &&
6316
- mergeableState === 'dirty' &&
6317
- entry.mergeableState !== 'dirty' &&
6318
- this.prWatchEvents.has('merge_conflict')) {
6319
- events.push({
6320
- type: 'merge_conflict',
6321
- summary: copy.mergeConflict,
6322
- });
6323
- }
6324
- const prState = pr.state;
6325
- if (!firstObservation &&
6326
- prState === 'closed' &&
6327
- entry.prState !== 'closed' &&
6328
- this.prWatchEvents.has('state_change')) {
6329
- events.push({
6330
- type: 'state_change',
6331
- summary: pr.merged ? copy.prMerged : copy.prClosed,
6332
- });
6333
- }
6334
- const next = {
6335
- ...(headSha !== undefined ? { headSha } : {}),
6336
- ...(ci !== undefined
6337
- ? { ci }
6338
- : headChanged
6339
- ? {}
6340
- : entry.ci !== undefined
6341
- ? { ci: entry.ci }
6342
- : {}),
6343
- ...(mergeableState !== undefined
6344
- ? { mergeableState }
6345
- : entry.mergeableState !== undefined
6346
- ? { mergeableState: entry.mergeableState }
6347
- : {}),
6348
- ...(prState !== undefined ? { prState } : {}),
6349
- ...(pr.title !== undefined
6350
- ? { title: pr.title }
6351
- : entry.title !== undefined
6352
- ? { title: entry.title }
6353
- : {}),
6354
- ...(prUpdatedAt !== undefined ? { prUpdatedAt } : {}),
6355
- ...(firstObservation || headChanged
6356
- ? { headObservedAt: Date.now() }
6357
- : entry.headObservedAt !== undefined
6358
- ? { headObservedAt: entry.headObservedAt }
6359
- : {}),
6360
- ...(ciFetchAttempted
6361
- ? { lastCiFetchAt: Date.now() }
6362
- : entry.lastCiFetchAt !== undefined
6363
- ? { lastCiFetchAt: entry.lastCiFetchAt }
6364
- : {}),
6365
- ...(entry.seq !== undefined ? { seq: entry.seq } : {}),
6366
- ...(entry.pending !== undefined ? { pending: entry.pending } : {}),
6367
- ...(entry.fired !== undefined ? { fired: entry.fired } : {}),
6368
- ...(!headChanged && entry.ciFiredSha !== undefined
6369
- ? { ciFiredSha: entry.ciFiredSha }
6370
- : {}),
6371
- // The comment watch cursor is independent of head/CI transitions; carry
6372
- // it through so the state baseline write does not drop it.
6373
- ...(entry.commentBaseline !== undefined
6374
- ? { commentBaseline: entry.commentBaseline }
6375
- : {}),
6376
- ...(entry.commentSince !== undefined
6377
- ? { commentSince: entry.commentSince }
6378
- : {}),
6379
- ...(entry.commentLastFetchAt !== undefined
6380
- ? { commentLastFetchAt: entry.commentLastFetchAt }
6381
- : {}),
6382
- };
6383
- // Bake the PR number and detection time into every watch key. The
6384
- // delivery idempotency key is chatId + messageId only, so without the
6385
- // PR number two PRs of one repo bound to the same session would issue
6386
- // identical first-episode keys and the daemon ring would silently
6387
- // dedupe the second PR's event. The timestamp survives episode-counter
6388
- // resets (prune, corruption recovery): the daemon ring outlives the
6389
- // worker, and a re-issued bare seq key would dedupe into the old
6390
- // admission instead of delivering the new transition. The identity is
6391
- // instance-local by design: two channel configurations watching the
6392
- // same repo each deliver their own watch notifications (at-least-once
6393
- // per subscription) — the ring dedupes retries of ONE delivery, not
6394
- // independent subscriptions. Comment events still dedupe across
6395
- // instances via their stable GitHub ids.
6396
- const detectedAt = Date.now();
6397
- // Overflow retires sliced during this pass; their skip rows are journalled
6398
- // only after the end-of-pass save commits the baseline and queue together.
6399
- const overflowRetires = [];
6400
- for (const event of events) {
6401
- // ci_failure dedupes per head SHA: once per head even when the
6402
- // aggregate flaps back to success and fails again. The other three
6403
- // identify the transition INSTANCE with a monotonic episode counter,
6404
- // so a legitimate recurrence fires again: dirty -> clean -> dirty,
6405
- // close -> reopen -> close, and a force-push revisit of a recent SHA.
6406
- // A state-valued key (the old `open`/`closed`/target-SHA shape) would
6407
- // suppress those forever within the fired ring's window, contradicting
6408
- // the documented edge-triggered semantics.
6409
- let dedupeKey;
6410
- if (event.type === 'ci_failure') {
6411
- dedupeKey = `watch:ci_failure:${number}:${headSha ?? 'unknown'}:${detectedAt}`;
6412
- }
6413
- else {
6414
- next.seq = (next.seq ?? 0) + 1;
6415
- dedupeKey = `watch:${event.type}:${number}:${next.seq}:${detectedAt}`;
6416
- }
6417
- // The fired ring is the durable once-per-transition record: inbound
6418
- // tasks are removed on success, so task-level dedupe alone would let
6419
- // a flapping aggregate re-fire the same head after a restart.
6420
- // ci_failure matches by PR+SHA PREFIX: the nonce suffix makes every
6421
- // detection key unique, but once-per-head must survive head changes
6422
- // (the ciFiredSha pin drops on a head change) and flaps while an
6423
- // earlier episode is still pending.
6424
- const ciPrefix = event.type === 'ci_failure'
6425
- ? `watch:ci_failure:${number}:${headSha ?? 'unknown'}:`
6426
- : undefined;
6427
- const recorded = (key) => ciPrefix !== undefined ? key.startsWith(ciPrefix) : key === dedupeKey;
6428
- if (next.fired?.some(recorded))
6429
- continue;
6430
- // The fired ring is capped: 64 non-ci episodes on a long-lived head
6431
- // can evict the ci_failure key. The ciFiredSha pin keeps ci_failure
6432
- // once-per-head even after that eviction (a flapping aggregate must
6433
- // not re-fire on the same head).
6434
- if (event.type === 'ci_failure' &&
6435
- headSha !== undefined &&
6436
- next.ciFiredSha === headSha) {
6437
- continue;
6438
- }
6439
- if (next.pending?.some((p) => recorded(p.key)))
6440
- continue;
6441
- const envelope = {
6442
- channelName: this.name,
6443
- senderId: 'github',
6444
- senderName: 'GitHub',
6445
- chatId,
6446
- threadId: `pr:${number}`,
6447
- messageId: dedupeKey,
6448
- text: event.summary,
6449
- isGroup: true,
6450
- isMentioned: true,
6451
- isReplyToBot: false,
6452
- metadata: `${this.buildMetadata(chatId, `pr:${number}`, pr.title ?? '')}\nEvent: ${event.type}.`,
6453
- };
6454
- (next.pending ??= []).push({
6455
- key: dedupeKey,
6456
- issueNumber: number,
6457
- envelope,
6458
- delivery: this.resolveBoundDelivery(chatId, number),
6459
- });
6460
- if (next.pending.length > MAX_PENDING_WATCH_PER_ENTRY) {
6461
- const oldest = next.pending[0];
6462
- if (!this.isDeadLettered(oldest.key)) {
6463
- const record = {
6464
- retiredAt: new Date().toISOString(),
6465
- issueNumber: oldest.issueNumber,
6466
- source: {
6467
- chatId,
6468
- threadId: `pr:${number}`,
6469
- messageId: oldest.key,
6470
- },
6471
- delivery: oldest.delivery,
6472
- reason: `watch pending queue overflow (cap ${MAX_PENDING_WATCH_PER_ENTRY}); oldest event retired undelivered`,
6473
- text: oldest.envelope.text,
6474
- };
6475
- try {
6476
- const path = this.channelFilePath('github-bound-deadletter.jsonl');
6477
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
6478
- appendFileSync(path, `${JSON.stringify(record)}\n`, {
6479
- encoding: 'utf-8',
6480
- mode: 0o600,
6481
- });
6482
- this.deadLetteredKeys.add(oldest.key);
6483
- }
6484
- catch (err) {
6485
- // The exhaustion surface cannot be written: keep the event queued
6486
- // (over cap) and retry the overflow on the next detection instead
6487
- // of dropping it. The body has nowhere else to go, so dump it to
6488
- // stderr — sanitized without truncation, like retireBoundTask.
6489
- const payload = JSON.stringify(record);
6490
- 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`);
6491
- }
6492
- }
6493
- if (this.isDeadLettered(oldest.key)) {
6494
- // The dead-letter record is the retire's commit point. Slice in
6495
- // memory ONLY: the end-of-pass save below commits the advanced
6496
- // baseline and the full queue in one write. A mid-pass save here
6497
- // would persist the baseline before this pass's later events are
6498
- // queued, so a crash would never re-derive them. The skip row is
6499
- // journalled after that save, never before; if the save throws, the
6500
- // drain completes the retire next poll (the head is dead-lettered,
6501
- // so it is never delivered).
6502
- next.pending = next.pending.slice(1);
6503
- this.prWatchState.entries[key] = next;
6504
- overflowRetires.push(oldest);
6505
- process.stderr.write(`[Channel:${this.name}] watch pending overflow for ${key}: retired ${oldest.key} to dead-letter (cap ${MAX_PENDING_WATCH_PER_ENTRY})\n`);
6506
- }
6507
- }
6508
- if (event.type === 'ci_failure' && headSha !== undefined) {
6509
- next.ciFiredSha = headSha;
6510
- }
6511
- }
6512
- this.prWatchState.entries[key] = next;
6513
- // Baseline and pending queue commit in one write: a crash from here on
6514
- // either finds the pending event (drained next poll) or the claimed
6515
- // task (recovery), never a consumed transition with nothing to retry.
6516
- this.savePrWatchState();
6517
- // The overflow retires are durable only now. Journal their skip rows after
6518
- // the save: a throwing save leaves no claim for an event still queued on
6519
- // disk, and the drain completes the retire next poll instead.
6520
- for (const retired of overflowRetires) {
6521
- this.recordWatchOverflowSkip(retired);
6522
- }
6523
- await this.drainPendingWatch(key, next);
6524
- }
6525
5909
  /**
6526
5910
  * Bound PR comment watch (docs/design/2026-11-08-bound-pr-comment-watch.md).
6527
5911
  * Poll conversation + inline review comments on a bound PR and deliver each
@@ -6534,13 +5918,21 @@ export class GithubChannel extends PollingChannelBase {
6534
5918
  *
6535
5919
  * Default-on with deliverToBoundSessions; `prCommentWatch: false` disables
6536
5920
  * it. Failures are isolated here so they never skip the state transitions.
5921
+ *
5922
+ * `digestMode` (the persisted per-entry arm set by a detected downtime gap,
5923
+ * or a window larger than the per-comment pass cap) renders AT MOST the
5924
+ * newest members that fit the shared body budget as ONE private summary
5925
+ * prompt; the remainder is named in a front omission notice with its keys
5926
+ * unrecorded and the cursor held before the backlog head, so the next pass
5927
+ * digests the remainder. The event class stays `comment`, so role routing is
5928
+ * identical to individual deliveries.
6537
5929
  */
6538
- async watchPrComments(key, chatId, number, budget) {
6539
- if (!this.deliverToBoundSessions ||
6540
- !this.prCommentWatchEnabled ||
6541
- !this.boundSessions) {
5930
+ async watchPrComments(key, chatId, number, budget, digestMode) {
5931
+ // The poll loop only reaches this pass with bound delivery and comment
5932
+ // watching enabled, and clears any stale digest arm when they are off. The
5933
+ // handle guard narrows the nullable handle for the delivery lookups below.
5934
+ if (!this.boundSessions)
6542
5935
  return;
6543
- }
6544
5936
  const entry = this.prWatchState.entries[key] ?? {};
6545
5937
  const now = Date.now();
6546
5938
  const nowIso = new Date(now).toISOString();
@@ -6552,6 +5944,10 @@ export class GithubChannel extends PollingChannelBase {
6552
5944
  commentBaseline: nowIso,
6553
5945
  commentSince: nowIso,
6554
5946
  commentLastFetchAt: now,
5947
+ digestPending: false,
5948
+ digestSizeArmed: false,
5949
+ digestRendered: [],
5950
+ digestRetiredCount: 0,
6555
5951
  };
6556
5952
  this.savePrWatchState();
6557
5953
  return;
@@ -6563,6 +5959,8 @@ export class GithubChannel extends PollingChannelBase {
6563
5959
  // The burst budget is shared by every watched PR in this pass. A PR that
6564
5960
  // arrives after it is spent fetches nothing and keeps its cursor untouched,
6565
5961
  // so its tail resumes on the next pass instead of being skipped past.
5962
+ // The digest path never decrements it (one task per PR, not per comment),
5963
+ // so a digest pass always finds the budget intact.
6566
5964
  if (budget.remaining <= 0) {
6567
5965
  return;
6568
5966
  }
@@ -6635,7 +6033,13 @@ export class GithubChannel extends PollingChannelBase {
6635
6033
  return;
6636
6034
  }
6637
6035
  const baseline = entry.commentBaseline;
6638
- const alreadyDispatched = (commentKey) => this.cursor.dispatchedComments?.includes(commentKey) === true;
6036
+ // The held digest's rendered frontier backs up the shared dispatchedComments
6037
+ // ring: the ring evicts keys older than the notification cursor, which a
6038
+ // healthy poll advances past a held digest's backlog, so a rendered key can
6039
+ // be evicted mid-drain. The per-entry frontier keeps it deduped regardless.
6040
+ const renderedFrontier = new Set(entry.digestRendered ?? []);
6041
+ const alreadyDispatched = (commentKey) => this.cursor.dispatchedComments?.includes(commentKey) === true ||
6042
+ renderedFrontier.has(commentKey);
6639
6043
  const candidates = [];
6640
6044
  const threadId = `pr:${number}`;
6641
6045
  const metadata = `${this.buildMetadata(chatId, threadId, entry.title ?? '')}\nTrigger: comment.`;
@@ -6649,11 +6053,12 @@ export class GithubChannel extends PollingChannelBase {
6649
6053
  // past the cut. The bound prompt caps the final body at the same value.
6650
6054
  const omitted = total - BOUND_PROMPT_BODY_MAX_CODE_POINTS;
6651
6055
  if (omitted <= 0)
6652
- return { text: display, boundText: display };
6056
+ return { text: display, boundText: display, display };
6653
6057
  const prefix = truncateCodePoints(display, BOUND_PROMPT_BODY_MAX_CODE_POINTS);
6654
6058
  return {
6655
6059
  text: `${prefix}… [${BOUND_DELIVERY_COPY.en.commentTruncated(omitted)}]`,
6656
6060
  boundText: `${prefix}… [${copy.commentTruncated(omitted)}]`,
6061
+ display,
6657
6062
  };
6658
6063
  };
6659
6064
  // The watch closes the SAME-account gap: GitHub sends the channel account no
@@ -6682,6 +6087,9 @@ export class GithubChannel extends PollingChannelBase {
6682
6087
  key: commentKey,
6683
6088
  attrKey: `ic:${comment.id}`,
6684
6089
  createdAt: comment.created_at,
6090
+ author,
6091
+ url,
6092
+ body: rendered.display,
6685
6093
  boundText: this.locale === 'en'
6686
6094
  ? undefined
6687
6095
  : `${copy.newCommentLead(author)}\n${rendered.boundText}\nComment: ${url}`,
@@ -6718,6 +6126,10 @@ export class GithubChannel extends PollingChannelBase {
6718
6126
  key: commentKey,
6719
6127
  attrKey: `rc:${comment.id}`,
6720
6128
  createdAt: comment.created_at,
6129
+ author,
6130
+ url,
6131
+ body: rendered.display,
6132
+ inlineLocation: location,
6721
6133
  boundText: this.locale === 'en'
6722
6134
  ? undefined
6723
6135
  : `${copy.newInlineReviewCommentLead(author)}\n${location}\n${rendered.boundText}\nComment: ${url}`,
@@ -6737,7 +6149,7 @@ export class GithubChannel extends PollingChannelBase {
6737
6149
  });
6738
6150
  }
6739
6151
  candidates.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
6740
- const commitCursor = (newSince) => {
6152
+ const commitCursor = (newSince, clearDigest = false) => {
6741
6153
  // GitHub compares `since` at whole-second granularity while nowIso carries
6742
6154
  // milliseconds: a comment created later in the same second as the fetch
6743
6155
  // snapshot would be excluded from every later fetch. Floor the cursor to
@@ -6748,12 +6160,22 @@ export class GithubChannel extends PollingChannelBase {
6748
6160
  ...(this.prWatchState.entries[key] ?? {}),
6749
6161
  commentSince: floored,
6750
6162
  commentLastFetchAt: now,
6163
+ // The digest arm clears only when this PR's backlog is consumed;
6164
+ // a held cursor (omitted tail, refused dispatch) keeps it armed.
6165
+ ...(clearDigest
6166
+ ? {
6167
+ digestPending: false,
6168
+ digestSizeArmed: false,
6169
+ digestRendered: [],
6170
+ digestRetiredCount: 0,
6171
+ }
6172
+ : {}),
6751
6173
  };
6752
6174
  this.savePrWatchState();
6753
6175
  };
6754
6176
  // No new comments: advance the cursor without any attribution round-trip.
6755
6177
  if (candidates.length === 0) {
6756
- commitCursor(nowIso);
6178
+ commitCursor(nowIso, true);
6757
6179
  return;
6758
6180
  }
6759
6181
  // Look up posted comments only now that there is something to deliver, so a
@@ -6830,9 +6252,231 @@ export class GithubChannel extends PollingChannelBase {
6830
6252
  });
6831
6253
  }
6832
6254
  if (deliverable.length === 0) {
6833
- commitCursor(gateHoldCursor ?? nowIso);
6255
+ // A gate grace hold keeps the backlog (and the digest arm) for the next
6256
+ // pass; a genuine no-target retirement consumes it with a trace.
6257
+ commitCursor(gateHoldCursor ?? nowIso, gateHoldCursor === undefined);
6834
6258
  return;
6835
6259
  }
6260
+ // Digest mode is armed by a downtime gap (per-entry flag) OR by backlog
6261
+ // size: a window larger than the per-comment pass cap would flood one
6262
+ // prompt per comment however it accumulated (a healed endpoint after
6263
+ // sustained per-PR fetch failures keeps the heartbeat fresh, so the gap
6264
+ // alone never arms it).
6265
+ const digesting = digestMode || deliverable.length > MAX_WATCH_COMMENTS_PER_PASS;
6266
+ if (digesting) {
6267
+ // The gap arm reports the outage; the size arm (and its follow-ups,
6268
+ // which re-enter via the persisted arm) fires on a healthy heartbeat and
6269
+ // must not claim the channel was not running.
6270
+ const gapLead = digestMode && this.prWatchState.entries[key]?.digestSizeArmed !== true;
6271
+ // Allocate the shared body ceiling NEWEST-FIRST: the cap keeps the
6272
+ // prefix, so rendering oldest-first would let it eat exactly the
6273
+ // newest, most actionable members. Members that do not fit are named
6274
+ // in the front omission notice, their keys are NOT recorded, and the
6275
+ // cursor holds before the backlog head so the next pass digests the
6276
+ // remainder — nothing is consumed without being delivered.
6277
+ const newest = deliverable.slice(-MAX_AGGREGATE_COMMENTS);
6278
+ const memberLine = (candidate, language) => {
6279
+ const digestCopy = BOUND_DELIVERY_COPY[language];
6280
+ const total = Array.from(candidate.body).length;
6281
+ const excerpt = total > MAX_AGGREGATE_COMMENT_CHARS
6282
+ ? `${truncateCodePoints(candidate.body, MAX_AGGREGATE_COMMENT_CHARS)}… [${digestCopy.commentTruncated(total - MAX_AGGREGATE_COMMENT_CHARS)}]`
6283
+ : candidate.body;
6284
+ const lead = candidate.inlineLocation !== undefined
6285
+ ? `${digestCopy.newInlineReviewCommentLead(candidate.author)}\n${candidate.inlineLocation}`
6286
+ : digestCopy.newCommentLead(candidate.author);
6287
+ return `${lead}\n${excerpt}\nComment: ${candidate.url}`;
6288
+ };
6289
+ const cp = (text) => Array.from(text).length;
6290
+ const renderFor = (language, members) => {
6291
+ const digestCopy = BOUND_DELIVERY_COPY[language];
6292
+ const omitted = deliverable.length - members.length;
6293
+ const leadText = gapLead
6294
+ ? digestCopy.offlineCommentsLead(deliverable.length)
6295
+ : digestCopy.commentBacklogLead(deliverable.length);
6296
+ // The omission notice rides at the FRONT: a tail notice would be
6297
+ // the first thing the shared body cap truncates away.
6298
+ return (leadText +
6299
+ (omitted > 0
6300
+ ? `\n[${digestCopy.offlineOmittedNotice(omitted)}]`
6301
+ : '') +
6302
+ `\n${members.map((candidate) => memberLine(candidate, language)).join('\n')}`);
6303
+ };
6304
+ const leadCp = cp(gapLead
6305
+ ? BOUND_DELIVERY_COPY[this.locale].offlineCommentsLead(deliverable.length)
6306
+ : BOUND_DELIVERY_COPY[this.locale].commentBacklogLead(deliverable.length));
6307
+ const rendered = [];
6308
+ let used = leadCp + 1;
6309
+ for (let i = newest.length - 1; i >= 0; i -= 1) {
6310
+ const candidate = newest[i];
6311
+ const lineCp = cp(memberLine(candidate, this.locale));
6312
+ // Notice sized for the count IF this member is accepted; the final
6313
+ // notice is no larger, so a fit here stays a fit at the end.
6314
+ const noticeCp = deliverable.length - (rendered.length + 1) > 0
6315
+ ? cp(`\n[${BOUND_DELIVERY_COPY[this.locale].offlineOmittedNotice(deliverable.length - (rendered.length + 1))}]`)
6316
+ : 0;
6317
+ if (used + lineCp + 1 + noticeCp > BOUND_PROMPT_BODY_MAX_CODE_POINTS) {
6318
+ break;
6319
+ }
6320
+ rendered.unshift(candidate);
6321
+ used += lineCp + 1;
6322
+ }
6323
+ if (rendered.length > 0) {
6324
+ // Authorship exclusion is computed over the RENDERED slice (the
6325
+ // body the session actually sees) and over the SAME follower
6326
+ // population as the per-comment path, so the delivery-time Gone
6327
+ // fallback cannot hand the digest back to a session that authored
6328
+ // every rendered member. A follower is excluded only if it authored
6329
+ // EVERY rendered member; a partial author still receives the digest
6330
+ // (the mutual-authorship case must not consume with zero prompts).
6331
+ // An all-targets exclusion is unreachable: every deliverable member
6332
+ // has some target that did not author it.
6333
+ const exclude = new Set();
6334
+ for (const sessionId of followerIds) {
6335
+ if (rendered.every((candidate) => excludeFor(candidate).has(sessionId))) {
6336
+ exclude.add(sessionId);
6337
+ }
6338
+ }
6339
+ const omitted = deliverable.length - rendered.length;
6340
+ // Content-hash identity over the RENDERED members (the aggregate
6341
+ // lane's superset semantics): a crash before the cursor save
6342
+ // re-lists the window, the member dedupe filters consumed comments,
6343
+ // and a grown window dispatches only the new remainder.
6344
+ const digestId = `comment-digest:${number}:${createHash('sha256')
6345
+ .update(rendered
6346
+ .map((candidate) => candidate.key)
6347
+ .sort()
6348
+ .join('\n'))
6349
+ .digest('hex')
6350
+ .slice(0, 40)}`;
6351
+ // The digest carries the CHANNEL ACCOUNT's identity, exactly like
6352
+ // the per-comment envelopes on this same-account lane: a synthetic
6353
+ // sender would fail the group sender allowlist preflight (the
6354
+ // waiver matches the channel login), retiring the digest while the
6355
+ // cursor advanced past the whole backlog.
6356
+ const envelope = {
6357
+ channelName: this.name,
6358
+ senderId: this.botUsername?.toLowerCase() ?? 'github',
6359
+ senderName: this.botUsername ?? 'GitHub',
6360
+ chatId,
6361
+ threadId,
6362
+ messageId: digestId,
6363
+ text: renderFor('en', rendered),
6364
+ isGroup: true,
6365
+ isMentioned: true,
6366
+ isReplyToBot: false,
6367
+ metadata,
6368
+ };
6369
+ const settled = await this.dispatchEnvelope(envelope, number, { dispatchedComments: rendered.map((candidate) => candidate.key) }, true, exclude, this.locale === 'en' ? undefined : renderFor(this.locale, rendered));
6370
+ // A retired verdict (e.g. preflight rejection) consumes the task
6371
+ // and returns settled WITHOUT recording a delivery: treat it as
6372
+ // unconsumed so the cursor never advances past members that were
6373
+ // never delivered. The durable delivery ring is the evidence. An
6374
+ // unreadable ring is unknown, not positive evidence — but once a
6375
+ // successful write latches the repair, the digest may prove its OWN
6376
+ // acceptance from the freshly written key. The unreadable verdict
6377
+ // itself is never cleared: the suppression callers keep failing
6378
+ // closed for the keys lost with the file (gate the repair here only).
6379
+ const delivered = settled &&
6380
+ (this.boundDeliveredUnreadable
6381
+ ? this.boundDeliveredRepaired &&
6382
+ this.boundDeliveredKeys.has(this.boundEventKey(envelope))
6383
+ : this.boundEventAlreadyDelivered(envelope));
6384
+ if (!delivered) {
6385
+ const heldEntry = this.prWatchState.entries[key];
6386
+ if (settled) {
6387
+ // Permanent retirement: preflight rejected the digest (settled
6388
+ // with no delivery). Bound the retry — the route/sender gate may
6389
+ // be fixed, but a permanently-rejected digest must not hold the
6390
+ // cursor and spend the pass-wide watch budget every poll for the
6391
+ // process lifetime with zero prompts. A transient deferral
6392
+ // (settled === false) keeps the fail-closed hold below instead.
6393
+ const retiredCount = (heldEntry?.digestRetiredCount ?? 0) + 1;
6394
+ if (heldEntry)
6395
+ heldEntry.digestRetiredCount = retiredCount;
6396
+ if (retiredCount >= MAX_DIGEST_RETIREMENT_RETRIES) {
6397
+ // Consume the WHOLE deliverable window with a visible trace
6398
+ // rather than retry the identical rejected attempt forever: the
6399
+ // cursor advances past every deliverable member (the rendered
6400
+ // keys stay recorded; the omitted tail is consumed by the cursor
6401
+ // advance), so none of them re-list.
6402
+ this.recordChannelEvent({
6403
+ type: 'inbound',
6404
+ outcome: 'skipped',
6405
+ reason: 'comment_digest_retired',
6406
+ repository: chatId,
6407
+ thread: threadId,
6408
+ number,
6409
+ messageId: digestId,
6410
+ detail: {
6411
+ consumedComments: deliverable.length,
6412
+ retirements: retiredCount,
6413
+ },
6414
+ });
6415
+ process.stderr.write(`[Channel:${this.name}] comment digest for ${key} retired at preflight ${retiredCount} times; consuming ${deliverable.length} comment(s) with a trace instead of retrying\n`);
6416
+ commitCursor(nowIso, true);
6417
+ return;
6418
+ }
6419
+ }
6420
+ else if (heldEntry) {
6421
+ // Transient deferral, not a permanent retirement: reset the streak.
6422
+ heldEntry.digestRetiredCount = 0;
6423
+ }
6424
+ // Undo the claim-time member recording: otherwise the next pass
6425
+ // filters every member as already dispatched, the empty candidate
6426
+ // set advances the cursor past the whole backlog, and the retired
6427
+ // digest is consumed with zero prompts one poll later. The removed
6428
+ // keys re-list next pass; the arm and commentSince are kept.
6429
+ const claimed = new Set(rendered.map((candidate) => candidate.key));
6430
+ this.cursor.dispatchedComments = (this.cursor.dispatchedComments ?? []).filter((key) => !claimed.has(key));
6431
+ const times = this.cursor.dispatchedCommentTimes;
6432
+ if (times) {
6433
+ for (const key of claimed)
6434
+ delete times[key];
6435
+ }
6436
+ commitCursor(since);
6437
+ return;
6438
+ }
6439
+ if (omitted === 0) {
6440
+ commitCursor(nowIso, true);
6441
+ }
6442
+ else {
6443
+ // Hold before the backlog head and KEEP the arm: the omitted
6444
+ // prefix re-lists next pass and digests again (the notice promised
6445
+ // further digests); the rendered suffix is deduped. Arm regardless
6446
+ // of how the digest was entered — the size arm has no gap-arming
6447
+ // loop, so the omitted tail must persist its own arm or it would
6448
+ // drain one prompt per comment. Remember a size-triggered origin so
6449
+ // the follow-up keeps the neutral lead (no outage was detected).
6450
+ const armedEntry = this.prWatchState.entries[key];
6451
+ if (armedEntry) {
6452
+ armedEntry.digestPending = true;
6453
+ if (!digestMode)
6454
+ armedEntry.digestSizeArmed = true;
6455
+ // A delivered digest breaks any permanent-retirement streak.
6456
+ armedEntry.digestRetiredCount = 0;
6457
+ // Persist the rendered frontier so the shared ring's eviction
6458
+ // (keyed to the notification cursor, which a healthy poll advances
6459
+ // past this held backlog) cannot re-list and re-deliver a rendered
6460
+ // member, nor over-count the follow-up digest's "new comment(s)".
6461
+ armedEntry.digestRendered = [
6462
+ ...new Set([
6463
+ ...(armedEntry.digestRendered ?? []),
6464
+ ...rendered.map((candidate) => candidate.key),
6465
+ ]),
6466
+ ];
6467
+ }
6468
+ // Clamp the hold anchor at `since`: the fetch filters on updated_at,
6469
+ // so an old comment edited today re-lists and sorts to deliverable[0]
6470
+ // even though it was created before commentSince. Anchoring at its
6471
+ // creation time would drag the cursor backwards and re-fetch (then
6472
+ // re-deliver, once the ring evicts their keys) the whole window.
6473
+ commitCursor(new Date(Math.max(Date.parse(deliverable[0].createdAt), Date.parse(since)) - 1000).toISOString());
6474
+ }
6475
+ return;
6476
+ }
6477
+ // Not even one member fits (a pathologically long URL): fall through
6478
+ // to the per-comment path rather than consume anything.
6479
+ }
6836
6480
  // Cap the burst against the pass-wide budget shared by all watched PRs;
6837
6481
  // the cursor resumes before the last processed comment when capped so the
6838
6482
  // tail drains over subsequent passes.
@@ -6855,414 +6499,26 @@ export class GithubChannel extends PollingChannelBase {
6855
6499
  // independent one). Keep commentSince so the next pass re-fetches and
6856
6500
  // retries; dispatchedComments dedupes anything already claimed. Advancing
6857
6501
  // here would skip the comment past with no task and no re-delivery chance.
6502
+ // The cursor stays held, so keep the arm AND the rendered frontier too —
6503
+ // clearing the frontier would re-deliver ring-evicted rendered members.
6858
6504
  commitCursor(since);
6859
6505
  }
6860
6506
  else {
6861
6507
  // Resume just before the last processed comment when capped so the
6862
6508
  // unprocessed tail is re-fetched next pass (a second of overlap is
6863
6509
  // deduped, never lost). A gate-held comment never reaches here: a hold
6864
- // implies an empty deliverable, which returned above.
6510
+ // implies an empty deliverable, which returned above. A digest that
6511
+ // fell through to this path (no member fit the body budget) consumes
6512
+ // its arm: the backlog delivers individually from here on.
6865
6513
  const last = batch[batch.length - 1];
6866
6514
  commitCursor(capped
6867
6515
  ? new Date(Date.parse(last.createdAt) - 1000).toISOString()
6868
- : nowIso);
6869
- }
6870
- }
6871
- /**
6872
- * Deliver queued watch events. Order per event: claim the inbound task
6873
- * (durable), move the key from pending to fired (durable), then run the
6874
- * task. A crash at any point leaves either a pending event or a claimed
6875
- * task for the next poll / recovery, and the fired ring prevents a second
6876
- * delivery of the same transition.
6877
- */
6878
- async drainPendingWatch(key, entry) {
6879
- if (this.boundRoleAware) {
6880
- return this.drainPendingWatchRoleAware(key, entry);
6881
- }
6882
- // Per-PR ordering across passes: an earlier watch transition that is
6883
- // still unsettled (a failed/backpressure/running task from a previous
6884
- // attempt) must settle via recovery BEFORE any later pending event
6885
- // drains — the watch pass re-drains after reconcile, and the next
6886
- // poll's reconcile runs before recovery, so a per-pass break alone
6887
- // would still let the later event arrive first. Skip the whole entry
6888
- // until recovery settles the predecessor; nothing is lost (pending
6889
- // and fired are persisted). A task whose key EQUALS the pending head
6890
- // is that same event's own claim (the crash window between claim and
6891
- // fire-save), not a predecessor — draining reuses it, so let it pass.
6892
- const headKey = entry.pending?.[0]?.key;
6893
- const unsettledPredecessor = this.readInboundTasks().some((task) => this.isRecoverableInboundTask(task) &&
6894
- task.envelope?.messageId?.startsWith('watch:') === true &&
6895
- task.source.messageId !== headKey &&
6896
- this.prBindingKey(task.source.chatId, task.issueNumber) === key);
6897
- if (unsettledPredecessor)
6898
- return;
6899
- while (entry.pending && entry.pending.length > 0) {
6900
- const pending = entry.pending[0];
6901
- if (this.isDeadLettered(pending.key)) {
6902
- // This head already carries a durable "retired undelivered" record
6903
- // (an overflow whose end-of-pass save failed, or a crash before it).
6904
- // Complete the retire instead of delivering: a delivered event must
6905
- // never also stand in the dead-letter file as retired undelivered.
6906
- const pendingBefore = entry.pending;
6907
- entry.pending = entry.pending.slice(1);
6908
- this.prWatchState.entries[key] = entry;
6909
- try {
6910
- this.savePrWatchState();
6911
- }
6912
- catch (err) {
6913
- entry.pending = pendingBefore;
6914
- this.prWatchState.entries[key] = entry;
6915
- throw err;
6916
- }
6917
- this.recordWatchOverflowSkip(pending);
6918
- continue;
6919
- }
6920
- // Re-validate the frozen recipient against the latest COMPLETE
6921
- // snapshot: a live rebind must not misdeliver to the old session. On
6922
- // a partial/failed scan the persisted target stands (fail-closed).
6923
- // With no candidate left on a complete snapshot the watch event is
6924
- // private-only: retire it with a log rather than queue a delivery
6925
- // that would retire publicly anyway.
6926
- let delivery = pending.delivery;
6927
- if (this.boundSnapshotTrusted &&
6928
- !this.lastBindingsPartial &&
6929
- !this.boundRefreshFailed) {
6930
- const current = this.resolveBoundDelivery(pending.envelope.chatId, pending.issueNumber);
6931
- if (current) {
6932
- delivery = current;
6933
- this.gateGraceClear(pending.key);
6934
- }
6935
- else {
6936
- // One grace cycle when the gate is the cause: a watch installed
6937
- // after the snapshot was fetched surfaces on the next refresh, and
6938
- // the transition it was installed to catch must not retire first.
6939
- // The grace is scoped to the snapshot generation, so a second drain
6940
- // of the same PR in the same poll does not spend it.
6941
- if (this.gateExcludedAllFollowers(pending.envelope.chatId, pending.issueNumber) &&
6942
- this.gateGraceShouldHold(pending.key)) {
6943
- return;
6944
- }
6945
- this.gateGraceClear(pending.key);
6946
- process.stderr.write(`[Channel:${this.name}] watch event ${pending.key} has no bound candidate left; retiring without public fallback\n`);
6947
- const pendingBefore = entry.pending;
6948
- entry.pending = entry.pending.slice(1);
6949
- this.prWatchState.entries[key] = entry;
6950
- try {
6951
- this.savePrWatchState();
6952
- }
6953
- catch (err) {
6954
- // The slice already mutated the loaded state, and a failed save
6955
- // does not clear prWatchStateLoaded — without this rollback the
6956
- // next poll skips the entry and the end-of-pass save persists the
6957
- // truncation, losing the event with no trace at all. Mirrors the
6958
- // claim path's rollback below.
6959
- entry.pending = pendingBefore;
6960
- this.prWatchState.entries[key] = entry;
6961
- throw err;
6962
- }
6963
- // Retired before any task was claimed, so there is no task row to
6964
- // close: the skip is the event's only journal trace. After the
6965
- // durable save — the rollback above keeps the event queued when the
6966
- // save throws, and the journal must not claim a retire that did not
6967
- // happen.
6968
- const lostTarget = pending.delivery?.kind === 'bound-session'
6969
- ? pending.delivery.sessionId
6970
- : undefined;
6971
- const lostWorkspace = lostTarget
6972
- ? this.sessionWorkspaceFor(lostTarget)
6973
- : undefined;
6974
- this.recordChannelEvent({
6975
- type: 'inbound',
6976
- outcome: 'skipped',
6977
- reason: 'watch_no_candidate',
6978
- repository: pending.envelope.chatId,
6979
- thread: pending.envelope.threadId,
6980
- number: pending.issueNumber,
6981
- messageId: pending.key,
6982
- // The frozen target is in hand; this retire writes no dead-letter
6983
- // record (only the overflow retire does), so the skip row is the
6984
- // event's only trace — without the target it cannot say whether
6985
- // the retired event ever belonged to a session.
6986
- ...(lostTarget ? { sessionId: lostTarget } : {}),
6987
- ...(lostWorkspace ? { sessionWorkspaceCwd: lostWorkspace } : {}),
6988
- });
6989
- continue;
6990
- }
6991
- }
6992
- // A partial/failed scan keeps the frozen target — which may be absent
6993
- // because the gate filtered the map at detection time. Give that state
6994
- // the same one grace cycle before claiming a task that would retire
6995
- // targetless at run time.
6996
- if (delivery === undefined &&
6997
- this.gateExcludedAllFollowers(pending.envelope.chatId, pending.issueNumber) &&
6998
- this.gateGraceShouldHold(pending.key)) {
6999
- return;
7000
- }
7001
- let task;
7002
- try {
7003
- task = this.claimInboundTask(pending.envelope, pending.issueNumber, {}, delivery);
7004
- }
7005
- catch (err) {
7006
- // Claim persistence failed: keep the event queued and retry on the
7007
- // next poll instead of consuming the transition. Propagate so the
7008
- // reconcile pass fails and sets watchReconcileBlocked: a swallowed
7009
- // failure would let recovery deliver an accepted watch task whose
7010
- // pending record is still unreconciled on disk.
7011
- process.stderr.write(`[Channel:${this.name}] failed to claim watch event ${pending.key}, will retry: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
7012
- throw err;
7013
- }
7014
- const firedBefore = entry.fired;
7015
- const pendingBefore = entry.pending;
7016
- entry.fired = [...(entry.fired ?? []), pending.key].slice(-MAX_FIRED_KEYS);
7017
- entry.pending = entry.pending.slice(1);
7018
- this.prWatchState.entries[key] = entry;
7019
- try {
7020
- this.savePrWatchState();
7021
- }
7022
- catch (err) {
7023
- // The claim is durable but the pending->fired save failed (watch
7024
- // file unwritable while the task file is writable). Roll the claim
7025
- // back so the event stays queued: otherwise same-poll recovery would
7026
- // deliver and remove the task while the on-disk pending survives,
7027
- // and a restart would re-claim and deliver the same transition twice.
7028
- entry.fired = firedBefore;
7029
- entry.pending = pendingBefore;
7030
- this.prWatchState.entries[key] = entry;
7031
- this.removeInboundTask(task.id);
7032
- process.stderr.write(`[Channel:${this.name}] failed to persist watch fire for ${pending.key}, rolled back claim, will retry: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
7033
- return;
7034
- }
7035
- const delivered = await this.runInboundTask(task);
7036
- if (!delivered) {
7037
- // Preserve per-PR ordering: a failed/deferred event retries via
7038
- // recovery next poll; delivering later pendings now would arrive
7039
- // out of order. Pending and fired are already persisted, so
7040
- // stopping here loses nothing.
7041
- return;
7042
- }
7043
- }
7044
- }
7045
- /**
7046
- * Role-aware watch drain: one durable task per (event, matched role
7047
- * winner). The event leaves `pending` for `fired` only after EVERY
7048
- * matched target is claimed, so a crash mid-fan-out re-claims exactly the
7049
- * missing targets (claimInboundTask reuses an existing (event, target)
7050
- * task). Ordering is per (PR, target): a target with an unsettled
7051
- * predecessor waits while the event's other targets drain — one stuck
7052
- * role never head-of-line-blocks another.
7053
- */
7054
- async drainPendingWatchRoleAware(key, entry) {
7055
- while (entry.pending && entry.pending.length > 0) {
7056
- const pending = entry.pending[0];
7057
- if (this.isDeadLettered(pending.key)) {
7058
- // A dead-lettered head is committed to retire; complete it rather than
7059
- // deliver, so no event is both delivered and filed as retired
7060
- // undelivered. Mirrors the legacy drain's guard.
7061
- const pendingBefore = entry.pending;
7062
- entry.pending = entry.pending.slice(1);
7063
- this.prWatchState.entries[key] = entry;
7064
- try {
7065
- this.savePrWatchState();
7066
- }
7067
- catch (err) {
7068
- entry.pending = pendingBefore;
7069
- this.prWatchState.entries[key] = entry;
7070
- throw err;
7071
- }
7072
- this.recordWatchOverflowSkip(pending);
7073
- continue;
7074
- }
7075
- const { targets } = this.resolveBoundTargets(pending.envelope.chatId, pending.issueNumber, this.boundEventClass(pending.envelope));
7076
- if (targets.length === 0) {
7077
- // An incomplete enumeration is not an absence: defer instead of
7078
- // retiring while the snapshot cannot prove no role matches.
7079
- if (!this.boundSnapshotTrusted ||
7080
- this.lastBindingsPartial ||
7081
- this.boundRefreshFailed) {
7082
- return;
7083
- }
7084
- // One grace cycle when the gate is the cause: a watch installed
7085
- // after the snapshot was fetched surfaces on the next refresh. The
7086
- // grace is scoped to the snapshot generation (a second drain of the
7087
- // same PR in the same poll must not spend it).
7088
- if (this.gateExcludedAllFollowers(pending.envelope.chatId, pending.issueNumber) &&
7089
- this.gateGraceShouldHold(pending.key)) {
7090
- return;
7091
- }
7092
- this.gateGraceClear(pending.key);
7093
- process.stderr.write(`[Channel:${this.name}] watch event ${pending.key} has no matching role target; retiring without public fallback\n`);
7094
- entry.pending = entry.pending.slice(1);
7095
- this.prWatchState.entries[key] = entry;
7096
- this.savePrWatchState();
7097
- continue;
7098
- }
7099
- this.gateGraceClear(pending.key);
7100
- const tasksBefore = this.readInboundTasks();
7101
- const knownIds = new Set(tasksBefore.map((task) => task.id));
7102
- const claimable = targets.filter((target) => !tasksBefore.some((task) => this.isRecoverableInboundTask(task) &&
7103
- task.envelope?.messageId?.startsWith('watch:') === true &&
7104
- task.source.messageId !== pending.key &&
7105
- task.delivery?.sessionId === target.sessionId &&
7106
- this.prBindingKey(task.source.chatId, task.issueNumber) === key));
7107
- if (claimable.length === 0)
7108
- return;
7109
- const claimed = [];
7110
- const newlyClaimed = [];
7111
- try {
7112
- for (const target of claimable) {
7113
- const task = this.claimInboundTask(pending.envelope, pending.issueNumber, {}, {
7114
- kind: 'bound-session',
7115
- sessionId: target.sessionId,
7116
- ...(target.role ? { role: target.role } : {}),
7117
- });
7118
- claimed.push(task);
7119
- if (!knownIds.has(task.id))
7120
- newlyClaimed.push(task.id);
7121
- }
7122
- }
7123
- catch (err) {
7124
- // Claim persistence failed: keep the event queued and surface the
7125
- // failure so reconcile blocks recovery (same contract as legacy).
7126
- process.stderr.write(`[Channel:${this.name}] failed to claim watch event ${pending.key}, will retry: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
7127
- throw err;
7128
- }
7129
- if (claimable.length === targets.length) {
7130
- const firedBefore = entry.fired;
7131
- const pendingBefore = entry.pending;
7132
- entry.fired = [...(entry.fired ?? []), pending.key].slice(-MAX_FIRED_KEYS);
7133
- entry.pending = entry.pending.slice(1);
7134
- this.prWatchState.entries[key] = entry;
7135
- try {
7136
- this.savePrWatchState();
7137
- }
7138
- catch (err) {
7139
- // Roll back every NEW claim of this event so the pending record
7140
- // and the task store cannot diverge across a restart; reused
7141
- // tasks predate this pass and stay.
7142
- entry.fired = firedBefore;
7143
- entry.pending = pendingBefore;
7144
- this.prWatchState.entries[key] = entry;
7145
- for (const id of newlyClaimed)
7146
- this.removeInboundTask(id);
7147
- process.stderr.write(`[Channel:${this.name}] failed to persist watch fire for ${pending.key}, rolled back claims, will retry: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
7148
- return;
7149
- }
7150
- }
7151
- for (const task of claimed) {
7152
- const delivered = await this.runInboundTask(task);
7153
- if (!delivered)
7154
- return;
7155
- }
7156
- if (claimable.length !== targets.length) {
7157
- // Blocked targets keep the event pending; their predecessors
7158
- // settle via recovery, and the next drain re-claims only them
7159
- // (delivered siblings dedupe at admission if re-listed).
7160
- return;
7161
- }
7162
- }
7163
- }
7164
- async fetchCiAggregate(owner, repo, sha) {
7165
- // The observation is accumulated per ATTEMPT, inside the retried
7166
- // closure: githubApi retries the whole pagination, and state carried
7167
- // over from an attempt that died on a later page would let its partial
7168
- // pending/success readings decide the retry's aggregate.
7169
- const checks = await this.githubApi(async () => {
7170
- let sawFailure = false;
7171
- let sawPending = false;
7172
- let sawSuccess = false;
7173
- let namesIncomplete = false;
7174
- const failedChecks = [];
7175
- await this.octokit.paginate(this.octokit.rest.checks.listForRef, {
7176
- owner,
7177
- repo,
7178
- ref: sha,
7179
- per_page: 100,
7180
- }, (response, done) => {
7181
- // Octokit's conclusion union omits 'startup_failure', which the
7182
- // API does return and this aggregate must count as a failure.
7183
- const runs = response.data;
7184
- for (const run of runs) {
7185
- if (run.status !== 'completed') {
7186
- sawPending = true;
7187
- continue;
7188
- }
7189
- if (run.conclusion === 'failure' ||
7190
- run.conclusion === 'timed_out' ||
7191
- run.conclusion === 'action_required' ||
7192
- // A workflow that fails at startup (e.g. a broken workflow
7193
- // file) never runs a single job; missing it would certify a
7194
- // broken CI as 'none' or even 'success'. A deliberate SUBSET
7195
- // of core's FAILING_CHECK_RUN_CONCLUSIONS: core also counts
7196
- // cancelled/stale, which the design excludes as
7197
- // concurrency-cancel noise (a superseded run's cancellation
7198
- // is not a CI failure of this head).
7199
- run.conclusion === 'startup_failure') {
7200
- sawFailure = true;
7201
- if (typeof run.name === 'string' &&
7202
- run.name.length > 0 &&
7203
- failedChecks.length < MAX_REPORTED_FAILED_CHECKS) {
7204
- failedChecks.push(run.name);
7205
- }
7206
- }
7207
- else if (run.conclusion === 'success') {
7208
- sawSuccess = true;
7209
- }
7210
- }
7211
- // A failure decides the aggregate: no later page can overturn
7212
- // it, so stop paging instead of spending one request per page
7213
- // of a head that carries hundreds of check runs. Whole pages are
7214
- // still read, so a head whose failures all fit in the pages read
7215
- // reports the same names as before.
7216
- if (sawFailure) {
7217
- // Only unread pages make the list partial: stopping on the
7218
- // LAST page read everything. The iterator follows this same
7219
- // header, so its presence is exactly "a page went unread".
7220
- namesIncomplete = /<[^<>]+>;\s*rel="next"/.test(response.headers?.link ?? '');
7221
- done();
7222
- }
7223
- return [];
7224
- });
7225
- return {
7226
- sawFailure,
7227
- sawPending,
7228
- sawSuccess,
7229
- failedChecks,
7230
- namesIncomplete,
7231
- };
7232
- }, `checks.listForRef(${sha})`, 3, (err) => !isWatchFailFastError(err));
7233
- let { sawFailure, sawPending, sawSuccess } = checks;
7234
- const { failedChecks, namesIncomplete } = checks;
7235
- // A check run already failed, so the combined status could only confirm
7236
- // 'failure' — skip the request rather than pay for a decided aggregate.
7237
- if (!sawFailure) {
7238
- const { data: combined } = await this.githubApi(() => this.octokit.rest.repos.getCombinedStatusForRef({
7239
- owner,
7240
- repo,
7241
- ref: sha,
7242
- }), `combinedStatus(${sha})`, 3, (err) => !isWatchFailFastError(err));
7243
- // GitHub returns {state:"pending", total_count:0, statuses:[]} for a
7244
- // SHA with no legacy commit statuses; an empty combined status must not
7245
- // count as active CI (it would keep every poll re-fetching forever).
7246
- if (combined.total_count > 0) {
7247
- if (combined.state === 'failure' || combined.state === 'error') {
7248
- sawFailure = true;
7249
- }
7250
- else if (combined.state === 'pending') {
7251
- sawPending = true;
7252
- }
7253
- else {
7254
- sawSuccess = true;
7255
- }
7256
- }
6516
+ : nowIso,
6517
+ // A capped cursor resumes before the last processed comment (still
6518
+ // held), so it must keep the rendered frontier; only an uncapped
6519
+ // advance to nowIso has consumed the backlog and may clear it.
6520
+ digesting && !capped);
7257
6521
  }
7258
- const aggregate = sawFailure
7259
- ? 'failure'
7260
- : sawPending
7261
- ? 'pending'
7262
- : sawSuccess
7263
- ? 'success'
7264
- : 'none';
7265
- return { aggregate, failedChecks, namesIncomplete };
7266
6522
  }
7267
6523
  async markNotificationsAsRead(lastReadAt) {
7268
6524
  await this.githubApi(() => this.octokit.rest.activity.markNotificationsAsRead({