@qwen-code/channel-github 0.27.0 → 0.27.2-preview.0

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.
@@ -5,7 +5,7 @@ import { dirname, join } from 'node:path';
5
5
  import process from 'node:process';
6
6
  import { Octokit } from '@octokit/rest';
7
7
  import { HttpsProxyAgent } from 'https-proxy-agent';
8
- import { boundActionTemplateEntries, BoundSessionGoneError, BoundSessionQueueFullError, BoundSessionUnavailableError, buildBoundEventPrompt, getGlobalQwenDir, getWorkspaceScopeDirName, lowercaseGroupAllowedUsers, PollingChannelBase, PR_BINDING_ROLES, renderBoundActionTemplate, resolveBoundActionTemplate, sanitizeDisplayText, sanitizeLogText, truncateCodePoints, validateBoundActionEntries, } from '@qwen-code/channel-base';
8
+ import { boundActionTemplateEntries, BOUND_PROMPT_BODY_MAX_CODE_POINTS, BoundSessionGoneError, BoundSessionQueueFullError, BoundSessionUnavailableError, buildBoundEventPrompt, DEFAULT_BOUND_ROLE_GUIDANCE, getGlobalQwenDir, getWorkspaceScopeDirName, lowercaseGroupAllowedUsers, MAX_POLL_INTERVAL_MS, PollingChannelBase, PR_BINDING_ROLES, renderBoundActionTemplate, resolveBoundActionTemplate, sanitizeDisplayText, sanitizeLogText, truncateCodePoints, validateBoundActionEntries, } from '@qwen-code/channel-base';
9
9
  import { testBotMention, stripBotMention } from './mention.js';
10
10
  import { resolveGithubWebOrigin } from './web-origin.js';
11
11
  const GH_AUTH_TIMEOUT_MS = 10_000;
@@ -106,6 +106,20 @@ const KNOWN_NOTIFICATION_REASONS = new Set([
106
106
  'security_advisory_credit',
107
107
  ]);
108
108
  const MAX_DISPATCHED = 500;
109
+ /** Bounds each list of GithubCursor.boundaryComments (one second's worth). */
110
+ const MAX_BOUNDARY_COMMENTS = 500;
111
+ function noteLatestSecond(latest, at, key) {
112
+ if (!latest || at > latest.at) {
113
+ return { at, keys: new Set([key]), overflow: false };
114
+ }
115
+ if (at === latest.at && !latest.keys.has(key)) {
116
+ if (latest.keys.size < MAX_BOUNDARY_COMMENTS)
117
+ latest.keys.add(key);
118
+ else
119
+ latest.overflow = true;
120
+ }
121
+ return latest;
122
+ }
109
123
  /**
110
124
  * Ceiling on the dispatchedCommentTimes map. The ring itself has no hard
111
125
  * cap: window-aware eviction never drops a protected (re-listable) key, so
@@ -132,6 +146,17 @@ const MAX_AGGREGATE_COMMENT_CHARS = 400;
132
146
  * prompt end; the cap only bounds orphans (a batch whose end never runs).
133
147
  */
134
148
  const MAX_ACK_ANCHORS = 1024;
