@qwen-code/channel-github 0.27.4 → 0.28.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.
@@ -314,6 +314,14 @@ const PR_WATCH_BUDGET_RESERVE = 200;
314
314
  * bound PR. Above the 60s poll interval to bound the fan-out at the watch cap.
315
315
  */
316
316
  const COMMENT_RECHECK_INTERVAL_MS = 2 * 60 * 1000;
317
+ /**
318
+ * Minimum downtime gap before the first watch pass after startup digests the
319
+ * comment backlog instead of delivering one prompt per comment. The effective
320
+ * threshold scales with the poll interval (5 intervals) so a long-interval
321
+ * channel does not digest every poll; a sustained API outage counts as a gap
322
+ * because failed polls do not save the cursor heartbeat.
323
+ */
324
+ const STARTUP_DIGEST_MIN_GAP_MS = 10 * 60 * 1000;
317
325
  /**
318
326
  * Pass-wide budget on watched comments, shared by every watched PR in a single
319
327
  * watch pass (not a per-PR cap): commentSince survives a restart, so after a
@@ -324,6 +332,17 @@ const COMMENT_RECHECK_INTERVAL_MS = 2 * 60 * 1000;
324
332
  * processed comment so the tail drains over subsequent passes, never dropped.
325
333
  */
326
334
  const MAX_WATCH_COMMENTS_PER_PASS = 20;
335
+ /**
336
+ * Bound on consecutive PERMANENT digest retirements (a preflight rejection
337
+ * returns settled with no delivery). A retired digest is re-listed and retried
338
+ * — the route/sender gate may be fixed — but not forever: without a bound a
339
+ * permanently-rejected digest holds its cursor and spends the pass-wide watch
340
+ * budget every poll for the process lifetime with zero prompts. At this bound
341
+ * the backlog is consumed with a visible journal trace instead. Transient
342
+ * deferrals (settled === false) do not count toward it and keep the fail-closed
343
+ * hold.
344
+ */
345
+ const MAX_DIGEST_RETIREMENT_RETRIES = 3;
327
346
  /**
328
347
  * Backpressure horizon for bound-session delivery: queue-full and
329
348
  * temporarily-unavailable conditions defer without consuming the failure
@@ -371,7 +390,15 @@ function isPrWatchEntryShape(value) {
371
390
  return (stringOrUndef(entry.title) &&
372
391
  stringOrUndef(entry.commentBaseline) &&
373
392
  stringOrUndef(entry.commentSince) &&
374
- numberOrUndef(entry.commentLastFetchAt));
393
+ numberOrUndef(entry.commentLastFetchAt) &&
394
+ (entry.digestPending === undefined ||
395
+ typeof entry.digestPending === 'boolean') &&
396
+ (entry.digestSizeArmed === undefined ||
397
+ typeof entry.digestSizeArmed === 'boolean') &&
398
+ (entry.digestRendered === undefined ||
399
+ (Array.isArray(entry.digestRendered) &&
400
+ entry.digestRendered.every((k) => typeof k === 'string'))) &&
401
+ numberOrUndef(entry.digestRetiredCount));
375
402
  }
376
403
  /**
377
404
  * Parse and validate boundSessionActions into the lookup map connect() and
@@ -394,10 +421,12 @@ function normalizeBoundSessionActions(config, channelName) {
394
421
  return validateBoundActionEntries(entries, source, BOUND_ACTION_VOCABULARY);
395
422
  }
396
423
  /**
397
- * Whether the channel still uses the deprecated state-watch surface:
398
- * `prWatchEvents` itself, or a `watch:*` key in `boundSessionActions`.
399
- * These keys are accepted for one minor release; the daemon reads them as a
400
- * per-host alias when `serve.sessionPrWatch` is unset.
424
+ * Whether the channel still uses any of the four deprecated state-watch keys:
425
+ * `prWatchEvents`, a `watch:*` key in `boundSessionActions`, `prWatchLimit`
426
+ * or `prWatchBudgetReserve`. The first two are accepted for one minor release
427
+ * and read by the daemon as a per-host alias while `serve.sessionPrWatch` and
428
+ * its events environment override are both unset; the two limit knobs are
429
+ * ignored, and the pass uses its built-in budget.
401
430
  */
