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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,7 @@ import { dirname, join } from 'node:path';
5
5
  import process from 'node:process';
6
6
  import { Octokit } from '@octokit/rest';
7
7
  import { HttpsProxyAgent } from 'https-proxy-agent';
8
- import { boundActionTemplateEntries, 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';
8
+ import { boundActionTemplateEntries, BOUND_PROMPT_BODY_MAX_CODE_POINTS, BoundSessionGoneError, BoundSessionQueueFullError, BoundSessionUnavailableError, buildBoundEventPrompt, DEFAULT_BOUND_ROLE_GUIDANCE, getGlobalQwenDir, getWorkspaceScopeDirName, lowercaseGroupAllowedUsers, MAX_POLL_INTERVAL_MS, PollingChannelBase, PR_BINDING_ROLES, renderBoundActionTemplate, resolveBoundActionTemplate, sanitizeDisplayText, sanitizeLogText, truncateCodePoints, validateBoundActionEntries, } from '@qwen-code/channel-base';
9
9
  import { testBotMention, stripBotMention } from './mention.js';
10
10
  import { resolveGithubWebOrigin } from './web-origin.js';
11
11
  const GH_AUTH_TIMEOUT_MS = 10_000;
@@ -503,6 +503,14 @@ export function validateBoundSessionConfig(config, channelName) {
503
503
  config.deliverToBoundSessions !== true) {
504
504
  return `prWatchLimit for channel ${channelName} requires deliverToBoundSessions: true.`;
505
505
  }
506
+ if (config.requireBoundWatch !== undefined &&
507
+ typeof config.requireBoundWatch !== 'boolean') {
508
+ return `[Channel:${channelName}] requireBoundWatch must be a boolean.`;
509
+ }
510
+ if (config.requireBoundWatch === true &&
511
+ config.deliverToBoundSessions !== true) {
512
+ return `requireBoundWatch for channel ${channelName} requires deliverToBoundSessions: true.`;
513
+ }
506
514
  if (config.prCommentWatch !== undefined &&
507
515
  typeof config.prCommentWatch !== 'boolean') {
508
516
  return `[Channel:${channelName}] prCommentWatch must be a boolean.`;
@@ -514,10 +522,12 @@ export function validateBoundSessionConfig(config, channelName) {
514
522
  config.deliverToBoundSessions !== true) {
515
523
  return `prWatchBudgetReserve for channel ${channelName} requires deliverToBoundSessions: true.`;
516
524
  }
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.
525
+ // The descriptor now declares minimum: 0, so the editor refuses a negative
526
+ // the operator types. This check still guards everything else: a hand-edited
527
+ // settings.json or a daemon API call, and a stored negative the editor
528
+ // re-sends unchanged under its descriptor-level tolerance. The getter would
529
+ // silently fall back to the default for a negative, letting a saved value
530
+ // mean something other than it says.
521
531
  // Positive fractions stay legal: the getter rounds them UP, which is the
522
532
  // documented behaviour, not a silent fallback.
523
533
  if (config.prWatchBudgetReserve !== undefined) {
@@ -661,6 +671,7 @@ function isInboundTaskRecord(value) {
661
671
  typeof record.backpressure === 'boolean') &&
662
672
  (record.privateOnly === undefined ||
663
673
  typeof record.privateOnly === 'boolean') &&
674
+ isOptionalStringArray(record.authorExclude) &&
664
675
  (record.lostSessionId === undefined ||
665
676
  typeof record.lostSessionId === 'string'));
666
677
  }
@@ -684,6 +695,48 @@ function isNoReplySentinel(text) {
684
695
  }
685
696
  /** GitHub's wording for a secondary (abuse) rate limit. */
686
697
  const SECONDARY_RATE_LIMIT_MESSAGE = /secondary rate limit|abuse detection/i;
698
+ /**
699
+ * Cap on cached conditional responses, sized from the fan-out it has to
700
+ * serve: up to MAX_PR_WATCH_LIMIT open PRs, a terminal-drain slice on top,
701
+ * and the notifications pages. A cap below the sweep does not degrade
702
+ * proportionally — each miss evicts the entry the sweep is about to read, so
703
+ * every read of every later pass misses and the saving is exactly zero for
704
+ * the high-fan-out deployments this is meant to help. Derived from the watch
705
+ * limit so the two cannot drift apart.
706
+ *
707
+ * A moved notifications `since` cursor still mints new keys, so the map is
708
+ * bounded and evicts least-recently-used first; an evicted URL simply pays
709
+ * for one full 200 again.
710
+ */
711
+ export const CONDITIONAL_CACHE_MAX_ENTRIES = MAX_PR_WATCH_LIMIT * 2;
712
+ /**
713
+ * Bodies above this size are not cached, so a pathologically large page
714
+ * cannot pin memory. Sized against the entry cap above to keep the retention
715
+ * bound in the same order as a smaller cache of larger bodies. A declined URL
716
+ * stays unconditional — the behavior from before conditional requests
717
+ * existed — and a page this large is one whose contents are churning, where a
718
+ * 304 was unlikely anyway.
719
+ */
720
+ const CONDITIONAL_CACHE_MAX_BODY_BYTES = 256 * 1024;
721
+ /**
722
+ * Total retained body bytes. The entry and per-body caps only bound the
723
+ * product loosely — a thousand maximum-size bodies would be a quarter of a
724
+ * gigabyte — so the cache is also bounded directly. Real responses are one to
725
+ * two orders of magnitude below the per-body cap, so this binds only the
726
+ * pathological case and never evicts a working set.
727
+ */
728
+ export const CONDITIONAL_CACHE_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
729
+ /**
730
+ * The two polling reads worth making conditional: the PR state watch and the
731
+ * notifications list. Matching on the pathname suffix keeps this working
732
+ * under an enterprise baseUrl prefix, and anchors the end so thread reads
733
+ * (`/notifications/threads/<id>`) and issue comments stay out of scope.
734
+ */
735
+ function isConditionalPollUrl(url) {
736
+ const { pathname } = new URL(url);
737
+ return (/\/repos\/[^/]+\/[^/]+\/pulls\/\d+$/.test(pathname) ||
738
+ /\/notifications$/.test(pathname));
739
+ }
687
740
  /**
688
741
  * A rate-limit header value (remaining count or reset epoch) as a
689
742
  * non-negative integer; absent or malformed is undefined. GitHub sends
@@ -840,6 +893,7 @@ export class GithubChannel extends PollingChannelBase {
840
893
  reasonFilter = null;
841
894
  repoFilter = null;
842
895
  deliverToBoundSessions = false;
896
+ requireBoundWatch = false;
843
897
  /**
844
898
  * Bound PR comment watch: poll conversation + inline review comments and
845
899
  * deliver each to every bound session that did not post it. Default-on
@@ -919,6 +973,46 @@ export class GithubChannel extends PollingChannelBase {
919
973
  // otherwise silent; this drives a throttled diagnostic so the operator sees
920
974
  // a hint before the dead-letter alert hours later (doudouOUC).
921
975
  partialSnapshotStreak = 0;
976
+ /**
977
+ * Snapshot generation, bumped on every successful binding refresh. The
978
+ * gate grace is scoped to a generation, not to a drain call: pollOnce can
979
+ * drain the same PR twice against one snapshot, and a per-call grace would
980
+ * be spent by the second drain before any newer snapshot exists.
981
+ */
982
+ bindingsGeneration = 0;
983
+ /**
984
+ * Comment/watch keys the gate has deferred, mapped to the snapshot
985
+ * generation at the deferral. A watch installed after the bindings
986
+ * snapshot was fetched surfaces on the next refresh; the first gate-only
987
+ * exclusion holds the event (cursor unmoved / pending kept), and it stays
988
+ * held until a NEWER generation still finds it gated — then it is consumed
989
+ * like any other no-target event. In-memory: a restart resets the grace,
990
+ * which is harmless. Keys are removed when the event delivers or is
991
+ * consumed.
992
+ */
993
+ gateDeferredOnce = new Map();
994
+ /**
995
+ * Whether a gate-excluded event should keep being held. Defers on first
996
+ * sight and while the snapshot generation is unchanged; once a newer
997
+ * generation has landed and the event is still gated, the grace is spent
998
+ * (returns false and clears the key) so the caller consumes it.
999
+ */
1000
+ gateGraceShouldHold(key) {
1001
+ const deferredAt = this.gateDeferredOnce.get(key);
1002
+ if (deferredAt === undefined) {
1003
+ this.gateDeferredOnce.set(key, this.bindingsGeneration);
1004
+ return true;
1005
+ }
1006
+ if (deferredAt === this.bindingsGeneration) {
1007
+ return true;
1008
+ }
1009
+ this.gateDeferredOnce.delete(key);
1010
+ return false;
1011
+ }
1012
+ /** Clear any grace for an event that delivered (or is being consumed). */
1013
+ gateGraceClear(key) {
1014
+ this.gateDeferredOnce.delete(key);
1015
+ }
922
1016
  /**
923
1017
  * True while the most recent pending-watch reconciliation FAILED (e.g.
924
1018
  * the watch file is unreadable). Generic recovery must then leave watch
@@ -968,6 +1062,21 @@ export class GithubChannel extends PollingChannelBase {
968
1062
  * which the user guide states.
969
1063
  */
970
1064
  watchBudgetEpisodeOpen = false;
1065
+ /**
1066
+ * ETag cache for the two polling reads, keyed by full request URL so a
1067
+ * moved notifications `since` cursor is a distinct entry rather than a
1068
+ * false hit. Connection-scoped: cleared on disconnect so a reconnect never
1069
+ * serves a body cached under a previous credential.
1070
+ */
1071
+ conditionalCache = new Map();
1072
+ /** Running total of cached body bytes, maintained by the two helpers below. */
1073
+ conditionalCacheBytes = 0;
1074
+ /**
1075
+ * Floor (ms) from the notifications endpoint's `X-Poll-Interval`. GitHub
1076
+ * asks polling clients not to poll faster than this; pollInterval raises
1077
+ * the whole loop to it, which also slows the watch pass.
1078
+ */
1079
+ notificationsPollFloorMs = 0;
971
1080
  /**
972
1081
  * Consecutive binding-refresh failures since the last success. While no
973
1082
  * snapshot has ever succeeded, the cold-start gate defers the comment lane,
@@ -1158,6 +1267,7 @@ export class GithubChannel extends PollingChannelBase {
1158
1267
  this.prWatchEvents = normalizePrWatchEvents(cfg, this.name);
1159
1268
  this.boundSessionActions = normalizeBoundSessionActions(cfg, this.name);
1160
1269
  this.deliverToBoundSessions = cfg.deliverToBoundSessions === true;
1270
+ this.requireBoundWatch = cfg.requireBoundWatch === true;
1161
1271
  this.prCommentWatchEnabled = cfg.prCommentWatch !== false;
1162
1272
  if (this.deliverToBoundSessions) {
1163
1273
  this.loadBoundDeliveredRing();
@@ -1165,6 +1275,7 @@ export class GithubChannel extends PollingChannelBase {
1165
1275
  if (this.deliverToBoundSessions && !this.boundSessions) {
1166
1276
  process.stderr.write(`[Channel:${this.name}] warning: deliverToBoundSessions requires a daemon-managed channel; ignoring (standalone mode).\n`);
1167
1277
  this.deliverToBoundSessions = false;
1278
+ this.requireBoundWatch = false;
1168
1279
  this.prWatchEvents = new Set();
1169
1280
  this.boundSessionActions = new Map();
1170
1281
  }
@@ -1189,9 +1300,10 @@ export class GithubChannel extends PollingChannelBase {
1189
1300
  this.octokit = new Octokit({
1190
1301
  auth,
1191
1302
  baseUrl,
1192
- ...(this.proxy
1193
- ? { request: { agent: new HttpsProxyAgent(this.proxy) } }
1194
- : {}),
1303
+ request: {
1304
+ ...(this.proxy ? { agent: new HttpsProxyAgent(this.proxy) } : {}),
1305
+ fetch: this.conditionalFetch,
1306
+ },
1195
1307
  });
1196
1308
  // One choke point for the success-path budget: the wrap sees the response
1197
1309
  // headers on every request, including each page of a paginate call,
@@ -1201,6 +1313,12 @@ export class GithubChannel extends PollingChannelBase {
1201
1313
  this.octokit.hook.wrap('request', async (request, options) => {
1202
1314
  const response = await request(options);
1203
1315
  this.recordRateLimitBudget(response.headers);
1316
+ // Only the notifications endpoint sends this header, in seconds. It
1317
+ // survives a 304, so an idle channel keeps honouring it.
1318
+ const pollSeconds = parseRateLimitCount(response.headers['x-poll-interval']);
1319
+ if (pollSeconds !== undefined) {
1320
+ this.notificationsPollFloorMs = pollSeconds * 1000;
1321
+ }
1204
1322
  return response;
1205
1323
  });
1206
1324
  try {
@@ -1281,8 +1399,27 @@ export class GithubChannel extends PollingChannelBase {
1281
1399
  this.pendingFinalDeliveryRetryAbort = retryAbort;
1282
1400
  this.pendingFinalDeliveryRetry = retry;
1283
1401
  }
1402
+ /**
1403
+ * GitHub asks polling clients not to poll the notifications endpoint
1404
+ * faster than its `X-Poll-Interval`. The base class exposes one interval
1405
+ * for the whole poll and the watch pass runs before the notifications lane,
1406
+ * so honouring the floor also slows the watch. At the default 60s poll the
1407
+ * header is also 60 and nothing changes; only a faster configured poll is
1408
+ * raised, which is exactly what GitHub is asking for.
1409
+ *
1410
+ * The ceiling is re-applied because the header is server-controlled and
1411
+ * super's clamp only covers the configured value: Node rounds a timeout
1412
+ * above its 32-bit range down to 1ms, so an unbounded floor would turn the
1413
+ * poll loop into a hot loop that burns the quota this is meant to save.
1414
+ */
1415
+ get pollInterval() {
1416
+ return Math.min(Math.max(super.pollInterval, this.notificationsPollFloorMs), MAX_POLL_INTERVAL_MS);
1417
+ }
1284
1418
  disconnect() {
1285
1419
  this.stopPollLoop();
1420
+ this.conditionalCache.clear();
1421
+ this.conditionalCacheBytes = 0;
1422
+ this.notificationsPollFloorMs = 0;
1286
1423
  // Retire the runner generation: an idle runner wakes and exits, and a
1287
1424
  // runner mid-turn exits after that turn. The durable task stays
1288
1425
  // recoverable for the next connection. Release idle waiters: with the
@@ -1890,6 +2027,10 @@ export class GithubChannel extends PollingChannelBase {
1890
2027
  if (this.deliverToBoundSessions &&
1891
2028
  !this.boundSnapshotTrusted &&
1892
2029
  this.boundSessionByPr.size === 0 &&
2030
+ // Under the gate the map can be empty while raw bindings exist (every
2031
+ // listed follower watch-ineligible): the sidecars ARE readable, so the
2032
+ // cold-empty premise is false and the lane must not stall.
2033
+ !(this.requireBoundWatch && this.hasRawBoundPrs()) &&
1893
2034
  this.lastBindingsPartial &&
1894
2035
  this.coldEmptyPartialStreak < MAX_COLD_EMPTY_PARTIAL_POLLS) {
1895
2036
  if (this.coldEmptyPartialStreak === 1 ||
@@ -2327,12 +2468,21 @@ export class GithubChannel extends PollingChannelBase {
2327
2468
  this.admitsMessageRoute(text) &&
2328
2469
  this.resolveBoundTargets(ctx.chatId, ctx.issueNumber, 'comment', 'comment').targets.length > 0;
2329
2470
  if (onlyMentioned && !hasMention && !mentionWaived) {
2330
- if (!this.journalOncePerWindow(`mention_required\0${key}`))
2471
+ // Name the actual filter: when the waiver would have admitted this
2472
+ // comment but the watch gate excluded every follower, the skip is
2473
+ // bound_watch_required — not the mention_required an unbound PR's
2474
+ // ambient chatter produces.
2475
+ const reason = this.gateExcludedAllFollowers(ctx.chatId, ctx.issueNumber) &&
2476
+ this.waivesBoundMention(ctx.chatId, senderId) &&
2477
+ this.admitsMessageRoute(text)
2478
+ ? 'bound_watch_required'
2479
+ : 'mention_required';
2480
+ if (!this.journalOncePerWindow(`${reason}\0${key}`))
2331
2481
  continue;
2332
2482
  this.recordChannelEvent({
2333
2483
  type: 'inbound',
2334
2484
  outcome: 'skipped',
2335
- reason: 'mention_required',
2485
+ reason,
2336
2486
  triggerKind: ctx.reason,
2337
2487
  repository: ctx.chatId,
2338
2488
  thread: ctx.threadId,
@@ -2905,7 +3055,7 @@ export class GithubChannel extends PollingChannelBase {
2905
3055
  return settled;
2906
3056
  }
2907
3057
  if (followed &&
2908
- this.boundRoleAware &&
3058
+ (this.boundRoleAware || this.requireBoundWatch) &&
2909
3059
  this.boundSnapshotTrusted &&
2910
3060
  !this.lastBindingsPartial &&
2911
3061
  !this.boundRefreshFailed) {
@@ -2916,9 +3066,16 @@ export class GithubChannel extends PollingChannelBase {
2916
3066
  // role. Under a partial or failing scan an unscanned role might
2917
3067
  // still match, so fall through to the untargeted claim: the absence
2918
3068
  // gate defers it as backpressure instead of consuming the event on
2919
- // incomplete evidence.
3069
+ // incomplete evidence. The watch gate retires the same way in legacy
3070
+ // mode: every follower is bound but none is watch-eligible. The
3071
+ // journal reason names the ACTUAL filter: a gate exclusion is
3072
+ // bound_watch_required in BOTH modes, not the role-aware template
3073
+ // reason that would send the operator to templates that matched fine.
3074
+ const gateExcludedAll = this.gateExcludedAllFollowers(envelope.chatId, issueNumber);
2920
3075
  this.applyTaskDedupe(dedupe);
2921
- process.stderr.write(`[Channel:${this.name}] event ${envelope.messageId} matched no role's boundSessionActions; retiring without public fallback\n`);
3076
+ process.stderr.write(`[Channel:${this.name}] event ${envelope.messageId} ${gateExcludedAll
3077
+ ? 'has no watch-eligible bound session (requireBoundWatch)'
3078
+ : "matched no role's boundSessionActions"}; retiring without public fallback\n`);
2922
3079
  // Retired before any task was claimed, so there is no task row to
2923
3080
  // close: the skip is the event's only journal trace. The dedupe cursor
2924
3081
  // is still in memory here — the base saves it after pollOnce returns —
@@ -2928,7 +3085,7 @@ export class GithubChannel extends PollingChannelBase {
2928
3085
  this.recordChannelEvent({
2929
3086
  type: 'inbound',
2930
3087
  outcome: 'skipped',
2931
- reason: 'no_role_matched',
3088
+ reason: gateExcludedAll ? 'bound_watch_required' : 'no_role_matched',
2932
3089
  triggerKind: parseTriggerKind(envelope.metadata),
2933
3090
  repository: envelope.chatId,
2934
3091
  thread: envelope.threadId,
@@ -3516,8 +3673,11 @@ export class GithubChannel extends PollingChannelBase {
3516
3673
  // snapshot: the operator's subscription scoping retires this
3517
3674
  // event, not an absence. Under a partial or failing scan an
3518
3675
  // unscanned role might still match — leave the task untargeted
3519
- // so the absence gate keeps deferring it as backpressure.
3520
- this.retireBoundTask(task, 'no role matched the event class (operator subscription)');
3676
+ // so the absence gate keeps deferring it as backpressure. Name
3677
+ // the gate when the gate (not the templates) excluded everyone.
3678
+ this.retireBoundTask(task, this.gateExcludedAllFollowers(task.envelope.chatId, task.issueNumber)
3679
+ ? 'no watch-eligible bound session (requireBoundWatch)'
3680
+ : 'no role matched the event class (operator subscription)');
3521
3681
  continue;
3522
3682
  }
3523
3683
  }
@@ -3527,6 +3687,19 @@ export class GithubChannel extends PollingChannelBase {
3527
3687
  this.transitionInboundTask(task.id, 'running', { delivery });
3528
3688
  task.delivery = delivery;
3529
3689
  }
3690
+ else if (this.requireBoundWatch &&
3691
+ this.boundSnapshotTrusted &&
3692
+ !this.lastBindingsPartial &&
3693
+ !this.boundRefreshFailed &&
3694
+ this.boundFollowersOf(task.envelope.chatId, task.issueNumber)
3695
+ .length > 0) {
3696
+ // The filtered map has no winner but raw followers exist on a
3697
+ // COMPLETE fresh snapshot: every follower is bound but none is
3698
+ // watch-eligible. The operator's scoping retires this event,
3699
+ // not an absence — same rule as the role-aware branch above.
3700
+ this.retireBoundTask(task, 'no watch-eligible bound session (requireBoundWatch)');
3701
+ continue;
3702
+ }
3530
3703
  }
3531
3704
  }
3532
3705
  if (pendingDeliveries.some((record) => record.chatId === task.source.chatId &&
@@ -3940,6 +4113,85 @@ export class GithubChannel extends PollingChannelBase {
3940
4113
  removeInboundTask(taskId) {
3941
4114
  this.updateInboundTasks((records) => records.filter((record) => record.id !== taskId));
3942
4115
  }
4116
+ /**
4117
+ * The conditional exchange, owned at the transport boundary rather than in
4118
+ * a request hook: `@octokit/request` hard-codes 304 into a RequestError
4119
+ * INSIDE plugin-request-log's own wrap, so catching it any higher leaves an
4120
+ * error-level log line per 304 (~1,800/hour at the watch cap) and hands
4121
+ * githubApi a retryable failure. Converting it here means no layer above
4122
+ * ever learns there was a 304.
4123
+ */
4124
+ conditionalFetch = async (input, init) => {
4125
+ const url = String(input);
4126
+ if ((init?.method ?? 'GET').toUpperCase() !== 'GET' ||
4127
+ !isConditionalPollUrl(url)) {
4128
+ return fetch(input, init);
4129
+ }
4130
+ const cached = this.conditionalCache.get(url);
4131
+ const headers = new Headers(init?.headers);
4132
+ if (cached)
4133
+ headers.set('if-none-match', cached.etag);
4134
+ const response = await fetch(url, { ...init, headers });
4135
+ if (response.status === 304 && cached) {
4136
+ const merged = new Headers(response.headers);
4137
+ // GitHub omits Link on a 304 (verified against the live API: the same
4138
+ // URL's 200 carried next+last, the 304 carried neither). Without the
4139
+ // cached value paginate stops after page 1 and silently drops the rest
4140
+ // of the notifications list.
4141
+ if (!merged.has('link') && cached.link !== undefined) {
4142
+ merged.set('link', cached.link);
4143
+ }
4144
+ // The body is the cached, already-decoded text, so any framing headers
4145
+ // describing the empty 304 body would misdescribe it.
4146
+ merged.delete('content-length');
4147
+ merged.delete('content-encoding');
4148
+ merged.set('content-type', 'application/json; charset=utf-8');
4149
+ // Refresh recency on a hit, not just on a write: a moved `since` cursor
4150
+ // keeps minting dead notification entries, and without this they would
4151
+ // evict the quiet PRs that are being read every poll.
4152
+ this.storeCached(url, cached);
4153
+ return new Response(cached.body, { status: 200, headers: merged });
4154
+ }
4155
+ if (response.status === 200) {
4156
+ const etag = response.headers.get('etag');
4157
+ if (etag !== null) {
4158
+ const body = await response.clone().text();
4159
+ const bytes = Buffer.byteLength(body);
4160
+ if (bytes <= CONDITIONAL_CACHE_MAX_BODY_BYTES) {
4161
+ this.storeCached(url, {
4162
+ etag,
4163
+ body,
4164
+ link: response.headers.get('link') ?? undefined,
4165
+ bytes,
4166
+ });
4167
+ for (const oldest of this.conditionalCache.keys()) {
4168
+ if (this.conditionalCache.size <= CONDITIONAL_CACHE_MAX_ENTRIES &&
4169
+ this.conditionalCacheBytes <= CONDITIONAL_CACHE_MAX_TOTAL_BYTES) {
4170
+ break;
4171
+ }
4172
+ this.dropCached(oldest);
4173
+ }
4174
+ }
4175
+ }
4176
+ }
4177
+ return response;
4178
+ };
4179
+ /**
4180
+ * The only two writers of the cache, so the byte total cannot drift from
4181
+ * the map. Re-inserting moves the key to the most-recently-used end.
4182
+ */
4183
+ dropCached(url) {
4184
+ const entry = this.conditionalCache.get(url);
4185
+ if (entry === undefined)
4186
+ return;
4187
+ this.conditionalCacheBytes -= entry.bytes;
4188
+ this.conditionalCache.delete(url);
4189
+ }
4190
+ storeCached(url, entry) {
4191
+ this.dropCached(url);
4192
+ this.conditionalCache.set(url, entry);
4193
+ this.conditionalCacheBytes += entry.bytes;
4194
+ }
3943
4195
  /**
3944
4196
  * Record the REST budget from a successful response's headers. Called by
3945
4197
  * the request hook on every response. A missing or malformed remaining
@@ -4045,7 +4297,16 @@ export class GithubChannel extends PollingChannelBase {
4045
4297
  try {
4046
4298
  const parsed = JSON.parse(readFileSync(this.inboundTasksPath(), 'utf-8'));
4047
4299
  if (!Array.isArray(parsed) || !parsed.every(isInboundTaskRecord)) {
4048
- throw new Error('invalid GitHub inbound task state');
4300
+ // Name the offender: one bad record blocks every healthy task in the
4301
+ // file, so an operator repairing it by hand needs the index and id
4302
+ // rather than bisecting the JSON by eye.
4303
+ const badIndex = Array.isArray(parsed)
4304
+ ? parsed.findIndex((item) => !isInboundTaskRecord(item))
4305
+ : -1;
4306
+ const badId = badIndex === -1
4307
+ ? undefined
4308
+ : parsed[badIndex]?.id;
4309
+ throw new Error(`invalid GitHub inbound task state${badIndex === -1 ? '' : ` at record ${badIndex}`}${typeof badId === 'string' ? ` (${badId})` : ''}`);
4049
4310
  }
4050
4311
  this.inboundTaskSnapshot = parsed;
4051
4312
  return parsed;
@@ -4330,6 +4591,7 @@ export class GithubChannel extends PollingChannelBase {
4330
4591
  this.boundRefreshFailed = false;
4331
4592
  this.boundSnapshotSeen = true;
4332
4593
  this.boundSnapshotFailureStreak = 0;
4594
+ this.bindingsGeneration += 1;
4333
4595
  if (!snapshot.partial)
4334
4596
  this.boundSnapshotTrusted = true;
4335
4597
  const map = new Map();
@@ -4342,6 +4604,8 @@ export class GithubChannel extends PollingChannelBase {
4342
4604
  const identity = this.parsePrBindingUrl(pr.url);
4343
4605
  if (!identity || identity.number !== pr.number)
4344
4606
  continue;
4607
+ if (this.watchGateExcludes(pr.role, pr.watching))
4608
+ continue;
4345
4609
  const key = this.prBindingKey(identity.chatId, identity.number);
4346
4610
  const existing = map.get(key);
4347
4611
  if (!existing ||
@@ -4372,11 +4636,20 @@ export class GithubChannel extends PollingChannelBase {
4372
4636
  // authoritative) and surface in the dead-letter at the horizon —
4373
4637
  // never a silent loss or an irreversible public reply.
4374
4638
  const retained = this.lastBindings.filter((b) => !seen.has(b.sessionId));
4375
- const retainedCapped = retained.length > MAX_PARTIAL_RETAINED
4639
+ const retainedCapped = (retained.length > MAX_PARTIAL_RETAINED
4376
4640
  ? [...retained]
4377
4641
  .sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''))
4378
4642
  .slice(0, MAX_PARTIAL_RETAINED)
4379
- : retained;
4643
+ : retained).map((summary) => ({
4644
+ ...summary,
4645
+ // A retained row's last-stamped `watching` is stale evidence: the
4646
+ // scan that would refresh it cannot read this session's sidecar.
4647
+ // Keep the row (it still names its PRs and competes by recency)
4648
+ // but reset the flag to unknown so the gate fails open on it — a
4649
+ // watch installed during a permanent partial must not read as a
4650
+ // confirmed false and ban the session for the partial's life.
4651
+ prs: summary.prs.map((pr) => ({ ...pr, watching: undefined })),
4652
+ }));
4380
4653
  retainedSessionCount = retainedCapped.length;
4381
4654
  if (retainedCapped.length < retained.length) {
4382
4655
  process.stderr.write(`[Channel:${this.name}] binding retention cap exceeded under a partial snapshot: dropped ${retained.length - retainedCapped.length} oldest unlisted sessions (keeping ${MAX_PARTIAL_RETAINED}); their unmatched events defer until a complete snapshot establishes absence\n`);
@@ -4392,6 +4665,8 @@ export class GithubChannel extends PollingChannelBase {
4392
4665
  const identity = this.parsePrBindingUrl(pr.url);
4393
4666
  if (!identity || identity.number !== pr.number)
4394
4667
  continue;
4668
+ if (this.watchGateExcludes(pr.role, pr.watching))
4669
+ continue;
4395
4670
  const key = this.prBindingKey(identity.chatId, identity.number);
4396
4671
  const existing = map.get(key);
4397
4672
  if (!existing ||
@@ -4406,7 +4681,10 @@ export class GithubChannel extends PollingChannelBase {
4406
4681
  this.lastBindings = snapshot.bindings;
4407
4682
  }
4408
4683
  this.boundSessionByPr = map;
4409
- if (snapshot.partial && map.size === 0 && !this.boundSnapshotTrusted) {
4684
+ if (snapshot.partial &&
4685
+ map.size === 0 &&
4686
+ !this.boundSnapshotTrusted &&
4687
+ !(this.requireBoundWatch && this.hasRawBoundPrs())) {
4410
4688
  this.coldEmptyPartialStreak += 1;
4411
4689
  if (this.coldEmptyPartialStreak === MAX_COLD_EMPTY_PARTIAL_POLLS) {
4412
4690
  process.stderr.write(`[Channel:${this.name}] binding snapshot has been an empty partial for ${this.coldEmptyPartialStreak} consecutive binding scans: opening the comment lane. Unmatched PR events will defer (and dead-letter after the backpressure horizon) until a complete snapshot establishes absence. ${this.coldEmptyCapCause()}\n`);
@@ -4439,6 +4717,7 @@ export class GithubChannel extends PollingChannelBase {
4439
4717
  const listedSessions = snapshot.bindings.length + retainedSessionCount;
4440
4718
  process.stderr.write(`[Channel:${this.name}] binding snapshot has been partial for ${this.partialSnapshotStreak} consecutive binding scans (${listedSessions} sessions listed): the daemon could not read every PR sidecar, transcript or live session list, or a registered workspace has no runtime. ${!this.boundSnapshotTrusted &&
4441
4719
  map.size === 0 &&
4720
+ !(this.requireBoundWatch && this.hasRawBoundPrs()) &&
4442
4721
  this.coldEmptyPartialStreak < MAX_COLD_EMPTY_PARTIAL_POLLS
4443
4722
  ? `The comment lane is still deferred (${this.coldEmptyPartialStreak}/${MAX_COLD_EMPTY_PARTIAL_POLLS} cold binding scans), so PR and issue events are both stalled.`
4444
4723
  : 'Unmatched PR events defer to the dead-letter horizon instead of the channel (issue events are unaffected).'} Check the daemon's stderr for the failing workspace, and its \`PR bindings scan\` lines for the session it could not read.\n`);
@@ -4463,7 +4742,10 @@ export class GithubChannel extends PollingChannelBase {
4463
4742
  // No authoritative map exists: either no snapshot has ever succeeded,
4464
4743
  // or only empty partials / failures have (boundSnapshotSeen may already
4465
4744
  // be true). The cold-start gate defers the comment lane, so every
4466
- // notification is stalled.
4745
+ // notification is stalled. The gate's raw-presence suppression is NOT
4746
+ // applied here: a raw row left by an earlier scan says nothing about
4747
+ // THIS failing lookup, so the failure accounting and the
4748
+ // bindings_unreachable row must still run.
4467
4749
  const noAuthoritativeMap = !this.boundSnapshotTrusted && this.boundSessionByPr.size === 0;
4468
4750
  if (noAuthoritativeMap) {
4469
4751
  // A failing refresh with no authoritative map is as non-authoritative
@@ -4561,6 +4843,8 @@ export class GithubChannel extends PollingChannelBase {
4561
4843
  continue;
4562
4844
  if (roleFilter && follower.role !== roleFilter.role)
4563
4845
  continue;
4846
+ if (this.watchGateExcludes(follower.role, follower.watching))
4847
+ continue;
4564
4848
  if (!best ||
4565
4849
  (follower.summary.updatedAt ?? '') > (best.summary.updatedAt ?? '')) {
4566
4850
  best = follower;
@@ -4582,6 +4866,62 @@ export class GithubChannel extends PollingChannelBase {
4582
4866
  get boundRoleAware() {
4583
4867
  return this.boundSessionActions.size > 0;
4584
4868
  }
4869
+ /**
4870
+ * The active-watch gate (requireBoundWatch): a review/verify binding whose
4871
+ * session holds no active watch on THIS PR is not a delivery target.
4872
+ * Unknown watching (absent — detection failed or an older daemon) stays
4873
+ * eligible: the gate is a noise filter, fail-open. fix and untyped
4874
+ * bindings are never gated. Filtering happens at target selection only —
4875
+ * the raw binding list keeps naming excluded followers so `followed` /
4876
+ * absence semantics never mistake "bound but ineligible" for "unbound"
4877
+ * and open the irreversible public path.
4878
+ */
4879
+ watchGateExcludes(role, watching) {
4880
+ return (this.requireBoundWatch &&
4881
+ (role === 'review' || role === 'verify') &&
4882
+ watching === false);
4883
+ }
4884
+ /**
4885
+ * True when raw followers exist and the watch gate excludes EVERY one of
4886
+ * them — the only "no candidate" state the gate itself caused. A winner
4887
+ * that is merely author-excluded, or a removed binding (no followers), is
4888
+ * not this state and keeps the legacy frozen-target contract.
4889
+ */
4890
+ gateExcludedAllFollowers(chatId, issueNumber) {
4891
+ if (!this.requireBoundWatch)
4892
+ return false;
4893
+ const followers = this.boundFollowersOf(chatId, issueNumber);
4894
+ return (followers.length > 0 &&
4895
+ followers.every((f) => this.watchGateExcludes(f.role, f.watching)));
4896
+ }
4897
+ /**
4898
+ * Whether any non-channel raw binding row names a PR — the population the
4899
+ * gate can actually filter. The routing map is gate-filtered, so its
4900
+ * emptiness alone cannot prove "no bindings exist": cold-start decisions
4901
+ * must read raw presence, or a fully-ineligible snapshot stalls the lane
4902
+ * as if the sidecars were unreadable. Channel-owned rows are excluded
4903
+ * because the routing map deliberately skips them.
4904
+ */
4905
+ hasRawBoundPrs() {
4906
+ return this.lastBindings.some((b) => b.sourceType !== 'channel' && b.prs.length > 0);
4907
+ }
4908
+ /**
4909
+ * Whether the gate excluded the FROZEN delivery target itself. The
4910
+ * delivery-time retire must be about the target the event was frozen to,
4911
+ * not the whole follower set: an exempt fix/untyped target keeps the
4912
+ * legacy frozen-target contract even when some other ineligible
4913
+ * review/verify follower still lists the PR, and a removed binding (the
4914
+ * target no longer follows) keeps it too. Only a target whose own binding
4915
+ * the gate excludes retires.
4916
+ */
4917
+ frozenTargetGateExcluded(delivery, chatId, issueNumber) {
4918
+ if (!this.requireBoundWatch || delivery.kind !== 'bound-session') {
4919
+ return false;
4920
+ }
4921
+ const follower = this.boundFollowersOf(chatId, issueNumber).find((f) => f.summary.sessionId === delivery.sessionId);
4922
+ return (follower !== undefined &&
4923
+ this.watchGateExcludes(follower.role, follower.watching));
4924
+ }
4585
4925
  /**
4586
4926
  * Every non-channel follower of a PR from the full binding list, each with
4587
4927
  * the role of the entry that names THIS PR (a session may follow several
@@ -4597,7 +4937,11 @@ export class GithubChannel extends PollingChannelBase {
4597
4937
  const entry = this.boundPrEntryFor(summary, key);
4598
4938
  if (!entry)
4599
4939
  continue;
4600
- followers.push({ summary, ...(entry.role ? { role: entry.role } : {}) });
4940
+ followers.push({
4941
+ summary,
4942
+ ...(entry.role ? { role: entry.role } : {}),
4943
+ ...(entry.watching !== undefined ? { watching: entry.watching } : {}),
4944
+ });
4601
4945
  }
4602
4946
  return followers;
4603
4947
  }
@@ -4801,8 +5145,17 @@ export class GithubChannel extends PollingChannelBase {
4801
5145
  }
4802
5146
  if (!this.boundRoleAware) {
4803
5147
  const summary = this.boundSessionByPr.get(this.prBindingKey(chatId, issueNumber));
4804
- if (!summary)
4805
- return { targets: [], followed: false };
5148
+ if (!summary) {
5149
+ // The routing map holds only watch-eligible winners under the gate,
5150
+ // so its absence is not "unbound": raw followers may still exist
5151
+ // (all ineligible). `followed` must keep naming them, or the
5152
+ // absence gate would open the public path for a bound PR.
5153
+ return {
5154
+ targets: [],
5155
+ followed: this.requireBoundWatch &&
5156
+ this.boundFollowersOf(chatId, issueNumber).length > 0,
5157
+ };
5158
+ }
4806
5159
  const role = this.boundRoleOf(summary, chatId, issueNumber);
4807
5160
  return {
4808
5161
  targets: [{ sessionId: summary.sessionId, ...(role ? { role } : {}) }],
@@ -4812,6 +5165,8 @@ export class GithubChannel extends PollingChannelBase {
4812
5165
  const followers = this.boundFollowersOf(chatId, issueNumber);
4813
5166
  const byRole = new Map();
4814
5167
  for (const follower of followers) {
5168
+ if (this.watchGateExcludes(follower.role, follower.watching))
5169
+ continue;
4815
5170
  const groupKey = follower.role ?? '';
4816
5171
  const existing = byRole.get(groupKey);
4817
5172
  if (!existing ||
@@ -4848,6 +5203,7 @@ export class GithubChannel extends PollingChannelBase {
4848
5203
  }
4849
5204
  const winner = this.boundFollowersOf(chatId, issueNumber)
4850
5205
  .filter((follower) => follower.role === delivery.role)
5206
+ .filter((follower) => !this.watchGateExcludes(follower.role, follower.watching))
4851
5207
  .filter((follower) => !excludeSessionIds?.has(follower.summary.sessionId))
4852
5208
  .reduce((best, follower) => !best ||
4853
5209
  (follower.summary.updatedAt ?? '') > (best.summary.updatedAt ?? '')
@@ -5030,14 +5386,23 @@ export class GithubChannel extends PollingChannelBase {
5030
5386
  task.delivery = current;
5031
5387
  delivery = current;
5032
5388
  }
5033
- else if (!current && (isWatch || this.boundRoleAware)) {
5389
+ else if (!current &&
5390
+ (isWatch ||
5391
+ this.boundRoleAware ||
5392
+ this.frozenTargetGateExcluded(delivery, envelope.chatId, task.issueNumber))) {
5034
5393
  // On a complete snapshot with no candidate left for the task's role,
5035
5394
  // retire privately. Watch events are private-only by contract; a
5036
5395
  // role-aware COMMENT whose role lost its match (the binding's role
5037
5396
  // changed, or the operator removed the template) must not keep
5038
5397
  // injecting the obsolete role's instruction into the frozen session
5039
- // either. Legacy single-winner comments keep the frozen target —
5040
- // their public fallback contract is handled by the gone path below.
5398
+ // either. Under the watch gate a legacy comment retires too, but
5399
+ // ONLY when the gate excluded the FROZEN TARGET itself (it stopped
5400
+ // watching between claim and delivery). The decision is about the
5401
+ // target, not the follower set: an exempt fix/untyped target, a
5402
+ // merely author-excluded winner, or a REMOVED binding all keep the
5403
+ // legacy contract — the frozen target stands and the gone path below
5404
+ // owns the fallback — so the gate never changes behavior for the
5405
+ // fix/untyped sessions it exempts.
5041
5406
  process.stderr.write(`[Channel:${this.name}] ${isWatch ? 'watch' : 'bound'} event ${envelope.messageId} has no bound candidate left for its role; retiring without public fallback\n`);
5042
5407
  this.markPrivatelyRetired(task);
5043
5408
  return {
@@ -5176,8 +5541,15 @@ export class GithubChannel extends PollingChannelBase {
5176
5541
  // public. While any role still follows the PR, the event is (or will
5177
5542
  // be) delivered privately through that role's own task; a public
5178
5543
  // reply here would duplicate it on the PR. Only zero live followers
5179
- // across every role opens the public fallback below.
5180
- if (this.boundRoleAware &&
5544
+ // across every role opens the public fallback below. The watch gate
5545
+ // applies the same rule in legacy mode — but only on a COMPLETE
5546
+ // snapshot: under a partial/failed refresh an unscanned workspace may
5547
+ // still hold an eligible follower, so the deferral block below owns
5548
+ // the event instead of a retirement on incomplete evidence.
5549
+ if ((this.boundRoleAware ||
5550
+ (this.requireBoundWatch &&
5551
+ !this.lastBindingsPartial &&
5552
+ !this.boundRefreshFailed)) &&
5181
5553
  (this.boundFollowersOf(envelope.chatId, task.issueNumber).length > 0 ||
5182
5554
  this.boundEventAlreadyDelivered(envelope))) {
5183
5555
  process.stderr.write(`[Channel:${this.name}] bound event ${envelope.messageId} lost its role's session but other roles still follow the PR or already received it; retiring without public fallback\n`);
@@ -6174,21 +6546,39 @@ export class GithubChannel extends PollingChannelBase {
6174
6546
  // comments would re-fill every batch and the capped cursor would never reach
6175
6547
  // the tail. Filtering them out keeps the cap and the cursor progressing over
6176
6548
  // deliverable comments; the excluded ones are simply advanced past.
6549
+ // A gate-only exclusion (every follower watch-ineligible) additionally
6550
+ // earns ONE cycle of grace: a watch installed after this pass's snapshot
6551
+ // was fetched surfaces on the next pass, and the comment it was installed
6552
+ // to catch must not be skipped past with the cursor. The first such
6553
+ // comment holds the cursor before itself; the second consumes it.
6554
+ const gateBlocked = targets.length === 0 && this.gateExcludedAllFollowers(chatId, number);
6555
+ let gateHoldCursor;
6177
6556
  const deliverable = [];
6178
6557
  for (const candidate of candidates) {
6179
6558
  const exclude = excludeFor(candidate);
6180
6559
  if (targets.some((target) => !exclude.has(target.sessionId))) {
6560
+ this.gateGraceClear(candidate.key);
6181
6561
  deliverable.push(candidate);
6182
6562
  continue;
6183
6563
  }
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.
6564
+ // A comment every raw follower authored can never be delivered, no
6565
+ // matter what watch is installed: authorship, not the gate, is the
6566
+ // cause. Skip the grace (holding it would be futile and would suppress
6567
+ // its only journal row) and journal it as comment_watch_no_target.
6568
+ const gateCaused = gateBlocked && exclude.size !== followerIds.size;
6569
+ if (gateCaused && this.gateGraceShouldHold(candidate.key)) {
6570
+ gateHoldCursor ??= candidate.createdAt;
6571
+ continue;
6572
+ }
6573
+ this.gateGraceClear(candidate.key);
6574
+ // No session is left to receive this comment. The notification lanes
6575
+ // cannot see it either (same account => no notification), so this skip
6576
+ // row is the comment's only journal trace — record it instead of
6577
+ // consuming silently, naming the gate when the gate is the cause.
6188
6578
  this.recordChannelEvent({
6189
6579
  type: 'inbound',
6190
6580
  outcome: 'skipped',
6191
- reason: 'comment_watch_no_target',
6581
+ reason: gateCaused ? 'bound_watch_required' : 'comment_watch_no_target',
6192
6582
  repository: chatId,
6193
6583
  thread: threadId,
6194
6584
  number,
@@ -6196,7 +6586,7 @@ export class GithubChannel extends PollingChannelBase {
6196
6586
  });
6197
6587
  }
6198
6588
  if (deliverable.length === 0) {
6199
- commitCursor(nowIso);
6589
+ commitCursor(gateHoldCursor ?? nowIso);
6200
6590
  return;
6201
6591
  }
6202
6592
  // Cap the burst against the pass-wide budget shared by all watched PRs;
@@ -6223,14 +6613,15 @@ export class GithubChannel extends PollingChannelBase {
6223
6613
  // here would skip the comment past with no task and no re-delivery chance.
6224
6614
  commitCursor(since);
6225
6615
  }
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
6616
  else {
6233
- commitCursor(nowIso);
6617
+ // Resume just before the last processed comment when capped so the
6618
+ // unprocessed tail is re-fetched next pass (a second of overlap is
6619
+ // deduped, never lost). A gate-held comment never reaches here: a hold
6620
+ // implies an empty deliverable, which returned above.
6621
+ const last = batch[batch.length - 1];
6622
+ commitCursor(capped
6623
+ ? new Date(Date.parse(last.createdAt) - 1000).toISOString()
6624
+ : nowIso);
6234
6625
  }
6235
6626
  }
6236
6627
  /**
@@ -6295,8 +6686,19 @@ export class GithubChannel extends PollingChannelBase {
6295
6686
  const current = this.resolveBoundDelivery(pending.envelope.chatId, pending.issueNumber);
6296
6687
  if (current) {
6297
6688
  delivery = current;
6689
+ this.gateGraceClear(pending.key);
6298
6690
  }
6299
6691
  else {
6692
+ // One grace cycle when the gate is the cause: a watch installed
6693
+ // after the snapshot was fetched surfaces on the next refresh, and
6694
+ // the transition it was installed to catch must not retire first.
6695
+ // The grace is scoped to the snapshot generation, so a second drain
6696
+ // of the same PR in the same poll does not spend it.
6697
+ if (this.gateExcludedAllFollowers(pending.envelope.chatId, pending.issueNumber) &&
6698
+ this.gateGraceShouldHold(pending.key)) {
6699
+ return;
6700
+ }
6701
+ this.gateGraceClear(pending.key);
6300
6702
  process.stderr.write(`[Channel:${this.name}] watch event ${pending.key} has no bound candidate left; retiring without public fallback\n`);
6301
6703
  const pendingBefore = entry.pending;
6302
6704
  entry.pending = entry.pending.slice(1);
@@ -6343,6 +6745,15 @@ export class GithubChannel extends PollingChannelBase {
6343
6745
  continue;
6344
6746
  }
6345
6747
  }
6748
+ // A partial/failed scan keeps the frozen target — which may be absent
6749
+ // because the gate filtered the map at detection time. Give that state
6750
+ // the same one grace cycle before claiming a task that would retire
6751
+ // targetless at run time.
6752
+ if (delivery === undefined &&
6753
+ this.gateExcludedAllFollowers(pending.envelope.chatId, pending.issueNumber) &&
6754
+ this.gateGraceShouldHold(pending.key)) {
6755
+ return;
6756
+ }
6346
6757
  let task;
6347
6758
  try {
6348
6759
  task = this.claimInboundTask(pending.envelope, pending.issueNumber, {}, delivery);
@@ -6426,12 +6837,22 @@ export class GithubChannel extends PollingChannelBase {
6426
6837
  this.boundRefreshFailed) {
6427
6838
  return;
6428
6839
  }
6840
+ // One grace cycle when the gate is the cause: a watch installed
6841
+ // after the snapshot was fetched surfaces on the next refresh. The
6842
+ // grace is scoped to the snapshot generation (a second drain of the
6843
+ // same PR in the same poll must not spend it).
6844
+ if (this.gateExcludedAllFollowers(pending.envelope.chatId, pending.issueNumber) &&
6845
+ this.gateGraceShouldHold(pending.key)) {
6846
+ return;
6847
+ }
6848
+ this.gateGraceClear(pending.key);
6429
6849
  process.stderr.write(`[Channel:${this.name}] watch event ${pending.key} has no matching role target; retiring without public fallback\n`);
6430
6850
  entry.pending = entry.pending.slice(1);
6431
6851
  this.prWatchState.entries[key] = entry;
6432
6852
  this.savePrWatchState();
6433
6853
  continue;
6434
6854
  }
6855
+ this.gateGraceClear(pending.key);
6435
6856
  const tasksBefore = this.readInboundTasks();
6436
6857
  const knownIds = new Set(tasksBefore.map((task) => task.id));
6437
6858
  const claimable = targets.filter((target) => !tasksBefore.some((task) => this.isRecoverableInboundTask(task) &&