149
+ /**
150
+ * Whether a comment is past the window's lower bound: created after the
151
+ * cursor's second, or in it when the window that ended there did not read it.
152
+ */
153
+ function startsInWindow(ctx, createdAt, key) {
154
+ if (createdAt > ctx.windowSince)
155
+ return true;
156
+ return (createdAt === ctx.windowSince &&
157
+ ctx.boundaryComments !== null &&
158
+ !ctx.boundaryComments.has(key));
159
+ }
135
160
  function normalizeReasonFilter(config, channelName) {
136
161
  if (config.reasonFilter === undefined)
137
162
  return null;
@@ -274,6 +299,17 @@ const BOUND_ACTION_VOCABULARY = {
274
299
  export const DEFAULT_PR_WATCH_LIMIT = 30;
275
300
  /** Hard ceiling for the configurable watch fan-out. */
276
301
  export const MAX_PR_WATCH_LIMIT = 500;
302
+ /**
303
+ * Requests held back for the interactive notification lane. When the last
304
+ * known REST budget is at or below this, the watch pass is skipped for the
305
+ * poll so a human mention is not starved by background PR polling. ~4% of a
306
+ * 5,000/hour classic-PAT budget: enough for several polls of mention traffic
307
+ * while barely trimming a healthy watch. Operators on other scales (GitHub
308
+ * Enterprise, finer-grained tokens) set prWatchBudgetReserve explicitly.
309
+ */
310
+ export const DEFAULT_PR_WATCH_BUDGET_RESERVE = 200;
311
+ /** Hard ceiling for the configurable watch budget reserve. */
312
+ export const MAX_PR_WATCH_BUDGET_RESERVE = 5000;
277
313
  /**
278
314
  * After a head change, checks register asynchronously (queued or self-hosted
279
315
  * runners can take minutes). Within this window an empty CI aggregate
@@ -300,6 +336,23 @@ const CI_RECHECK_INTERVAL_MS = 10 * 60 * 1000;
300
336
  * pending still settles within one period of the real transition.
301
337
  */
302
338
  const CI_PENDING_RECHECK_INTERVAL_MS = 5 * 60 * 1000;
339
+ /**
340
+ * Bound PR comment watch re-check period. Comments are fetched when the PR's
341
+ * updated_at advances OR this interval elapses, so a settled PR still hears
342
+ * new comments without one listComments + one listReviewComments per poll per
343
+ * bound PR. Above the 60s poll interval to bound the fan-out at the watch cap.
344
+ */
345
+ const COMMENT_RECHECK_INTERVAL_MS = 2 * 60 * 1000;
346
+ /**
347
+ * Pass-wide budget on watched comments, shared by every watched PR in a single
348
+ * watch pass (not a per-PR cap): commentSince survives a restart, so after a
349
+ * long outage every comment in the gap would otherwise become eligible at once,
350
+ * each as its own durable task and prompt — a per-PR cap would still claim up to
351
+ * this many × watched-PR tasks in one poll. A PR that finds the budget spent
352
+ * keeps its cursor and resumes next pass; a capped PR resumes before its last
353
+ * processed comment so the tail drains over subsequent passes, never dropped.
354
+ */
355
+ const MAX_WATCH_COMMENTS_PER_PASS = 20;
303
356
  /**
304
357
  * Backpressure horizon for bound-session delivery: queue-full and
305
358
  * temporarily-unavailable conditions defer without consuming the failure
@@ -377,11 +430,15 @@ function isPrWatchEntryShape(value) {
377
430
  stringOrUndef(entry.ci) &&
378
431
  stringOrUndef(entry.mergeableState) &&
379
432
  stringOrUndef(entry.prState) &&
433
+ stringOrUndef(entry.title) &&
380
434
  stringOrUndef(entry.prUpdatedAt) &&
381
435
  numberOrUndef(entry.headObservedAt) &&
382
436
  numberOrUndef(entry.lastCiFetchAt) &&
383
437
  numberOrUndef(entry.seq) &&
384
438
  stringOrUndef(entry.ciFiredSha) &&
439
+ stringOrUndef(entry.commentBaseline) &&
440
+ stringOrUndef(entry.commentSince) &&
441
+ numberOrUndef(entry.commentLastFetchAt) &&
385
442
  (entry.pending === undefined ||
386
443
  (Array.isArray(entry.pending) && entry.pending.every(isPending))) &&
387
444
  (entry.fired === undefined ||
@@ -446,6 +503,41 @@ export function validateBoundSessionConfig(config, channelName) {
446
503
  config.deliverToBoundSessions !== true) {
447
504
  return `prWatchLimit for channel ${channelName} requires deliverToBoundSessions: true.`;
448
505
  }
506
+ if (config.requireBoundWatch !== undefined &&
507
+ typeof config.requireBoundWatch !== 'boolean') {
508
+ return `[Channel:${channelName}] requireBoundWatch must be a boolean.`;
509
+ }
510
+ if (config.requireBoundWatch === true &&
511
+ config.deliverToBoundSessions !== true) {
512
+ return `requireBoundWatch for channel ${channelName} requires deliverToBoundSessions: true.`;
513
+ }
514
+ if (config.prCommentWatch !== undefined &&
515
+ typeof config.prCommentWatch !== 'boolean') {
516
+ return `[Channel:${channelName}] prCommentWatch must be a boolean.`;
517
+ }
518
+ // No deliverToBoundSessions dependency: prCommentWatch is default-on, so the
519
+ // editor emits it even for channels without bound delivery. It is inert there
520
+ // (the watch is gated on deliverToBoundSessions at runtime), not an error.
521
+ if (config.prWatchBudgetReserve !== undefined &&
522
+ config.deliverToBoundSessions !== true) {
523
+ return `prWatchBudgetReserve for channel ${channelName} requires deliverToBoundSessions: true.`;
524
+ }
525
+ // The descriptor now declares minimum: 0, so the editor refuses a negative
526
+ // the operator types. This check still guards everything else: a hand-edited
527
+ // settings.json or a daemon API call, and a stored negative the editor
528
+ // re-sends unchanged under its descriptor-level tolerance. The getter would
529
+ // silently fall back to the default for a negative, letting a saved value
530
+ // mean something other than it says.
531
+ // Positive fractions stay legal: the getter rounds them UP, which is the
532
+ // documented behaviour, not a silent fallback.
533
+ if (config.prWatchBudgetReserve !== undefined) {
534
+ const reserve = config.prWatchBudgetReserve;
535
+ if (typeof reserve !== 'number' ||
536
+ !Number.isFinite(reserve) ||
537
+ reserve < 0) {
538
+ return `prWatchBudgetReserve for channel ${channelName} must be a non-negative number.`;
539
+ }
540
+ }
449
541
  try {
450
542
  normalizePrWatchEvents(config, channelName);
451
543
  normalizeBoundSessionActions(config, channelName);
@@ -579,6 +671,7 @@ function isInboundTaskRecord(value) {
579
671
  typeof record.backpressure === 'boolean') &&
580
672
  (record.privateOnly === undefined ||
581
673
  typeof record.privateOnly === 'boolean') &&
674
+ isOptionalStringArray(record.authorExclude) &&
582
675
  (record.lostSessionId === undefined ||
583
676
  typeof record.lostSessionId === 'string'));
584
677
  }
@@ -602,9 +695,54 @@ function isNoReplySentinel(text) {
602
695
  }
603
696
  /** GitHub's wording for a secondary (abuse) rate limit. */
604
697
  const SECONDARY_RATE_LIMIT_MESSAGE = /secondary rate limit|abuse detection/i;
605
- /** `x-ratelimit-remaining` as a count; absent or malformed is undefined. */
606
- function rateLimitRemaining(err) {
607
- const value = err.response?.headers?.['x-ratelimit-remaining'];
698
+ /**
699
+ * Cap on cached conditional responses, sized from the fan-out it has to
700
+ * serve: up to MAX_PR_WATCH_LIMIT open PRs, a terminal-drain slice on top,
701
+ * and the notifications pages. A cap below the sweep does not degrade
702
+ * proportionally — each miss evicts the entry the sweep is about to read, so
703
+ * every read of every later pass misses and the saving is exactly zero for
704
+ * the high-fan-out deployments this is meant to help. Derived from the watch
705
+ * limit so the two cannot drift apart.
706
+ *
707
+ * A moved notifications `since` cursor still mints new keys, so the map is
708
+ * bounded and evicts least-recently-used first; an evicted URL simply pays
709
+ * for one full 200 again.
710
+ */
711
+ export const CONDITIONAL_CACHE_MAX_ENTRIES = MAX_PR_WATCH_LIMIT * 2;
712
+ /**
713
+ * Bodies above this size are not cached, so a pathologically large page
714
+ * cannot pin memory. Sized against the entry cap above to keep the retention
715
+ * bound in the same order as a smaller cache of larger bodies. A declined URL
716
+ * stays unconditional — the behavior from before conditional requests
717
+ * existed — and a page this large is one whose contents are churning, where a
718
+ * 304 was unlikely anyway.
719
+ */
720
+ const CONDITIONAL_CACHE_MAX_BODY_BYTES = 256 * 1024;
721
+ /**
722
+ * Total retained body bytes. The entry and per-body caps only bound the
723
+ * product loosely — a thousand maximum-size bodies would be a quarter of a
724
+ * gigabyte — so the cache is also bounded directly. Real responses are one to
725
+ * two orders of magnitude below the per-body cap, so this binds only the
726
+ * pathological case and never evicts a working set.
727
+ */
728
+ export const CONDITIONAL_CACHE_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
729
+ /**
730
+ * The two polling reads worth making conditional: the PR state watch and the
731
+ * notifications list. Matching on the pathname suffix keeps this working
732
+ * under an enterprise baseUrl prefix, and anchors the end so thread reads
733
+ * (`/notifications/threads/<id>`) and issue comments stay out of scope.
734
+ */
735
+ function isConditionalPollUrl(url) {
736
+ const { pathname } = new URL(url);
737
+ return (/\/repos\/[^/]+\/[^/]+\/pulls\/\d+$/.test(pathname) ||
738
+ /\/notifications$/.test(pathname));
739
+ }
740
+ /**
741
+ * A rate-limit header value (remaining count or reset epoch) as a
742
+ * non-negative integer; absent or malformed is undefined. GitHub sends
743
+ * these as decimal strings; a number is accepted for tests and proxies.
744
+ */
745
+ function parseRateLimitCount(value) {
608
746
  if (typeof value === 'number') {
609
747
  return Number.isInteger(value) && value >= 0 ? value : undefined;
610
748
  }
@@ -612,6 +750,10 @@ function rateLimitRemaining(err) {
612
750
  ? Number(value)
613
751
  : undefined;
614
752
  }
753
+ /** `x-ratelimit-remaining` as a count; absent or malformed is undefined. */
754
+ function rateLimitRemaining(err) {
755
+ return parseRateLimitCount(err.response?.headers?.['x-ratelimit-remaining']);
756
+ }
615
757
  /**
616
758
  * A 403 or 429 carrying one of GitHub's rate-limit signals: an exhausted
617
759
  * budget, `retry-after`, or the secondary-limit wording. GitHub sends a
@@ -751,6 +893,13 @@ export class GithubChannel extends PollingChannelBase {
751
893
  reasonFilter = null;
752
894
  repoFilter = null;
753
895
  deliverToBoundSessions = false;
896
+ requireBoundWatch = false;
897
+ /**
898
+ * Bound PR comment watch: poll conversation + inline review comments and
899
+ * deliver each to every bound session that did not post it. Default-on
900
+ * with deliverToBoundSessions; `prCommentWatch: false` disables it.
901
+ */
902
+ prCommentWatchEnabled = true;
754
903
  prWatchEvents = new Set();
755
904
  /**
756
905
  * Operator instruction templates keyed by the closed bound-action
@@ -824,6 +973,46 @@ export class GithubChannel extends PollingChannelBase {
824
973
  // otherwise silent; this drives a throttled diagnostic so the operator sees
825
974
  // a hint before the dead-letter alert hours later (doudouOUC).
826
975
  partialSnapshotStreak = 0;
976
+ /**
977
+ * Snapshot generation, bumped on every successful binding refresh. The
978
+ * gate grace is scoped to a generation, not to a drain call: pollOnce can
979
+ * drain the same PR twice against one snapshot, and a per-call grace would
980
+ * be spent by the second drain before any newer snapshot exists.
981
+ */
982
+ bindingsGeneration = 0;
983
+ /**
984
+ * Comment/watch keys the gate has deferred, mapped to the snapshot
985
+ * generation at the deferral. A watch installed after the bindings
986
+ * snapshot was fetched surfaces on the next refresh; the first gate-only
987
+ * exclusion holds the event (cursor unmoved / pending kept), and it stays
988
+ * held until a NEWER generation still finds it gated — then it is consumed
989
+ * like any other no-target event. In-memory: a restart resets the grace,
990
+ * which is harmless. Keys are removed when the event delivers or is
991
+ * consumed.
992
+ */
993
+ gateDeferredOnce = new Map();
994
+ /**
995
+ * Whether a gate-excluded event should keep being held. Defers on first
996
+ * sight and while the snapshot generation is unchanged; once a newer
997
+ * generation has landed and the event is still gated, the grace is spent
998
+ * (returns false and clears the key) so the caller consumes it.
999
+ */
1000
+ gateGraceShouldHold(key) {
1001
+ const deferredAt = this.gateDeferredOnce.get(key);
1002
+ if (deferredAt === undefined) {
1003
+ this.gateDeferredOnce.set(key, this.bindingsGeneration);
1004
+ return true;
1005
+ }
1006
+ if (deferredAt === this.bindingsGeneration) {
1007
+ return true;
1008
+ }
1009
+ this.gateDeferredOnce.delete(key);
1010
+ return false;
1011
+ }
1012
+ /** Clear any grace for an event that delivered (or is being consumed). */
1013
+ gateGraceClear(key) {
1014
+ this.gateDeferredOnce.delete(key);
1015
+ }
827
1016
  /**
828
1017
  * True while the most recent pending-watch reconciliation FAILED (e.g.
829
1018
  * the watch file is unreadable). Generic recovery must then leave watch
@@ -841,6 +1030,53 @@ export class GithubChannel extends PollingChannelBase {
841
1030
  * recovery edge.
842
1031
  */
843
1032
  watchReconcileBlockedCause;
1033
+ /**
1034
+ * Last REST budget seen on a SUCCESSFUL response, recorded by the request
1035
+ * hook regardless of the call's return shape. Undefined until the first
1036
+ * response carries the header. Gates the watch pass so background polling
1037
+ * cannot starve the interactive notification lane.
1038
+ */
1039
+ lastRateLimitRemaining;
1040
+ /**
1041
+ * Reset time (epoch ms) of the window lastRateLimitRemaining belongs to.
1042
+ * Once passed, the reading is stale and must not gate the watch: a low
1043
+ * count from a window that has already reset would otherwise starve the
1044
+ * watch until the next successful response overwrites it.
1045
+ */
1046
+ lastRateLimitResetAt;
1047
+ /**
1048
+ * Whether the watch pass is currently skipped for low budget. Edge-triggered
1049
+ * journaling (the watchReconcileBlockedCause pattern): a permanent low-budget
1050
+ * condition journalled once on the edge, not every poll, so it cannot rotate
1051
+ * the useful rows out of the timeline. Cleared on the recovery edge.
1052
+ */
1053
+ watchBudgetLow = false;
1054
+ /**
1055
+ * A `watch_budget_low` row has been journaled and its episode has not been
1056
+ * closed by a recovery row yet. Tracked apart from watchBudgetLow because
1057
+ * the two answer different questions: the skip latch is released when the
1058
+ * watch stops being eligible (so a later starvation journals a fresh skip),
1059
+ * but the episode stays open until the BUDGET recovers — otherwise a budget
1060
+ * that recovers during an ineligible window would never get its recovery
1061
+ * row. In-memory by design: a restart mid-episode leaves no recovery row,
1062
+ * which the user guide states.
1063
+ */
1064
+ watchBudgetEpisodeOpen = false;
1065
+ /**
1066
+ * ETag cache for the two polling reads, keyed by full request URL so a
1067
+ * moved notifications `since` cursor is a distinct entry rather than a
1068
+ * false hit. Connection-scoped: cleared on disconnect so a reconnect never
1069
+ * serves a body cached under a previous credential.
1070
+ */
1071
+ conditionalCache = new Map();
1072
+ /** Running total of cached body bytes, maintained by the two helpers below. */
1073
+ conditionalCacheBytes = 0;
1074
+ /**
1075
+ * Floor (ms) from the notifications endpoint's `X-Poll-Interval`. GitHub
1076
+ * asks polling clients not to poll faster than this; pollInterval raises
1077
+ * the whole loop to it, which also slows the watch pass.
1078
+ */
1079
+ notificationsPollFloorMs = 0;
844
1080
  /**
845
1081
  * Consecutive binding-refresh failures since the last success. While no
846
1082
  * snapshot has ever succeeded, the cold-start gate defers the comment lane,
@@ -915,6 +1151,21 @@ export class GithubChannel extends PollingChannelBase {
915
1151
  * nothing new (a repeated skip) are written once per window.
916
1152
  */
917
1153
  windowJournalKeys = new Set();
1154
+ /**
1155
+ * The comments this window has read that were created in the latest second
1156
+ * it has read a comment from, and the threads it has listed whose
1157
+ * notification is of the latest second it has listed one from. When the
1158
+ * window is marked read, those of the new cursor's second become
1159
+ * GithubCursor.boundaryComments.
1160
+ */
1161
+ windowLatestComments;
1162
+ windowLatestThreads;
1163
+ /**
1164
+ * Threads of late notifications (see `late` in pollOnce) this window has
1165
+ * read: the comments of the cursor's second GitHub listed then were read,
1166
+ * so a later failure reading one again in the window is treated as stale.
1167
+ */
1168
+ windowLateThreadsRead = new Set();
918
1169
  constructor(name, config, bridge, options) {
919
1170
  config.instructions = [
920
1171
  config.instructions?.trim(),
@@ -986,6 +1237,23 @@ export class GithubChannel extends PollingChannelBase {
986
1237
  }
987
1238
  base.dispatchedCommentTimes = clean;
988
1239
  }
1240
+ // A record that does not belong to the cursor, or that cannot be read,
1241
+ // is dropped: the window then starts after the cursor's second, as it
1242
+ // did before the record existed, and nothing it read is read again.
1243
+ const boundary = base.boundaryComments;
1244
+ if (boundary !== undefined) {
1245
+ const record = boundary;
1246
+ const isKeyList = (list) => Array.isArray(list) &&
1247
+ list.length <= MAX_BOUNDARY_COMMENTS &&
1248
+ list.every((key) => typeof key === 'string');
1249
+ if (!record ||
1250
+ typeof record !== 'object' ||
1251
+ record.at !== base.lastProcessedAt ||
1252
+ !isKeyList(record.keys) ||
1253
+ !isKeyList(record.threads)) {
1254
+ delete base.boundaryComments;
1255
+ }
1256
+ }
989
1257
  return base;
990
1258
  }
991
1259
  async connect() {
@@ -999,12 +1267,15 @@ export class GithubChannel extends PollingChannelBase {
999
1267
  this.prWatchEvents = normalizePrWatchEvents(cfg, this.name);
1000
1268
  this.boundSessionActions = normalizeBoundSessionActions(cfg, this.name);
1001
1269
  this.deliverToBoundSessions = cfg.deliverToBoundSessions === true;
1270
+ this.requireBoundWatch = cfg.requireBoundWatch === true;
1271
+ this.prCommentWatchEnabled = cfg.prCommentWatch !== false;
1002
1272
  if (this.deliverToBoundSessions) {
1003
1273
  this.loadBoundDeliveredRing();
1004
1274
  }
1005
1275
  if (this.deliverToBoundSessions && !this.boundSessions) {
1006
1276
  process.stderr.write(`[Channel:${this.name}] warning: deliverToBoundSessions requires a daemon-managed channel; ignoring (standalone mode).\n`);
1007
1277
  this.deliverToBoundSessions = false;
1278
+ this.requireBoundWatch = false;
1008
1279
  this.prWatchEvents = new Set();
1009
1280
  this.boundSessionActions = new Map();
1010
1281
  }
@@ -1029,9 +1300,26 @@ export class GithubChannel extends PollingChannelBase {
1029
1300
  this.octokit = new Octokit({
1030
1301
  auth,
1031
1302
  baseUrl,
1032
- ...(this.proxy
1033
- ? { request: { agent: new HttpsProxyAgent(this.proxy) } }
1034
- : {}),
1303
+ request: {
1304
+ ...(this.proxy ? { agent: new HttpsProxyAgent(this.proxy) } : {}),
1305
+ fetch: this.conditionalFetch,
1306
+ },
1307
+ });
1308
+ // One choke point for the success-path budget: the wrap sees the response
1309
+ // headers on every request, including each page of a paginate call,
1310
+ // independent of what fn() returns (array vs {data,headers}). It records
1311
+ // the last known remaining budget so the watch gate can protect the
1312
+ // notification lane before a request is ever rejected.
1313
+ this.octokit.hook.wrap('request', async (request, options) => {
1314
+ const response = await request(options);
1315
+ this.recordRateLimitBudget(response.headers);
1316
+ // Only the notifications endpoint sends this header, in seconds. It
1317
+ // survives a 304, so an idle channel keeps honouring it.
1318
+ const pollSeconds = parseRateLimitCount(response.headers['x-poll-interval']);
1319
+ if (pollSeconds !== undefined) {
1320
+ this.notificationsPollFloorMs = pollSeconds * 1000;
1321
+ }
1322
+ return response;
1035
1323
  });
1036
1324
  try {
1037
1325
  const { data } = await this.octokit.rest.users.getAuthenticated();
@@ -1111,8 +1399,27 @@ export class GithubChannel extends PollingChannelBase {
1111
1399
  this.pendingFinalDeliveryRetryAbort = retryAbort;
1112
1400
  this.pendingFinalDeliveryRetry = retry;
1113
1401
  }
1402
+ /**
1403
+ * GitHub asks polling clients not to poll the notifications endpoint
1404
+ * faster than its `X-Poll-Interval`. The base class exposes one interval
1405
+ * for the whole poll and the watch pass runs before the notifications lane,
1406
+ * so honouring the floor also slows the watch. At the default 60s poll the
1407
+ * header is also 60 and nothing changes; only a faster configured poll is
1408
+ * raised, which is exactly what GitHub is asking for.
1409
+ *
1410
+ * The ceiling is re-applied because the header is server-controlled and
1411
+ * super's clamp only covers the configured value: Node rounds a timeout
1412
+ * above its 32-bit range down to 1ms, so an unbounded floor would turn the
1413
+ * poll loop into a hot loop that burns the quota this is meant to save.
1414
+ */
1415
+ get pollInterval() {
1416
+ return Math.min(Math.max(super.pollInterval, this.notificationsPollFloorMs), MAX_POLL_INTERVAL_MS);
1417
+ }
1114
1418
  disconnect() {
1115
1419
  this.stopPollLoop();
1420
+ this.conditionalCache.clear();
1421
+ this.conditionalCacheBytes = 0;
1422
+ this.notificationsPollFloorMs = 0;
1116
1423
  // Retire the runner generation: an idle runner wakes and exits, and a
1117
1424
  // runner mid-turn exits after that turn. The durable task stays
1118
1425
  // recoverable for the next connection. Release idle waiters: with the
@@ -1640,14 +1947,45 @@ export class GithubChannel extends PollingChannelBase {
1640
1947
  }
1641
1948
  // The watch pass runs before generic recovery so detection cannot race
1642
1949
  // recovery over the same task; pending events were already reconciled.
1643
- if (this.prWatchEvents.size > 0 && !this.boundRefreshFailed) {
1644
- try {
1645
- await this.runPrStateWatch();
1950
+ // The comment watch is independent of the state-event subscription, so an
1951
+ // empty prWatchEvents still runs the pass while comment watching is on.
1952
+ const commentWatchActive = this.deliverToBoundSessions && this.prCommentWatchEnabled;
1953
+ if ((this.prWatchEvents.size > 0 || commentWatchActive) &&
1954
+ !this.boundRefreshFailed) {
1955
+ // Protect the interactive notification lane: the watch runs first and
1956
+ // is best-effort edge-triggered detection, so when the last known REST
1957
+ // budget is at or below the reserve, skip the pass this poll rather
1958
+ // than spend the budget a human mention needs. Skipping delays
1959
+ // detection of a state that persists (baselines and pending queues are
1960
+ // durable); a transition that appears and reverts between passes is
1961
+ // not observed. The reactive isWatchFailFastError backstop still
1962
+ // covers a wrong estimate. The gate covers the comment fetches too:
1963
+ // they run inside the same pass and spend the same budget.
1964
+ if (this.watchBudgetExhausted()) {
1965
+ this.noteWatchBudgetLow();
1646
1966
  }
1647
- catch (err) {
1648
- process.stderr.write(`[Channel:${this.name}] PR state watch failed, will retry next poll: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
1967
+ else {
1968
+ this.watchBudgetLow = false;
1969
+ this.closeWatchBudgetEpisode();
1970
+ try {
1971
+ await this.runPrStateWatch();
1972
+ }
1973
+ catch (err) {
1974
+ process.stderr.write(`[Channel:${this.name}] PR state watch failed, will retry next poll: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
1975
+ }
1976
+ // The pass itself may have spent down to the reserve and yielded
1977
+ // mid-way; close nothing here, the next poll's gate sees the reading.
1649
1978
  }
1650
1979
  }
1980
+ else {
1981
+ // The watch stopped being eligible (subscriptions off, binding refresh
1982
+ // failing). Release the skip latch so a later starvation journals a
1983
+ // fresh skip rather than being suppressed as a repeat, but keep the
1984
+ // EPISODE open until the budget itself recovers — a budget that
1985
+ // recovers during this window still owes its recovery row.
1986
+ this.watchBudgetLow = false;
1987
+ this.closeWatchBudgetEpisode();
1988
+ }
1651
1989
  if (this.inboundRecoveryPending) {
1652
1990
  try {
1653
1991
  await this.recoverInboundTasks();
@@ -1689,6 +2027,10 @@ export class GithubChannel extends PollingChannelBase {
1689
2027
  if (this.deliverToBoundSessions &&
1690
2028
  !this.boundSnapshotTrusted &&
1691
2029
  this.boundSessionByPr.size === 0 &&
2030
+ // Under the gate the map can be empty while raw bindings exist (every
2031
+ // listed follower watch-ineligible): the sidecars ARE readable, so the
2032
+ // cold-empty premise is false and the lane must not stall.
2033
+ !(this.requireBoundWatch && this.hasRawBoundPrs()) &&
1692
2034
  this.lastBindingsPartial &&
1693
2035
  this.coldEmptyPartialStreak < MAX_COLD_EMPTY_PARTIAL_POLLS) {
1694
2036
  if (this.coldEmptyPartialStreak === 1 ||
@@ -1711,10 +2053,17 @@ export class GithubChannel extends PollingChannelBase {
1711
2053
  ? notifications[notifications.length - 1].updated_at
1712
2054
  : this.cursor.lastProcessedAt;
1713
2055
  // Comment window lower bound: the cursor BEFORE this poll advances it.
1714
- // Comments with updated_at <= windowSince were already eligible for
2056
+ // Comments created before windowSince were already eligible for
1715
2057
  // processing in a previous poll — skip them to prevent duplicates when
1716
- // PUT /notifications' async mark fails to mark the thread read.
2058
+ // PUT /notifications' async mark fails to mark the thread read. Comments
2059
+ // of the windowSince second itself are read unless the window that ended
2060
+ // there read them (see GithubCursor.boundaryComments).
1717
2061
  const windowSince = this.cursor.lastProcessedAt;
2062
+ const boundary = this.cursor.boundaryComments?.at === windowSince
2063
+ ? this.cursor.boundaryComments
2064
+ : undefined;
2065
+ const boundaryComments = boundary ? new Set(boundary.keys) : null;
2066
+ const boundaryThreads = new Set(boundary?.threads);
1718
2067
  if (maxUpdatedAt > this.cursor.lastProcessedAt) {
1719
2068
  this.pendingCursorUpdatedAt =
1720
2069
  !this.pendingCursorUpdatedAt ||
@@ -1814,17 +2163,31 @@ export class GithubChannel extends PollingChannelBase {
1814
2163
  issueNumber,
1815
2164
  lastReadAt,
1816
2165
  windowSince,
2166
+ boundaryComments,
1817
2167
  metaFloor: this.cursor.metaFloor,
1818
2168
  maxUpdatedAt,
1819
2169
  subjectTitle: notification.subject.title || '',
1820
2170
  reason,
1821
2171
  };
1822
2172
  const failureKey = `${chatId}|${threadId}`;
1823
- // A notification at or before the cursor belongs to a window that
1824
- // already committed; it is listed again only because its mark-as-read
1825
- // did not apply. A 5xx reading it neither holds the new window nor
1826
- // spends its budget; a rate limit still stops the poll.
1827
- const stale = notification.updated_at <= this.cursor.lastProcessedAt;
2173
+ this.windowLatestThreads = noteLatestSecond(this.windowLatestThreads, notification.updated_at, failureKey);
2174
+ // A notification before the cursor belongs to a window that already
2175
+ // committed; it is listed again only because its mark-as-read did not
2176
+ // apply. A 5xx reading it neither holds the new window nor spends its
2177
+ // budget; a rate limit still stops the poll. One of the cursor's own
2178
+ // second that the window ending there did not list can instead be a
2179
+ // late notification for a comment that window did not read, when the
2180
+ // window reads that second: it holds a newer window waiting to be
2181
+ // marked read, and while none waits it is not marked read anyway, so
2182
+ // it spends no budget. Once the window has read its thread, it is
2183
+ // stale again.
2184
+ const late = notification.updated_at === windowSince &&
2185
+ boundaryComments !== null &&
2186
+ !boundaryThreads.has(failureKey) &&
2187
+ !this.windowLateThreadsRead.has(failureKey);
2188
+ const stale = notification.updated_at < windowSince ||
2189
+ (notification.updated_at === windowSince &&
2190
+ (!late || !this.pendingCursorUpdatedAt));
1828
2191
  try {
1829
2192
  switch (reason) {
1830
2193
  case 'mention':
@@ -1850,6 +2213,15 @@ export class GithubChannel extends PollingChannelBase {
1850
2213
  default:
1851
2214
  await this.processCommentLane(ctx, false);
1852
2215
  }
2216
+ // A thread held at poll start was not read (see fetchNewComments),
2217
+ // and a failing task store or audit may have refused what it read.
2218
+ if (late &&
2219
+ !this.threadHeldAtPollStart(chatId, threadId) &&
2220
+ !this.inboundPersistenceBlocked &&
2221
+ !this.publicationAuditBlocked &&
2222
+ this.windowLateThreadsRead.size < MAX_WINDOW_KEYS) {
2223
+ this.windowLateThreadsRead.add(failureKey);
2224
+ }
1853
2225
  }
1854
2226
  catch (err) {
1855
2227
  const failure = classifyThreadFailure(err);
@@ -1895,7 +2267,16 @@ export class GithubChannel extends PollingChannelBase {
1895
2267
  // leaves it running) holds the window as well: the cursor waits for
1896
2268
  // that task, so the thread is read again.
1897
2269
  const taskHeld = !retry && !storeHeld && this.threadTaskHoldsCursor(chatId, threadId);
1898
- const held = retry || storeHeld || taskHeld;
2270
+ // A late notification of the cursor's own second that fails with a
2271
+ // 5xx while no newer window waits is stale only for the budget:
2272
+ // nothing is marked read this poll, so the thread is read again.
2273
+ const idleHeld = failure === 'transient' &&
2274
+ !retry &&
2275
+ !storeHeld &&
2276
+ !taskHeld &&
2277
+ late &&
2278
+ !this.pendingCursorUpdatedAt;
2279
+ const held = retry || storeHeld || taskHeld || idleHeld;
1899
2280
  const milestone = (n) => n === 1 || n % 10 === 0;
1900
2281
  const report = failure === 'shared'
1901
2282
  ? milestone(heldPolls)
@@ -1903,7 +2284,7 @@ export class GithubChannel extends PollingChannelBase {
1903
2284
  ? counted
1904
2285
  ? milestone(failures)
1905
2286
  : this.journalOncePerWindow(`failing\0${failureKey}`)
1906
- : this.journalOncePerWindow(`${storeHeld || taskHeld ? 'held' : stale ? 'stale' : 'skip'}\0${failureKey}`);
2287
+ : this.journalOncePerWindow(`${storeHeld || taskHeld || idleHeld ? 'held' : stale ? 'stale' : 'skip'}\0${failureKey}`);
1907
2288
  if (report) {
1908
2289
  const error = sanitizeLogText(err instanceof Error ? err.message : String(err), 200);
1909
2290
  process.stderr.write(failure === 'shared'
@@ -1914,7 +2295,9 @@ export class GithubChannel extends PollingChannelBase {
1914
2295
  ? `[Channel:${this.name}] error processing ${threadId} while channel state cannot be persisted, keeping it unread for the next poll: ${error}\n`
1915
2296
  : taskHeld
1916
2297
  ? `[Channel:${this.name}] error processing ${threadId} while its task is unfinished, keeping it unread for the next poll: ${error}\n`
1917
- : `[Channel:${this.name}] API error processing ${threadId}, skipping: ${error}\n`);
2298
+ : idleHeld
2299
+ ? `[Channel:${this.name}] API error processing ${threadId} while no newer notification waits, keeping it unread for the next poll: ${error}\n`
2300
+ : `[Channel:${this.name}] API error processing ${threadId}, skipping: ${error}\n`);
1918
2301
  let detail;
1919
2302
  if (failure === 'transient' && !stale) {
1920
2303
  detail = retry ? { failures, heldPolls } : { failures };
@@ -1981,14 +2364,31 @@ export class GithubChannel extends PollingChannelBase {
1981
2364
  await this.markNotificationsAsRead(committedAt);
1982
2365
  if (committedAt > this.cursor.lastProcessedAt) {
1983
2366
  this.cursor.lastProcessedAt = committedAt;
2367
+ const read = this.windowLatestComments;
2368
+ const listed = this.windowLatestThreads;
2369
+ if (read?.at === committedAt && read.overflow) {
2370
+ delete this.cursor.boundaryComments;
2371
+ }
2372
+ else {
2373
+ // Past the bound a listed thread is left out, so a notification
2374
+ // of it listed again counts as late: the cautious direction.
2375
+ this.cursor.boundaryComments = {
2376
+ at: committedAt,
2377
+ keys: read?.at === committedAt ? [...read.keys] : [],
2378
+ threads: listed?.at === committedAt ? [...listed.keys] : [],
2379
+ };
2380
+ }
1984
2381
  }
1985
2382
  this.pendingCursorUpdatedAt = undefined;
1986
- // A new window starts: its hold budget, streaks and once-per-window
1987
- // journal keys start again.
2383
+ // A new window starts: its hold budget, streaks, once-per-window
2384
+ // journal keys and what it has read and listed start again.
1988
2385
  this.transientHoldPolls = 0;
1989
2386
  this.sharedHoldPolls = 0;
1990
2387
  this.transientNotificationFailures.clear();
1991
2388
  this.windowJournalKeys.clear();
2389
+ this.windowLatestComments = undefined;
2390
+ this.windowLatestThreads = undefined;
2391
+ this.windowLateThreadsRead.clear();
1992
2392
  }
1993
2393
  }
1994
2394
  finally {
@@ -2068,12 +2468,21 @@ export class GithubChannel extends PollingChannelBase {
2068
2468
  this.admitsMessageRoute(text) &&
2069
2469
  this.resolveBoundTargets(ctx.chatId, ctx.issueNumber, 'comment', 'comment').targets.length > 0;
2070
2470
  if (onlyMentioned && !hasMention && !mentionWaived) {
2071
- if (!this.journalOncePerWindow(`mention_required\0${key}`))
2471
+ // Name the actual filter: when the waiver would have admitted this
2472
+ // comment but the watch gate excluded every follower, the skip is
2473
+ // bound_watch_required — not the mention_required an unbound PR's
2474
+ // ambient chatter produces.
2475
+ const reason = this.gateExcludedAllFollowers(ctx.chatId, ctx.issueNumber) &&
2476
+ this.waivesBoundMention(ctx.chatId, senderId) &&
2477
+ this.admitsMessageRoute(text)
2478
+ ? 'bound_watch_required'
2479
+ : 'mention_required';
2480
+ if (!this.journalOncePerWindow(`${reason}\0${key}`))
2072
2481
  continue;
2073
2482
  this.recordChannelEvent({
2074
2483
  type: 'inbound',
2075
2484
  outcome: 'skipped',
2076
- reason: 'mention_required',
2485
+ reason,
2077
2486
  triggerKind: ctx.reason,
2078
2487
  repository: ctx.chatId,
2079
2488
  thread: ctx.threadId,
@@ -2334,11 +2743,17 @@ export class GithubChannel extends PollingChannelBase {
2334
2743
  if (this.threadHeldAtPollStart(ctx.chatId, ctx.threadId))
2335
2744
  return [];
2336
2745
  const [owner, repo] = ctx.chatId.split('/');
2746
+ // When the window reads the cursor's own second, list from a second
2747
+ // earlier, as the notification list does, so a comment last updated in
2748
+ // that second is listed whether GitHub's `since` includes it or not.
2749
+ const since = ctx.boundaryComments
2750
+ ? new Date(new Date(ctx.windowSince).getTime() - 1000).toISOString()
2751
+ : ctx.windowSince;
2337
2752
  const comments = (await this.githubApi(() => this.octokit.paginate(this.octokit.rest.issues.listComments, {
2338
2753
  owner,
2339
2754
  repo,
2340
2755
  issue_number: ctx.issueNumber,
2341
- since: ctx.windowSince,
2756
+ since,
2342
2757
  per_page: 100,
2343
2758
  }), `listComments(${ctx.threadId})`));
2344
2759
  comments.sort((a, b) => (a.created_at || '').localeCompare(b.created_at || ''));
@@ -2351,10 +2766,66 @@ export class GithubChannel extends PollingChannelBase {
2351
2766
  times[comment.node_id || String(comment.id)] = comment.created_at;
2352
2767
  }
2353
2768
  }
2354
- return comments.filter((comment) => comment.user?.login !== this.botUsername &&
2769
+ this.recordEditedMentions(ctx, comments);
2770
+ const inWindow = comments.filter((comment) => comment.user?.login !== this.botUsername &&
2355
2771
  (!comment.created_at ||
2356
- (comment.created_at > ctx.windowSince &&
2772
+ (startsInWindow(ctx, comment.created_at, comment.node_id || String(comment.id)) &&
2357
2773
  comment.created_at <= ctx.maxUpdatedAt)));
2774
+ for (const comment of inWindow)
2775
+ this.noteWindowComment(comment);
2776
+ return inWindow;
2777
+ }
2778
+ /**
2779
+ * Remember a comment this window read, if it is of the latest second the
2780
+ * window has read a comment from (the cursor can advance at most to the
2781
+ * newest notification, and no comment it reads is newer than that).
2782
+ */
2783
+ noteWindowComment(comment) {
2784
+ if (!comment.created_at)
2785
+ return;
2786
+ this.windowLatestComments = noteLatestSecond(this.windowLatestComments, comment.created_at, comment.node_id || String(comment.id));
2787
+ }
2788
+ /**
2789
+ * GitHub notifies a mention that an edit adds to an older comment, but the
2790
+ * lanes read only comments created in the window. Journal such a comment
2791
+ * once per window, so the notification it raised is not consumed without a
2792
+ * trace (unless it arrives after the cursor has passed the edit, as a late
2793
+ * notification for a new comment can). The edit time has no upper bound: a later edit (or a notification
2794
+ * stamped before the edit) leaves the comment newer than the window, and
2795
+ * once the window commits nothing reads it again. A later window that
2796
+ * reads the thread again can record it once more.
2797
+ */
2798
+ recordEditedMentions(ctx, comments) {
2799
+ const botUsername = this.botUsername;
2800
+ if (!botUsername)
2801
+ return;
2802
+ for (const comment of comments) {
2803
+ if (comment.user?.login === botUsername ||
2804
+ !comment.created_at ||
2805
+ startsInWindow(ctx, comment.created_at, comment.node_id || String(comment.id)) ||
2806
+ !comment.updated_at ||
2807
+ comment.updated_at <= ctx.windowSince ||
2808
+ !testBotMention(comment.body || '', botUsername)) {
2809
+ continue;
2810
+ }
2811
+ const key = comment.node_id || String(comment.id);
2812
+ // An edit to a comment the channel already took is not a new request.
2813
+ if (this.cursor.dispatchedComments?.includes(key))
2814
+ continue;
2815
+ if (!this.journalOncePerWindow(`edited_comment\0${key}`))
2816
+ continue;
2817
+ this.recordChannelEvent({
2818
+ type: 'inbound',
2819
+ outcome: 'skipped',
2820
+ reason: 'edited_comment',
2821
+ triggerKind: 'comment',
2822
+ repository: ctx.chatId,
2823
+ thread: ctx.threadId,
2824
+ number: ctx.issueNumber,
2825
+ messageId: key,
2826
+ actor: (comment.user?.login || 'unknown').toLowerCase(),
2827
+ });
2828
+ }
2358
2829
  }
2359
2830
  async fetchIssueMeta(ctx) {
2360
2831
  const { data } = await this.githubApi(() => this.octokit.rest.issues.get({
@@ -2446,9 +2917,11 @@ export class GithubChannel extends PollingChannelBase {
2446
2917
  }
2447
2918
  /**
2448
2919
  * Window-aware eviction. Once over the soft cap, drop EVERY key whose
2449
- * comment can no longer be re-listed (created_at <= the committed cursor),
2450
- * keeping protected keys regardless of position. A key newer than the
2451
- * cursor — or with no recorded time (legacy migration) — is protected:
2920
+ * comment can no longer be re-listed (created_at before the committed
2921
+ * cursor; the window can read the cursor's own second again, see
2922
+ * GithubCursor.boundaryComments), keeping protected keys regardless of
2923
+ * position. A key at or after the cursor — or with no recorded time
2924
+ * (legacy migration) — is protected:
2452
2925
  * evicting it would let a re-listed aggregate SUPERSET re-dispatch
2453
2926
  * already-replied comments under a fresh batch hash that misses the
2454
2927
  * publication-audit backstop (duplicate public reply / private injection
@@ -2467,13 +2940,13 @@ export class GithubChannel extends PollingChannelBase {
2467
2940
  const cursor = this.cursor.lastProcessedAt;
2468
2941
  return list.filter((key) => {
2469
2942
  const time = times[key];
2470
- return time === undefined || time > cursor;
2943
+ return time === undefined || time >= cursor;
2471
2944
  });
2472
2945
  }
2473
2946
  /**
2474
2947
  * Bound the time map: drop entries that are neither in the ring nor still
2475
2948
  * re-listable. Times for fetched-but-not-yet-dispatched comments survive
2476
- * while their created_at is newer than the cursor (they may be dispatched
2949
+ * while their created_at is not before the cursor (they may be dispatched
2477
2950
  * later this poll), so eviction never loses a key's protection mid-poll.
2478
2951
  */
2479
2952
  pruneCommentTimes() {
@@ -2483,7 +2956,7 @@ export class GithubChannel extends PollingChannelBase {
2483
2956
  const live = new Set(this.cursor.dispatchedComments ?? []);
2484
2957
  const cursor = this.cursor.lastProcessedAt;
2485
2958
  for (const [key, time] of Object.entries(times)) {
2486
- if (!live.has(key) && time <= cursor)
2959
+ if (!live.has(key) && time < cursor)
2487
2960
  delete times[key];
2488
2961
  }
2489
2962
  // Bound the map even under a permanently frozen cursor (nothing expires):
@@ -2507,7 +2980,7 @@ export class GithubChannel extends PollingChannelBase {
2507
2980
  }
2508
2981
  }
2509
2982
  }
2510
- async dispatchEnvelope(envelope, issueNumber, dedupe = {}, privateOnly = false) {
2983
+ async dispatchEnvelope(envelope, issueNumber, dedupe = {}, privateOnly = false, excludeSessionIds) {
2511
2984
  // The publication audit is the durable consumption record for the
2512
2985
  // public path: a reply can land (audit `posted`), the task be removed,
2513
2986
  // and the cursor save still be lost (mark-read failure, crash). The
@@ -2543,7 +3016,13 @@ export class GithubChannel extends PollingChannelBase {
2543
3016
  // class `comment` is the resolution fallback so a `fix:comment`
2544
3017
  // template also catches a comment delivered under another reason.
2545
3018
  const laneClass = dedupe.dispatchedComments !== undefined ? 'comment' : undefined;
2546
- const { targets, followed } = this.resolveBoundTargets(envelope.chatId, issueNumber, eventClass, laneClass);
3019
+ const resolved = this.resolveBoundTargets(envelope.chatId, issueNumber, eventClass, laneClass);
3020
+ // The bound PR comment watch withholds a comment from the session that
3021
+ // posted it (authorship attribution), keeping every other bound target.
3022
+ const targets = excludeSessionIds && excludeSessionIds.size > 0
3023
+ ? resolved.targets.filter((target) => !excludeSessionIds.has(target.sessionId))
3024
+ : resolved.targets;
3025
+ const followed = resolved.followed;
2547
3026
  if (targets.length > 0) {
2548
3027
  // Fan-out: one durable task per (event, target). Each settles
2549
3028
  // independently — a queue-full role defers without head-of-line
@@ -2566,7 +3045,7 @@ export class GithubChannel extends PollingChannelBase {
2566
3045
  kind: 'bound-session',
2567
3046
  sessionId: target.sessionId,
2568
3047
  ...(target.role ? { role: target.role } : {}),
2569
- }, first && targets.length > 1 ? targets : undefined, privateOnly));
3048
+ }, first && targets.length > 1 ? targets : undefined, privateOnly, excludeSessionIds));
2570
3049
  first = false;
2571
3050
  }
2572
3051
  let settled = true;
@@ -2576,7 +3055,7 @@ export class GithubChannel extends PollingChannelBase {
2576
3055
  return settled;
2577
3056
  }
2578
3057
  if (followed &&
2579
- this.boundRoleAware &&
3058
+ (this.boundRoleAware || this.requireBoundWatch) &&
2580
3059
  this.boundSnapshotTrusted &&
2581
3060
  !this.lastBindingsPartial &&
2582
3061
  !this.boundRefreshFailed) {
@@ -2587,9 +3066,16 @@ export class GithubChannel extends PollingChannelBase {
2587
3066
  // role. Under a partial or failing scan an unscanned role might
2588
3067
  // still match, so fall through to the untargeted claim: the absence
2589
3068
  // gate defers it as backpressure instead of consuming the event on
2590
- // incomplete evidence.
3069
+ // incomplete evidence. The watch gate retires the same way in legacy
3070
+ // mode: every follower is bound but none is watch-eligible. The
3071
+ // journal reason names the ACTUAL filter: a gate exclusion is
3072
+ // bound_watch_required in BOTH modes, not the role-aware template
3073
+ // reason that would send the operator to templates that matched fine.
3074
+ const gateExcludedAll = this.gateExcludedAllFollowers(envelope.chatId, issueNumber);
2591
3075
  this.applyTaskDedupe(dedupe);
2592
- process.stderr.write(`[Channel:${this.name}] event ${envelope.messageId} matched no role's boundSessionActions; retiring without public fallback\n`);
3076
+ process.stderr.write(`[Channel:${this.name}] event ${envelope.messageId} ${gateExcludedAll
3077
+ ? 'has no watch-eligible bound session (requireBoundWatch)'
3078
+ : "matched no role's boundSessionActions"}; retiring without public fallback\n`);
2593
3079
  // Retired before any task was claimed, so there is no task row to
2594
3080
  // close: the skip is the event's only journal trace. The dedupe cursor
2595
3081
  // is still in memory here — the base saves it after pollOnce returns —
@@ -2599,7 +3085,7 @@ export class GithubChannel extends PollingChannelBase {
2599
3085
  this.recordChannelEvent({
2600
3086
  type: 'inbound',
2601
3087
  outcome: 'skipped',
2602
- reason: 'no_role_matched',
3088
+ reason: gateExcludedAll ? 'bound_watch_required' : 'no_role_matched',
2603
3089
  triggerKind: parseTriggerKind(envelope.metadata),
2604
3090
  repository: envelope.chatId,
2605
3091
  thread: envelope.threadId,
@@ -2621,7 +3107,7 @@ export class GithubChannel extends PollingChannelBase {
2621
3107
  this.enqueuePublicTask(task);
2622
3108
  return true;
2623
3109
  }
2624
- claimInboundTask(envelope, issueNumber, dedupe, delivery, fanout, privateOnly = false) {
3110
+ claimInboundTask(envelope, issueNumber, dedupe, delivery, fanout, privateOnly = false, authorExclude) {
2625
3111
  const existing = this.readInboundTasks().find((record) => record.source.chatId === envelope.chatId &&
2626
3112
  record.source.threadId === envelope.threadId &&
2627
3113
  record.source.messageId === envelope.messageId &&
@@ -2669,6 +3155,9 @@ export class GithubChannel extends PollingChannelBase {
2669
3155
  ...(delivery ? { delivery } : {}),
2670
3156
  ...(fanout ? { fanout } : {}),
2671
3157
  ...(privateOnly ? { privateOnly: true } : {}),
3158
+ ...(authorExclude && authorExclude.size > 0
3159
+ ? { authorExclude: [...authorExclude] }
3160
+ : {}),
2672
3161
  };
2673
3162
  this.updateInboundTasks((records) => [...records, task]);
2674
3163
  this.applyTaskDedupe(task.dedupe);
@@ -2925,7 +3414,13 @@ export class GithubChannel extends PollingChannelBase {
2925
3414
  let posted = task.errorCommentPosted === true;
2926
3415
  // Bound-session delivery is private: a failure must not post a public
2927
3416
  // error comment. The fallback path clears delivery before retrying.
2928
- if (!posted && !stillBound && task.privateOnly !== true) {
3417
+ // A failed public attempt is run again on a later poll until the
3418
+ // budget is spent (see isRecoverableInboundTask), so the comment,
3419
+ // which asks the user to mention the bot again, waits for the last.
3420
+ if (!posted &&
3421
+ !stillBound &&
3422
+ task.privateOnly !== true &&
3423
+ attempts >= MAX_INBOUND_TASK_ATTEMPTS) {
2929
3424
  posted = await this.postErrorComment(envelope.chatId, task.issueNumber, this.getInboundErrorSourceLabel(envelope));
2930
3425
  }
2931
3426
  // Queue full and temporarily-unavailable sessions/workspaces are
@@ -3072,7 +3567,12 @@ export class GithubChannel extends PollingChannelBase {
3072
3567
  kind: 'bound-session',
3073
3568
  sessionId: target.sessionId,
3074
3569
  ...(target.role ? { role: target.role } : {}),
3075
- }, undefined, task.privateOnly === true);
3570
+ }, undefined, task.privateOnly === true,
3571
+ // The reconstructed sibling must inherit the authorship exclusion:
3572
+ // it is the same event, so the same sessions authored it. Without
3573
+ // this the reselection filter receives an empty set and can route
3574
+ // the comment to its author once that session becomes the newest.
3575
+ task.authorExclude ? new Set(task.authorExclude) : undefined);
3076
3576
  }
3077
3577
  }
3078
3578
  const tasks = this.readInboundTasks().filter((task) => this.isRecoverableInboundTask(task));
@@ -3173,8 +3673,11 @@ export class GithubChannel extends PollingChannelBase {
3173
3673
  // snapshot: the operator's subscription scoping retires this
3174
3674
  // event, not an absence. Under a partial or failing scan an
3175
3675
  // unscanned role might still match — leave the task untargeted
3176
- // so the absence gate keeps deferring it as backpressure.
3177
- this.retireBoundTask(task, 'no role matched the event class (operator subscription)');
3676
+ // so the absence gate keeps deferring it as backpressure. Name
3677
+ // the gate when the gate (not the templates) excluded everyone.
3678
+ this.retireBoundTask(task, this.gateExcludedAllFollowers(task.envelope.chatId, task.issueNumber)
3679
+ ? 'no watch-eligible bound session (requireBoundWatch)'
3680
+ : 'no role matched the event class (operator subscription)');
3178
3681
  continue;
3179
3682
  }
3180
3683
  }
@@ -3184,6 +3687,19 @@ export class GithubChannel extends PollingChannelBase {
3184
3687
  this.transitionInboundTask(task.id, 'running', { delivery });
3185
3688
  task.delivery = delivery;
3186
3689
  }
3690
+ else if (this.requireBoundWatch &&
3691
+ this.boundSnapshotTrusted &&
3692
+ !this.lastBindingsPartial &&
3693
+ !this.boundRefreshFailed &&
3694
+ this.boundFollowersOf(task.envelope.chatId, task.issueNumber)
3695
+ .length > 0) {
3696
+ // The filtered map has no winner but raw followers exist on a
3697
+ // COMPLETE fresh snapshot: every follower is bound but none is
3698
+ // watch-eligible. The operator's scoping retires this event,
3699
+ // not an absence — same rule as the role-aware branch above.
3700
+ this.retireBoundTask(task, 'no watch-eligible bound session (requireBoundWatch)');
3701
+ continue;
3702
+ }
3187
3703
  }
3188
3704
  }
3189
3705
  if (pendingDeliveries.some((record) => record.chatId === task.source.chatId &&
@@ -3597,6 +4113,154 @@ export class GithubChannel extends PollingChannelBase {
3597
4113
  removeInboundTask(taskId) {
3598
4114
  this.updateInboundTasks((records) => records.filter((record) => record.id !== taskId));
3599
4115
  }
4116
+ /**
4117
+ * The conditional exchange, owned at the transport boundary rather than in
4118
+ * a request hook: `@octokit/request` hard-codes 304 into a RequestError
4119
+ * INSIDE plugin-request-log's own wrap, so catching it any higher leaves an
4120
+ * error-level log line per 304 (~1,800/hour at the watch cap) and hands
4121
+ * githubApi a retryable failure. Converting it here means no layer above
4122
+ * ever learns there was a 304.
4123
+ */
4124
+ conditionalFetch = async (input, init) => {
4125
+ const url = String(input);
4126
+ if ((init?.method ?? 'GET').toUpperCase() !== 'GET' ||
4127
+ !isConditionalPollUrl(url)) {
4128
+ return fetch(input, init);
4129
+ }
4130
+ const cached = this.conditionalCache.get(url);
4131
+ const headers = new Headers(init?.headers);
4132
+ if (cached)
4133
+ headers.set('if-none-match', cached.etag);
4134
+ const response = await fetch(url, { ...init, headers });
4135
+ if (response.status === 304 && cached) {
4136
+ const merged = new Headers(response.headers);
4137
+ // GitHub omits Link on a 304 (verified against the live API: the same
4138
+ // URL's 200 carried next+last, the 304 carried neither). Without the
4139
+ // cached value paginate stops after page 1 and silently drops the rest
4140
+ // of the notifications list.
4141
+ if (!merged.has('link') && cached.link !== undefined) {
4142
+ merged.set('link', cached.link);
4143
+ }
4144
+ // The body is the cached, already-decoded text, so any framing headers
4145
+ // describing the empty 304 body would misdescribe it.
4146
+ merged.delete('content-length');
4147
+ merged.delete('content-encoding');
4148
+ merged.set('content-type', 'application/json; charset=utf-8');
4149
+ // Refresh recency on a hit, not just on a write: a moved `since` cursor
4150
+ // keeps minting dead notification entries, and without this they would
4151
+ // evict the quiet PRs that are being read every poll.
4152
+ this.storeCached(url, cached);
4153
+ return new Response(cached.body, { status: 200, headers: merged });
4154
+ }
4155
+ if (response.status === 200) {
4156
+ const etag = response.headers.get('etag');
4157
+ if (etag !== null) {
4158
+ const body = await response.clone().text();
4159
+ const bytes = Buffer.byteLength(body);
4160
+ if (bytes <= CONDITIONAL_CACHE_MAX_BODY_BYTES) {
4161
+ this.storeCached(url, {
4162
+ etag,
4163
+ body,
4164
+ link: response.headers.get('link') ?? undefined,
4165
+ bytes,
4166
+ });
4167
+ for (const oldest of this.conditionalCache.keys()) {
4168
+ if (this.conditionalCache.size <= CONDITIONAL_CACHE_MAX_ENTRIES &&
4169
+ this.conditionalCacheBytes <= CONDITIONAL_CACHE_MAX_TOTAL_BYTES) {
4170
+ break;
4171
+ }
4172
+ this.dropCached(oldest);
4173
+ }
4174
+ }
4175
+ }
4176
+ }
4177
+ return response;
4178
+ };
4179
+ /**
4180
+ * The only two writers of the cache, so the byte total cannot drift from
4181
+ * the map. Re-inserting moves the key to the most-recently-used end.
4182
+ */
4183
+ dropCached(url) {
4184
+ const entry = this.conditionalCache.get(url);
4185
+ if (entry === undefined)
4186
+ return;
4187
+ this.conditionalCacheBytes -= entry.bytes;
4188
+ this.conditionalCache.delete(url);
4189
+ }
4190
+ storeCached(url, entry) {
4191
+ this.dropCached(url);
4192
+ this.conditionalCache.set(url, entry);
4193
+ this.conditionalCacheBytes += entry.bytes;
4194
+ }
4195
+ /**
4196
+ * Record the REST budget from a successful response's headers. Called by
4197
+ * the request hook on every response. A missing or malformed remaining
4198
+ * header leaves the last known value untouched (a proxy that strips the
4199
+ * header must not erase a real reading). The reset time is refreshed from
4200
+ * the same response; if that header is absent the reset is cleared, so the
4201
+ * gate falls back to protecting on the count alone rather than trusting a
4202
+ * reset time from a different window.
4203
+ */
4204
+ recordRateLimitBudget(headers) {
4205
+ const remaining = parseRateLimitCount(headers?.['x-ratelimit-remaining']);
4206
+ if (remaining === undefined)
4207
+ return;
4208
+ this.lastRateLimitRemaining = remaining;
4209
+ const reset = parseRateLimitCount(headers?.['x-ratelimit-reset']);
4210
+ this.lastRateLimitResetAt = reset === undefined ? undefined : reset * 1000;
4211
+ }
4212
+ /**
4213
+ * Whether the watch pass must yield this poll to protect the notification
4214
+ * lane. True only when a usable remaining reading is at or below the
4215
+ * reserve AND its window has not already reset (a stale low count from a
4216
+ * rolled-over window must not starve the watch). With no reading yet the
4217
+ * watch runs normally; the reactive isWatchFailFastError backstop still
4218
+ * covers a wrong estimate or a secondary limit.
4219
+ */
4220
+ watchBudgetExhausted() {
4221
+ const reserve = this.prWatchBudgetReserve;
4222
+ // A reserve of 0 disables the gate outright. Without this, a remaining
4223
+ // of 0 would still satisfy `0 <= 0` and skip the watch the operator
4224
+ // explicitly opted out of protecting.
4225
+ if (reserve === 0)
4226
+ return false;
4227
+ if (this.lastRateLimitRemaining === undefined)
4228
+ return false;
4229
+ if (this.lastRateLimitResetAt !== undefined &&
4230
+ Date.now() >= this.lastRateLimitResetAt) {
4231
+ return false;
4232
+ }
4233
+ return this.lastRateLimitRemaining <= reserve;
4234
+ }
4235
+ /**
4236
+ * Open a low-budget episode: latch the skip and journal its edge once.
4237
+ * Shared by the poll-boundary gate and the in-pass yield so a mid-pass stop
4238
+ * records the same row rather than a second vocabulary.
4239
+ */
4240
+ noteWatchBudgetLow() {
4241
+ this.watchBudgetEpisodeOpen = true;
4242
+ if (this.watchBudgetLow)
4243
+ return;
4244
+ this.watchBudgetLow = true;
4245
+ this.recordPollDegraded('watch_budget_low', {
4246
+ remaining: this.lastRateLimitRemaining ?? 0,
4247
+ reserve: this.prWatchBudgetReserve,
4248
+ });
4249
+ 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`);
4250
+ }
4251
+ /**
4252
+ * Close the episode once the budget is no longer exhausted. A still-low
4253
+ * budget keeps it open: the watch being ineligible says nothing about the
4254
+ * budget, and claiming recovery there would be a false report.
4255
+ */
4256
+ closeWatchBudgetEpisode() {
4257
+ if (!this.watchBudgetEpisodeOpen)
4258
+ return;
4259
+ if (this.watchBudgetExhausted())
4260
+ return;
4261
+ this.watchBudgetEpisodeOpen = false;
4262
+ this.recordPollDegraded('watch_budget_recovered');
4263
+ }
3600
4264
  /**
3601
4265
  * Journals a degraded dependency the poll loop itself survived: the poll
3602
4266
  * still reports `ok`, so without this row a binding scan that stalls every
@@ -3633,7 +4297,16 @@ export class GithubChannel extends PollingChannelBase {
3633
4297
  try {
3634
4298
  const parsed = JSON.parse(readFileSync(this.inboundTasksPath(), 'utf-8'));
3635
4299
  if (!Array.isArray(parsed) || !parsed.every(isInboundTaskRecord)) {
3636
- throw new Error('invalid GitHub inbound task state');
4300
+ // Name the offender: one bad record blocks every healthy task in the
4301
+ // file, so an operator repairing it by hand needs the index and id
4302
+ // rather than bisecting the JSON by eye.
4303
+ const badIndex = Array.isArray(parsed)
4304
+ ? parsed.findIndex((item) => !isInboundTaskRecord(item))
4305
+ : -1;
4306
+ const badId = badIndex === -1
4307
+ ? undefined
4308
+ : parsed[badIndex]?.id;
4309
+ throw new Error(`invalid GitHub inbound task state${badIndex === -1 ? '' : ` at record ${badIndex}`}${typeof badId === 'string' ? ` (${badId})` : ''}`);
3637
4310
  }
3638
4311
  this.inboundTaskSnapshot = parsed;
3639
4312
  return parsed;
@@ -3918,6 +4591,7 @@ export class GithubChannel extends PollingChannelBase {
3918
4591
  this.boundRefreshFailed = false;
3919
4592
  this.boundSnapshotSeen = true;
3920
4593
  this.boundSnapshotFailureStreak = 0;
4594
+ this.bindingsGeneration += 1;
3921
4595
  if (!snapshot.partial)
3922
4596
  this.boundSnapshotTrusted = true;
3923
4597
  const map = new Map();
@@ -3930,6 +4604,8 @@ export class GithubChannel extends PollingChannelBase {
3930
4604
  const identity = this.parsePrBindingUrl(pr.url);
3931
4605
  if (!identity || identity.number !== pr.number)
3932
4606
  continue;
4607
+ if (this.watchGateExcludes(pr.role, pr.watching))
4608
+ continue;
3933
4609
  const key = this.prBindingKey(identity.chatId, identity.number);
3934
4610
  const existing = map.get(key);
3935
4611
  if (!existing ||
@@ -3960,11 +4636,20 @@ export class GithubChannel extends PollingChannelBase {
3960
4636
  // authoritative) and surface in the dead-letter at the horizon —
3961
4637
  // never a silent loss or an irreversible public reply.
3962
4638
  const retained = this.lastBindings.filter((b) => !seen.has(b.sessionId));
3963
- const retainedCapped = retained.length > MAX_PARTIAL_RETAINED
4639
+ const retainedCapped = (retained.length > MAX_PARTIAL_RETAINED
3964
4640
  ? [...retained]
3965
4641
  .sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''))
3966
4642
  .slice(0, MAX_PARTIAL_RETAINED)
3967
- : retained;
4643
+ : retained).map((summary) => ({
4644
+ ...summary,
4645
+ // A retained row's last-stamped `watching` is stale evidence: the
4646
+ // scan that would refresh it cannot read this session's sidecar.
4647
+ // Keep the row (it still names its PRs and competes by recency)
4648
+ // but reset the flag to unknown so the gate fails open on it — a
4649
+ // watch installed during a permanent partial must not read as a
4650
+ // confirmed false and ban the session for the partial's life.
4651
+ prs: summary.prs.map((pr) => ({ ...pr, watching: undefined })),
4652
+ }));
3968
4653
  retainedSessionCount = retainedCapped.length;
3969
4654
  if (retainedCapped.length < retained.length) {
3970
4655
  process.stderr.write(`[Channel:${this.name}] binding retention cap exceeded under a partial snapshot: dropped ${retained.length - retainedCapped.length} oldest unlisted sessions (keeping ${MAX_PARTIAL_RETAINED}); their unmatched events defer until a complete snapshot establishes absence\n`);
@@ -3980,6 +4665,8 @@ export class GithubChannel extends PollingChannelBase {
3980
4665
  const identity = this.parsePrBindingUrl(pr.url);
3981
4666
  if (!identity || identity.number !== pr.number)
3982
4667
  continue;
4668
+ if (this.watchGateExcludes(pr.role, pr.watching))
4669
+ continue;
3983
4670
  const key = this.prBindingKey(identity.chatId, identity.number);
3984
4671
  const existing = map.get(key);
3985
4672
  if (!existing ||
@@ -3994,7 +4681,10 @@ export class GithubChannel extends PollingChannelBase {
3994
4681
  this.lastBindings = snapshot.bindings;
3995
4682
  }
3996
4683
  this.boundSessionByPr = map;
3997
- if (snapshot.partial && map.size === 0 && !this.boundSnapshotTrusted) {
4684
+ if (snapshot.partial &&
4685
+ map.size === 0 &&
4686
+ !this.boundSnapshotTrusted &&
4687
+ !(this.requireBoundWatch && this.hasRawBoundPrs())) {
3998
4688
  this.coldEmptyPartialStreak += 1;
3999
4689
  if (this.coldEmptyPartialStreak === MAX_COLD_EMPTY_PARTIAL_POLLS) {
4000
4690
  process.stderr.write(`[Channel:${this.name}] binding snapshot has been an empty partial for ${this.coldEmptyPartialStreak} consecutive binding scans: opening the comment lane. Unmatched PR events will defer (and dead-letter after the backpressure horizon) until a complete snapshot establishes absence. ${this.coldEmptyCapCause()}\n`);
@@ -4027,6 +4717,7 @@ export class GithubChannel extends PollingChannelBase {
4027
4717
  const listedSessions = snapshot.bindings.length + retainedSessionCount;
4028
4718
  process.stderr.write(`[Channel:${this.name}] binding snapshot has been partial for ${this.partialSnapshotStreak} consecutive binding scans (${listedSessions} sessions listed): the daemon could not read every PR sidecar, transcript or live session list, or a registered workspace has no runtime. ${!this.boundSnapshotTrusted &&
4029
4719
  map.size === 0 &&
4720
+ !(this.requireBoundWatch && this.hasRawBoundPrs()) &&
4030
4721
  this.coldEmptyPartialStreak < MAX_COLD_EMPTY_PARTIAL_POLLS
4031
4722
  ? `The comment lane is still deferred (${this.coldEmptyPartialStreak}/${MAX_COLD_EMPTY_PARTIAL_POLLS} cold binding scans), so PR and issue events are both stalled.`
4032
4723
  : 'Unmatched PR events defer to the dead-letter horizon instead of the channel (issue events are unaffected).'} Check the daemon's stderr for the failing workspace, and its \`PR bindings scan\` lines for the session it could not read.\n`);
@@ -4051,7 +4742,10 @@ export class GithubChannel extends PollingChannelBase {
4051
4742
  // No authoritative map exists: either no snapshot has ever succeeded,
4052
4743
  // or only empty partials / failures have (boundSnapshotSeen may already
4053
4744
  // be true). The cold-start gate defers the comment lane, so every
4054
- // notification is stalled.
4745
+ // notification is stalled. The gate's raw-presence suppression is NOT
4746
+ // applied here: a raw row left by an earlier scan says nothing about
4747
+ // THIS failing lookup, so the failure accounting and the
4748
+ // bindings_unreachable row must still run.
4055
4749
  const noAuthoritativeMap = !this.boundSnapshotTrusted && this.boundSessionByPr.size === 0;
4056
4750
  if (noAuthoritativeMap) {
4057
4751
  // A failing refresh with no authoritative map is as non-authoritative
@@ -4091,9 +4785,38 @@ export class GithubChannel extends PollingChannelBase {
4091
4785
  if (!this.deliverToBoundSessions)
4092
4786
  return undefined;
4093
4787
  const summary = this.boundSessionByPr.get(this.prBindingKey(chatId, issueNumber));
4094
- return summary
4095
- ? { kind: 'bound-session', sessionId: summary.sessionId }
4096
- : undefined;
4788
+ if (!summary)
4789
+ return undefined;
4790
+ const role = this.boundRoleOf(summary, chatId, issueNumber);
4791
+ return {
4792
+ kind: 'bound-session',
4793
+ sessionId: summary.sessionId,
4794
+ ...(role ? { role } : {}),
4795
+ };
4796
+ }
4797
+ /**
4798
+ * The role of the entry that names THIS PR, or undefined for an untyped
4799
+ * binding. Takes the winner legacy routing already resolved, so the URL
4800
+ * parse stays within that one session's entries instead of repeating the
4801
+ * whole follower scan on a path that used to be a single Map lookup.
4802
+ */
4803
+ boundRoleOf(summary, chatId, issueNumber) {
4804
+ return this.boundPrEntryFor(summary, this.prBindingKey(chatId, issueNumber))
4805
+ ?.role;
4806
+ }
4807
+ /**
4808
+ * The entry of `summary` that names the PR behind `key`, matched the same
4809
+ * way for every candidate: the URL must parse, agree with its own number,
4810
+ * and normalize to that key. Shared so the legacy role lookup and the
4811
+ * role-aware follower scan cannot drift apart.
4812
+ */
4813
+ boundPrEntryFor(summary, key) {
4814
+ return summary.prs.find((pr) => {
4815
+ const identity = this.parsePrBindingUrl(pr.url);
4816
+ return (!!identity &&
4817
+ identity.number === pr.number &&
4818
+ this.prBindingKey(identity.chatId, identity.number) === key);
4819
+ });
4097
4820
  }
4098
4821
  /**
4099
4822
  * Pick the most-recent live follower of a PR from the full binding list,
@@ -4120,6 +4843,8 @@ export class GithubChannel extends PollingChannelBase {
4120
4843
  continue;
4121
4844
  if (roleFilter && follower.role !== roleFilter.role)
4122
4845
  continue;
4846
+ if (this.watchGateExcludes(follower.role, follower.watching))
4847
+ continue;
4123
4848
  if (!best ||
4124
4849
  (follower.summary.updatedAt ?? '') > (best.summary.updatedAt ?? '')) {
4125
4850
  best = follower;
@@ -4129,10 +4854,7 @@ export class GithubChannel extends PollingChannelBase {
4129
4854
  ? {
4130
4855
  kind: 'bound-session',
4131
4856
  sessionId: best.summary.sessionId,
4132
- // Legacy mode must stay byte-compatible even when bindings carry
4133
- // roles (a /review backfill stamps them with no map configured):
4134
- // a role here would grow a Role: line in the generic prompt.
4135
- ...(this.boundRoleAware && best.role ? { role: best.role } : {}),
4857
+ ...(best.role ? { role: best.role } : {}),
4136
4858
  }
4137
4859
  : undefined;
4138
4860
  }
@@ -4144,6 +4866,62 @@ export class GithubChannel extends PollingChannelBase {
4144
4866
  get boundRoleAware() {
4145
4867
  return this.boundSessionActions.size > 0;
4146
4868
  }
4869
+ /**
4870
+ * The active-watch gate (requireBoundWatch): a review/verify binding whose
4871
+ * session holds no active watch on THIS PR is not a delivery target.
4872
+ * Unknown watching (absent — detection failed or an older daemon) stays
4873
+ * eligible: the gate is a noise filter, fail-open. fix and untyped
4874
+ * bindings are never gated. Filtering happens at target selection only —
4875
+ * the raw binding list keeps naming excluded followers so `followed` /
4876
+ * absence semantics never mistake "bound but ineligible" for "unbound"
4877
+ * and open the irreversible public path.
4878
+ */
4879
+ watchGateExcludes(role, watching) {
4880
+ return (this.requireBoundWatch &&
4881
+ (role === 'review' || role === 'verify') &&
4882
+ watching === false);
4883
+ }
4884
+ /**
4885
+ * True when raw followers exist and the watch gate excludes EVERY one of
4886
+ * them — the only "no candidate" state the gate itself caused. A winner
4887
+ * that is merely author-excluded, or a removed binding (no followers), is
4888
+ * not this state and keeps the legacy frozen-target contract.
4889
+ */
4890
+ gateExcludedAllFollowers(chatId, issueNumber) {
4891
+ if (!this.requireBoundWatch)
4892
+ return false;
4893
+ const followers = this.boundFollowersOf(chatId, issueNumber);
4894
+ return (followers.length > 0 &&
4895
+ followers.every((f) => this.watchGateExcludes(f.role, f.watching)));
4896
+ }
4897
+ /**
4898
+ * Whether any non-channel raw binding row names a PR — the population the
4899
+ * gate can actually filter. The routing map is gate-filtered, so its
4900
+ * emptiness alone cannot prove "no bindings exist": cold-start decisions
4901
+ * must read raw presence, or a fully-ineligible snapshot stalls the lane
4902
+ * as if the sidecars were unreadable. Channel-owned rows are excluded
4903
+ * because the routing map deliberately skips them.
4904
+ */
4905
+ hasRawBoundPrs() {
4906
+ return this.lastBindings.some((b) => b.sourceType !== 'channel' && b.prs.length > 0);
4907
+ }
4908
+ /**
4909
+ * Whether the gate excluded the FROZEN delivery target itself. The
4910
+ * delivery-time retire must be about the target the event was frozen to,
4911
+ * not the whole follower set: an exempt fix/untyped target keeps the
4912
+ * legacy frozen-target contract even when some other ineligible
4913
+ * review/verify follower still lists the PR, and a removed binding (the
4914
+ * target no longer follows) keeps it too. Only a target whose own binding
4915
+ * the gate excludes retires.
4916
+ */
4917
+ frozenTargetGateExcluded(delivery, chatId, issueNumber) {
4918
+ if (!this.requireBoundWatch || delivery.kind !== 'bound-session') {
4919
+ return false;
4920
+ }
4921
+ const follower = this.boundFollowersOf(chatId, issueNumber).find((f) => f.summary.sessionId === delivery.sessionId);
4922
+ return (follower !== undefined &&
4923
+ this.watchGateExcludes(follower.role, follower.watching));
4924
+ }
4147
4925
  /**
4148
4926
  * Every non-channel follower of a PR from the full binding list, each with
4149
4927
  * the role of the entry that names THIS PR (a session may follow several
@@ -4156,15 +4934,14 @@ export class GithubChannel extends PollingChannelBase {
4156
4934
  for (const summary of this.lastBindings) {
4157
4935
  if (summary.sourceType === 'channel')
4158
4936
  continue;
4159
- const entry = summary.prs.find((pr) => {
4160
- const identity = this.parsePrBindingUrl(pr.url);
4161
- return (!!identity &&
4162
- identity.number === pr.number &&
4163
- this.prBindingKey(identity.chatId, identity.number) === key);
4164
- });
4937
+ const entry = this.boundPrEntryFor(summary, key);
4165
4938
  if (!entry)
4166
4939
  continue;
4167
- followers.push({ summary, ...(entry.role ? { role: entry.role } : {}) });
4940
+ followers.push({
4941
+ summary,
4942
+ ...(entry.role ? { role: entry.role } : {}),
4943
+ ...(entry.watching !== undefined ? { watching: entry.watching } : {}),
4944
+ });
4168
4945
  }
4169
4946
  return followers;
4170
4947
  }
@@ -4368,16 +5145,28 @@ export class GithubChannel extends PollingChannelBase {
4368
5145
  }
4369
5146
  if (!this.boundRoleAware) {
4370
5147
  const summary = this.boundSessionByPr.get(this.prBindingKey(chatId, issueNumber));
4371
- return summary
4372
- ? {
4373
- targets: [{ sessionId: summary.sessionId }],
4374
- followed: true,
4375
- }
4376
- : { targets: [], followed: false };
5148
+ if (!summary) {
5149
+ // The routing map holds only watch-eligible winners under the gate,
5150
+ // so its absence is not "unbound": raw followers may still exist
5151
+ // (all ineligible). `followed` must keep naming them, or the
5152
+ // absence gate would open the public path for a bound PR.
5153
+ return {
5154
+ targets: [],
5155
+ followed: this.requireBoundWatch &&
5156
+ this.boundFollowersOf(chatId, issueNumber).length > 0,
5157
+ };
5158
+ }
5159
+ const role = this.boundRoleOf(summary, chatId, issueNumber);
5160
+ return {
5161
+ targets: [{ sessionId: summary.sessionId, ...(role ? { role } : {}) }],
5162
+ followed: true,
5163
+ };
4377
5164
  }
4378
5165
  const followers = this.boundFollowersOf(chatId, issueNumber);
4379
5166
  const byRole = new Map();
4380
5167
  for (const follower of followers) {
5168
+ if (this.watchGateExcludes(follower.role, follower.watching))
5169
+ continue;
4381
5170
  const groupKey = follower.role ?? '';
4382
5171
  const existing = byRole.get(groupKey);
4383
5172
  if (!existing ||
@@ -4405,12 +5194,17 @@ export class GithubChannel extends PollingChannelBase {
4405
5194
  * and a role that lost its match retires privately instead of leaking
4406
5195
  * into another role's session.
4407
5196
  */
4408
- revalidateBoundTarget(delivery, chatId, issueNumber, eventClass, laneClass) {
5197
+ revalidateBoundTarget(delivery, chatId, issueNumber, eventClass, laneClass, excludeSessionIds) {
4409
5198
  if (!this.boundRoleAware) {
4410
- return this.resolveBoundDelivery(chatId, issueNumber);
5199
+ const legacy = this.resolveBoundDelivery(chatId, issueNumber);
5200
+ if (legacy && excludeSessionIds?.has(legacy.sessionId))
5201
+ return undefined;
5202
+ return legacy;
4411
5203
  }
4412
5204
  const winner = this.boundFollowersOf(chatId, issueNumber)
4413
5205
  .filter((follower) => follower.role === delivery.role)
5206
+ .filter((follower) => !this.watchGateExcludes(follower.role, follower.watching))
5207
+ .filter((follower) => !excludeSessionIds?.has(follower.summary.sessionId))
4414
5208
  .reduce((best, follower) => !best ||
4415
5209
  (follower.summary.updatedAt ?? '') > (best.summary.updatedAt ?? '')
4416
5210
  ? follower
@@ -4510,8 +5304,9 @@ export class GithubChannel extends PollingChannelBase {
4510
5304
  // removed on acceptance, so a silent cut would drop the tail from every
4511
5305
  // surface. With a matching operator template the generic workflow line
4512
5306
  // becomes a labeled trusted instruction block; the untrusted warning
4513
- // extends to the substituted values. Without one (and without a role)
4514
- // the prompt is byte-identical to the pre-template contract.
5307
+ // extends to the substituted values. Without one, a role-carrying binding
5308
+ // gets the built-in guidance for that role and an untyped binding keeps
5309
+ // the prompt byte-identical to the pre-template contract.
4515
5310
  const eventClass = this.boundEventClass(envelope);
4516
5311
  const template = resolveBoundActionTemplate(this.boundSessionActions, role, eventClass, laneClass);
4517
5312
  return buildBoundEventPrompt({
@@ -4527,6 +5322,11 @@ export class GithubChannel extends PollingChannelBase {
4527
5322
  : {}),
4528
5323
  dataLines: [identity, ...contextLines],
4529
5324
  ...(role ? { role } : {}),
5325
+ // The builder uses this only when no operator instruction resolved.
5326
+ // Role-aware targets are selected BY template match, so they always
5327
+ // carry an instruction and the guidance is inert there; the per-role
5328
+ // subscription is enforced at selection, not by a flag here.
5329
+ ...(role ? { roleGuidance: DEFAULT_BOUND_ROLE_GUIDANCE[role] } : {}),
4530
5330
  body: text,
4531
5331
  });
4532
5332
  }
@@ -4572,20 +5372,37 @@ export class GithubChannel extends PollingChannelBase {
4572
5372
  if (this.boundSnapshotTrusted &&
4573
5373
  !this.lastBindingsPartial &&
4574
5374
  !this.boundRefreshFailed) {
4575
- const current = this.revalidateBoundTarget(delivery, envelope.chatId, task.issueNumber, this.boundEventClass(envelope), this.boundLaneClass(task.dedupe));
4576
- if (current && current.sessionId !== delivery.sessionId) {
5375
+ const current = this.revalidateBoundTarget(delivery, envelope.chatId, task.issueNumber, this.boundEventClass(envelope), this.boundLaneClass(task.dedupe), task.authorExclude ? new Set(task.authorExclude) : undefined);
5376
+ // The ROLE is part of the target, not just the session: a deferred
5377
+ // legacy delivery whose binding was re-roled in the meantime must not
5378
+ // build its prompt from the frozen role, or a session that is now a
5379
+ // verifier still receives the fixer's guidance. Role-aware targets are
5380
+ // re-resolved within their own role group, so the role half is inert
5381
+ // there.
5382
+ if (current &&
5383
+ (current.sessionId !== delivery.sessionId ||
5384
+ current.role !== delivery.role)) {
4577
5385
  this.transitionInboundTask(task.id, 'running', { delivery: current });
4578
5386
  task.delivery = current;
4579
5387
  delivery = current;
4580
5388
  }
4581
- else if (!current && (isWatch || this.boundRoleAware)) {
5389
+ else if (!current &&
5390
+ (isWatch ||
5391
+ this.boundRoleAware ||
5392
+ this.frozenTargetGateExcluded(delivery, envelope.chatId, task.issueNumber))) {
4582
5393
  // On a complete snapshot with no candidate left for the task's role,
4583
5394
  // retire privately. Watch events are private-only by contract; a
4584
5395
  // role-aware COMMENT whose role lost its match (the binding's role
4585
5396
  // changed, or the operator removed the template) must not keep
4586
5397
  // injecting the obsolete role's instruction into the frozen session
4587
- // either. Legacy single-winner comments keep the frozen target —
4588
- // their public fallback contract is handled by the gone path below.
5398
+ // either. Under the watch gate a legacy comment retires too, but
5399
+ // ONLY when the gate excluded the FROZEN TARGET itself (it stopped
5400
+ // watching between claim and delivery). The decision is about the
5401
+ // target, not the follower set: an exempt fix/untyped target, a
5402
+ // merely author-excluded winner, or a REMOVED binding all keep the
5403
+ // legacy contract — the frozen target stands and the gone path below
5404
+ // owns the fallback — so the gate never changes behavior for the
5405
+ // fix/untyped sessions it exempts.
4589
5406
  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`);
4590
5407
  this.markPrivatelyRetired(task);
4591
5408
  return {
@@ -4606,6 +5423,12 @@ export class GithubChannel extends PollingChannelBase {
4606
5423
  const preflight = this.preflightInbound(envelope, {
4607
5424
  waiveGroupMention: !envelope.messageId?.startsWith('issue-body-') &&
4608
5425
  this.waivesBoundMention(envelope.chatId, envelope.senderId),
5426
+ // The comment watch delivers the channel account's own comments (the
5427
+ // notification lanes filter that login out, so this can only be the
5428
+ // watch). The sender allowlist guidance excludes that account, which
5429
+ // would otherwise retire every watched comment as preflight_rejected.
5430
+ waiveGroupSender: this.botUsername != null &&
5431
+ envelope.senderId === this.botUsername.toLowerCase(),
4609
5432
  });
4610
5433
  const admitted = typeof preflight === 'boolean' ? preflight : await preflight;
4611
5434
  if (!admitted) {
@@ -4657,6 +5480,13 @@ export class GithubChannel extends PollingChannelBase {
4657
5480
  // loop by the finite follower count even if a stale snapshot keeps
4658
5481
  // re-listing dead sessions.
4659
5482
  const goneSessions = new Set([delivery.sessionId]);
5483
+ // The comment watch withholds the comment from its author; the fallback
5484
+ // re-resolves over the followers and must honor that exclusion too, or a
5485
+ // Gone primary target would hand the comment back to its author. When no
5486
+ // non-author follower remains the loop retires privately below.
5487
+ for (const sessionId of task.authorExclude ?? []) {
5488
+ goneSessions.add(sessionId);
5489
+ }
4660
5490
  // The local `delivery` is the FIRST follower; the loop walks past it.
4661
5491
  // The terminal row must name the last one tried, or the operator opens
4662
5492
  // the workspace of a session evicted a step earlier.
@@ -4670,8 +5500,15 @@ export class GithubChannel extends PollingChannelBase {
4670
5500
  this.transitionInboundTask(task.id, 'running', { delivery: next });
4671
5501
  task.delivery = next;
4672
5502
  try {
5503
+ // Rebuild for THIS target: the legacy fallback scans every
5504
+ // follower, so it can land on a different role (or an untyped
5505
+ // binding). Reusing the first target's prompt would hand this
5506
+ // session the gone session's Role line and role guidance.
5507
+ // Role-aware fallbacks stay inside their role group, where the
5508
+ // deterministic renderer rebuilds the identical string.
5509
+ const targetPrompt = this.buildBoundSessionPrompt(envelope, next.role, this.boundLaneClass(task.dedupe));
4673
5510
  // Same event key: a different session's ring has never seen it.
4674
- await boundSessions.deliverPrompt(next.sessionId, prompt, idempotencyKey);
5511
+ await boundSessions.deliverPrompt(next.sessionId, targetPrompt, idempotencyKey);
4675
5512
  this.recordBoundDelivered(envelope, next.sessionId);
4676
5513
  return { kind: 'delivered' };
4677
5514
  }
@@ -4704,8 +5541,15 @@ export class GithubChannel extends PollingChannelBase {
4704
5541
  // public. While any role still follows the PR, the event is (or will
4705
5542
  // be) delivered privately through that role's own task; a public
4706
5543
  // reply here would duplicate it on the PR. Only zero live followers
4707
- // across every role opens the public fallback below.
4708
- if (this.boundRoleAware &&
5544
+ // across every role opens the public fallback below. The watch gate
5545
+ // applies the same rule in legacy mode — but only on a COMPLETE
5546
+ // snapshot: under a partial/failed refresh an unscanned workspace may
5547
+ // still hold an eligible follower, so the deferral block below owns
5548
+ // the event instead of a retirement on incomplete evidence.
5549
+ if ((this.boundRoleAware ||
5550
+ (this.requireBoundWatch &&
5551
+ !this.lastBindingsPartial &&
5552
+ !this.boundRefreshFailed)) &&
4709
5553
  (this.boundFollowersOf(envelope.chatId, task.issueNumber).length > 0 ||
4710
5554
  this.boundEventAlreadyDelivered(envelope))) {
4711
5555
  process.stderr.write(`[Channel:${this.name}] bound event ${envelope.messageId} lost its role's session but other roles still follow the PR or already received it; retiring without public fallback\n`);
@@ -4936,14 +5780,37 @@ export class GithubChannel extends PollingChannelBase {
4936
5780
  }
4937
5781
  return DEFAULT_PR_WATCH_LIMIT;
4938
5782
  }
5783
+ /**
5784
+ * Requests reserved for the notification lane: at or below this remaining
5785
+ * budget the watch pass yields. Clamped like prWatchLimit; a configured 0
5786
+ * is honoured (disables the gate) so an operator can opt out, while unset
5787
+ * or invalid keeps the default. Rounds up so the reserve is never silently
5788
+ * smaller than requested.
5789
+ */
5790
+ get prWatchBudgetReserve() {
5791
+ const configured = this.config
5792
+ .prWatchBudgetReserve;
5793
+ if (typeof configured === 'number' &&
5794
+ Number.isFinite(configured) &&
5795
+ configured >= 0) {
5796
+ return Math.min(Math.ceil(configured), MAX_PR_WATCH_BUDGET_RESERVE);
5797
+ }
5798
+ return DEFAULT_PR_WATCH_BUDGET_RESERVE;
5799
+ }
4939
5800
  /**
4940
5801
  * Edge-triggered state watch over the PRs bound to live sessions. Runs
4941
5802
  * inside the existing poll loop; detection is API-level and costs no model
4942
5803
  * tokens until a real transition fires.
4943
5804
  */
4944
5805
  async runPrStateWatch() {
4945
- if (!this.boundSessions || this.prWatchEvents.size === 0)
5806
+ // The comment watch is default-on with deliverToBoundSessions and is
5807
+ // independent of the state-event subscription, so an empty prWatchEvents
5808
+ // must not skip the pass while comment watching is enabled.
5809
+ const commentWatchActive = this.deliverToBoundSessions && this.prCommentWatchEnabled;
5810
+ if (!this.boundSessions ||
5811
+ (this.prWatchEvents.size === 0 && !commentWatchActive)) {
4946
5812
  return;
5813
+ }
4947
5814
  this.loadPrWatchState();
4948
5815
  const candidates = new Map();
4949
5816
  const active = new Map();
@@ -4972,9 +5839,14 @@ export class GithubChannel extends PollingChannelBase {
4972
5839
  // the PR: pruning it here would re-add the closed PR as a first
4973
5840
  // observation on the next poll (query oscillation) and lose the
4974
5841
  // terminal record. Binding retention and active polling are
4975
- // separate concerns.
5842
+ // separate concerns. A comment-only channel subscribes no state
5843
+ // event, so there is no state_change to observe and watchOnePr (the
5844
+ // only prState writer) never runs: drain on the binding's terminal
5845
+ // state alone, else merged/closed bindings would be comment-fetched
5846
+ // forever. A reopened binding flips back to open and resumes.
4976
5847
  if ((pr.state === 'merged' || pr.state === 'closed') &&
4977
- this.prWatchState.entries[key]?.prState === 'closed') {
5848
+ (this.prWatchState.entries[key]?.prState === 'closed' ||
5849
+ this.prWatchEvents.size === 0)) {
4978
5850
  continue;
4979
5851
  }
4980
5852
  const existingActive = active.get(key);
@@ -5081,9 +5953,31 @@ export class GithubChannel extends PollingChannelBase {
5081
5953
  const excluded = [...active.keys()].filter((key) => !watchedKeys.has(key));
5082
5954
  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`);
5083
5955
  }
5956
+ // One burst budget for the whole pass: after an outage every watched PR
5957
+ // can be due at once, and a per-PR cap would claim up to cap × watched-PR
5958
+ // durable tasks in a single poll. PRs that find it spent keep their cursor
5959
+ // and resume next pass.
5960
+ const commentBudget = { remaining: MAX_WATCH_COMMENTS_PER_PASS };
5084
5961
  for (const [key, candidate] of watched) {
5962
+ // Yield at the spend site, not only at the poll boundary: one pass can
5963
+ // issue several requests per watched PR, so a pass entered just above
5964
+ // the reserve would otherwise spend the whole reserve before the
5965
+ // notification lane runs. Break (not return) so the baseline observed
5966
+ // so far still reaches savePrWatchState below.
5967
+ if (this.watchBudgetExhausted()) {
5968
+ this.noteWatchBudgetLow();
5969
+ break;
5970
+ }
5085
5971
  try {
5086
- await this.watchOnePr(key, candidate.chatId, candidate.number);
5972
+ // The state observation costs a pulls.get per watched PR per poll; skip
5973
+ // it when no state event is subscribed so a comment-only channel does
5974
+ // not pay for transitions it never emits.
5975
+ if (this.prWatchEvents.size > 0) {
5976
+ await this.watchOnePr(key, candidate.chatId, candidate.number);
5977
+ }
5978
+ // Additive comment watch: isolates its own failures so a comment
5979
+ // fetch problem never skips the state transitions above.
5980
+ await this.watchPrComments(key, candidate.chatId, candidate.number, commentBudget);
5087
5981
  }
5088
5982
  catch (err) {
5089
5983
  if (isWatchPassAbortError(err)) {
@@ -5172,11 +6066,13 @@ export class GithubChannel extends PollingChannelBase {
5172
6066
  prevCiForThisHead !== 'failure' &&
5173
6067
  this.prWatchEvents.has('ci_failure')) {
5174
6068
  const failedChecks = ciResult && ciResult.failedChecks.length > 0
5175
- ? ` Failed checks: ${ciResult.failedChecks.join(', ')}.`
6069
+ ? ` Failed checks: ${ciResult.failedChecks.join(', ')}${ciResult.namesIncomplete
6070
+ ? ' (list may be incomplete: later check pages were not read)'
6071
+ : ''}.`
5176
6072
  : '';
5177
6073
  events.push({
5178
6074
  type: 'ci_failure',
5179
- summary: `CI failed on head ${headSha}.${failedChecks} Inspect the failed checks and fix or attribute the failure.`,
6075
+ summary: `CI failed on head ${headSha}.${failedChecks}`,
5180
6076
  });
5181
6077
  }
5182
6078
  // mergeable === null means GitHub is still computing; never overwrite
@@ -5190,7 +6086,7 @@ export class GithubChannel extends PollingChannelBase {
5190
6086
  this.prWatchEvents.has('merge_conflict')) {
5191
6087
  events.push({
5192
6088
  type: 'merge_conflict',
5193
- summary: `Merge conflicts detected (mergeable_state: dirty). Rebase or merge the base branch and resolve the conflicts.`,
6089
+ summary: 'Merge conflicts detected (mergeable_state: dirty).',
5194
6090
  });
5195
6091
  }
5196
6092
  const prState = pr.state;
@@ -5201,7 +6097,7 @@ export class GithubChannel extends PollingChannelBase {
5201
6097
  events.push({
5202
6098
  type: 'state_change',
5203
6099
  summary: pr.merged
5204
- ? 'The PR was merged. Wrap up any follow-up work.'
6100
+ ? 'The PR was merged.'
5205
6101
  : 'The PR was closed without merging.',
5206
6102
  });
5207
6103
  }
@@ -5220,6 +6116,11 @@ export class GithubChannel extends PollingChannelBase {
5220
6116
  ? { mergeableState: entry.mergeableState }
5221
6117
  : {}),
5222
6118
  ...(prState !== undefined ? { prState } : {}),
6119
+ ...(pr.title !== undefined
6120
+ ? { title: pr.title }
6121
+ : entry.title !== undefined
6122
+ ? { title: entry.title }
6123
+ : {}),
5223
6124
  ...(prUpdatedAt !== undefined ? { prUpdatedAt } : {}),
5224
6125
  ...(firstObservation || headChanged
5225
6126
  ? { headObservedAt: Date.now() }
@@ -5237,6 +6138,17 @@ export class GithubChannel extends PollingChannelBase {
5237
6138
  ...(!headChanged && entry.ciFiredSha !== undefined
5238
6139
  ? { ciFiredSha: entry.ciFiredSha }
5239
6140
  : {}),
6141
+ // The comment watch cursor is independent of head/CI transitions; carry
6142
+ // it through so the state baseline write does not drop it.
6143
+ ...(entry.commentBaseline !== undefined
6144
+ ? { commentBaseline: entry.commentBaseline }
6145
+ : {}),
6146
+ ...(entry.commentSince !== undefined
6147
+ ? { commentSince: entry.commentSince }
6148
+ : {}),
6149
+ ...(entry.commentLastFetchAt !== undefined
6150
+ ? { commentLastFetchAt: entry.commentLastFetchAt }
6151
+ : {}),
5240
6152
  };
5241
6153
  // Bake the PR number and detection time into every watch key. The
5242
6154
  // delivery idempotency key is chatId + messageId only, so without the
@@ -5380,6 +6292,338 @@ export class GithubChannel extends PollingChannelBase {
5380
6292
  }
5381
6293
  await this.drainPendingWatch(key, next);
5382
6294
  }
6295
+ /**
6296
+ * Bound PR comment watch (docs/design/2026-11-08-bound-pr-comment-watch.md).
6297
+ * Poll conversation + inline review comments on a bound PR and deliver each
6298
+ * new one to every bound session that did NOT post it. Unlike the
6299
+ * notification lanes this does not filter the channel's own account: a
6300
+ * comment by the same GitHub login used by a DIFFERENT session/agent must
6301
+ * reach the follower. Authorship attribution (the daemon's posted-comment
6302
+ * lookup) withholds a comment only from the session that wrote it, which is
6303
+ * what prevents a fix session's own reply from re-triggering it.
6304
+ *
6305
+ * Default-on with deliverToBoundSessions; `prCommentWatch: false` disables
6306
+ * it. Failures are isolated here so they never skip the state transitions.
6307
+ */
6308
+ async watchPrComments(key, chatId, number, budget) {
6309
+ if (!this.deliverToBoundSessions ||
6310
+ !this.prCommentWatchEnabled ||
6311
+ !this.boundSessions) {
6312
+ return;
6313
+ }
6314
+ const entry = this.prWatchState.entries[key] ?? {};
6315
+ const now = Date.now();
6316
+ const nowIso = new Date(now).toISOString();
6317
+ // First observation baselines silently (no backlog delivery), matching
6318
+ // the state-watch convention; only comments created after it are eligible.
6319
+ if (entry.commentBaseline === undefined) {
6320
+ this.prWatchState.entries[key] = {
6321
+ ...entry,
6322
+ commentBaseline: nowIso,
6323
+ commentSince: nowIso,
6324
+ commentLastFetchAt: now,
6325
+ };
6326
+ this.savePrWatchState();
6327
+ return;
6328
+ }
6329
+ if (entry.commentLastFetchAt !== undefined &&
6330
+ now - entry.commentLastFetchAt < COMMENT_RECHECK_INTERVAL_MS) {
6331
+ return;
6332
+ }
6333
+ // The burst budget is shared by every watched PR in this pass. A PR that
6334
+ // arrives after it is spent fetches nothing and keeps its cursor untouched,
6335
+ // so its tail resumes on the next pass instead of being skipped past.
6336
+ if (budget.remaining <= 0) {
6337
+ return;
6338
+ }
6339
+ const [owner, repo] = chatId.split('/');
6340
+ const since = entry.commentSince ?? entry.commentBaseline;
6341
+ let conversation = [];
6342
+ let review = [];
6343
+ try {
6344
+ // Same fail-fast rule as the state watch: a rate-limited or credential
6345
+ // answer must not sleep-retry inside the watch pass (it runs before task
6346
+ // recovery and notification intake), and a shared error aborts the pass.
6347
+ conversation = (await this.githubApi(() => this.octokit.paginate(this.octokit.rest.issues.listComments, {
6348
+ owner,
6349
+ repo,
6350
+ issue_number: number,
6351
+ since,
6352
+ per_page: 100,
6353
+ }), `listComments(comment watch ${key})`, 3, (err) => !isWatchFailFastError(err)));
6354
+ review = (await this.githubApi(() => this.octokit.paginate(this.octokit.rest.pulls.listReviewComments, {
6355
+ owner,
6356
+ repo,
6357
+ pull_number: number,
6358
+ since,
6359
+ per_page: 100,
6360
+ }), `listReviewComments(comment watch ${key})`, 3, (err) => !isWatchFailFastError(err)));
6361
+ }
6362
+ catch (err) {
6363
+ // A shared credential/rate-limit error condemns the whole pass: hand it
6364
+ // to the outer watch loop's abort logic instead of swallowing it here.
6365
+ if (isWatchPassAbortError(err))
6366
+ throw err;
6367
+ // Per-PR failure: advance the fetch clock so a persistent endpoint
6368
+ // problem retries on the interval, not every poll, but keep commentSince
6369
+ // so no comment is skipped past without a delivery attempt.
6370
+ this.prWatchState.entries[key] = {
6371
+ ...(this.prWatchState.entries[key] ?? {}),
6372
+ commentLastFetchAt: now,
6373
+ };
6374
+ this.savePrWatchState();
6375
+ process.stderr.write(`[Channel:${this.name}] comment watch fetch failed for ${key}, continuing without comments this pass: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
6376
+ return;
6377
+ }
6378
+ // Record created_at per fetched comment exactly as the notification lanes'
6379
+ // fetch does, so the watch's dispatchedComments keys carry a time and stay
6380
+ // evictable once older than the cursor. Without a time a key is treated as
6381
+ // protected and the ring would grow monotonically for the daemon's life.
6382
+ const commentTimes = (this.cursor.dispatchedCommentTimes ??= {});
6383
+ for (const comment of [...conversation, ...review]) {
6384
+ if (comment.created_at) {
6385
+ commentTimes[comment.node_id || String(comment.id)] =
6386
+ comment.created_at;
6387
+ }
6388
+ }
6389
+ const { targets } = this.resolveBoundTargets(chatId, number, 'comment', 'comment');
6390
+ // A partial/untrusted snapshot may omit bound sessions, so the target list
6391
+ // is not a complete enumeration: retiring a comment as "no target" (or
6392
+ // delivering to the visible subset and advancing past it) would skip it
6393
+ // past a session in the unscanned workspace, and no other lane can deliver
6394
+ // a same-account comment. Defer rather than consume (fail-closed, as the
6395
+ // state watch): keep commentSince, advance only the fetch clock, and let a
6396
+ // trustworthy pass re-evaluate.
6397
+ if (!this.boundSnapshotTrusted ||
6398
+ this.lastBindingsPartial ||
6399
+ this.boundRefreshFailed) {
6400
+ this.prWatchState.entries[key] = {
6401
+ ...(this.prWatchState.entries[key] ?? {}),
6402
+ commentLastFetchAt: now,
6403
+ };
6404
+ this.savePrWatchState();
6405
+ return;
6406
+ }
6407
+ const baseline = entry.commentBaseline;
6408
+ const alreadyDispatched = (commentKey) => this.cursor.dispatchedComments?.includes(commentKey) === true;
6409
+ const candidates = [];
6410
+ const threadId = `pr:${number}`;
6411
+ const metadata = `${this.buildMetadata(chatId, threadId, entry.title ?? '')}\nTrigger: comment.`;
6412
+ const renderBody = (body) => {
6413
+ const display = sanitizeDisplayText((body ?? '').trim());
6414
+ const total = Array.from(display).length;
6415
+ // A watch delivery carries ONE comment, so it uses the bound prompt's
6416
+ // body ceiling, not the aggregate lane's per-comment batch budget (400):
6417
+ // cutting a single finding at 400 code points drops the actionable steps
6418
+ // past the cut. The bound prompt caps the final body at the same value.
6419
+ return total > BOUND_PROMPT_BODY_MAX_CODE_POINTS
6420
+ ? `${truncateCodePoints(display, BOUND_PROMPT_BODY_MAX_CODE_POINTS)}… [comment truncated: ${total - BOUND_PROMPT_BODY_MAX_CODE_POINTS} more characters]`
6421
+ : display;
6422
+ };
6423
+ // The watch closes the SAME-account gap: GitHub sends the channel account no
6424
+ // notification for its own comments, so the notification lanes never see
6425
+ // them. Comments by any OTHER account do produce notifications and are
6426
+ // delivered by the notification lanes under the thread's own reason and
6427
+ // role templates. Watching them here too would pre-empt those lanes: the
6428
+ // watch resolves the narrower `comment` class, and consuming the shared
6429
+ // dedupe key after reaching only a subset of roles would starve the rest
6430
+ // (e.g. fix:comment delivered, verify:mention lost). Leave other-account
6431
+ // comments to the lanes.
6432
+ const botLogin = this.botUsername?.toLowerCase();
6433
+ const sameAccount = (login) => botLogin !== undefined && login?.toLowerCase() === botLogin;
6434
+ for (const comment of conversation) {
6435
+ const commentKey = comment.node_id || String(comment.id);
6436
+ if (!sameAccount(comment.user?.login) ||
6437
+ !comment.created_at ||
6438
+ comment.created_at <= baseline ||
6439
+ alreadyDispatched(commentKey)) {
6440
+ continue;
6441
+ }
6442
+ const author = comment.user?.login || 'unknown';
6443
+ const url = `${this.webOrigin}/${chatId}/pull/${number}#issuecomment-${comment.id}`;
6444
+ candidates.push({
6445
+ key: commentKey,
6446
+ attrKey: `ic:${comment.id}`,
6447
+ createdAt: comment.created_at,
6448
+ envelope: {
6449
+ channelName: this.name,
6450
+ senderId: author.toLowerCase(),
6451
+ senderName: author,
6452
+ chatId,
6453
+ threadId,
6454
+ messageId: commentKey,
6455
+ text: `New comment by @${author}:\n${renderBody(comment.body)}\nComment: ${url}`,
6456
+ isGroup: true,
6457
+ isMentioned: true,
6458
+ isReplyToBot: false,
6459
+ metadata,
6460
+ },
6461
+ });
6462
+ }
6463
+ for (const comment of review) {
6464
+ const commentKey = comment.node_id || String(comment.id);
6465
+ if (!sameAccount(comment.user?.login) ||
6466
+ !comment.created_at ||
6467
+ comment.created_at <= baseline ||
6468
+ alreadyDispatched(commentKey)) {
6469
+ continue;
6470
+ }
6471
+ const author = comment.user?.login || 'unknown';
6472
+ const url = comment.html_url ||
6473
+ `${this.webOrigin}/${chatId}/pull/${number}#discussion_r${comment.id}`;
6474
+ const line = comment.line ?? comment.original_line;
6475
+ const location = `File: ${comment.path ?? '?'}${line != null ? ` (line ${line}${comment.side ? `, ${comment.side}` : ''})` : ''}`;
6476
+ candidates.push({
6477
+ key: commentKey,
6478
+ attrKey: `rc:${comment.id}`,
6479
+ createdAt: comment.created_at,
6480
+ envelope: {
6481
+ channelName: this.name,
6482
+ senderId: author.toLowerCase(),
6483
+ senderName: author,
6484
+ chatId,
6485
+ threadId,
6486
+ messageId: commentKey,
6487
+ text: `New inline review comment by @${author}:\n${location}\n${renderBody(comment.body)}\nComment: ${url}`,
6488
+ isGroup: true,
6489
+ isMentioned: true,
6490
+ isReplyToBot: false,
6491
+ metadata,
6492
+ },
6493
+ });
6494
+ }
6495
+ candidates.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
6496
+ const commitCursor = (newSince) => {
6497
+ // GitHub compares `since` at whole-second granularity while nowIso carries
6498
+ // milliseconds: a comment created later in the same second as the fetch
6499
+ // snapshot would be excluded from every later fetch. Floor the cursor to
6500
+ // the second so that whole second is re-listed next pass (anything already
6501
+ // delivered is deduped), never skipped past.
6502
+ const floored = new Date(Math.floor(Date.parse(newSince) / 1000) * 1000).toISOString();
6503
+ this.prWatchState.entries[key] = {
6504
+ ...(this.prWatchState.entries[key] ?? {}),
6505
+ commentSince: floored,
6506
+ commentLastFetchAt: now,
6507
+ };
6508
+ this.savePrWatchState();
6509
+ };
6510
+ // No new comments: advance the cursor without any attribution round-trip.
6511
+ if (candidates.length === 0) {
6512
+ commitCursor(nowIso);
6513
+ return;
6514
+ }
6515
+ // Look up posted comments only now that there is something to deliver, so a
6516
+ // quiet pass costs no serve round-trips. A comment is withheld only from the
6517
+ // session that wrote it. Query EVERY bound follower, not just the resolved
6518
+ // targets: the delivery-time Gone fallback re-resolves over the followers,
6519
+ // so the exclusion must also cover a same-role author that is not the
6520
+ // primary target, or the fallback would hand the comment back to it.
6521
+ const followerIds = new Set(targets.map((target) => target.sessionId));
6522
+ for (const follower of this.boundFollowersOf(chatId, number)) {
6523
+ followerIds.add(follower.summary.sessionId);
6524
+ }
6525
+ const postedBySession = new Map();
6526
+ for (const sessionId of followerIds) {
6527
+ const lookup = this.boundSessions.postedCommentIds;
6528
+ const ids = lookup
6529
+ ? await lookup
6530
+ .call(this.boundSessions, sessionId)
6531
+ .catch(() => new Set())
6532
+ : new Set();
6533
+ postedBySession.set(sessionId, ids);
6534
+ }
6535
+ const excludeFor = (candidate) => {
6536
+ const exclude = new Set();
6537
+ for (const sessionId of followerIds) {
6538
+ if (postedBySession.get(sessionId)?.has(candidate.attrKey)) {
6539
+ exclude.add(sessionId);
6540
+ }
6541
+ }
6542
+ return exclude;
6543
+ };
6544
+ // Exclude author-owned comments BEFORE the batch cap. They record no dedupe
6545
+ // key, so if they occupied batch slots a run of same-second self-authored
6546
+ // comments would re-fill every batch and the capped cursor would never reach
6547
+ // the tail. Filtering them out keeps the cap and the cursor progressing over
6548
+ // deliverable comments; the excluded ones are simply advanced past.
6549
+ // A gate-only exclusion (every follower watch-ineligible) additionally
6550
+ // earns ONE cycle of grace: a watch installed after this pass's snapshot
6551
+ // was fetched surfaces on the next pass, and the comment it was installed
6552
+ // to catch must not be skipped past with the cursor. The first such
6553
+ // comment holds the cursor before itself; the second consumes it.
6554
+ const gateBlocked = targets.length === 0 && this.gateExcludedAllFollowers(chatId, number);
6555
+ let gateHoldCursor;
6556
+ const deliverable = [];
6557
+ for (const candidate of candidates) {
6558
+ const exclude = excludeFor(candidate);
6559
+ if (targets.some((target) => !exclude.has(target.sessionId))) {
6560
+ this.gateGraceClear(candidate.key);
6561
+ deliverable.push(candidate);
6562
+ continue;
6563
+ }
6564
+ // A comment every raw follower authored can never be delivered, no
6565
+ // matter what watch is installed: authorship, not the gate, is the
6566
+ // cause. Skip the grace (holding it would be futile and would suppress
6567
+ // its only journal row) and journal it as comment_watch_no_target.
6568
+ const gateCaused = gateBlocked && exclude.size !== followerIds.size;
6569
+ if (gateCaused && this.gateGraceShouldHold(candidate.key)) {
6570
+ gateHoldCursor ??= candidate.createdAt;
6571
+ continue;
6572
+ }
6573
+ this.gateGraceClear(candidate.key);
6574
+ // No session is left to receive this comment. The notification lanes
6575
+ // cannot see it either (same account => no notification), so this skip
6576
+ // row is the comment's only journal trace — record it instead of
6577
+ // consuming silently, naming the gate when the gate is the cause.
6578
+ this.recordChannelEvent({
6579
+ type: 'inbound',
6580
+ outcome: 'skipped',
6581
+ reason: gateCaused ? 'bound_watch_required' : 'comment_watch_no_target',
6582
+ repository: chatId,
6583
+ thread: threadId,
6584
+ number,
6585
+ messageId: candidate.key,
6586
+ });
6587
+ }
6588
+ if (deliverable.length === 0) {
6589
+ commitCursor(gateHoldCursor ?? nowIso);
6590
+ return;
6591
+ }
6592
+ // Cap the burst against the pass-wide budget shared by all watched PRs;
6593
+ // the cursor resumes before the last processed comment when capped so the
6594
+ // tail drains over subsequent passes.
6595
+ const batch = deliverable.slice(0, Math.min(MAX_WATCH_COMMENTS_PER_PASS, budget.remaining));
6596
+ budget.remaining -= batch.length;
6597
+ const capped = deliverable.length > batch.length;
6598
+ let allSettled = true;
6599
+ for (const candidate of batch) {
6600
+ // Private-only: never answered in public. The stable comment id dedupes
6601
+ // across polls. Only same-account comments reach this loop (see the
6602
+ // candidate filter), and those generate no GitHub notification, so
6603
+ // recording the shared key cannot pre-empt a notification lane.
6604
+ const settled = await this.dispatchEnvelope(candidate.envelope, number, { dispatchedComments: [candidate.key] }, true, excludeFor(candidate));
6605
+ if (!settled)
6606
+ allSettled = false;
6607
+ }
6608
+ if (!allSettled) {
6609
+ // A dispatch returned false without a durable claim (e.g. the publication
6610
+ // audit is unreadable, which freezes the notification cursor but not this
6611
+ // independent one). Keep commentSince so the next pass re-fetches and
6612
+ // retries; dispatchedComments dedupes anything already claimed. Advancing
6613
+ // here would skip the comment past with no task and no re-delivery chance.
6614
+ commitCursor(since);
6615
+ }
6616
+ else {
6617
+ // Resume just before the last processed comment when capped so the
6618
+ // unprocessed tail is re-fetched next pass (a second of overlap is
6619
+ // deduped, never lost). A gate-held comment never reaches here: a hold
6620
+ // implies an empty deliverable, which returned above.
6621
+ const last = batch[batch.length - 1];
6622
+ commitCursor(capped
6623
+ ? new Date(Date.parse(last.createdAt) - 1000).toISOString()
6624
+ : nowIso);
6625
+ }
6626
+ }
5383
6627
  /**
5384
6628
  * Deliver queued watch events. Order per event: claim the inbound task
5385
6629
  * (durable), move the key from pending to fired (durable), then run the
@@ -5442,8 +6686,19 @@ export class GithubChannel extends PollingChannelBase {
5442
6686
  const current = this.resolveBoundDelivery(pending.envelope.chatId, pending.issueNumber);
5443
6687
  if (current) {
5444
6688
  delivery = current;
6689
+ this.gateGraceClear(pending.key);
5445
6690
  }
5446
6691
  else {
6692
+ // One grace cycle when the gate is the cause: a watch installed
6693
+ // after the snapshot was fetched surfaces on the next refresh, and
6694
+ // the transition it was installed to catch must not retire first.
6695
+ // The grace is scoped to the snapshot generation, so a second drain
6696
+ // of the same PR in the same poll does not spend it.
6697
+ if (this.gateExcludedAllFollowers(pending.envelope.chatId, pending.issueNumber) &&
6698
+ this.gateGraceShouldHold(pending.key)) {
6699
+ return;
6700
+ }
6701
+ this.gateGraceClear(pending.key);
5447
6702
  process.stderr.write(`[Channel:${this.name}] watch event ${pending.key} has no bound candidate left; retiring without public fallback\n`);
5448
6703
  const pendingBefore = entry.pending;
5449
6704
  entry.pending = entry.pending.slice(1);
@@ -5490,6 +6745,15 @@ export class GithubChannel extends PollingChannelBase {
5490
6745
  continue;
5491
6746
  }
5492
6747
  }
6748
+ // A partial/failed scan keeps the frozen target — which may be absent
6749
+ // because the gate filtered the map at detection time. Give that state
6750
+ // the same one grace cycle before claiming a task that would retire
6751
+ // targetless at run time.
6752
+ if (delivery === undefined &&
6753
+ this.gateExcludedAllFollowers(pending.envelope.chatId, pending.issueNumber) &&
6754
+ this.gateGraceShouldHold(pending.key)) {
6755
+ return;
6756
+ }
5493
6757
  let task;
5494
6758
  try {
5495
6759
  task = this.claimInboundTask(pending.envelope, pending.issueNumber, {}, delivery);
@@ -5573,12 +6837,22 @@ export class GithubChannel extends PollingChannelBase {
5573
6837
  this.boundRefreshFailed) {
5574
6838
  return;
5575
6839
  }
6840
+ // One grace cycle when the gate is the cause: a watch installed
6841
+ // after the snapshot was fetched surfaces on the next refresh. The
6842
+ // grace is scoped to the snapshot generation (a second drain of the
6843
+ // same PR in the same poll must not spend it).
6844
+ if (this.gateExcludedAllFollowers(pending.envelope.chatId, pending.issueNumber) &&
6845
+ this.gateGraceShouldHold(pending.key)) {
6846
+ return;
6847
+ }
6848
+ this.gateGraceClear(pending.key);
5576
6849
  process.stderr.write(`[Channel:${this.name}] watch event ${pending.key} has no matching role target; retiring without public fallback\n`);
5577
6850
  entry.pending = entry.pending.slice(1);
5578
6851
  this.prWatchState.entries[key] = entry;
5579
6852
  this.savePrWatchState();
5580
6853
  continue;
5581
6854
  }
6855
+ this.gateGraceClear(pending.key);
5582
6856
  const tasksBefore = this.readInboundTasks();
5583
6857
  const knownIds = new Set(tasksBefore.map((task) => task.id));
5584
6858
  const claimable = targets.filter((target) => !tasksBefore.some((task) => this.isRecoverableInboundTask(task) &&
@@ -5644,59 +6918,97 @@ export class GithubChannel extends PollingChannelBase {
5644
6918
  }
5645
6919
  }
5646
6920
  async fetchCiAggregate(owner, repo, sha) {
5647
- const checkRuns = (await this.githubApi(() => this.octokit.paginate(this.octokit.rest.checks.listForRef, {
5648
- owner,
5649
- repo,
5650
- ref: sha,
5651
- per_page: 100,
5652
- }), `checks.listForRef(${sha})`, 3, (err) => !isWatchFailFastError(err)));
5653
- let sawFailure = false;
5654
- let sawPending = false;
5655
- let sawSuccess = false;
5656
- const failedChecks = [];
5657
- for (const run of checkRuns) {
5658
- if (run.status !== 'completed') {
5659
- sawPending = true;
5660
- continue;
5661
- }
5662
- if (run.conclusion === 'failure' ||
5663
- run.conclusion === 'timed_out' ||
5664
- run.conclusion === 'action_required' ||
5665
- // A workflow that fails at startup (e.g. a broken workflow file)
5666
- // never runs a single job; missing it would certify a broken CI as
5667
- // 'none' or even 'success'. A deliberate SUBSET of core's
5668
- // FAILING_CHECK_RUN_CONCLUSIONS: core also counts cancelled/stale,
5669
- // which the design excludes as concurrency-cancel noise (a
5670
- // superseded run's cancellation is not a CI failure of this head).
5671
- run.conclusion === 'startup_failure') {
5672
- sawFailure = true;
5673
- if (typeof run.name === 'string' &&
5674
- run.name.length > 0 &&
5675
- failedChecks.length < MAX_REPORTED_FAILED_CHECKS) {
5676
- failedChecks.push(run.name);
6921
+ // The observation is accumulated per ATTEMPT, inside the retried
6922
+ // closure: githubApi retries the whole pagination, and state carried
6923
+ // over from an attempt that died on a later page would let its partial
6924
+ // pending/success readings decide the retry's aggregate.
6925
+ const checks = await this.githubApi(async () => {
6926
+ let sawFailure = false;
6927
+ let sawPending = false;
6928
+ let sawSuccess = false;
6929
+ let namesIncomplete = false;
6930
+ const failedChecks = [];
6931
+ await this.octokit.paginate(this.octokit.rest.checks.listForRef, {
6932
+ owner,
6933
+ repo,
6934
+ ref: sha,
6935
+ per_page: 100,
6936
+ }, (response, done) => {
6937
+ // Octokit's conclusion union omits 'startup_failure', which the
6938
+ // API does return and this aggregate must count as a failure.
6939
+ const runs = response.data;
6940
+ for (const run of runs) {
6941
+ if (run.status !== 'completed') {
6942
+ sawPending = true;
6943
+ continue;
6944
+ }
6945
+ if (run.conclusion === 'failure' ||
6946
+ run.conclusion === 'timed_out' ||
6947
+ run.conclusion === 'action_required' ||
6948
+ // A workflow that fails at startup (e.g. a broken workflow
6949
+ // file) never runs a single job; missing it would certify a
6950
+ // broken CI as 'none' or even 'success'. A deliberate SUBSET
6951
+ // of core's FAILING_CHECK_RUN_CONCLUSIONS: core also counts
6952
+ // cancelled/stale, which the design excludes as
6953
+ // concurrency-cancel noise (a superseded run's cancellation
6954
+ // is not a CI failure of this head).
6955
+ run.conclusion === 'startup_failure') {
6956
+ sawFailure = true;
6957
+ if (typeof run.name === 'string' &&
6958
+ run.name.length > 0 &&
6959
+ failedChecks.length < MAX_REPORTED_FAILED_CHECKS) {
6960
+ failedChecks.push(run.name);
6961
+ }
6962
+ }
6963
+ else if (run.conclusion === 'success') {
6964
+ sawSuccess = true;
6965
+ }
6966
+ }
6967
+ // A failure decides the aggregate: no later page can overturn
6968
+ // it, so stop paging instead of spending one request per page
6969
+ // of a head that carries hundreds of check runs. Whole pages are
6970
+ // still read, so a head whose failures all fit in the pages read
6971
+ // reports the same names as before.
6972
+ if (sawFailure) {
6973
+ // Only unread pages make the list partial: stopping on the
6974
+ // LAST page read everything. The iterator follows this same
6975
+ // header, so its presence is exactly "a page went unread".
6976
+ namesIncomplete = /<[^<>]+>;\s*rel="next"/.test(response.headers?.link ?? '');
6977
+ done();
6978
+ }
6979
+ return [];
6980
+ });
6981
+ return {
6982
+ sawFailure,
6983
+ sawPending,
6984
+ sawSuccess,
6985
+ failedChecks,
6986
+ namesIncomplete,
6987
+ };
6988
+ }, `checks.listForRef(${sha})`, 3, (err) => !isWatchFailFastError(err));
6989
+ let { sawFailure, sawPending, sawSuccess } = checks;
6990
+ const { failedChecks, namesIncomplete } = checks;
6991
+ // A check run already failed, so the combined status could only confirm
6992
+ // 'failure' — skip the request rather than pay for a decided aggregate.
6993
+ if (!sawFailure) {
6994
+ const { data: combined } = await this.githubApi(() => this.octokit.rest.repos.getCombinedStatusForRef({
6995
+ owner,
6996
+ repo,
6997
+ ref: sha,
6998
+ }), `combinedStatus(${sha})`, 3, (err) => !isWatchFailFastError(err));
6999
+ // GitHub returns {state:"pending", total_count:0, statuses:[]} for a
7000
+ // SHA with no legacy commit statuses; an empty combined status must not
7001
+ // count as active CI (it would keep every poll re-fetching forever).
7002
+ if (combined.total_count > 0) {
7003
+ if (combined.state === 'failure' || combined.state === 'error') {
7004
+ sawFailure = true;
7005
+ }
7006
+ else if (combined.state === 'pending') {
7007
+ sawPending = true;
7008
+ }
7009
+ else {
7010
+ sawSuccess = true;
5677
7011
  }
5678
- }
5679
- else if (run.conclusion === 'success') {
5680
- sawSuccess = true;
5681
- }
5682
- }
5683
- const { data: combined } = await this.githubApi(() => this.octokit.rest.repos.getCombinedStatusForRef({
5684
- owner,
5685
- repo,
5686
- ref: sha,
5687
- }), `combinedStatus(${sha})`, 3, (err) => !isWatchFailFastError(err));
5688
- // GitHub returns {state:"pending", total_count:0, statuses:[]} for a
5689
- // SHA with no legacy commit statuses; an empty combined status must not
5690
- // count as active CI (it would keep every poll re-fetching forever).
5691
- if (combined.total_count > 0) {
5692
- if (combined.state === 'failure' || combined.state === 'error') {
5693
- sawFailure = true;
5694
- }
5695
- else if (combined.state === 'pending') {
5696
- sawPending = true;
5697
- }
5698
- else {
5699
- sawSuccess = true;
5700
7012
  }
5701
7013
  }
5702
7014
  const aggregate = sawFailure
@@ -5706,7 +7018,7 @@ export class GithubChannel extends PollingChannelBase {
5706
7018
  : sawSuccess
5707
7019
  ? 'success'
5708
7020
  : 'none';
5709
- return { aggregate, failedChecks };
7021
+ return { aggregate, failedChecks, namesIncomplete };
5710
7022
  }
5711
7023
  async markNotificationsAsRead(lastReadAt) {
5712
7024
  await this.githubApi(() => this.octokit.rest.activity.markNotificationsAsRead({