402
431
  function usesDeprecatedPrWatchSurface(config) {
403
432
  if (config.prWatchEvents !== undefined)
@@ -611,6 +640,9 @@ const BOUND_DELIVERY_COPY = {
611
640
  commentTruncated: (count) => `comment truncated: ${count} more characters`,
612
641
  newCommentLead: (author) => `New comment by @${author}:`,
613
642
  newInlineReviewCommentLead: (author) => `New inline review comment by @${author}:`,
643
+ offlineCommentsLead: (count) => `Offline backlog: ${count} new comment(s) on the PR since the last successful poll:`,
644
+ commentBacklogLead: (count) => `Comment backlog: ${count} new comment(s) on this PR:`,
645
+ offlineOmittedNotice: (count) => `${count} comment(s) omitted from this digest to fit the prompt budget; they will follow in further digests`,
614
646
  reviewRequestedInstruction: 'Return a formal review summary with verified actionable findings, or a concise no-blocker result.',
615
647
  assignInstruction: 'Triage this issue and respond with the next action.',
616
648
  },
@@ -622,6 +654,9 @@ const BOUND_DELIVERY_COPY = {
622
654
  commentTruncated: (count) => `评论已截断:省略了 ${count} 个字符`,
623
655
  newCommentLead: (author) => `@${author} 的新评论:`,
624
656
  newInlineReviewCommentLead: (author) => `@${author} 的新行内评审评论:`,
657
+ offlineCommentsLead: (count) => `离线积压:自上次成功轮询以来 PR 新增 ${count} 条评论:`,
658
+ commentBacklogLead: (count) => `评论积压:本 PR 新增 ${count} 条评论:`,
659
+ offlineOmittedNotice: (count) => `本摘要因篇幅省略了 ${count} 条评论,将分批摘要补投`,
625
660
  reviewRequestedInstruction: '请给出正式的评审总结,包含经核实的可操作发现;若没有阻塞问题,给出简洁的无阻塞结论。',
626
661
  assignInstruction: '请分诊该 issue 并给出下一步行动。',
627
662
  },
@@ -885,9 +920,20 @@ export class GithubChannel extends PollingChannelBase {
885
920
  boundDeliveredOrder = [];
886
921
  /**
887
922
  * An unreadable ring cannot prove a negative: fail CLOSED for the public
888
- * fallback (suppress it) rather than risk an irreversible duplicate.
923
+ * fallback (suppress it) rather than risk an irreversible duplicate. This
924
+ * verdict is NEVER cleared by a repair: the keys lost with the file stay
925
+ * unknown, so the suppression callers must keep failing closed for them.
889
926
  */
890
927
  boundDeliveredUnreadable = false;
928
+ /**
929
+ * A successful ring write after a startup-unreadable ring. Lets the digest
930
+ * prove its OWN acceptance from the freshly written key without clearing
931
+ * boundDeliveredUnreadable (which would convert the lost history from
932
+ * "unknown" to "not delivered" and open the public-duplicate window for
933
+ * every pre-corruption event). Suppression stays fail-closed; only the
934
+ * digest's delivered check consults this latch.
935
+ */
936
+ boundDeliveredRepaired = false;
891
937
  /**
892
938
  * Tasks retired privately during the current runInboundTask call (role
893
939
  * lost its match, siblings already delivered, ring suppression). Their
@@ -908,6 +954,14 @@ export class GithubChannel extends PollingChannelBase {
908
954
  * gated on this (a partial answer is not an absence).
909
955
  */
910
956
  boundSnapshotTrusted = false;
957
+ /**
958
+ * One-shot flag set when a downtime gap is detected; it arms the per-entry
959
+ * digestPending flags and clears as soon as it has armed them, so a skipped,
960
+ * aborted or untrusted pass cannot re-arm an entry an earlier pass already
961
+ * drained. The per-entry flags carry the digest for individual PRs across
962
+ * errors, cap exclusion, and restarts.
963
+ */
964
+ startupDigestPending = false;
911
965
  /**
912
966
  * False until ANY binding snapshot succeeds (complete or partial). The
913
967
  * cold-start comment-lane gate uses this, not boundSnapshotTrusted: the
@@ -1139,6 +1193,11 @@ export class GithubChannel extends PollingChannelBase {
1139
1193
  Number.isNaN(new Date(base.metaFloor).getTime()))) {
1140
1194
  delete base.metaFloor;
1141
1195
  }
1196
+ if (base.lastPollAt !== undefined &&
1197
+ (typeof base.lastPollAt !== 'string' ||
1198
+ Number.isNaN(new Date(base.lastPollAt).getTime()))) {
1199
+ delete base.lastPollAt;
1200
+ }
1142
1201
  for (const field of [
1143
1202
  'dispatchedBodies',
1144
1203
  'dispatchedComments',
@@ -1870,10 +1929,56 @@ export class GithubChannel extends PollingChannelBase {
1870
1929
  });
1871
1930
  }
1872
1931
  async pollOnce() {
1932
+ await this.runPollOnce();
1933
+ // Heartbeat stamped only on a SUCCESSFUL poll (the base class saves the
1934
+ // cursor after this resolves): failed polls leave it stale, so an
1935
+ // in-process outage grows the gap and is detected when polls recover.
1936
+ this.cursor.lastPollAt = new Date().toISOString();
1937
+ }
1938
+ async runPollOnce() {
1873
1939
  this.inboundPersistenceBlocked = false;
1874
1940
  this.notificationRetryPending = false;
1875
1941
  this.publicationAuditBlocked = false;
1876
1942
  this.publicationAuditKeysCache = undefined;
1943
+ // Downtime-gap detection on EVERY poll: a pure local comparison against
1944
+ // the last successful heartbeat. A healthy poll re-stamps it, so this
1945
+ // cannot fire in steady state; a restart OR an in-process outage whose
1946
+ // failed polls skipped the cursor save both grow the gap past the
1947
+ // threshold. The threshold scales with the poll interval so a
1948
+ // long-interval channel does not digest every poll.
1949
+ const lastPollAt = this.cursor.lastPollAt;
1950
+ if (lastPollAt !== undefined) {
1951
+ const gapMs = Date.now() - Date.parse(lastPollAt);
1952
+ const thresholdMs = Math.max(STARTUP_DIGEST_MIN_GAP_MS, 5 * this.pollInterval);
1953
+ if (gapMs > thresholdMs &&
1954
+ !this.startupDigestPending &&
1955
+ this.deliverToBoundSessions &&
1956
+ this.prCommentWatchEnabled) {
1957
+ this.startupDigestPending = true;
1958
+ // Persist the arm immediately: this poll's comment watch may be
1959
+ // skipped (failed binding refresh), and a restart before a trusted
1960
+ // pass must still find the arm and digest the backlog instead of
1961
+ // flooding one prompt per comment.
1962
+ try {
1963
+ this.loadPrWatchState();
1964
+ for (const entry of Object.values(this.prWatchState.entries)) {
1965
+ entry.digestPending = true;
1966
+ // A genuine gap is the current origin: reset any stale size-arm
1967
+ // origin so an outage that interrupts a size-armed drain still
1968
+ // reports the offline lead rather than the neutral one.
1969
+ entry.digestSizeArmed = false;
1970
+ }
1971
+ this.savePrWatchState();
1972
+ }
1973
+ catch (err) {
1974
+ // Watch state unreadable or the arm write failed: the in-memory flag
1975
+ // still arms the next successful pass. Surface it so a persisted-arm
1976
+ // write failure is not swallowed silently.
1977
+ process.stderr.write(`[Channel:${this.name}] could not persist the downtime-gap digest arm (the in-memory flag still arms the next pass): ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
1978
+ }
1979
+ process.stderr.write(`[Channel:${this.name}] downtime gap detected (${Math.round(gapMs / 1000)}s since the last successful poll); each bound PR's comment backlog digests into one prompt\n`);
1980
+ }
1981
+ }
1877
1982
  if (this.deliverToBoundSessions) {
1878
1983
  await this.refreshBoundSessions();
1879
1984
  }
@@ -1915,6 +2020,36 @@ export class GithubChannel extends PollingChannelBase {
1915
2020
  // recovers during this window still owes its recovery row.
1916
2021
  this.watchBudgetLow = false;
1917
2022
  this.closeWatchBudgetEpisode();
2023
+ if (!commentWatchActive) {
2024
+ // Comment watching is OFF (not merely skipped this poll): a persisted
2025
+ // digest arm must not survive a disabled restart and later digest the
2026
+ // comments accumulated while it was off. This is the observable site —
2027
+ // runPrStateWatch is never called while disabled. The design promises
2028
+ // per-comment delivery for comments accumulated while watching is off.
2029
+ // A transient boundRefreshFailed skip keeps the arm (the backlog is real).
2030
+ try {
2031
+ this.loadPrWatchState();
2032
+ let cleared = false;
2033
+ for (const entry of Object.values(this.prWatchState.entries)) {
2034
+ if (entry.digestPending === true) {
2035
+ entry.digestPending = false;
2036
+ entry.digestSizeArmed = false;
2037
+ // Keep the rendered frontier: it dedupes already-DELIVERED
2038
+ // members while commentSince stays held. Clearing it here would
2039
+ // let ring-evicted rendered keys re-list and re-deliver on
2040
+ // re-enable. It clears through the consumption paths instead.
2041
+ entry.digestRetiredCount = 0;
2042
+ cleared = true;
2043
+ }
2044
+ }
2045
+ if (cleared)
2046
+ this.savePrWatchState();
2047
+ }
2048
+ catch {
2049
+ // Watch state unreadable: nothing to clear, and the arm cannot be
2050
+ // consumed while watching is off anyway.
2051
+ }
2052
+ }
1918
2053
  }
1919
2054
  if (this.inboundRecoveryPending) {
1920
2055
  try {
@@ -4976,6 +5111,13 @@ export class GithubChannel extends PollingChannelBase {
4976
5111
  const path = this.channelFilePath('github-bound-delivered.json');
4977
5112
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
4978
5113
  writeFileSync(path, `${JSON.stringify({ keys: this.boundDeliveredOrder })}\n`, { encoding: 'utf-8', mode: 0o600 });
5114
+ // A successful write repairs the ring for the digest's own acceptance
5115
+ // check: latch the repair so the digest can prove its freshly written
5116
+ // key. Do NOT clear boundDeliveredUnreadable — the keys lost with the
5117
+ // file stay unknown, and the public-duplicate suppression callers must
5118
+ // keep failing closed for them (clearing it would open an irreversible
5119
+ // public-reply window for every pre-corruption event).
5120
+ this.boundDeliveredRepaired = true;
4979
5121
  }
4980
5122
  catch (err) {
4981
5123
  process.stderr.write(`[Channel:${this.name}] failed to persist bound-delivered ring (in-memory suppression still active): ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
@@ -5714,6 +5856,24 @@ export class GithubChannel extends PollingChannelBase {
5714
5856
  // can be due at once, and a per-PR cap would claim up to cap × watched-PR
5715
5857
  // durable tasks in a single poll. PRs that find it spent keep their cursor
5716
5858
  // and resume next pass.
5859
+ // Arm the digest on EVERY persisted entry — not just this snapshot's
5860
+ // active keys: a degraded (empty/partial) first poll must still arm the
5861
+ // entries on disk, so a restart before a complete snapshot finds the arm
5862
+ // and digests the backlog instead of flooding per comment. Entries
5863
+ // outside the watch-cap slice keep their arm until watched. The one-shot
5864
+ // clears HERE, once it has armed: the per-entry flags (persisted below)
5865
+ // carry the digest across per-PR errors, cap exclusion, untrusted
5866
+ // snapshots, and restarts. Keeping the global flag alive across aborted
5867
+ // passes would re-arm entries an earlier pass already drained, so a later
5868
+ // single fresh comment would digest under an outage lead that never
5869
+ // happened.
5870
+ if (this.startupDigestPending) {
5871
+ for (const entry of Object.values(this.prWatchState.entries)) {
5872
+ entry.digestPending = true;
5873
+ entry.digestSizeArmed = false;
5874
+ }
5875
+ this.startupDigestPending = false;
5876
+ }
5717
5877
  const commentBudget = { remaining: MAX_WATCH_COMMENTS_PER_PASS };
5718
5878
  for (const [key, candidate] of candidates) {
5719
5879
  if (candidate.terminal)
@@ -5730,13 +5890,14 @@ export class GithubChannel extends PollingChannelBase {
5730
5890
  try {
5731
5891
  // Additive comment watch: isolates its own failures so a comment
5732
5892
  // fetch problem never skips the next PR.
5733
- await this.watchPrComments(key, candidate.chatId, candidate.number, commentBudget);
5893
+ await this.watchPrComments(key, candidate.chatId, candidate.number, commentBudget, this.prWatchState.entries[key]?.digestPending === true);
5734
5894
  }
5735
5895
  catch (err) {
5736
5896
  if (isWatchPassAbortError(err)) {
5737
5897
  // Shared credential/rate-limit failure: abort the rest of the
5738
5898
  // pass instead of issuing one doomed request per watched PR.
5739
- // Later polls retry the full set once the condition clears.
5899
+ // Later polls retry the full set once the condition clears. The
5900
+ // per-entry arms persisted below carry the digest across the abort.
5740
5901
  process.stderr.write(`[Channel:${this.name}] PR watch pass aborted at ${key} (credential/rate limit); the remaining watched PRs skip this poll: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
5741
5902
  break;
5742
5903
  }
@@ -5756,14 +5917,22 @@ export class GithubChannel extends PollingChannelBase {
5756
5917
  * what prevents a fix session's own reply from re-triggering it.
5757
5918
  *
5758
5919
  * Default-on with deliverToBoundSessions; `prCommentWatch: false` disables
5759
- * it. Failures are isolated here so one PR's fetch never skips the next.
5920
+ * it. Failures are isolated here so they never skip the state transitions.
5921
+ *
5922
+ * `digestMode` (the persisted per-entry arm set by a detected downtime gap,
5923
+ * or a window larger than the per-comment pass cap) renders AT MOST the
5924
+ * newest members that fit the shared body budget as ONE private summary
5925
+ * prompt; the remainder is named in a front omission notice with its keys
5926
+ * unrecorded and the cursor held before the backlog head, so the next pass
5927
+ * digests the remainder. The event class stays `comment`, so role routing is
5928
+ * identical to individual deliveries.
5760
5929
  */
5761
- async watchPrComments(key, chatId, number, budget) {
5762
- if (!this.deliverToBoundSessions ||
5763
- !this.prCommentWatchEnabled ||
5764
- !this.boundSessions) {
5930
+ async watchPrComments(key, chatId, number, budget, digestMode) {
5931
+ // The poll loop only reaches this pass with bound delivery and comment
5932
+ // watching enabled, and clears any stale digest arm when they are off. The
5933
+ // handle guard narrows the nullable handle for the delivery lookups below.
5934
+ if (!this.boundSessions)
5765
5935
  return;
5766
- }
5767
5936
  const entry = this.prWatchState.entries[key] ?? {};
5768
5937
  const now = Date.now();
5769
5938
  const nowIso = new Date(now).toISOString();
@@ -5775,6 +5944,10 @@ export class GithubChannel extends PollingChannelBase {
5775
5944
  commentBaseline: nowIso,
5776
5945
  commentSince: nowIso,
5777
5946
  commentLastFetchAt: now,
5947
+ digestPending: false,
5948
+ digestSizeArmed: false,
5949
+ digestRendered: [],
5950
+ digestRetiredCount: 0,
5778
5951
  };
5779
5952
  this.savePrWatchState();
5780
5953
  return;
@@ -5786,6 +5959,8 @@ export class GithubChannel extends PollingChannelBase {
5786
5959
  // The burst budget is shared by every watched PR in this pass. A PR that
5787
5960
  // arrives after it is spent fetches nothing and keeps its cursor untouched,
5788
5961
  // so its tail resumes on the next pass instead of being skipped past.
5962
+ // The digest path never decrements it (one task per PR, not per comment),
5963
+ // so a digest pass always finds the budget intact.
5789
5964
  if (budget.remaining <= 0) {
5790
5965
  return;
5791
5966
  }
@@ -5858,7 +6033,13 @@ export class GithubChannel extends PollingChannelBase {
5858
6033
  return;
5859
6034
  }
5860
6035
  const baseline = entry.commentBaseline;
5861
- const alreadyDispatched = (commentKey) => this.cursor.dispatchedComments?.includes(commentKey) === true;
6036
+ // The held digest's rendered frontier backs up the shared dispatchedComments
6037
+ // ring: the ring evicts keys older than the notification cursor, which a
6038
+ // healthy poll advances past a held digest's backlog, so a rendered key can
6039
+ // be evicted mid-drain. The per-entry frontier keeps it deduped regardless.
6040
+ const renderedFrontier = new Set(entry.digestRendered ?? []);
6041
+ const alreadyDispatched = (commentKey) => this.cursor.dispatchedComments?.includes(commentKey) === true ||
6042
+ renderedFrontier.has(commentKey);
5862
6043
  const candidates = [];
5863
6044
  const threadId = `pr:${number}`;
5864
6045
  const metadata = `${this.buildMetadata(chatId, threadId, entry.title ?? '')}\nTrigger: comment.`;
@@ -5872,11 +6053,12 @@ export class GithubChannel extends PollingChannelBase {
5872
6053
  // past the cut. The bound prompt caps the final body at the same value.
5873
6054
  const omitted = total - BOUND_PROMPT_BODY_MAX_CODE_POINTS;
5874
6055
  if (omitted <= 0)
5875
- return { text: display, boundText: display };
6056
+ return { text: display, boundText: display, display };
5876
6057
  const prefix = truncateCodePoints(display, BOUND_PROMPT_BODY_MAX_CODE_POINTS);
5877
6058
  return {
5878
6059
  text: `${prefix}… [${BOUND_DELIVERY_COPY.en.commentTruncated(omitted)}]`,
5879
6060
  boundText: `${prefix}… [${copy.commentTruncated(omitted)}]`,
6061
+ display,
5880
6062
  };
5881
6063
  };
5882
6064
  // The watch closes the SAME-account gap: GitHub sends the channel account no
@@ -5905,6 +6087,9 @@ export class GithubChannel extends PollingChannelBase {
5905
6087
  key: commentKey,
5906
6088
  attrKey: `ic:${comment.id}`,
5907
6089
  createdAt: comment.created_at,
6090
+ author,
6091
+ url,
6092
+ body: rendered.display,
5908
6093
  boundText: this.locale === 'en'
5909
6094
  ? undefined
5910
6095
  : `${copy.newCommentLead(author)}\n${rendered.boundText}\nComment: ${url}`,
@@ -5941,6 +6126,10 @@ export class GithubChannel extends PollingChannelBase {
5941
6126
  key: commentKey,
5942
6127
  attrKey: `rc:${comment.id}`,
5943
6128
  createdAt: comment.created_at,
6129
+ author,
6130
+ url,
6131
+ body: rendered.display,
6132
+ inlineLocation: location,
5944
6133
  boundText: this.locale === 'en'
5945
6134
  ? undefined
5946
6135
  : `${copy.newInlineReviewCommentLead(author)}\n${location}\n${rendered.boundText}\nComment: ${url}`,
@@ -5960,7 +6149,7 @@ export class GithubChannel extends PollingChannelBase {
5960
6149
  });
5961
6150
  }
5962
6151
  candidates.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
5963
- const commitCursor = (newSince) => {
6152
+ const commitCursor = (newSince, clearDigest = false) => {
5964
6153
  // GitHub compares `since` at whole-second granularity while nowIso carries
5965
6154
  // milliseconds: a comment created later in the same second as the fetch
5966
6155
  // snapshot would be excluded from every later fetch. Floor the cursor to
@@ -5971,12 +6160,22 @@ export class GithubChannel extends PollingChannelBase {
5971
6160
  ...(this.prWatchState.entries[key] ?? {}),
5972
6161
  commentSince: floored,
5973
6162
  commentLastFetchAt: now,
6163
+ // The digest arm clears only when this PR's backlog is consumed;
6164
+ // a held cursor (omitted tail, refused dispatch) keeps it armed.
6165
+ ...(clearDigest
6166
+ ? {
6167
+ digestPending: false,
6168
+ digestSizeArmed: false,
6169
+ digestRendered: [],
6170
+ digestRetiredCount: 0,
6171
+ }
6172
+ : {}),
5974
6173
  };
5975
6174
  this.savePrWatchState();
5976
6175
  };
5977
6176
  // No new comments: advance the cursor without any attribution round-trip.
5978
6177
  if (candidates.length === 0) {
5979
- commitCursor(nowIso);
6178
+ commitCursor(nowIso, true);
5980
6179
  return;
5981
6180
  }
5982
6181
  // Look up posted comments only now that there is something to deliver, so a
@@ -6053,9 +6252,231 @@ export class GithubChannel extends PollingChannelBase {
6053
6252
  });
6054
6253
  }
6055
6254
  if (deliverable.length === 0) {
6056
- commitCursor(gateHoldCursor ?? nowIso);
6255
+ // A gate grace hold keeps the backlog (and the digest arm) for the next
6256
+ // pass; a genuine no-target retirement consumes it with a trace.
6257
+ commitCursor(gateHoldCursor ?? nowIso, gateHoldCursor === undefined);
6057
6258
  return;
6058
6259
  }
6260
+ // Digest mode is armed by a downtime gap (per-entry flag) OR by backlog
6261
+ // size: a window larger than the per-comment pass cap would flood one
6262
+ // prompt per comment however it accumulated (a healed endpoint after
6263
+ // sustained per-PR fetch failures keeps the heartbeat fresh, so the gap
6264
+ // alone never arms it).
6265
+ const digesting = digestMode || deliverable.length > MAX_WATCH_COMMENTS_PER_PASS;
6266
+ if (digesting) {
6267
+ // The gap arm reports the outage; the size arm (and its follow-ups,
6268
+ // which re-enter via the persisted arm) fires on a healthy heartbeat and
6269
+ // must not claim the channel was not running.
6270
+ const gapLead = digestMode && this.prWatchState.entries[key]?.digestSizeArmed !== true;
6271
+ // Allocate the shared body ceiling NEWEST-FIRST: the cap keeps the
6272
+ // prefix, so rendering oldest-first would let it eat exactly the
6273
+ // newest, most actionable members. Members that do not fit are named
6274
+ // in the front omission notice, their keys are NOT recorded, and the
6275
+ // cursor holds before the backlog head so the next pass digests the
6276
+ // remainder — nothing is consumed without being delivered.
6277
+ const newest = deliverable.slice(-MAX_AGGREGATE_COMMENTS);
6278
+ const memberLine = (candidate, language) => {
6279
+ const digestCopy = BOUND_DELIVERY_COPY[language];
6280
+ const total = Array.from(candidate.body).length;
6281
+ const excerpt = total > MAX_AGGREGATE_COMMENT_CHARS
6282
+ ? `${truncateCodePoints(candidate.body, MAX_AGGREGATE_COMMENT_CHARS)}… [${digestCopy.commentTruncated(total - MAX_AGGREGATE_COMMENT_CHARS)}]`
6283
+ : candidate.body;
6284
+ const lead = candidate.inlineLocation !== undefined
6285
+ ? `${digestCopy.newInlineReviewCommentLead(candidate.author)}\n${candidate.inlineLocation}`
6286
+ : digestCopy.newCommentLead(candidate.author);
6287
+ return `${lead}\n${excerpt}\nComment: ${candidate.url}`;
6288
+ };
6289
+ const cp = (text) => Array.from(text).length;
6290
+ const renderFor = (language, members) => {
6291
+ const digestCopy = BOUND_DELIVERY_COPY[language];
6292
+ const omitted = deliverable.length - members.length;
6293
+ const leadText = gapLead
6294
+ ? digestCopy.offlineCommentsLead(deliverable.length)
6295
+ : digestCopy.commentBacklogLead(deliverable.length);
6296
+ // The omission notice rides at the FRONT: a tail notice would be
6297
+ // the first thing the shared body cap truncates away.
6298
+ return (leadText +
6299
+ (omitted > 0
6300
+ ? `\n[${digestCopy.offlineOmittedNotice(omitted)}]`
6301
+ : '') +
6302
+ `\n${members.map((candidate) => memberLine(candidate, language)).join('\n')}`);
6303
+ };
6304
+ const leadCp = cp(gapLead
6305
+ ? BOUND_DELIVERY_COPY[this.locale].offlineCommentsLead(deliverable.length)
6306
+ : BOUND_DELIVERY_COPY[this.locale].commentBacklogLead(deliverable.length));
6307
+ const rendered = [];
6308
+ let used = leadCp + 1;
6309
+ for (let i = newest.length - 1; i >= 0; i -= 1) {
6310
+ const candidate = newest[i];
6311
+ const lineCp = cp(memberLine(candidate, this.locale));
6312
+ // Notice sized for the count IF this member is accepted; the final
6313
+ // notice is no larger, so a fit here stays a fit at the end.
6314
+ const noticeCp = deliverable.length - (rendered.length + 1) > 0
6315
+ ? cp(`\n[${BOUND_DELIVERY_COPY[this.locale].offlineOmittedNotice(deliverable.length - (rendered.length + 1))}]`)
6316
+ : 0;
6317
+ if (used + lineCp + 1 + noticeCp > BOUND_PROMPT_BODY_MAX_CODE_POINTS) {
6318
+ break;
6319
+ }
6320
+ rendered.unshift(candidate);
6321
+ used += lineCp + 1;
6322
+ }
6323
+ if (rendered.length > 0) {
6324
+ // Authorship exclusion is computed over the RENDERED slice (the
6325
+ // body the session actually sees) and over the SAME follower
6326
+ // population as the per-comment path, so the delivery-time Gone
6327
+ // fallback cannot hand the digest back to a session that authored
6328
+ // every rendered member. A follower is excluded only if it authored
6329
+ // EVERY rendered member; a partial author still receives the digest
6330
+ // (the mutual-authorship case must not consume with zero prompts).
6331
+ // An all-targets exclusion is unreachable: every deliverable member
6332
+ // has some target that did not author it.
6333
+ const exclude = new Set();
6334
+ for (const sessionId of followerIds) {
6335
+ if (rendered.every((candidate) => excludeFor(candidate).has(sessionId))) {
6336
+ exclude.add(sessionId);
6337
+ }
6338
+ }
6339
+ const omitted = deliverable.length - rendered.length;
6340
+ // Content-hash identity over the RENDERED members (the aggregate
6341
+ // lane's superset semantics): a crash before the cursor save
6342
+ // re-lists the window, the member dedupe filters consumed comments,
6343
+ // and a grown window dispatches only the new remainder.
6344
+ const digestId = `comment-digest:${number}:${createHash('sha256')
6345
+ .update(rendered
6346
+ .map((candidate) => candidate.key)
6347
+ .sort()
6348
+ .join('\n'))
6349
+ .digest('hex')
6350
+ .slice(0, 40)}`;
6351
+ // The digest carries the CHANNEL ACCOUNT's identity, exactly like
6352
+ // the per-comment envelopes on this same-account lane: a synthetic
6353
+ // sender would fail the group sender allowlist preflight (the
6354
+ // waiver matches the channel login), retiring the digest while the
6355
+ // cursor advanced past the whole backlog.
6356
+ const envelope = {
6357
+ channelName: this.name,
6358
+ senderId: this.botUsername?.toLowerCase() ?? 'github',
6359
+ senderName: this.botUsername ?? 'GitHub',
6360
+ chatId,
6361
+ threadId,
6362
+ messageId: digestId,
6363
+ text: renderFor('en', rendered),
6364
+ isGroup: true,
6365
+ isMentioned: true,
6366
+ isReplyToBot: false,
6367
+ metadata,
6368
+ };
6369
+ const settled = await this.dispatchEnvelope(envelope, number, { dispatchedComments: rendered.map((candidate) => candidate.key) }, true, exclude, this.locale === 'en' ? undefined : renderFor(this.locale, rendered));
6370
+ // A retired verdict (e.g. preflight rejection) consumes the task
6371
+ // and returns settled WITHOUT recording a delivery: treat it as
6372
+ // unconsumed so the cursor never advances past members that were
6373
+ // never delivered. The durable delivery ring is the evidence. An
6374
+ // unreadable ring is unknown, not positive evidence — but once a
6375
+ // successful write latches the repair, the digest may prove its OWN
6376
+ // acceptance from the freshly written key. The unreadable verdict
6377
+ // itself is never cleared: the suppression callers keep failing
6378
+ // closed for the keys lost with the file (gate the repair here only).
6379
+ const delivered = settled &&
6380
+ (this.boundDeliveredUnreadable
6381
+ ? this.boundDeliveredRepaired &&
6382
+ this.boundDeliveredKeys.has(this.boundEventKey(envelope))
6383
+ : this.boundEventAlreadyDelivered(envelope));
6384
+ if (!delivered) {
6385
+ const heldEntry = this.prWatchState.entries[key];
6386
+ if (settled) {
6387
+ // Permanent retirement: preflight rejected the digest (settled
6388
+ // with no delivery). Bound the retry — the route/sender gate may
6389
+ // be fixed, but a permanently-rejected digest must not hold the
6390
+ // cursor and spend the pass-wide watch budget every poll for the
6391
+ // process lifetime with zero prompts. A transient deferral
6392
+ // (settled === false) keeps the fail-closed hold below instead.
6393
+ const retiredCount = (heldEntry?.digestRetiredCount ?? 0) + 1;
6394
+ if (heldEntry)
6395
+ heldEntry.digestRetiredCount = retiredCount;
6396
+ if (retiredCount >= MAX_DIGEST_RETIREMENT_RETRIES) {
6397
+ // Consume the WHOLE deliverable window with a visible trace
6398
+ // rather than retry the identical rejected attempt forever: the
6399
+ // cursor advances past every deliverable member (the rendered
6400
+ // keys stay recorded; the omitted tail is consumed by the cursor
6401
+ // advance), so none of them re-list.
6402
+ this.recordChannelEvent({
6403
+ type: 'inbound',
6404
+ outcome: 'skipped',
6405
+ reason: 'comment_digest_retired',
6406
+ repository: chatId,
6407
+ thread: threadId,
6408
+ number,
6409
+ messageId: digestId,
6410
+ detail: {
6411
+ consumedComments: deliverable.length,
6412
+ retirements: retiredCount,
6413
+ },
6414
+ });
6415
+ process.stderr.write(`[Channel:${this.name}] comment digest for ${key} retired at preflight ${retiredCount} times; consuming ${deliverable.length} comment(s) with a trace instead of retrying\n`);
6416
+ commitCursor(nowIso, true);
6417
+ return;
6418
+ }
6419
+ }
6420
+ else if (heldEntry) {
6421
+ // Transient deferral, not a permanent retirement: reset the streak.
6422
+ heldEntry.digestRetiredCount = 0;
6423
+ }
6424
+ // Undo the claim-time member recording: otherwise the next pass
6425
+ // filters every member as already dispatched, the empty candidate
6426
+ // set advances the cursor past the whole backlog, and the retired
6427
+ // digest is consumed with zero prompts one poll later. The removed
6428
+ // keys re-list next pass; the arm and commentSince are kept.
6429
+ const claimed = new Set(rendered.map((candidate) => candidate.key));
6430
+ this.cursor.dispatchedComments = (this.cursor.dispatchedComments ?? []).filter((key) => !claimed.has(key));
6431
+ const times = this.cursor.dispatchedCommentTimes;
6432
+ if (times) {
6433
+ for (const key of claimed)
6434
+ delete times[key];
6435
+ }
6436
+ commitCursor(since);
6437
+ return;
6438
+ }
6439
+ if (omitted === 0) {
6440
+ commitCursor(nowIso, true);
6441
+ }
6442
+ else {
6443
+ // Hold before the backlog head and KEEP the arm: the omitted
6444
+ // prefix re-lists next pass and digests again (the notice promised
6445
+ // further digests); the rendered suffix is deduped. Arm regardless
6446
+ // of how the digest was entered — the size arm has no gap-arming
6447
+ // loop, so the omitted tail must persist its own arm or it would
6448
+ // drain one prompt per comment. Remember a size-triggered origin so
6449
+ // the follow-up keeps the neutral lead (no outage was detected).
6450
+ const armedEntry = this.prWatchState.entries[key];
6451
+ if (armedEntry) {
6452
+ armedEntry.digestPending = true;
6453
+ if (!digestMode)
6454
+ armedEntry.digestSizeArmed = true;
6455
+ // A delivered digest breaks any permanent-retirement streak.
6456
+ armedEntry.digestRetiredCount = 0;
6457
+ // Persist the rendered frontier so the shared ring's eviction
6458
+ // (keyed to the notification cursor, which a healthy poll advances
6459
+ // past this held backlog) cannot re-list and re-deliver a rendered
6460
+ // member, nor over-count the follow-up digest's "new comment(s)".
6461
+ armedEntry.digestRendered = [
6462
+ ...new Set([
6463
+ ...(armedEntry.digestRendered ?? []),
6464
+ ...rendered.map((candidate) => candidate.key),
6465
+ ]),
6466
+ ];
6467
+ }
6468
+ // Clamp the hold anchor at `since`: the fetch filters on updated_at,
6469
+ // so an old comment edited today re-lists and sorts to deliverable[0]
6470
+ // even though it was created before commentSince. Anchoring at its
6471
+ // creation time would drag the cursor backwards and re-fetch (then
6472
+ // re-deliver, once the ring evicts their keys) the whole window.
6473
+ commitCursor(new Date(Math.max(Date.parse(deliverable[0].createdAt), Date.parse(since)) - 1000).toISOString());
6474
+ }
6475
+ return;
6476
+ }
6477
+ // Not even one member fits (a pathologically long URL): fall through
6478
+ // to the per-comment path rather than consume anything.
6479
+ }
6059
6480
  // Cap the burst against the pass-wide budget shared by all watched PRs;
6060
6481
  // the cursor resumes before the last processed comment when capped so the
6061
6482
  // tail drains over subsequent passes.
@@ -6078,17 +6499,25 @@ export class GithubChannel extends PollingChannelBase {
6078
6499
  // independent one). Keep commentSince so the next pass re-fetches and
6079
6500
  // retries; dispatchedComments dedupes anything already claimed. Advancing
6080
6501
  // here would skip the comment past with no task and no re-delivery chance.
6502
+ // The cursor stays held, so keep the arm AND the rendered frontier too —
6503
+ // clearing the frontier would re-deliver ring-evicted rendered members.
6081
6504
  commitCursor(since);
6082
6505
  }
6083
6506
  else {
6084
6507
  // Resume just before the last processed comment when capped so the
6085
6508
  // unprocessed tail is re-fetched next pass (a second of overlap is
6086
6509
  // deduped, never lost). A gate-held comment never reaches here: a hold
6087
- // implies an empty deliverable, which returned above.
6510
+ // implies an empty deliverable, which returned above. A digest that
6511
+ // fell through to this path (no member fit the body budget) consumes
6512
+ // its arm: the backlog delivers individually from here on.
6088
6513
  const last = batch[batch.length - 1];
6089
6514
  commitCursor(capped
6090
6515
  ? new Date(Date.parse(last.createdAt) - 1000).toISOString()
6091
- : nowIso);
6516
+ : nowIso,
6517
+ // A capped cursor resumes before the last processed comment (still
6518
+ // held), so it must keep the rendered frontier; only an uncapped
6519
+ // advance to nowIso has consumed the backlog and may clear it.
6520
+ digesting && !capped);
6092
6521
  }
6093
6522
  }
6094
6523
  async markNotificationsAsRead(lastReadAt) {