@qwen-code/channel-github 0.27.0 → 0.27.1

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, 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,31 @@ 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.prCommentWatch !== undefined &&
507
+ typeof config.prCommentWatch !== 'boolean') {
508
+ return `[Channel:${channelName}] prCommentWatch must be a boolean.`;
509
+ }
510
+ // No deliverToBoundSessions dependency: prCommentWatch is default-on, so the
511
+ // editor emits it even for channels without bound delivery. It is inert there
512
+ // (the watch is gated on deliverToBoundSessions at runtime), not an error.
513
+ if (config.prWatchBudgetReserve !== undefined &&
514
+ config.deliverToBoundSessions !== true) {
515
+ return `prWatchBudgetReserve for channel ${channelName} requires deliverToBoundSessions: true.`;
516
+ }
517
+ // The descriptor's only lower bound is exclusiveMinimum: -1 (so 0 can
518
+ // disable the gate), which also admits values in (-1, 0). The getter would
519
+ // silently fall back to the default for a negative, so reject it here
520
+ // instead of letting a saved value mean something other than it says.
521
+ // Positive fractions stay legal: the getter rounds them UP, which is the
522
+ // documented behaviour, not a silent fallback.
523
+ if (config.prWatchBudgetReserve !== undefined) {
524
+ const reserve = config.prWatchBudgetReserve;
525
+ if (typeof reserve !== 'number' ||
526
+ !Number.isFinite(reserve) ||
527
+ reserve < 0) {
528
+ return `prWatchBudgetReserve for channel ${channelName} must be a non-negative number.`;
529
+ }
530
+ }
449
531
  try {
450
532
  normalizePrWatchEvents(config, channelName);
451
533
  normalizeBoundSessionActions(config, channelName);
@@ -602,9 +684,12 @@ function isNoReplySentinel(text) {
602
684
  }
603
685
  /** GitHub's wording for a secondary (abuse) rate limit. */
604
686
  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'];
687
+ /**
688
+ * A rate-limit header value (remaining count or reset epoch) as a
689
+ * non-negative integer; absent or malformed is undefined. GitHub sends
690
+ * these as decimal strings; a number is accepted for tests and proxies.
691
+ */
692
+ function parseRateLimitCount(value) {
608
693
  if (typeof value === 'number') {
609
694
  return Number.isInteger(value) && value >= 0 ? value : undefined;
610
695
  }
@@ -612,6 +697,10 @@ function rateLimitRemaining(err) {
612
697
  ? Number(value)
613
698
  : undefined;
614
699
  }
700
+ /** `x-ratelimit-remaining` as a count; absent or malformed is undefined. */
701
+ function rateLimitRemaining(err) {
702
+ return parseRateLimitCount(err.response?.headers?.['x-ratelimit-remaining']);
703
+ }
615
704
  /**
616
705
  * A 403 or 429 carrying one of GitHub's rate-limit signals: an exhausted
617
706
  * budget, `retry-after`, or the secondary-limit wording. GitHub sends a
@@ -751,6 +840,12 @@ export class GithubChannel extends PollingChannelBase {
751
840
  reasonFilter = null;
752
841
  repoFilter = null;
753
842
  deliverToBoundSessions = false;
843
+ /**
844
+ * Bound PR comment watch: poll conversation + inline review comments and
845
+ * deliver each to every bound session that did not post it. Default-on
846
+ * with deliverToBoundSessions; `prCommentWatch: false` disables it.
847
+ */
848
+ prCommentWatchEnabled = true;
754
849
  prWatchEvents = new Set();
755
850
  /**
756
851
  * Operator instruction templates keyed by the closed bound-action
@@ -841,6 +936,38 @@ export class GithubChannel extends PollingChannelBase {
841
936
  * recovery edge.
842
937
  */
843
938
  watchReconcileBlockedCause;
939
+ /**
940
+ * Last REST budget seen on a SUCCESSFUL response, recorded by the request
941
+ * hook regardless of the call's return shape. Undefined until the first
942
+ * response carries the header. Gates the watch pass so background polling
943
+ * cannot starve the interactive notification lane.
944
+ */
945
+ lastRateLimitRemaining;
946
+ /**
947
+ * Reset time (epoch ms) of the window lastRateLimitRemaining belongs to.
948
+ * Once passed, the reading is stale and must not gate the watch: a low
949
+ * count from a window that has already reset would otherwise starve the
950
+ * watch until the next successful response overwrites it.
951
+ */
952
+ lastRateLimitResetAt;
953
+ /**
954
+ * Whether the watch pass is currently skipped for low budget. Edge-triggered
955
+ * journaling (the watchReconcileBlockedCause pattern): a permanent low-budget
956
+ * condition journalled once on the edge, not every poll, so it cannot rotate
957
+ * the useful rows out of the timeline. Cleared on the recovery edge.
958
+ */
959
+ watchBudgetLow = false;
960
+ /**
961
+ * A `watch_budget_low` row has been journaled and its episode has not been
962
+ * closed by a recovery row yet. Tracked apart from watchBudgetLow because
963
+ * the two answer different questions: the skip latch is released when the
964
+ * watch stops being eligible (so a later starvation journals a fresh skip),
965
+ * but the episode stays open until the BUDGET recovers — otherwise a budget
966
+ * that recovers during an ineligible window would never get its recovery
967
+ * row. In-memory by design: a restart mid-episode leaves no recovery row,
968
+ * which the user guide states.
969
+ */
970
+ watchBudgetEpisodeOpen = false;
844
971
  /**
845
972
  * Consecutive binding-refresh failures since the last success. While no
846
973
  * snapshot has ever succeeded, the cold-start gate defers the comment lane,
@@ -915,6 +1042,21 @@ export class GithubChannel extends PollingChannelBase {
915
1042
  * nothing new (a repeated skip) are written once per window.
916
1043
  */
917
1044
  windowJournalKeys = new Set();
1045
+ /**
1046
+ * The comments this window has read that were created in the latest second
1047
+ * it has read a comment from, and the threads it has listed whose
1048
+ * notification is of the latest second it has listed one from. When the
1049
+ * window is marked read, those of the new cursor's second become
1050
+ * GithubCursor.boundaryComments.
1051
+ */
1052
+ windowLatestComments;
1053
+ windowLatestThreads;
1054
+ /**
1055
+ * Threads of late notifications (see `late` in pollOnce) this window has
1056
+ * read: the comments of the cursor's second GitHub listed then were read,
1057
+ * so a later failure reading one again in the window is treated as stale.
1058
+ */
1059
+ windowLateThreadsRead = new Set();
918
1060
  constructor(name, config, bridge, options) {
919
1061
  config.instructions = [
920
1062
  config.instructions?.trim(),
@@ -986,6 +1128,23 @@ export class GithubChannel extends PollingChannelBase {
986
1128
  }
987
1129
  base.dispatchedCommentTimes = clean;
988
1130
  }
1131
+ // A record that does not belong to the cursor, or that cannot be read,
1132
+ // is dropped: the window then starts after the cursor's second, as it
1133
+ // did before the record existed, and nothing it read is read again.
1134
+ const boundary = base.boundaryComments;
1135
+ if (boundary !== undefined) {
1136
+ const record = boundary;
1137
+ const isKeyList = (list) => Array.isArray(list) &&
1138
+ list.length <= MAX_BOUNDARY_COMMENTS &&
1139
+ list.every((key) => typeof key === 'string');
1140
+ if (!record ||
1141
+ typeof record !== 'object' ||
1142
+ record.at !== base.lastProcessedAt ||
1143
+ !isKeyList(record.keys) ||
1144
+ !isKeyList(record.threads)) {
1145
+ delete base.boundaryComments;
1146
+ }
1147
+ }
989
1148
  return base;
990
1149
  }
991
1150
  async connect() {
@@ -999,6 +1158,7 @@ export class GithubChannel extends PollingChannelBase {
999
1158
  this.prWatchEvents = normalizePrWatchEvents(cfg, this.name);
1000
1159
  this.boundSessionActions = normalizeBoundSessionActions(cfg, this.name);
1001
1160
  this.deliverToBoundSessions = cfg.deliverToBoundSessions === true;
1161
+ this.prCommentWatchEnabled = cfg.prCommentWatch !== false;
1002
1162
  if (this.deliverToBoundSessions) {
1003
1163
  this.loadBoundDeliveredRing();
1004
1164
  }
@@ -1033,6 +1193,16 @@ export class GithubChannel extends PollingChannelBase {
1033
1193
  ? { request: { agent: new HttpsProxyAgent(this.proxy) } }
1034
1194
  : {}),
1035
1195
  });
1196
+ // One choke point for the success-path budget: the wrap sees the response
1197
+ // headers on every request, including each page of a paginate call,
1198
+ // independent of what fn() returns (array vs {data,headers}). It records
1199
+ // the last known remaining budget so the watch gate can protect the
1200
+ // notification lane before a request is ever rejected.
1201
+ this.octokit.hook.wrap('request', async (request, options) => {
1202
+ const response = await request(options);
1203
+ this.recordRateLimitBudget(response.headers);
1204
+ return response;
1205
+ });
1036
1206
  try {
1037
1207
  const { data } = await this.octokit.rest.users.getAuthenticated();
1038
1208
  this.botUsername = data.login;
@@ -1640,14 +1810,45 @@ export class GithubChannel extends PollingChannelBase {
1640
1810
  }
1641
1811
  // The watch pass runs before generic recovery so detection cannot race
1642
1812
  // recovery over the same task; pending events were already reconciled.
1643
- if (this.prWatchEvents.size > 0 && !this.boundRefreshFailed) {
1644
- try {
1645
- await this.runPrStateWatch();
1813
+ // The comment watch is independent of the state-event subscription, so an
1814
+ // empty prWatchEvents still runs the pass while comment watching is on.
1815
+ const commentWatchActive = this.deliverToBoundSessions && this.prCommentWatchEnabled;
1816
+ if ((this.prWatchEvents.size > 0 || commentWatchActive) &&
1817
+ !this.boundRefreshFailed) {
1818
+ // Protect the interactive notification lane: the watch runs first and
1819
+ // is best-effort edge-triggered detection, so when the last known REST
1820
+ // budget is at or below the reserve, skip the pass this poll rather
1821
+ // than spend the budget a human mention needs. Skipping delays
1822
+ // detection of a state that persists (baselines and pending queues are
1823
+ // durable); a transition that appears and reverts between passes is
1824
+ // not observed. The reactive isWatchFailFastError backstop still
1825
+ // covers a wrong estimate. The gate covers the comment fetches too:
1826
+ // they run inside the same pass and spend the same budget.
1827
+ if (this.watchBudgetExhausted()) {
1828
+ this.noteWatchBudgetLow();
1646
1829
  }
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`);
1830
+ else {
1831
+ this.watchBudgetLow = false;
1832
+ this.closeWatchBudgetEpisode();
1833
+ try {
1834
+ await this.runPrStateWatch();
1835
+ }
1836
+ catch (err) {
1837
+ process.stderr.write(`[Channel:${this.name}] PR state watch failed, will retry next poll: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
1838
+ }
1839
+ // The pass itself may have spent down to the reserve and yielded
1840
+ // mid-way; close nothing here, the next poll's gate sees the reading.
1649
1841
  }
1650
1842
  }
1843
+ else {
1844
+ // The watch stopped being eligible (subscriptions off, binding refresh
1845
+ // failing). Release the skip latch so a later starvation journals a
1846
+ // fresh skip rather than being suppressed as a repeat, but keep the
1847
+ // EPISODE open until the budget itself recovers — a budget that
1848
+ // recovers during this window still owes its recovery row.
1849
+ this.watchBudgetLow = false;
1850
+ this.closeWatchBudgetEpisode();
1851
+ }
1651
1852
  if (this.inboundRecoveryPending) {
1652
1853
  try {
1653
1854
  await this.recoverInboundTasks();
@@ -1711,10 +1912,17 @@ export class GithubChannel extends PollingChannelBase {
1711
1912
  ? notifications[notifications.length - 1].updated_at
1712
1913
  : this.cursor.lastProcessedAt;
1713
1914
  // Comment window lower bound: the cursor BEFORE this poll advances it.
1714
- // Comments with updated_at <= windowSince were already eligible for
1915
+ // Comments created before windowSince were already eligible for
1715
1916
  // processing in a previous poll — skip them to prevent duplicates when
1716
- // PUT /notifications' async mark fails to mark the thread read.
1917
+ // PUT /notifications' async mark fails to mark the thread read. Comments
1918
+ // of the windowSince second itself are read unless the window that ended
1919
+ // there read them (see GithubCursor.boundaryComments).
1717
1920
  const windowSince = this.cursor.lastProcessedAt;
1921
+ const boundary = this.cursor.boundaryComments?.at === windowSince
1922
+ ? this.cursor.boundaryComments
1923
+ : undefined;
1924
+ const boundaryComments = boundary ? new Set(boundary.keys) : null;
1925
+ const boundaryThreads = new Set(boundary?.threads);
1718
1926
  if (maxUpdatedAt > this.cursor.lastProcessedAt) {
1719
1927
  this.pendingCursorUpdatedAt =
1720
1928
  !this.pendingCursorUpdatedAt ||
@@ -1814,17 +2022,31 @@ export class GithubChannel extends PollingChannelBase {
1814
2022
  issueNumber,
1815
2023
  lastReadAt,
1816
2024
  windowSince,
2025
+ boundaryComments,
1817
2026
  metaFloor: this.cursor.metaFloor,
1818
2027
  maxUpdatedAt,
1819
2028
  subjectTitle: notification.subject.title || '',
1820
2029
  reason,
1821
2030
  };
1822
2031
  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;
2032
+ this.windowLatestThreads = noteLatestSecond(this.windowLatestThreads, notification.updated_at, failureKey);
2033
+ // A notification before the cursor belongs to a window that already
2034
+ // committed; it is listed again only because its mark-as-read did not
2035
+ // apply. A 5xx reading it neither holds the new window nor spends its
2036
+ // budget; a rate limit still stops the poll. One of the cursor's own
2037
+ // second that the window ending there did not list can instead be a
2038
+ // late notification for a comment that window did not read, when the
2039
+ // window reads that second: it holds a newer window waiting to be
2040
+ // marked read, and while none waits it is not marked read anyway, so
2041
+ // it spends no budget. Once the window has read its thread, it is
2042
+ // stale again.
2043
+ const late = notification.updated_at === windowSince &&
2044
+ boundaryComments !== null &&
2045
+ !boundaryThreads.has(failureKey) &&
2046
+ !this.windowLateThreadsRead.has(failureKey);
2047
+ const stale = notification.updated_at < windowSince ||
2048
+ (notification.updated_at === windowSince &&
2049
+ (!late || !this.pendingCursorUpdatedAt));
1828
2050
  try {
1829
2051
  switch (reason) {
1830
2052
  case 'mention':
@@ -1850,6 +2072,15 @@ export class GithubChannel extends PollingChannelBase {
1850
2072
  default:
1851
2073
  await this.processCommentLane(ctx, false);
1852
2074
  }
2075
+ // A thread held at poll start was not read (see fetchNewComments),
2076
+ // and a failing task store or audit may have refused what it read.
2077
+ if (late &&
2078
+ !this.threadHeldAtPollStart(chatId, threadId) &&
2079
+ !this.inboundPersistenceBlocked &&
2080
+ !this.publicationAuditBlocked &&
2081
+ this.windowLateThreadsRead.size < MAX_WINDOW_KEYS) {
2082
+ this.windowLateThreadsRead.add(failureKey);
2083
+ }
1853
2084
  }
1854
2085
  catch (err) {
1855
2086
  const failure = classifyThreadFailure(err);
@@ -1895,7 +2126,16 @@ export class GithubChannel extends PollingChannelBase {
1895
2126
  // leaves it running) holds the window as well: the cursor waits for
1896
2127
  // that task, so the thread is read again.
1897
2128
  const taskHeld = !retry && !storeHeld && this.threadTaskHoldsCursor(chatId, threadId);
1898
- const held = retry || storeHeld || taskHeld;
2129
+ // A late notification of the cursor's own second that fails with a
2130
+ // 5xx while no newer window waits is stale only for the budget:
2131
+ // nothing is marked read this poll, so the thread is read again.
2132
+ const idleHeld = failure === 'transient' &&
2133
+ !retry &&
2134
+ !storeHeld &&
2135
+ !taskHeld &&
2136
+ late &&
2137
+ !this.pendingCursorUpdatedAt;
2138
+ const held = retry || storeHeld || taskHeld || idleHeld;
1899
2139
  const milestone = (n) => n === 1 || n % 10 === 0;
1900
2140
  const report = failure === 'shared'
1901
2141
  ? milestone(heldPolls)
@@ -1903,7 +2143,7 @@ export class GithubChannel extends PollingChannelBase {
1903
2143
  ? counted
1904
2144
  ? milestone(failures)
1905
2145
  : this.journalOncePerWindow(`failing\0${failureKey}`)
1906
- : this.journalOncePerWindow(`${storeHeld || taskHeld ? 'held' : stale ? 'stale' : 'skip'}\0${failureKey}`);
2146
+ : this.journalOncePerWindow(`${storeHeld || taskHeld || idleHeld ? 'held' : stale ? 'stale' : 'skip'}\0${failureKey}`);
1907
2147
  if (report) {
1908
2148
  const error = sanitizeLogText(err instanceof Error ? err.message : String(err), 200);
1909
2149
  process.stderr.write(failure === 'shared'
@@ -1914,7 +2154,9 @@ export class GithubChannel extends PollingChannelBase {
1914
2154
  ? `[Channel:${this.name}] error processing ${threadId} while channel state cannot be persisted, keeping it unread for the next poll: ${error}\n`
1915
2155
  : taskHeld
1916
2156
  ? `[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`);
2157
+ : idleHeld
2158
+ ? `[Channel:${this.name}] API error processing ${threadId} while no newer notification waits, keeping it unread for the next poll: ${error}\n`
2159
+ : `[Channel:${this.name}] API error processing ${threadId}, skipping: ${error}\n`);
1918
2160
  let detail;
1919
2161
  if (failure === 'transient' && !stale) {
1920
2162
  detail = retry ? { failures, heldPolls } : { failures };
@@ -1981,14 +2223,31 @@ export class GithubChannel extends PollingChannelBase {
1981
2223
  await this.markNotificationsAsRead(committedAt);
1982
2224
  if (committedAt > this.cursor.lastProcessedAt) {
1983
2225
  this.cursor.lastProcessedAt = committedAt;
2226
+ const read = this.windowLatestComments;
2227
+ const listed = this.windowLatestThreads;
2228
+ if (read?.at === committedAt && read.overflow) {
2229
+ delete this.cursor.boundaryComments;
2230
+ }
2231
+ else {
2232
+ // Past the bound a listed thread is left out, so a notification
2233
+ // of it listed again counts as late: the cautious direction.
2234
+ this.cursor.boundaryComments = {
2235
+ at: committedAt,
2236
+ keys: read?.at === committedAt ? [...read.keys] : [],
2237
+ threads: listed?.at === committedAt ? [...listed.keys] : [],
2238
+ };
2239
+ }
1984
2240
  }
1985
2241
  this.pendingCursorUpdatedAt = undefined;
1986
- // A new window starts: its hold budget, streaks and once-per-window
1987
- // journal keys start again.
2242
+ // A new window starts: its hold budget, streaks, once-per-window
2243
+ // journal keys and what it has read and listed start again.
1988
2244
  this.transientHoldPolls = 0;
1989
2245
  this.sharedHoldPolls = 0;
1990
2246
  this.transientNotificationFailures.clear();
1991
2247
  this.windowJournalKeys.clear();
2248
+ this.windowLatestComments = undefined;
2249
+ this.windowLatestThreads = undefined;
2250
+ this.windowLateThreadsRead.clear();
1992
2251
  }
1993
2252
  }
1994
2253
  finally {
@@ -2334,11 +2593,17 @@ export class GithubChannel extends PollingChannelBase {
2334
2593
  if (this.threadHeldAtPollStart(ctx.chatId, ctx.threadId))
2335
2594
  return [];
2336
2595
  const [owner, repo] = ctx.chatId.split('/');
2596
+ // When the window reads the cursor's own second, list from a second
2597
+ // earlier, as the notification list does, so a comment last updated in
2598
+ // that second is listed whether GitHub's `since` includes it or not.
2599
+ const since = ctx.boundaryComments
2600
+ ? new Date(new Date(ctx.windowSince).getTime() - 1000).toISOString()
2601
+ : ctx.windowSince;
2337
2602
  const comments = (await this.githubApi(() => this.octokit.paginate(this.octokit.rest.issues.listComments, {
2338
2603
  owner,
2339
2604
  repo,
2340
2605
  issue_number: ctx.issueNumber,
2341
- since: ctx.windowSince,
2606
+ since,
2342
2607
  per_page: 100,
2343
2608
  }), `listComments(${ctx.threadId})`));
2344
2609
  comments.sort((a, b) => (a.created_at || '').localeCompare(b.created_at || ''));
@@ -2351,10 +2616,66 @@ export class GithubChannel extends PollingChannelBase {
2351
2616
  times[comment.node_id || String(comment.id)] = comment.created_at;
2352
2617
  }
2353
2618
  }
2354
- return comments.filter((comment) => comment.user?.login !== this.botUsername &&
2619
+ this.recordEditedMentions(ctx, comments);
2620
+ const inWindow = comments.filter((comment) => comment.user?.login !== this.botUsername &&
2355
2621
  (!comment.created_at ||
2356
- (comment.created_at > ctx.windowSince &&
2622
+ (startsInWindow(ctx, comment.created_at, comment.node_id || String(comment.id)) &&
2357
2623
  comment.created_at <= ctx.maxUpdatedAt)));
2624
+ for (const comment of inWindow)
2625
+ this.noteWindowComment(comment);
2626
+ return inWindow;
2627
+ }
2628
+ /**
2629
+ * Remember a comment this window read, if it is of the latest second the
2630
+ * window has read a comment from (the cursor can advance at most to the
2631
+ * newest notification, and no comment it reads is newer than that).
2632
+ */
2633
+ noteWindowComment(comment) {
2634
+ if (!comment.created_at)
2635
+ return;
2636
+ this.windowLatestComments = noteLatestSecond(this.windowLatestComments, comment.created_at, comment.node_id || String(comment.id));
2637
+ }
2638
+ /**
2639
+ * GitHub notifies a mention that an edit adds to an older comment, but the
2640
+ * lanes read only comments created in the window. Journal such a comment
2641
+ * once per window, so the notification it raised is not consumed without a
2642
+ * trace (unless it arrives after the cursor has passed the edit, as a late
2643
+ * notification for a new comment can). The edit time has no upper bound: a later edit (or a notification
2644
+ * stamped before the edit) leaves the comment newer than the window, and
2645
+ * once the window commits nothing reads it again. A later window that
2646
+ * reads the thread again can record it once more.
2647
+ */
2648
+ recordEditedMentions(ctx, comments) {
2649
+ const botUsername = this.botUsername;
2650
+ if (!botUsername)
2651
+ return;
2652
+ for (const comment of comments) {
2653
+ if (comment.user?.login === botUsername ||
2654
+ !comment.created_at ||
2655
+ startsInWindow(ctx, comment.created_at, comment.node_id || String(comment.id)) ||
2656
+ !comment.updated_at ||
2657
+ comment.updated_at <= ctx.windowSince ||
2658
+ !testBotMention(comment.body || '', botUsername)) {
2659
+ continue;
2660
+ }
2661
+ const key = comment.node_id || String(comment.id);
2662
+ // An edit to a comment the channel already took is not a new request.
2663
+ if (this.cursor.dispatchedComments?.includes(key))
2664
+ continue;
2665
+ if (!this.journalOncePerWindow(`edited_comment\0${key}`))
2666
+ continue;
2667
+ this.recordChannelEvent({
2668
+ type: 'inbound',
2669
+ outcome: 'skipped',
2670
+ reason: 'edited_comment',
2671
+ triggerKind: 'comment',
2672
+ repository: ctx.chatId,
2673
+ thread: ctx.threadId,
2674
+ number: ctx.issueNumber,
2675
+ messageId: key,
2676
+ actor: (comment.user?.login || 'unknown').toLowerCase(),
2677
+ });
2678
+ }
2358
2679
  }
2359
2680
  async fetchIssueMeta(ctx) {
2360
2681
  const { data } = await this.githubApi(() => this.octokit.rest.issues.get({
@@ -2446,9 +2767,11 @@ export class GithubChannel extends PollingChannelBase {
2446
2767
  }
2447
2768
  /**
2448
2769
  * 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:
2770
+ * comment can no longer be re-listed (created_at before the committed
2771
+ * cursor; the window can read the cursor's own second again, see
2772
+ * GithubCursor.boundaryComments), keeping protected keys regardless of
2773
+ * position. A key at or after the cursor — or with no recorded time
2774
+ * (legacy migration) — is protected:
2452
2775
  * evicting it would let a re-listed aggregate SUPERSET re-dispatch
2453
2776
  * already-replied comments under a fresh batch hash that misses the
2454
2777
  * publication-audit backstop (duplicate public reply / private injection
@@ -2467,13 +2790,13 @@ export class GithubChannel extends PollingChannelBase {
2467
2790
  const cursor = this.cursor.lastProcessedAt;
2468
2791
  return list.filter((key) => {
2469
2792
  const time = times[key];
2470
- return time === undefined || time > cursor;
2793
+ return time === undefined || time >= cursor;
2471
2794
  });
2472
2795
  }
2473
2796
  /**
2474
2797
  * Bound the time map: drop entries that are neither in the ring nor still
2475
2798
  * 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
2799
+ * while their created_at is not before the cursor (they may be dispatched
2477
2800
  * later this poll), so eviction never loses a key's protection mid-poll.
2478
2801
  */
2479
2802
  pruneCommentTimes() {
@@ -2483,7 +2806,7 @@ export class GithubChannel extends PollingChannelBase {
2483
2806
  const live = new Set(this.cursor.dispatchedComments ?? []);
2484
2807
  const cursor = this.cursor.lastProcessedAt;
2485
2808
  for (const [key, time] of Object.entries(times)) {
2486
- if (!live.has(key) && time <= cursor)
2809
+ if (!live.has(key) && time < cursor)
2487
2810
  delete times[key];
2488
2811
  }
2489
2812
  // Bound the map even under a permanently frozen cursor (nothing expires):
@@ -2507,7 +2830,7 @@ export class GithubChannel extends PollingChannelBase {
2507
2830
  }
2508
2831
  }
2509
2832
  }
2510
- async dispatchEnvelope(envelope, issueNumber, dedupe = {}, privateOnly = false) {
2833
+ async dispatchEnvelope(envelope, issueNumber, dedupe = {}, privateOnly = false, excludeSessionIds) {
2511
2834
  // The publication audit is the durable consumption record for the
2512
2835
  // public path: a reply can land (audit `posted`), the task be removed,
2513
2836
  // and the cursor save still be lost (mark-read failure, crash). The
@@ -2543,7 +2866,13 @@ export class GithubChannel extends PollingChannelBase {
2543
2866
  // class `comment` is the resolution fallback so a `fix:comment`
2544
2867
  // template also catches a comment delivered under another reason.
2545
2868
  const laneClass = dedupe.dispatchedComments !== undefined ? 'comment' : undefined;
2546
- const { targets, followed } = this.resolveBoundTargets(envelope.chatId, issueNumber, eventClass, laneClass);
2869
+ const resolved = this.resolveBoundTargets(envelope.chatId, issueNumber, eventClass, laneClass);
2870
+ // The bound PR comment watch withholds a comment from the session that
2871
+ // posted it (authorship attribution), keeping every other bound target.
2872
+ const targets = excludeSessionIds && excludeSessionIds.size > 0
2873
+ ? resolved.targets.filter((target) => !excludeSessionIds.has(target.sessionId))
2874
+ : resolved.targets;
2875
+ const followed = resolved.followed;
2547
2876
  if (targets.length > 0) {
2548
2877
  // Fan-out: one durable task per (event, target). Each settles
2549
2878
  // independently — a queue-full role defers without head-of-line
@@ -2566,7 +2895,7 @@ export class GithubChannel extends PollingChannelBase {
2566
2895
  kind: 'bound-session',
2567
2896
  sessionId: target.sessionId,
2568
2897
  ...(target.role ? { role: target.role } : {}),
2569
- }, first && targets.length > 1 ? targets : undefined, privateOnly));
2898
+ }, first && targets.length > 1 ? targets : undefined, privateOnly, excludeSessionIds));
2570
2899
  first = false;
2571
2900
  }
2572
2901
  let settled = true;
@@ -2621,7 +2950,7 @@ export class GithubChannel extends PollingChannelBase {
2621
2950
  this.enqueuePublicTask(task);
2622
2951
  return true;
2623
2952
  }
2624
- claimInboundTask(envelope, issueNumber, dedupe, delivery, fanout, privateOnly = false) {
2953
+ claimInboundTask(envelope, issueNumber, dedupe, delivery, fanout, privateOnly = false, authorExclude) {
2625
2954
  const existing = this.readInboundTasks().find((record) => record.source.chatId === envelope.chatId &&
2626
2955
  record.source.threadId === envelope.threadId &&
2627
2956
  record.source.messageId === envelope.messageId &&
@@ -2669,6 +2998,9 @@ export class GithubChannel extends PollingChannelBase {
2669
2998
  ...(delivery ? { delivery } : {}),
2670
2999
  ...(fanout ? { fanout } : {}),
2671
3000
  ...(privateOnly ? { privateOnly: true } : {}),
3001
+ ...(authorExclude && authorExclude.size > 0
3002
+ ? { authorExclude: [...authorExclude] }
3003
+ : {}),
2672
3004
  };
2673
3005
  this.updateInboundTasks((records) => [...records, task]);
2674
3006
  this.applyTaskDedupe(task.dedupe);
@@ -2925,7 +3257,13 @@ export class GithubChannel extends PollingChannelBase {
2925
3257
  let posted = task.errorCommentPosted === true;
2926
3258
  // Bound-session delivery is private: a failure must not post a public
2927
3259
  // error comment. The fallback path clears delivery before retrying.
2928
- if (!posted && !stillBound && task.privateOnly !== true) {
3260
+ // A failed public attempt is run again on a later poll until the
3261
+ // budget is spent (see isRecoverableInboundTask), so the comment,
3262
+ // which asks the user to mention the bot again, waits for the last.
3263
+ if (!posted &&
3264
+ !stillBound &&
3265
+ task.privateOnly !== true &&
3266
+ attempts >= MAX_INBOUND_TASK_ATTEMPTS) {
2929
3267
  posted = await this.postErrorComment(envelope.chatId, task.issueNumber, this.getInboundErrorSourceLabel(envelope));
2930
3268
  }
2931
3269
  // Queue full and temporarily-unavailable sessions/workspaces are
@@ -3072,7 +3410,12 @@ export class GithubChannel extends PollingChannelBase {
3072
3410
  kind: 'bound-session',
3073
3411
  sessionId: target.sessionId,
3074
3412
  ...(target.role ? { role: target.role } : {}),
3075
- }, undefined, task.privateOnly === true);
3413
+ }, undefined, task.privateOnly === true,
3414
+ // The reconstructed sibling must inherit the authorship exclusion:
3415
+ // it is the same event, so the same sessions authored it. Without
3416
+ // this the reselection filter receives an empty set and can route
3417
+ // the comment to its author once that session becomes the newest.
3418
+ task.authorExclude ? new Set(task.authorExclude) : undefined);
3076
3419
  }
3077
3420
  }
3078
3421
  const tasks = this.readInboundTasks().filter((task) => this.isRecoverableInboundTask(task));
@@ -3597,6 +3940,75 @@ export class GithubChannel extends PollingChannelBase {
3597
3940
  removeInboundTask(taskId) {
3598
3941
  this.updateInboundTasks((records) => records.filter((record) => record.id !== taskId));
3599
3942
  }
3943
+ /**
3944
+ * Record the REST budget from a successful response's headers. Called by
3945
+ * the request hook on every response. A missing or malformed remaining
3946
+ * header leaves the last known value untouched (a proxy that strips the
3947
+ * header must not erase a real reading). The reset time is refreshed from
3948
+ * the same response; if that header is absent the reset is cleared, so the
3949
+ * gate falls back to protecting on the count alone rather than trusting a
3950
+ * reset time from a different window.
3951
+ */
3952
+ recordRateLimitBudget(headers) {
3953
+ const remaining = parseRateLimitCount(headers?.['x-ratelimit-remaining']);
3954
+ if (remaining === undefined)
3955
+ return;
3956
+ this.lastRateLimitRemaining = remaining;
3957
+ const reset = parseRateLimitCount(headers?.['x-ratelimit-reset']);
3958
+ this.lastRateLimitResetAt = reset === undefined ? undefined : reset * 1000;
3959
+ }
3960
+ /**
3961
+ * Whether the watch pass must yield this poll to protect the notification
3962
+ * lane. True only when a usable remaining reading is at or below the
3963
+ * reserve AND its window has not already reset (a stale low count from a
3964
+ * rolled-over window must not starve the watch). With no reading yet the
3965
+ * watch runs normally; the reactive isWatchFailFastError backstop still
3966
+ * covers a wrong estimate or a secondary limit.
3967
+ */
3968
+ watchBudgetExhausted() {
3969
+ const reserve = this.prWatchBudgetReserve;
3970
+ // A reserve of 0 disables the gate outright. Without this, a remaining
3971
+ // of 0 would still satisfy `0 <= 0` and skip the watch the operator
3972
+ // explicitly opted out of protecting.
3973
+ if (reserve === 0)
3974
+ return false;
3975
+ if (this.lastRateLimitRemaining === undefined)
3976
+ return false;
3977
+ if (this.lastRateLimitResetAt !== undefined &&
3978
+ Date.now() >= this.lastRateLimitResetAt) {
3979
+ return false;
3980
+ }
3981
+ return this.lastRateLimitRemaining <= reserve;
3982
+ }
3983
+ /**
3984
+ * Open a low-budget episode: latch the skip and journal its edge once.
3985
+ * Shared by the poll-boundary gate and the in-pass yield so a mid-pass stop
3986
+ * records the same row rather than a second vocabulary.
3987
+ */
3988
+ noteWatchBudgetLow() {
3989
+ this.watchBudgetEpisodeOpen = true;
3990
+ if (this.watchBudgetLow)
3991
+ return;
3992
+ this.watchBudgetLow = true;
3993
+ this.recordPollDegraded('watch_budget_low', {
3994
+ remaining: this.lastRateLimitRemaining ?? 0,
3995
+ reserve: this.prWatchBudgetReserve,
3996
+ });
3997
+ 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`);
3998
+ }
3999
+ /**
4000
+ * Close the episode once the budget is no longer exhausted. A still-low
4001
+ * budget keeps it open: the watch being ineligible says nothing about the
4002
+ * budget, and claiming recovery there would be a false report.
4003
+ */
4004
+ closeWatchBudgetEpisode() {
4005
+ if (!this.watchBudgetEpisodeOpen)
4006
+ return;
4007
+ if (this.watchBudgetExhausted())
4008
+ return;
4009
+ this.watchBudgetEpisodeOpen = false;
4010
+ this.recordPollDegraded('watch_budget_recovered');
4011
+ }
3600
4012
  /**
3601
4013
  * Journals a degraded dependency the poll loop itself survived: the poll
3602
4014
  * still reports `ok`, so without this row a binding scan that stalls every
@@ -4091,9 +4503,38 @@ export class GithubChannel extends PollingChannelBase {
4091
4503
  if (!this.deliverToBoundSessions)
4092
4504
  return undefined;
4093
4505
  const summary = this.boundSessionByPr.get(this.prBindingKey(chatId, issueNumber));
4094
- return summary
4095
- ? { kind: 'bound-session', sessionId: summary.sessionId }
4096
- : undefined;
4506
+ if (!summary)
4507
+ return undefined;
4508
+ const role = this.boundRoleOf(summary, chatId, issueNumber);
4509
+ return {
4510
+ kind: 'bound-session',
4511
+ sessionId: summary.sessionId,
4512
+ ...(role ? { role } : {}),
4513
+ };
4514
+ }
4515
+ /**
4516
+ * The role of the entry that names THIS PR, or undefined for an untyped
4517
+ * binding. Takes the winner legacy routing already resolved, so the URL
4518
+ * parse stays within that one session's entries instead of repeating the
4519
+ * whole follower scan on a path that used to be a single Map lookup.
4520
+ */
4521
+ boundRoleOf(summary, chatId, issueNumber) {
4522
+ return this.boundPrEntryFor(summary, this.prBindingKey(chatId, issueNumber))
4523
+ ?.role;
4524
+ }
4525
+ /**
4526
+ * The entry of `summary` that names the PR behind `key`, matched the same
4527
+ * way for every candidate: the URL must parse, agree with its own number,
4528
+ * and normalize to that key. Shared so the legacy role lookup and the
4529
+ * role-aware follower scan cannot drift apart.
4530
+ */
4531
+ boundPrEntryFor(summary, key) {
4532
+ return summary.prs.find((pr) => {
4533
+ const identity = this.parsePrBindingUrl(pr.url);
4534
+ return (!!identity &&
4535
+ identity.number === pr.number &&
4536
+ this.prBindingKey(identity.chatId, identity.number) === key);
4537
+ });
4097
4538
  }
4098
4539
  /**
4099
4540
  * Pick the most-recent live follower of a PR from the full binding list,
@@ -4129,10 +4570,7 @@ export class GithubChannel extends PollingChannelBase {
4129
4570
  ? {
4130
4571
  kind: 'bound-session',
4131
4572
  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 } : {}),
4573
+ ...(best.role ? { role: best.role } : {}),
4136
4574
  }
4137
4575
  : undefined;
4138
4576
  }
@@ -4156,12 +4594,7 @@ export class GithubChannel extends PollingChannelBase {
4156
4594
  for (const summary of this.lastBindings) {
4157
4595
  if (summary.sourceType === 'channel')
4158
4596
  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
- });
4597
+ const entry = this.boundPrEntryFor(summary, key);
4165
4598
  if (!entry)
4166
4599
  continue;
4167
4600
  followers.push({ summary, ...(entry.role ? { role: entry.role } : {}) });
@@ -4368,12 +4801,13 @@ export class GithubChannel extends PollingChannelBase {
4368
4801
  }
4369
4802
  if (!this.boundRoleAware) {
4370
4803
  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 };
4804
+ if (!summary)
4805
+ return { targets: [], followed: false };
4806
+ const role = this.boundRoleOf(summary, chatId, issueNumber);
4807
+ return {
4808
+ targets: [{ sessionId: summary.sessionId, ...(role ? { role } : {}) }],
4809
+ followed: true,
4810
+ };
4377
4811
  }
4378
4812
  const followers = this.boundFollowersOf(chatId, issueNumber);
4379
4813
  const byRole = new Map();
@@ -4405,12 +4839,16 @@ export class GithubChannel extends PollingChannelBase {
4405
4839
  * and a role that lost its match retires privately instead of leaking
4406
4840
  * into another role's session.
4407
4841
  */
4408
- revalidateBoundTarget(delivery, chatId, issueNumber, eventClass, laneClass) {
4842
+ revalidateBoundTarget(delivery, chatId, issueNumber, eventClass, laneClass, excludeSessionIds) {
4409
4843
  if (!this.boundRoleAware) {
4410
- return this.resolveBoundDelivery(chatId, issueNumber);
4844
+ const legacy = this.resolveBoundDelivery(chatId, issueNumber);
4845
+ if (legacy && excludeSessionIds?.has(legacy.sessionId))
4846
+ return undefined;
4847
+ return legacy;
4411
4848
  }
4412
4849
  const winner = this.boundFollowersOf(chatId, issueNumber)
4413
4850
  .filter((follower) => follower.role === delivery.role)
4851
+ .filter((follower) => !excludeSessionIds?.has(follower.summary.sessionId))
4414
4852
  .reduce((best, follower) => !best ||
4415
4853
  (follower.summary.updatedAt ?? '') > (best.summary.updatedAt ?? '')
4416
4854
  ? follower
@@ -4510,8 +4948,9 @@ export class GithubChannel extends PollingChannelBase {
4510
4948
  // removed on acceptance, so a silent cut would drop the tail from every
4511
4949
  // surface. With a matching operator template the generic workflow line
4512
4950
  // 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.
4951
+ // extends to the substituted values. Without one, a role-carrying binding
4952
+ // gets the built-in guidance for that role and an untyped binding keeps
4953
+ // the prompt byte-identical to the pre-template contract.
4515
4954
  const eventClass = this.boundEventClass(envelope);
4516
4955
  const template = resolveBoundActionTemplate(this.boundSessionActions, role, eventClass, laneClass);
4517
4956
  return buildBoundEventPrompt({
@@ -4527,6 +4966,11 @@ export class GithubChannel extends PollingChannelBase {
4527
4966
  : {}),
4528
4967
  dataLines: [identity, ...contextLines],
4529
4968
  ...(role ? { role } : {}),
4969
+ // The builder uses this only when no operator instruction resolved.
4970
+ // Role-aware targets are selected BY template match, so they always
4971
+ // carry an instruction and the guidance is inert there; the per-role
4972
+ // subscription is enforced at selection, not by a flag here.
4973
+ ...(role ? { roleGuidance: DEFAULT_BOUND_ROLE_GUIDANCE[role] } : {}),
4530
4974
  body: text,
4531
4975
  });
4532
4976
  }
@@ -4572,8 +5016,16 @@ export class GithubChannel extends PollingChannelBase {
4572
5016
  if (this.boundSnapshotTrusted &&
4573
5017
  !this.lastBindingsPartial &&
4574
5018
  !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) {
5019
+ const current = this.revalidateBoundTarget(delivery, envelope.chatId, task.issueNumber, this.boundEventClass(envelope), this.boundLaneClass(task.dedupe), task.authorExclude ? new Set(task.authorExclude) : undefined);
5020
+ // The ROLE is part of the target, not just the session: a deferred
5021
+ // legacy delivery whose binding was re-roled in the meantime must not
5022
+ // build its prompt from the frozen role, or a session that is now a
5023
+ // verifier still receives the fixer's guidance. Role-aware targets are
5024
+ // re-resolved within their own role group, so the role half is inert
5025
+ // there.
5026
+ if (current &&
5027
+ (current.sessionId !== delivery.sessionId ||
5028
+ current.role !== delivery.role)) {
4577
5029
  this.transitionInboundTask(task.id, 'running', { delivery: current });
4578
5030
  task.delivery = current;
4579
5031
  delivery = current;
@@ -4606,6 +5058,12 @@ export class GithubChannel extends PollingChannelBase {
4606
5058
  const preflight = this.preflightInbound(envelope, {
4607
5059
  waiveGroupMention: !envelope.messageId?.startsWith('issue-body-') &&
4608
5060
  this.waivesBoundMention(envelope.chatId, envelope.senderId),
5061
+ // The comment watch delivers the channel account's own comments (the
5062
+ // notification lanes filter that login out, so this can only be the
5063
+ // watch). The sender allowlist guidance excludes that account, which
5064
+ // would otherwise retire every watched comment as preflight_rejected.
5065
+ waiveGroupSender: this.botUsername != null &&
5066
+ envelope.senderId === this.botUsername.toLowerCase(),
4609
5067
  });
4610
5068
  const admitted = typeof preflight === 'boolean' ? preflight : await preflight;
4611
5069
  if (!admitted) {
@@ -4657,6 +5115,13 @@ export class GithubChannel extends PollingChannelBase {
4657
5115
  // loop by the finite follower count even if a stale snapshot keeps
4658
5116
  // re-listing dead sessions.
4659
5117
  const goneSessions = new Set([delivery.sessionId]);
5118
+ // The comment watch withholds the comment from its author; the fallback
5119
+ // re-resolves over the followers and must honor that exclusion too, or a
5120
+ // Gone primary target would hand the comment back to its author. When no
5121
+ // non-author follower remains the loop retires privately below.
5122
+ for (const sessionId of task.authorExclude ?? []) {
5123
+ goneSessions.add(sessionId);
5124
+ }
4660
5125
  // The local `delivery` is the FIRST follower; the loop walks past it.
4661
5126
  // The terminal row must name the last one tried, or the operator opens
4662
5127
  // the workspace of a session evicted a step earlier.
@@ -4670,8 +5135,15 @@ export class GithubChannel extends PollingChannelBase {
4670
5135
  this.transitionInboundTask(task.id, 'running', { delivery: next });
4671
5136
  task.delivery = next;
4672
5137
  try {
5138
+ // Rebuild for THIS target: the legacy fallback scans every
5139
+ // follower, so it can land on a different role (or an untyped
5140
+ // binding). Reusing the first target's prompt would hand this
5141
+ // session the gone session's Role line and role guidance.
5142
+ // Role-aware fallbacks stay inside their role group, where the
5143
+ // deterministic renderer rebuilds the identical string.
5144
+ const targetPrompt = this.buildBoundSessionPrompt(envelope, next.role, this.boundLaneClass(task.dedupe));
4673
5145
  // Same event key: a different session's ring has never seen it.
4674
- await boundSessions.deliverPrompt(next.sessionId, prompt, idempotencyKey);
5146
+ await boundSessions.deliverPrompt(next.sessionId, targetPrompt, idempotencyKey);
4675
5147
  this.recordBoundDelivered(envelope, next.sessionId);
4676
5148
  return { kind: 'delivered' };
4677
5149
  }
@@ -4936,14 +5408,37 @@ export class GithubChannel extends PollingChannelBase {
4936
5408
  }
4937
5409
  return DEFAULT_PR_WATCH_LIMIT;
4938
5410
  }
5411
+ /**
5412
+ * Requests reserved for the notification lane: at or below this remaining
5413
+ * budget the watch pass yields. Clamped like prWatchLimit; a configured 0
5414
+ * is honoured (disables the gate) so an operator can opt out, while unset
5415
+ * or invalid keeps the default. Rounds up so the reserve is never silently
5416
+ * smaller than requested.
5417
+ */
5418
+ get prWatchBudgetReserve() {
5419
+ const configured = this.config
5420
+ .prWatchBudgetReserve;
5421
+ if (typeof configured === 'number' &&
5422
+ Number.isFinite(configured) &&
5423
+ configured >= 0) {
5424
+ return Math.min(Math.ceil(configured), MAX_PR_WATCH_BUDGET_RESERVE);
5425
+ }
5426
+ return DEFAULT_PR_WATCH_BUDGET_RESERVE;
5427
+ }
4939
5428
  /**
4940
5429
  * Edge-triggered state watch over the PRs bound to live sessions. Runs
4941
5430
  * inside the existing poll loop; detection is API-level and costs no model
4942
5431
  * tokens until a real transition fires.
4943
5432
  */
4944
5433
  async runPrStateWatch() {
4945
- if (!this.boundSessions || this.prWatchEvents.size === 0)
5434
+ // The comment watch is default-on with deliverToBoundSessions and is
5435
+ // independent of the state-event subscription, so an empty prWatchEvents
5436
+ // must not skip the pass while comment watching is enabled.
5437
+ const commentWatchActive = this.deliverToBoundSessions && this.prCommentWatchEnabled;
5438
+ if (!this.boundSessions ||
5439
+ (this.prWatchEvents.size === 0 && !commentWatchActive)) {
4946
5440
  return;
5441
+ }
4947
5442
  this.loadPrWatchState();
4948
5443
  const candidates = new Map();
4949
5444
  const active = new Map();
@@ -4972,9 +5467,14 @@ export class GithubChannel extends PollingChannelBase {
4972
5467
  // the PR: pruning it here would re-add the closed PR as a first
4973
5468
  // observation on the next poll (query oscillation) and lose the
4974
5469
  // terminal record. Binding retention and active polling are
4975
- // separate concerns.
5470
+ // separate concerns. A comment-only channel subscribes no state
5471
+ // event, so there is no state_change to observe and watchOnePr (the
5472
+ // only prState writer) never runs: drain on the binding's terminal
5473
+ // state alone, else merged/closed bindings would be comment-fetched
5474
+ // forever. A reopened binding flips back to open and resumes.
4976
5475
  if ((pr.state === 'merged' || pr.state === 'closed') &&
4977
- this.prWatchState.entries[key]?.prState === 'closed') {
5476
+ (this.prWatchState.entries[key]?.prState === 'closed' ||
5477
+ this.prWatchEvents.size === 0)) {
4978
5478
  continue;
4979
5479
  }
4980
5480
  const existingActive = active.get(key);
@@ -5081,9 +5581,31 @@ export class GithubChannel extends PollingChannelBase {
5081
5581
  const excluded = [...active.keys()].filter((key) => !watchedKeys.has(key));
5082
5582
  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
5583
  }
5584
+ // One burst budget for the whole pass: after an outage every watched PR
5585
+ // can be due at once, and a per-PR cap would claim up to cap × watched-PR
5586
+ // durable tasks in a single poll. PRs that find it spent keep their cursor
5587
+ // and resume next pass.
5588
+ const commentBudget = { remaining: MAX_WATCH_COMMENTS_PER_PASS };
5084
5589
  for (const [key, candidate] of watched) {
5590
+ // Yield at the spend site, not only at the poll boundary: one pass can
5591
+ // issue several requests per watched PR, so a pass entered just above
5592
+ // the reserve would otherwise spend the whole reserve before the
5593
+ // notification lane runs. Break (not return) so the baseline observed
5594
+ // so far still reaches savePrWatchState below.
5595
+ if (this.watchBudgetExhausted()) {
5596
+ this.noteWatchBudgetLow();
5597
+ break;
5598
+ }
5085
5599
  try {
5086
- await this.watchOnePr(key, candidate.chatId, candidate.number);
5600
+ // The state observation costs a pulls.get per watched PR per poll; skip
5601
+ // it when no state event is subscribed so a comment-only channel does
5602
+ // not pay for transitions it never emits.
5603
+ if (this.prWatchEvents.size > 0) {
5604
+ await this.watchOnePr(key, candidate.chatId, candidate.number);
5605
+ }
5606
+ // Additive comment watch: isolates its own failures so a comment
5607
+ // fetch problem never skips the state transitions above.
5608
+ await this.watchPrComments(key, candidate.chatId, candidate.number, commentBudget);
5087
5609
  }
5088
5610
  catch (err) {
5089
5611
  if (isWatchPassAbortError(err)) {
@@ -5172,11 +5694,13 @@ export class GithubChannel extends PollingChannelBase {
5172
5694
  prevCiForThisHead !== 'failure' &&
5173
5695
  this.prWatchEvents.has('ci_failure')) {
5174
5696
  const failedChecks = ciResult && ciResult.failedChecks.length > 0
5175
- ? ` Failed checks: ${ciResult.failedChecks.join(', ')}.`
5697
+ ? ` Failed checks: ${ciResult.failedChecks.join(', ')}${ciResult.namesIncomplete
5698
+ ? ' (list may be incomplete: later check pages were not read)'
5699
+ : ''}.`
5176
5700
  : '';
5177
5701
  events.push({
5178
5702
  type: 'ci_failure',
5179
- summary: `CI failed on head ${headSha}.${failedChecks} Inspect the failed checks and fix or attribute the failure.`,
5703
+ summary: `CI failed on head ${headSha}.${failedChecks}`,
5180
5704
  });
5181
5705
  }
5182
5706
  // mergeable === null means GitHub is still computing; never overwrite
@@ -5190,7 +5714,7 @@ export class GithubChannel extends PollingChannelBase {
5190
5714
  this.prWatchEvents.has('merge_conflict')) {
5191
5715
  events.push({
5192
5716
  type: 'merge_conflict',
5193
- summary: `Merge conflicts detected (mergeable_state: dirty). Rebase or merge the base branch and resolve the conflicts.`,
5717
+ summary: 'Merge conflicts detected (mergeable_state: dirty).',
5194
5718
  });
5195
5719
  }
5196
5720
  const prState = pr.state;
@@ -5201,7 +5725,7 @@ export class GithubChannel extends PollingChannelBase {
5201
5725
  events.push({
5202
5726
  type: 'state_change',
5203
5727
  summary: pr.merged
5204
- ? 'The PR was merged. Wrap up any follow-up work.'
5728
+ ? 'The PR was merged.'
5205
5729
  : 'The PR was closed without merging.',
5206
5730
  });
5207
5731
  }
@@ -5220,6 +5744,11 @@ export class GithubChannel extends PollingChannelBase {
5220
5744
  ? { mergeableState: entry.mergeableState }
5221
5745
  : {}),
5222
5746
  ...(prState !== undefined ? { prState } : {}),
5747
+ ...(pr.title !== undefined
5748
+ ? { title: pr.title }
5749
+ : entry.title !== undefined
5750
+ ? { title: entry.title }
5751
+ : {}),
5223
5752
  ...(prUpdatedAt !== undefined ? { prUpdatedAt } : {}),
5224
5753
  ...(firstObservation || headChanged
5225
5754
  ? { headObservedAt: Date.now() }
@@ -5237,6 +5766,17 @@ export class GithubChannel extends PollingChannelBase {
5237
5766
  ...(!headChanged && entry.ciFiredSha !== undefined
5238
5767
  ? { ciFiredSha: entry.ciFiredSha }
5239
5768
  : {}),
5769
+ // The comment watch cursor is independent of head/CI transitions; carry
5770
+ // it through so the state baseline write does not drop it.
5771
+ ...(entry.commentBaseline !== undefined
5772
+ ? { commentBaseline: entry.commentBaseline }
5773
+ : {}),
5774
+ ...(entry.commentSince !== undefined
5775
+ ? { commentSince: entry.commentSince }
5776
+ : {}),
5777
+ ...(entry.commentLastFetchAt !== undefined
5778
+ ? { commentLastFetchAt: entry.commentLastFetchAt }
5779
+ : {}),
5240
5780
  };
5241
5781
  // Bake the PR number and detection time into every watch key. The
5242
5782
  // delivery idempotency key is chatId + messageId only, so without the
@@ -5380,6 +5920,319 @@ export class GithubChannel extends PollingChannelBase {
5380
5920
  }
5381
5921
  await this.drainPendingWatch(key, next);
5382
5922
  }
5923
+ /**
5924
+ * Bound PR comment watch (docs/design/2026-11-08-bound-pr-comment-watch.md).
5925
+ * Poll conversation + inline review comments on a bound PR and deliver each
5926
+ * new one to every bound session that did NOT post it. Unlike the
5927
+ * notification lanes this does not filter the channel's own account: a
5928
+ * comment by the same GitHub login used by a DIFFERENT session/agent must
5929
+ * reach the follower. Authorship attribution (the daemon's posted-comment
5930
+ * lookup) withholds a comment only from the session that wrote it, which is
5931
+ * what prevents a fix session's own reply from re-triggering it.
5932
+ *
5933
+ * Default-on with deliverToBoundSessions; `prCommentWatch: false` disables
5934
+ * it. Failures are isolated here so they never skip the state transitions.
5935
+ */
5936
+ async watchPrComments(key, chatId, number, budget) {
5937
+ if (!this.deliverToBoundSessions ||
5938
+ !this.prCommentWatchEnabled ||
5939
+ !this.boundSessions) {
5940
+ return;
5941
+ }
5942
+ const entry = this.prWatchState.entries[key] ?? {};
5943
+ const now = Date.now();
5944
+ const nowIso = new Date(now).toISOString();
5945
+ // First observation baselines silently (no backlog delivery), matching
5946
+ // the state-watch convention; only comments created after it are eligible.
5947
+ if (entry.commentBaseline === undefined) {
5948
+ this.prWatchState.entries[key] = {
5949
+ ...entry,
5950
+ commentBaseline: nowIso,
5951
+ commentSince: nowIso,
5952
+ commentLastFetchAt: now,
5953
+ };
5954
+ this.savePrWatchState();
5955
+ return;
5956
+ }
5957
+ if (entry.commentLastFetchAt !== undefined &&
5958
+ now - entry.commentLastFetchAt < COMMENT_RECHECK_INTERVAL_MS) {
5959
+ return;
5960
+ }
5961
+ // The burst budget is shared by every watched PR in this pass. A PR that
5962
+ // arrives after it is spent fetches nothing and keeps its cursor untouched,
5963
+ // so its tail resumes on the next pass instead of being skipped past.
5964
+ if (budget.remaining <= 0) {
5965
+ return;
5966
+ }
5967
+ const [owner, repo] = chatId.split('/');
5968
+ const since = entry.commentSince ?? entry.commentBaseline;
5969
+ let conversation = [];
5970
+ let review = [];
5971
+ try {
5972
+ // Same fail-fast rule as the state watch: a rate-limited or credential
5973
+ // answer must not sleep-retry inside the watch pass (it runs before task
5974
+ // recovery and notification intake), and a shared error aborts the pass.
5975
+ conversation = (await this.githubApi(() => this.octokit.paginate(this.octokit.rest.issues.listComments, {
5976
+ owner,
5977
+ repo,
5978
+ issue_number: number,
5979
+ since,
5980
+ per_page: 100,
5981
+ }), `listComments(comment watch ${key})`, 3, (err) => !isWatchFailFastError(err)));
5982
+ review = (await this.githubApi(() => this.octokit.paginate(this.octokit.rest.pulls.listReviewComments, {
5983
+ owner,
5984
+ repo,
5985
+ pull_number: number,
5986
+ since,
5987
+ per_page: 100,
5988
+ }), `listReviewComments(comment watch ${key})`, 3, (err) => !isWatchFailFastError(err)));
5989
+ }
5990
+ catch (err) {
5991
+ // A shared credential/rate-limit error condemns the whole pass: hand it
5992
+ // to the outer watch loop's abort logic instead of swallowing it here.
5993
+ if (isWatchPassAbortError(err))
5994
+ throw err;
5995
+ // Per-PR failure: advance the fetch clock so a persistent endpoint
5996
+ // problem retries on the interval, not every poll, but keep commentSince
5997
+ // so no comment is skipped past without a delivery attempt.
5998
+ this.prWatchState.entries[key] = {
5999
+ ...(this.prWatchState.entries[key] ?? {}),
6000
+ commentLastFetchAt: now,
6001
+ };
6002
+ this.savePrWatchState();
6003
+ 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`);
6004
+ return;
6005
+ }
6006
+ // Record created_at per fetched comment exactly as the notification lanes'
6007
+ // fetch does, so the watch's dispatchedComments keys carry a time and stay
6008
+ // evictable once older than the cursor. Without a time a key is treated as
6009
+ // protected and the ring would grow monotonically for the daemon's life.
6010
+ const commentTimes = (this.cursor.dispatchedCommentTimes ??= {});
6011
+ for (const comment of [...conversation, ...review]) {
6012
+ if (comment.created_at) {
6013
+ commentTimes[comment.node_id || String(comment.id)] =
6014
+ comment.created_at;
6015
+ }
6016
+ }
6017
+ const { targets } = this.resolveBoundTargets(chatId, number, 'comment', 'comment');
6018
+ // A partial/untrusted snapshot may omit bound sessions, so the target list
6019
+ // is not a complete enumeration: retiring a comment as "no target" (or
6020
+ // delivering to the visible subset and advancing past it) would skip it
6021
+ // past a session in the unscanned workspace, and no other lane can deliver
6022
+ // a same-account comment. Defer rather than consume (fail-closed, as the
6023
+ // state watch): keep commentSince, advance only the fetch clock, and let a
6024
+ // trustworthy pass re-evaluate.
6025
+ if (!this.boundSnapshotTrusted ||
6026
+ this.lastBindingsPartial ||
6027
+ this.boundRefreshFailed) {
6028
+ this.prWatchState.entries[key] = {
6029
+ ...(this.prWatchState.entries[key] ?? {}),
6030
+ commentLastFetchAt: now,
6031
+ };
6032
+ this.savePrWatchState();
6033
+ return;
6034
+ }
6035
+ const baseline = entry.commentBaseline;
6036
+ const alreadyDispatched = (commentKey) => this.cursor.dispatchedComments?.includes(commentKey) === true;
6037
+ const candidates = [];
6038
+ const threadId = `pr:${number}`;
6039
+ const metadata = `${this.buildMetadata(chatId, threadId, entry.title ?? '')}\nTrigger: comment.`;
6040
+ const renderBody = (body) => {
6041
+ const display = sanitizeDisplayText((body ?? '').trim());
6042
+ const total = Array.from(display).length;
6043
+ // A watch delivery carries ONE comment, so it uses the bound prompt's
6044
+ // body ceiling, not the aggregate lane's per-comment batch budget (400):
6045
+ // cutting a single finding at 400 code points drops the actionable steps
6046
+ // past the cut. The bound prompt caps the final body at the same value.
6047
+ return total > BOUND_PROMPT_BODY_MAX_CODE_POINTS
6048
+ ? `${truncateCodePoints(display, BOUND_PROMPT_BODY_MAX_CODE_POINTS)}… [comment truncated: ${total - BOUND_PROMPT_BODY_MAX_CODE_POINTS} more characters]`
6049
+ : display;
6050
+ };
6051
+ // The watch closes the SAME-account gap: GitHub sends the channel account no
6052
+ // notification for its own comments, so the notification lanes never see
6053
+ // them. Comments by any OTHER account do produce notifications and are
6054
+ // delivered by the notification lanes under the thread's own reason and
6055
+ // role templates. Watching them here too would pre-empt those lanes: the
6056
+ // watch resolves the narrower `comment` class, and consuming the shared
6057
+ // dedupe key after reaching only a subset of roles would starve the rest
6058
+ // (e.g. fix:comment delivered, verify:mention lost). Leave other-account
6059
+ // comments to the lanes.
6060
+ const botLogin = this.botUsername?.toLowerCase();
6061
+ const sameAccount = (login) => botLogin !== undefined && login?.toLowerCase() === botLogin;
6062
+ for (const comment of conversation) {
6063
+ const commentKey = comment.node_id || String(comment.id);
6064
+ if (!sameAccount(comment.user?.login) ||
6065
+ !comment.created_at ||
6066
+ comment.created_at <= baseline ||
6067
+ alreadyDispatched(commentKey)) {
6068
+ continue;
6069
+ }
6070
+ const author = comment.user?.login || 'unknown';
6071
+ const url = `${this.webOrigin}/${chatId}/pull/${number}#issuecomment-${comment.id}`;
6072
+ candidates.push({
6073
+ key: commentKey,
6074
+ attrKey: `ic:${comment.id}`,
6075
+ createdAt: comment.created_at,
6076
+ envelope: {
6077
+ channelName: this.name,
6078
+ senderId: author.toLowerCase(),
6079
+ senderName: author,
6080
+ chatId,
6081
+ threadId,
6082
+ messageId: commentKey,
6083
+ text: `New comment by @${author}:\n${renderBody(comment.body)}\nComment: ${url}`,
6084
+ isGroup: true,
6085
+ isMentioned: true,
6086
+ isReplyToBot: false,
6087
+ metadata,
6088
+ },
6089
+ });
6090
+ }
6091
+ for (const comment of review) {
6092
+ const commentKey = comment.node_id || String(comment.id);
6093
+ if (!sameAccount(comment.user?.login) ||
6094
+ !comment.created_at ||
6095
+ comment.created_at <= baseline ||
6096
+ alreadyDispatched(commentKey)) {
6097
+ continue;
6098
+ }
6099
+ const author = comment.user?.login || 'unknown';
6100
+ const url = comment.html_url ||
6101
+ `${this.webOrigin}/${chatId}/pull/${number}#discussion_r${comment.id}`;
6102
+ const line = comment.line ?? comment.original_line;
6103
+ const location = `File: ${comment.path ?? '?'}${line != null ? ` (line ${line}${comment.side ? `, ${comment.side}` : ''})` : ''}`;
6104
+ candidates.push({
6105
+ key: commentKey,
6106
+ attrKey: `rc:${comment.id}`,
6107
+ createdAt: comment.created_at,
6108
+ envelope: {
6109
+ channelName: this.name,
6110
+ senderId: author.toLowerCase(),
6111
+ senderName: author,
6112
+ chatId,
6113
+ threadId,
6114
+ messageId: commentKey,
6115
+ text: `New inline review comment by @${author}:\n${location}\n${renderBody(comment.body)}\nComment: ${url}`,
6116
+ isGroup: true,
6117
+ isMentioned: true,
6118
+ isReplyToBot: false,
6119
+ metadata,
6120
+ },
6121
+ });
6122
+ }
6123
+ candidates.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
6124
+ const commitCursor = (newSince) => {
6125
+ // GitHub compares `since` at whole-second granularity while nowIso carries
6126
+ // milliseconds: a comment created later in the same second as the fetch
6127
+ // snapshot would be excluded from every later fetch. Floor the cursor to
6128
+ // the second so that whole second is re-listed next pass (anything already
6129
+ // delivered is deduped), never skipped past.
6130
+ const floored = new Date(Math.floor(Date.parse(newSince) / 1000) * 1000).toISOString();
6131
+ this.prWatchState.entries[key] = {
6132
+ ...(this.prWatchState.entries[key] ?? {}),
6133
+ commentSince: floored,
6134
+ commentLastFetchAt: now,
6135
+ };
6136
+ this.savePrWatchState();
6137
+ };
6138
+ // No new comments: advance the cursor without any attribution round-trip.
6139
+ if (candidates.length === 0) {
6140
+ commitCursor(nowIso);
6141
+ return;
6142
+ }
6143
+ // Look up posted comments only now that there is something to deliver, so a
6144
+ // quiet pass costs no serve round-trips. A comment is withheld only from the
6145
+ // session that wrote it. Query EVERY bound follower, not just the resolved
6146
+ // targets: the delivery-time Gone fallback re-resolves over the followers,
6147
+ // so the exclusion must also cover a same-role author that is not the
6148
+ // primary target, or the fallback would hand the comment back to it.
6149
+ const followerIds = new Set(targets.map((target) => target.sessionId));
6150
+ for (const follower of this.boundFollowersOf(chatId, number)) {
6151
+ followerIds.add(follower.summary.sessionId);
6152
+ }
6153
+ const postedBySession = new Map();
6154
+ for (const sessionId of followerIds) {
6155
+ const lookup = this.boundSessions.postedCommentIds;
6156
+ const ids = lookup
6157
+ ? await lookup
6158
+ .call(this.boundSessions, sessionId)
6159
+ .catch(() => new Set())
6160
+ : new Set();
6161
+ postedBySession.set(sessionId, ids);
6162
+ }
6163
+ const excludeFor = (candidate) => {
6164
+ const exclude = new Set();
6165
+ for (const sessionId of followerIds) {
6166
+ if (postedBySession.get(sessionId)?.has(candidate.attrKey)) {
6167
+ exclude.add(sessionId);
6168
+ }
6169
+ }
6170
+ return exclude;
6171
+ };
6172
+ // Exclude author-owned comments BEFORE the batch cap. They record no dedupe
6173
+ // key, so if they occupied batch slots a run of same-second self-authored
6174
+ // comments would re-fill every batch and the capped cursor would never reach
6175
+ // the tail. Filtering them out keeps the cap and the cursor progressing over
6176
+ // deliverable comments; the excluded ones are simply advanced past.
6177
+ const deliverable = [];
6178
+ for (const candidate of candidates) {
6179
+ const exclude = excludeFor(candidate);
6180
+ if (targets.some((target) => !exclude.has(target.sessionId))) {
6181
+ deliverable.push(candidate);
6182
+ continue;
6183
+ }
6184
+ // Every bound target authored this same-account comment itself, so no
6185
+ // session is left to receive it. The notification lanes cannot see it
6186
+ // either (same account => no notification), so this skip row is the
6187
+ // comment's only journal trace — record it instead of consuming silently.
6188
+ this.recordChannelEvent({
6189
+ type: 'inbound',
6190
+ outcome: 'skipped',
6191
+ reason: 'comment_watch_no_target',
6192
+ repository: chatId,
6193
+ thread: threadId,
6194
+ number,
6195
+ messageId: candidate.key,
6196
+ });
6197
+ }
6198
+ if (deliverable.length === 0) {
6199
+ commitCursor(nowIso);
6200
+ return;
6201
+ }
6202
+ // Cap the burst against the pass-wide budget shared by all watched PRs;
6203
+ // the cursor resumes before the last processed comment when capped so the
6204
+ // tail drains over subsequent passes.
6205
+ const batch = deliverable.slice(0, Math.min(MAX_WATCH_COMMENTS_PER_PASS, budget.remaining));
6206
+ budget.remaining -= batch.length;
6207
+ const capped = deliverable.length > batch.length;
6208
+ let allSettled = true;
6209
+ for (const candidate of batch) {
6210
+ // Private-only: never answered in public. The stable comment id dedupes
6211
+ // across polls. Only same-account comments reach this loop (see the
6212
+ // candidate filter), and those generate no GitHub notification, so
6213
+ // recording the shared key cannot pre-empt a notification lane.
6214
+ const settled = await this.dispatchEnvelope(candidate.envelope, number, { dispatchedComments: [candidate.key] }, true, excludeFor(candidate));
6215
+ if (!settled)
6216
+ allSettled = false;
6217
+ }
6218
+ if (!allSettled) {
6219
+ // A dispatch returned false without a durable claim (e.g. the publication
6220
+ // audit is unreadable, which freezes the notification cursor but not this
6221
+ // independent one). Keep commentSince so the next pass re-fetches and
6222
+ // retries; dispatchedComments dedupes anything already claimed. Advancing
6223
+ // here would skip the comment past with no task and no re-delivery chance.
6224
+ commitCursor(since);
6225
+ }
6226
+ else if (capped) {
6227
+ // Resume just before the last processed comment so the unprocessed tail is
6228
+ // re-fetched next pass (a second of overlap is deduped, never lost).
6229
+ const last = batch[batch.length - 1];
6230
+ commitCursor(new Date(Date.parse(last.createdAt) - 1000).toISOString());
6231
+ }
6232
+ else {
6233
+ commitCursor(nowIso);
6234
+ }
6235
+ }
5383
6236
  /**
5384
6237
  * Deliver queued watch events. Order per event: claim the inbound task
5385
6238
  * (durable), move the key from pending to fired (durable), then run the
@@ -5644,59 +6497,97 @@ export class GithubChannel extends PollingChannelBase {
5644
6497
  }
5645
6498
  }
5646
6499
  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);
6500
+ // The observation is accumulated per ATTEMPT, inside the retried
6501
+ // closure: githubApi retries the whole pagination, and state carried
6502
+ // over from an attempt that died on a later page would let its partial
6503
+ // pending/success readings decide the retry's aggregate.
6504
+ const checks = await this.githubApi(async () => {
6505
+ let sawFailure = false;
6506
+ let sawPending = false;
6507
+ let sawSuccess = false;
6508
+ let namesIncomplete = false;
6509
+ const failedChecks = [];
6510
+ await this.octokit.paginate(this.octokit.rest.checks.listForRef, {
6511
+ owner,
6512
+ repo,
6513
+ ref: sha,
6514
+ per_page: 100,
6515
+ }, (response, done) => {
6516
+ // Octokit's conclusion union omits 'startup_failure', which the
6517
+ // API does return and this aggregate must count as a failure.
6518
+ const runs = response.data;
6519
+ for (const run of runs) {
6520
+ if (run.status !== 'completed') {
6521
+ sawPending = true;
6522
+ continue;
6523
+ }
6524
+ if (run.conclusion === 'failure' ||
6525
+ run.conclusion === 'timed_out' ||
6526
+ run.conclusion === 'action_required' ||
6527
+ // A workflow that fails at startup (e.g. a broken workflow
6528
+ // file) never runs a single job; missing it would certify a
6529
+ // broken CI as 'none' or even 'success'. A deliberate SUBSET
6530
+ // of core's FAILING_CHECK_RUN_CONCLUSIONS: core also counts
6531
+ // cancelled/stale, which the design excludes as
6532
+ // concurrency-cancel noise (a superseded run's cancellation
6533
+ // is not a CI failure of this head).
6534
+ run.conclusion === 'startup_failure') {
6535
+ sawFailure = true;
6536
+ if (typeof run.name === 'string' &&
6537
+ run.name.length > 0 &&
6538
+ failedChecks.length < MAX_REPORTED_FAILED_CHECKS) {
6539
+ failedChecks.push(run.name);
6540
+ }
6541
+ }
6542
+ else if (run.conclusion === 'success') {
6543
+ sawSuccess = true;
6544
+ }
6545
+ }
6546
+ // A failure decides the aggregate: no later page can overturn
6547
+ // it, so stop paging instead of spending one request per page
6548
+ // of a head that carries hundreds of check runs. Whole pages are
6549
+ // still read, so a head whose failures all fit in the pages read
6550
+ // reports the same names as before.
6551
+ if (sawFailure) {
6552
+ // Only unread pages make the list partial: stopping on the
6553
+ // LAST page read everything. The iterator follows this same
6554
+ // header, so its presence is exactly "a page went unread".
6555
+ namesIncomplete = /<[^<>]+>;\s*rel="next"/.test(response.headers?.link ?? '');
6556
+ done();
6557
+ }
6558
+ return [];
6559
+ });
6560
+ return {
6561
+ sawFailure,
6562
+ sawPending,
6563
+ sawSuccess,
6564
+ failedChecks,
6565
+ namesIncomplete,
6566
+ };
6567
+ }, `checks.listForRef(${sha})`, 3, (err) => !isWatchFailFastError(err));
6568
+ let { sawFailure, sawPending, sawSuccess } = checks;
6569
+ const { failedChecks, namesIncomplete } = checks;
6570
+ // A check run already failed, so the combined status could only confirm
6571
+ // 'failure' — skip the request rather than pay for a decided aggregate.
6572
+ if (!sawFailure) {
6573
+ const { data: combined } = await this.githubApi(() => this.octokit.rest.repos.getCombinedStatusForRef({
6574
+ owner,
6575
+ repo,
6576
+ ref: sha,
6577
+ }), `combinedStatus(${sha})`, 3, (err) => !isWatchFailFastError(err));
6578
+ // GitHub returns {state:"pending", total_count:0, statuses:[]} for a
6579
+ // SHA with no legacy commit statuses; an empty combined status must not
6580
+ // count as active CI (it would keep every poll re-fetching forever).
6581
+ if (combined.total_count > 0) {
6582
+ if (combined.state === 'failure' || combined.state === 'error') {
6583
+ sawFailure = true;
6584
+ }
6585
+ else if (combined.state === 'pending') {
6586
+ sawPending = true;
6587
+ }
6588
+ else {
6589
+ sawSuccess = true;
5677
6590
  }
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
6591
  }
5701
6592
  }
5702
6593
  const aggregate = sawFailure
@@ -5706,7 +6597,7 @@ export class GithubChannel extends PollingChannelBase {
5706
6597
  : sawSuccess
5707
6598
  ? 'success'
5708
6599
  : 'none';
5709
- return { aggregate, failedChecks };
6600
+ return { aggregate, failedChecks, namesIncomplete };
5710
6601
  }
5711
6602
  async markNotificationsAsRead(lastReadAt) {
5712
6603
  await this.githubApi(() => this.octokit.rest.activity.markNotificationsAsRead({