@qwen-code/channel-github 0.27.3 → 0.27.4
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.
- package/dist/GithubAdapter.d.ts +45 -160
- package/dist/GithubAdapter.d.ts.map +1 -1
- package/dist/GithubAdapter.js +241 -1414
- package/dist/GithubAdapter.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -27
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/GithubAdapter.js
CHANGED
|
@@ -246,10 +246,9 @@ export function validateRepoFilterConfig(config, channelName) {
|
|
|
246
246
|
return undefined;
|
|
247
247
|
}
|
|
248
248
|
/**
|
|
249
|
-
* The prWatchEvents vocabulary, shared by the
|
|
250
|
-
*
|
|
251
|
-
*
|
|
252
|
-
* editor and normalizePrWatchEvents both lowercase before matching.
|
|
249
|
+
* The prWatchEvents vocabulary, shared by the deprecated alias's option list
|
|
250
|
+
* (built from this constant in index.ts) and the bound-action validator, so
|
|
251
|
+
* the management UI cannot drift from the key vocabulary (R2-18). Lowercase.
|
|
253
252
|
*/
|
|
254
253
|
export const PR_WATCH_EVENTS = [
|
|
255
254
|
'ci_failure',
|
|
@@ -300,55 +299,14 @@ const BOUND_ACTION_VOCABULARY = {
|
|
|
300
299
|
: PR_NOTIFICATION_REASONS.includes(event),
|
|
301
300
|
eventClassDescription: 'an event class (watch:<type> or a notification reason)',
|
|
302
301
|
};
|
|
303
|
-
/**
|
|
304
|
-
* Default open-PR watch fan-out per poll (~1 pulls.get per watched PR plus
|
|
305
|
-
* conditional Checks fetches; terminal-pending bindings drain in an
|
|
306
|
-
* additional slice of up to 20% outside this budget). Operators with more
|
|
307
|
-
* open bindings raise `prWatchLimit` (and `pollInterval`) deliberately;
|
|
308
|
-
* the watch pass already fails fast on rate limits, so an over-budget
|
|
309
|
-
* configuration degrades instead of hammering the API. Exported for the
|
|
310
|
-
* descriptor so the form bound and the effective bound cannot drift.
|
|
311
|
-
*/
|
|
312
|
-
export const DEFAULT_PR_WATCH_LIMIT = 30;
|
|
313
|
-
/** Hard ceiling for the configurable watch fan-out. */
|
|
314
|
-
export const MAX_PR_WATCH_LIMIT = 500;
|
|
315
302
|
/**
|
|
316
303
|
* Requests held back for the interactive notification lane. When the last
|
|
317
304
|
* known REST budget is at or below this, the watch pass is skipped for the
|
|
318
305
|
* poll so a human mention is not starved by background PR polling. ~4% of a
|
|
319
306
|
* 5,000/hour classic-PAT budget: enough for several polls of mention traffic
|
|
320
|
-
* while barely trimming a healthy watch.
|
|
321
|
-
* Enterprise, finer-grained tokens) set prWatchBudgetReserve explicitly.
|
|
322
|
-
*/
|
|
323
|
-
export const DEFAULT_PR_WATCH_BUDGET_RESERVE = 200;
|
|
324
|
-
/** Hard ceiling for the configurable watch budget reserve. */
|
|
325
|
-
export const MAX_PR_WATCH_BUDGET_RESERVE = 5000;
|
|
326
|
-
/**
|
|
327
|
-
* After a head change, checks register asynchronously (queued or self-hosted
|
|
328
|
-
* runners can take minutes). Within this window an empty CI aggregate
|
|
329
|
-
* ('none') is treated as unsettled and re-checked every poll.
|
|
330
|
-
*/
|
|
331
|
-
const CI_NONE_GRACE_MS = 10 * 60 * 1000;
|
|
332
|
-
/**
|
|
333
|
-
* Settled heads are re-checked on this period even when nothing observable
|
|
334
|
-
* advances: PR updated_at does NOT bump on check re-runs (verified against
|
|
335
|
-
* the live API), and CI can appear long after the grace window on a manual
|
|
336
|
-
* workflow_dispatch. Without a periodic re-check a settled head that turns
|
|
337
|
-
* red later would be missed forever. Cost: at most 2 extra calls per watched
|
|
338
|
-
* PR per interval (30 PRs x 2 x 6/hour = 360/hour on top of the 1800/hour
|
|
339
|
-
* steady state, well under the 5000/hour token budget).
|
|
307
|
+
* while barely trimming a healthy comment watch.
|
|
340
308
|
*/
|
|
341
|
-
const
|
|
342
|
-
/**
|
|
343
|
-
* Pending aggregates re-check on this period, NOT every poll: a workflow
|
|
344
|
-
* queued for environment approval or an offline runner can stay pending for
|
|
345
|
-
* hours, and an unbounded per-poll re-fetch turns the settled-head cost
|
|
346
|
-
* model into ~3,600 CI calls/hour at the watch cap — over the 5,000/hour
|
|
347
|
-
* PAT budget once pulls.get is counted, starving the notification lane.
|
|
348
|
-
* Must stay above the poll interval (60s) to actually bound the fan-out;
|
|
349
|
-
* pending still settles within one period of the real transition.
|
|
350
|
-
*/
|
|
351
|
-
const CI_PENDING_RECHECK_INTERVAL_MS = 5 * 60 * 1000;
|
|
309
|
+
const PR_WATCH_BUDGET_RESERVE = 200;
|
|
352
310
|
/**
|
|
353
311
|
* Bound PR comment watch re-check period. Comments are fetched when the PR's
|
|
354
312
|
* updated_at advances OR this interval elapses, so a settled PR still hears
|
|
@@ -390,33 +348,18 @@ const MAX_BOUND_DEFERRALS = 240;
|
|
|
390
348
|
const MAX_COLD_EMPTY_PARTIAL_POLLS = 30;
|
|
391
349
|
/**
|
|
392
350
|
* Retention bound under a PERMANENT partial snapshot: prune never runs while
|
|
393
|
-
* the binding answer is incomplete, so unlisted
|
|
394
|
-
*
|
|
395
|
-
*
|
|
396
|
-
*
|
|
397
|
-
* bindings and in-flight tasks, and an evicted entry's PR has no delivery
|
|
398
|
-
* target — a later rebind re-baselines silently like any first observation,
|
|
399
|
-
* so eviction bounds memory without losing a deliverable event.
|
|
351
|
+
* the binding answer is incomplete, so unlisted PR entries would otherwise
|
|
352
|
+
* accumulate for the daemon's whole uptime. Oldest-first eviction, surfaced
|
|
353
|
+
* on stderr; an evicted entry has no retained binding, so a later rebind
|
|
354
|
+
* re-baselines it silently.
|
|
400
355
|
*/
|
|
401
356
|
const MAX_PARTIAL_RETAINED = 1024;
|
|
402
|
-
/**
|
|
403
|
-
* Per-entry pending queue bound. A persistently failing claim (task store
|
|
404
|
-
* unreadable/unwritable) keeps every detected transition queued; without a
|
|
405
|
-
* cap the entry is also exempt from retention eviction, and the watch file
|
|
406
|
-
* would grow without bound. Overflow retires the OLDEST queued event to the
|
|
407
|
-
* private dead-letter (surfaced, never silent); a failed dead-letter write
|
|
408
|
-
* keeps the event queued and retries the overflow next detection.
|
|
409
|
-
*/
|
|
410
|
-
const MAX_PENDING_WATCH_PER_ENTRY = 64;
|
|
411
|
-
const MAX_REPORTED_FAILED_CHECKS = 5;
|
|
412
|
-
const MAX_FIRED_KEYS = 64;
|
|
413
357
|
/**
|
|
414
358
|
* Shape check for a persisted watch entry. The container check alone lets a
|
|
415
|
-
* legal-JSON malformed value (e.g. `null`) through, and
|
|
416
|
-
*
|
|
417
|
-
*
|
|
418
|
-
*
|
|
419
|
-
* resetting the whole file.
|
|
359
|
+
* legal-JSON malformed value (e.g. `null`) through, and the comment pass
|
|
360
|
+
* dereferences every entry — one bad entry would throw each poll and starve
|
|
361
|
+
* the entries after it. A malformed entry is dropped (healthy entries
|
|
362
|
+
* survive) rather than resetting the whole file.
|
|
420
363
|
*/
|
|
421
364
|
function isPrWatchEntryShape(value) {
|
|
422
365
|
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
@@ -425,38 +368,10 @@ function isPrWatchEntryShape(value) {
|
|
|
425
368
|
const entry = value;
|
|
426
369
|
const stringOrUndef = (v) => v === undefined || typeof v === 'string';
|
|
427
370
|
const numberOrUndef = (v) => v === undefined || typeof v === 'number';
|
|
428
|
-
|
|
429
|
-
// store applies at claim time: a shape-valid envelope missing chatId
|
|
430
|
-
// would throw in prBindingKey and abort the whole reconcile loop
|
|
431
|
-
// (starving the healthy entries queued behind it), and a partial
|
|
432
|
-
// envelope would be claimed verbatim, rejected by isInboundTaskRecord on
|
|
433
|
-
// the next read, and wedge the task file until an operator deletes it.
|
|
434
|
-
const isPending = (item) => item !== null &&
|
|
435
|
-
typeof item === 'object' &&
|
|
436
|
-
typeof item.key === 'string' &&
|
|
437
|
-
typeof item.issueNumber === 'number' &&
|
|
438
|
-
item.envelope !== undefined &&
|
|
439
|
-
isInboundEnvelope(item.envelope) &&
|
|
440
|
-
(item.delivery === undefined ||
|
|
441
|
-
isBoundDeliveryShape(item.delivery));
|
|
442
|
-
return (stringOrUndef(entry.headSha) &&
|
|
443
|
-
stringOrUndef(entry.ci) &&
|
|
444
|
-
stringOrUndef(entry.mergeableState) &&
|
|
445
|
-
stringOrUndef(entry.prState) &&
|
|
446
|
-
stringOrUndef(entry.title) &&
|
|
447
|
-
stringOrUndef(entry.prUpdatedAt) &&
|
|
448
|
-
numberOrUndef(entry.headObservedAt) &&
|
|
449
|
-
numberOrUndef(entry.lastCiFetchAt) &&
|
|
450
|
-
numberOrUndef(entry.seq) &&
|
|
451
|
-
stringOrUndef(entry.ciFiredSha) &&
|
|
371
|
+
return (stringOrUndef(entry.title) &&
|
|
452
372
|
stringOrUndef(entry.commentBaseline) &&
|
|
453
373
|
stringOrUndef(entry.commentSince) &&
|
|
454
|
-
numberOrUndef(entry.commentLastFetchAt)
|
|
455
|
-
(entry.pending === undefined ||
|
|
456
|
-
(Array.isArray(entry.pending) && entry.pending.every(isPending))) &&
|
|
457
|
-
(entry.fired === undefined ||
|
|
458
|
-
(Array.isArray(entry.fired) &&
|
|
459
|
-
entry.fired.every((k) => typeof k === 'string'))));
|
|
374
|
+
numberOrUndef(entry.commentLastFetchAt));
|
|
460
375
|
}
|
|
461
376
|
/**
|
|
462
377
|
* Parse and validate boundSessionActions into the lookup map connect() and
|
|
@@ -478,29 +393,31 @@ function normalizeBoundSessionActions(config, channelName) {
|
|
|
478
393
|
}
|
|
479
394
|
return validateBoundActionEntries(entries, source, BOUND_ACTION_VOCABULARY);
|
|
480
395
|
}
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
}
|
|
500
|
-
if (events.size > 0 && config.deliverToBoundSessions !== true) {
|
|
501
|
-
throw new Error(`prWatchEvents for channel ${channelName} requires deliverToBoundSessions: true.`);
|
|
396
|
+
/**
|
|
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.
|
|
401
|
+
*/
|
|
402
|
+
function usesDeprecatedPrWatchSurface(config) {
|
|
403
|
+
if (config.prWatchEvents !== undefined)
|
|
404
|
+
return true;
|
|
405
|
+
if (config.prWatchLimit !== undefined)
|
|
406
|
+
return true;
|
|
407
|
+
if (config.prWatchBudgetReserve !== undefined)
|
|
408
|
+
return true;
|
|
409
|
+
const actions = config.boundSessionActions;
|
|
410
|
+
if (actions === null ||
|
|
411
|
+
typeof actions !== 'object' ||
|
|
412
|
+
Array.isArray(actions)) {
|
|
413
|
+
return false;
|
|
502
414
|
}
|
|
503
|
-
return
|
|
415
|
+
return Object.keys(actions).some((key) => {
|
|
416
|
+
if (key.startsWith('watch:'))
|
|
417
|
+
return true;
|
|
418
|
+
const colon = key.indexOf(':');
|
|
419
|
+
return colon !== -1 && key.slice(colon + 1).startsWith('watch:');
|
|
420
|
+
});
|
|
504
421
|
}
|
|
505
422
|
/**
|
|
506
423
|
* Shared validation for the plugin descriptor (returns the message) and
|
|
@@ -512,10 +429,6 @@ export function validateBoundSessionConfig(config, channelName) {
|
|
|
512
429
|
typeof config.deliverToBoundSessions !== 'boolean') {
|
|
513
430
|
return `[Channel:${channelName}] deliverToBoundSessions must be a boolean.`;
|
|
514
431
|
}
|
|
515
|
-
if (config.prWatchLimit !== undefined &&
|
|
516
|
-
config.deliverToBoundSessions !== true) {
|
|
517
|
-
return `prWatchLimit for channel ${channelName} requires deliverToBoundSessions: true.`;
|
|
518
|
-
}
|
|
519
432
|
if (config.requireBoundWatch !== undefined &&
|
|
520
433
|
typeof config.requireBoundWatch !== 'boolean') {
|
|
521
434
|
return `[Channel:${channelName}] requireBoundWatch must be a boolean.`;
|
|
@@ -531,28 +444,7 @@ export function validateBoundSessionConfig(config, channelName) {
|
|
|
531
444
|
// No deliverToBoundSessions dependency: prCommentWatch is default-on, so the
|
|
532
445
|
// editor emits it even for channels without bound delivery. It is inert there
|
|
533
446
|
// (the watch is gated on deliverToBoundSessions at runtime), not an error.
|
|
534
|
-
if (config.prWatchBudgetReserve !== undefined &&
|
|
535
|
-
config.deliverToBoundSessions !== true) {
|
|
536
|
-
return `prWatchBudgetReserve for channel ${channelName} requires deliverToBoundSessions: true.`;
|
|
537
|
-
}
|
|
538
|
-
// The descriptor now declares minimum: 0, so the editor refuses a negative
|
|
539
|
-
// the operator types. This check still guards everything else: a hand-edited
|
|
540
|
-
// settings.json or a daemon API call, and a stored negative the editor
|
|
541
|
-
// re-sends unchanged under its descriptor-level tolerance. The getter would
|
|
542
|
-
// silently fall back to the default for a negative, letting a saved value
|
|
543
|
-
// mean something other than it says.
|
|
544
|
-
// Positive fractions stay legal: the getter rounds them UP, which is the
|
|
545
|
-
// documented behaviour, not a silent fallback.
|
|
546
|
-
if (config.prWatchBudgetReserve !== undefined) {
|
|
547
|
-
const reserve = config.prWatchBudgetReserve;
|
|
548
|
-
if (typeof reserve !== 'number' ||
|
|
549
|
-
!Number.isFinite(reserve) ||
|
|
550
|
-
reserve < 0) {
|
|
551
|
-
return `prWatchBudgetReserve for channel ${channelName} must be a non-negative number.`;
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
447
|
try {
|
|
555
|
-
normalizePrWatchEvents(config, channelName);
|
|
556
448
|
normalizeBoundSessionActions(config, channelName);
|
|
557
449
|
}
|
|
558
450
|
catch (err) {
|
|
@@ -721,14 +613,6 @@ const BOUND_DELIVERY_COPY = {
|
|
|
721
613
|
newInlineReviewCommentLead: (author) => `New inline review comment by @${author}:`,
|
|
722
614
|
reviewRequestedInstruction: 'Return a formal review summary with verified actionable findings, or a concise no-blocker result.',
|
|
723
615
|
assignInstruction: 'Triage this issue and respond with the next action.',
|
|
724
|
-
headChange: (fromSha, toSha) => `New commits pushed: head moved from ${fromSha} to ${toSha}.`,
|
|
725
|
-
ciFailure: (headSha) => `CI failed on head ${headSha}.`,
|
|
726
|
-
failedChecks: (names, namesIncomplete) => ` Failed checks: ${names}${namesIncomplete
|
|
727
|
-
? ' (list may be incomplete: later check pages were not read)'
|
|
728
|
-
: ''}.`,
|
|
729
|
-
mergeConflict: 'Merge conflicts detected (mergeable_state: dirty).',
|
|
730
|
-
prMerged: 'The PR was merged.',
|
|
731
|
-
prClosed: 'The PR was closed without merging.',
|
|
732
616
|
},
|
|
733
617
|
zh: {
|
|
734
618
|
provenance: (channelName) => `由 "${channelName}" GitHub channel 投递,因为本会话绑定了下面的 PR。`,
|
|
@@ -740,12 +624,6 @@ const BOUND_DELIVERY_COPY = {
|
|
|
740
624
|
newInlineReviewCommentLead: (author) => `@${author} 的新行内评审评论:`,
|
|
741
625
|
reviewRequestedInstruction: '请给出正式的评审总结,包含经核实的可操作发现;若没有阻塞问题,给出简洁的无阻塞结论。',
|
|
742
626
|
assignInstruction: '请分诊该 issue 并给出下一步行动。',
|
|
743
|
-
headChange: (fromSha, toSha) => `有新提交推送:head 从 ${fromSha} 变为 ${toSha}。`,
|
|
744
|
-
ciFailure: (headSha) => `head ${headSha} 的 CI 失败。`,
|
|
745
|
-
failedChecks: (names, namesIncomplete) => `失败的检查:${names}${namesIncomplete ? '(列表可能不完整:未读取后续检查分页)' : ''}。`,
|
|
746
|
-
mergeConflict: '检测到合并冲突(mergeable_state: dirty)。',
|
|
747
|
-
prMerged: 'PR 已合并。',
|
|
748
|
-
prClosed: 'PR 已关闭,未合并。',
|
|
749
627
|
},
|
|
750
628
|
};
|
|
751
629
|
function isNoReplySentinel(text) {
|
|
@@ -756,19 +634,11 @@ function isNoReplySentinel(text) {
|
|
|
756
634
|
/** GitHub's wording for a secondary (abuse) rate limit. */
|
|
757
635
|
const SECONDARY_RATE_LIMIT_MESSAGE = /secondary rate limit|abuse detection/i;
|
|
758
636
|
/**
|
|
759
|
-
* Cap on cached conditional responses,
|
|
760
|
-
*
|
|
761
|
-
*
|
|
762
|
-
* proportionally — each miss evicts the entry the sweep is about to read, so
|
|
763
|
-
* every read of every later pass misses and the saving is exactly zero for
|
|
764
|
-
* the high-fan-out deployments this is meant to help. Derived from the watch
|
|
765
|
-
* limit so the two cannot drift apart.
|
|
766
|
-
*
|
|
767
|
-
* A moved notifications `since` cursor still mints new keys, so the map is
|
|
768
|
-
* bounded and evicts least-recently-used first; an evicted URL simply pays
|
|
769
|
-
* for one full 200 again.
|
|
637
|
+
* Cap on cached conditional responses. 1,000 is the former watch fan-out
|
|
638
|
+
* ceiling doubled; the state watch is gone, but the cache still serves the
|
|
639
|
+
* notification pages and the comment watch's list reads.
|
|
770
640
|
*/
|
|
771
|
-
export const CONDITIONAL_CACHE_MAX_ENTRIES =
|
|
641
|
+
export const CONDITIONAL_CACHE_MAX_ENTRIES = 1000;
|
|
772
642
|
/**
|
|
773
643
|
* Bodies above this size are not cached, so a pathologically large page
|
|
774
644
|
* cannot pin memory. Sized against the entry cap above to keep the retention
|
|
@@ -999,7 +869,6 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
999
869
|
* with deliverToBoundSessions; `prCommentWatch: false` disables it.
|
|
1000
870
|
*/
|
|
1001
871
|
prCommentWatchEnabled = true;
|
|
1002
|
-
prWatchEvents = new Set();
|
|
1003
872
|
/**
|
|
1004
873
|
* Operator instruction templates keyed by the closed bound-action
|
|
1005
874
|
* vocabulary. Non-empty switches routing to role-aware fan-out (one
|
|
@@ -1112,23 +981,6 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
1112
981
|
gateGraceClear(key) {
|
|
1113
982
|
this.gateDeferredOnce.delete(key);
|
|
1114
983
|
}
|
|
1115
|
-
/**
|
|
1116
|
-
* True while the most recent pending-watch reconciliation FAILED (e.g.
|
|
1117
|
-
* the watch file is unreadable). Generic recovery must then leave watch
|
|
1118
|
-
* tasks alone: delivering and removing an accepted watch task without
|
|
1119
|
-
* reconciling its on-disk pending record would let a later drain claim
|
|
1120
|
-
* and deliver the same transition a second time. Unrelated comment
|
|
1121
|
-
* recovery keeps running.
|
|
1122
|
-
*/
|
|
1123
|
-
watchReconcileBlocked = false;
|
|
1124
|
-
/**
|
|
1125
|
-
* The cause the blocking watch-guard row last named. The row is
|
|
1126
|
-
* edge-triggered per CAUSE, not just per blocked window: a pending backlog
|
|
1127
|
-
* that turns into an unreadable sidecar (or back) must re-journal, or the
|
|
1128
|
-
* timeline keeps naming a remedy that no longer applies. Cleared on the
|
|
1129
|
-
* recovery edge.
|
|
1130
|
-
*/
|
|
1131
|
-
watchReconcileBlockedCause;
|
|
1132
984
|
/**
|
|
1133
985
|
* Last REST budget seen on a SUCCESSFUL response, recorded by the request
|
|
1134
986
|
* hook regardless of the call's return shape. Undefined until the first
|
|
@@ -1145,9 +997,9 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
1145
997
|
lastRateLimitResetAt;
|
|
1146
998
|
/**
|
|
1147
999
|
* Whether the watch pass is currently skipped for low budget. Edge-triggered
|
|
1148
|
-
* journaling
|
|
1149
|
-
*
|
|
1150
|
-
*
|
|
1000
|
+
* journaling: a permanent low-budget condition is journalled once on the
|
|
1001
|
+
* edge, not every poll, so it cannot rotate the useful rows out of the
|
|
1002
|
+
* timeline. Cleared on the recovery edge.
|
|
1151
1003
|
*/
|
|
1152
1004
|
watchBudgetLow = false;
|
|
1153
1005
|
/**
|
|
@@ -1187,16 +1039,6 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
1187
1039
|
boundSnapshotFailureStreak = 0;
|
|
1188
1040
|
prWatchState = { version: 1, entries: {} };
|
|
1189
1041
|
prWatchStateLoaded = false;
|
|
1190
|
-
/**
|
|
1191
|
-
* Message keys that already have a durable dead-letter record, lazily
|
|
1192
|
-
* loaded from the never-rotated dead-letter file on first use and kept
|
|
1193
|
-
* current as this process appends. The file is the overflow retire's commit
|
|
1194
|
-
* point: a head with a record is never re-appended — even across a restart,
|
|
1195
|
-
* which empties this cache and reloads it from disk — and never delivered;
|
|
1196
|
-
* the drain completes its retire instead. Watch keys are unique per
|
|
1197
|
-
* episode, so a record can only match the same transition.
|
|
1198
|
-
*/
|
|
1199
|
-
deadLetteredKeys;
|
|
1200
1042
|
inboundRecoveryPending = true;
|
|
1201
1043
|
recoverableInboundTasks = 0;
|
|
1202
1044
|
/**
|
|
@@ -1363,11 +1205,13 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
1363
1205
|
if (boundConfigError) {
|
|
1364
1206
|
throw new Error(boundConfigError);
|
|
1365
1207
|
}
|
|
1366
|
-
this.prWatchEvents = normalizePrWatchEvents(cfg, this.name);
|
|
1367
1208
|
this.boundSessionActions = normalizeBoundSessionActions(cfg, this.name);
|
|
1368
1209
|
this.deliverToBoundSessions = cfg.deliverToBoundSessions === true;
|
|
1369
1210
|
this.requireBoundWatch = cfg.requireBoundWatch === true;
|
|
1370
1211
|
this.prCommentWatchEnabled = cfg.prCommentWatch !== false;
|
|
1212
|
+
if (usesDeprecatedPrWatchSurface(cfg)) {
|
|
1213
|
+
process.stderr.write(`[Channel:${this.name}] warning: prWatchEvents, the watch:* keys of boundSessionActions, prWatchLimit and prWatchBudgetReserve are deprecated; this channel no longer detects PR state transitions. Configure serve.sessionPrWatch in the daemon's settings instead. The watch keys are read as a per-host alias for one minor release; the two limit knobs are ignored and the pass uses its built-in budget.\n`);
|
|
1214
|
+
}
|
|
1371
1215
|
if (this.deliverToBoundSessions) {
|
|
1372
1216
|
this.loadBoundDeliveredRing();
|
|
1373
1217
|
}
|
|
@@ -1375,7 +1219,6 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
1375
1219
|
process.stderr.write(`[Channel:${this.name}] warning: deliverToBoundSessions requires a daemon-managed channel; ignoring (standalone mode).\n`);
|
|
1376
1220
|
this.deliverToBoundSessions = false;
|
|
1377
1221
|
this.requireBoundWatch = false;
|
|
1378
|
-
this.prWatchEvents = new Set();
|
|
1379
1222
|
this.boundSessionActions = new Map();
|
|
1380
1223
|
}
|
|
1381
1224
|
const baseUrl = cfg.baseUrl || 'https://api.github.com';
|
|
@@ -1454,6 +1297,7 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
1454
1297
|
this.config.operators = this.config.operators.map((u) => u.toLowerCase());
|
|
1455
1298
|
}
|
|
1456
1299
|
this.migrateLegacyPublicationState();
|
|
1300
|
+
this.retireLegacyPrWatchState();
|
|
1457
1301
|
this.inboundPersistenceBlocked = false;
|
|
1458
1302
|
this.inboundRecoveryPending = true;
|
|
1459
1303
|
// A reconnect starts a fresh runner generation; any runner left over
|
|
@@ -2033,115 +1877,11 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
2033
1877
|
if (this.deliverToBoundSessions) {
|
|
2034
1878
|
await this.refreshBoundSessions();
|
|
2035
1879
|
}
|
|
2036
|
-
//
|
|
2037
|
-
//
|
|
2038
|
-
//
|
|
2039
|
-
// first it would deliver and remove the task, then a later drain would
|
|
2040
|
-
// claim and deliver the same transition again. Draining needs no GitHub
|
|
2041
|
-
// calls, so a failing or rate-limited binding fetch must not starve it —
|
|
2042
|
-
// drain's own re-validation fails closed (keeps the frozen target) when
|
|
2043
|
-
// the snapshot is partial or the refresh failed.
|
|
2044
|
-
if (this.prWatchEvents.size > 0) {
|
|
2045
|
-
try {
|
|
2046
|
-
await this.reconcilePendingWatch();
|
|
2047
|
-
const wasBlocked = this.watchReconcileBlocked;
|
|
2048
|
-
this.watchReconcileBlocked = false;
|
|
2049
|
-
this.watchReconcileBlockedCause = undefined;
|
|
2050
|
-
// The clearing edge is the recovery signal. A `poll` / `ok` row is
|
|
2051
|
-
// not: the base writes one after every poll that does not throw,
|
|
2052
|
-
// including every poll of a sustained outage, so it is present
|
|
2053
|
-
// throughout the degraded window and cannot mark its end.
|
|
2054
|
-
if (wasBlocked) {
|
|
2055
|
-
this.recordPollDegraded('watch_reconcile_recovered');
|
|
2056
|
-
}
|
|
2057
|
-
}
|
|
2058
|
-
catch (err) {
|
|
2059
|
-
// Recovery must not deliver accepted watch tasks while their pending
|
|
2060
|
-
// records are unreconciled (a later drain would deliver them again).
|
|
2061
|
-
this.watchReconcileBlocked = true;
|
|
2062
|
-
const message = sanitizeLogText(err instanceof Error ? err.message : String(err), 200);
|
|
2063
|
-
process.stderr.write(`[Channel:${this.name}] pending watch reconciliation failed, will retry next poll: ${message}\n`);
|
|
2064
|
-
// Edge-triggered per cause: this catch runs on EVERY poll while the
|
|
2065
|
-
// watch state stays unreadable, so a per-poll row would rotate the
|
|
2066
|
-
// journal — but a cause that CHANGES while blocked must re-journal.
|
|
2067
|
-
if (this.watchReconcileBlockedCause !== 'reconcile_failed') {
|
|
2068
|
-
this.recordPollDegraded('watch_reconcile_blocked', undefined, message);
|
|
2069
|
-
this.watchReconcileBlockedCause = 'reconcile_failed';
|
|
2070
|
-
}
|
|
2071
|
-
}
|
|
2072
|
-
}
|
|
2073
|
-
else {
|
|
2074
|
-
// Subscriptions are off, but unreconciled pending records on disk
|
|
2075
|
-
// still own their accepted tasks: recovery must not deliver and
|
|
2076
|
-
// remove a task that a later re-enabled drain would claim and
|
|
2077
|
-
// deliver again. Keep the guard until no watch pending remains.
|
|
2078
|
-
//
|
|
2079
|
-
// Classify the cause first. hasUnreconciledWatchPending() is fail-closed
|
|
2080
|
-
// on a read error, so an unreadable sidecar also blocks recovery — but
|
|
2081
|
-
// reporting that as a pending backlog names a remedy (re-enable
|
|
2082
|
-
// subscriptions) that cannot clear it. The gate below is unchanged.
|
|
2083
|
-
let watchStateError;
|
|
2084
|
-
try {
|
|
2085
|
-
this.loadPrWatchState();
|
|
2086
|
-
}
|
|
2087
|
-
catch (err) {
|
|
2088
|
-
watchStateError = sanitizeLogText(err instanceof Error ? err.message : String(err), 200);
|
|
2089
|
-
}
|
|
2090
|
-
const wasBlocked = this.watchReconcileBlocked;
|
|
2091
|
-
this.watchReconcileBlocked = this.hasUnreconciledWatchPending();
|
|
2092
|
-
if (this.watchReconcileBlocked) {
|
|
2093
|
-
// Park the legacy watch tasks as backpressure so they stop
|
|
2094
|
-
// blocking the SHARED notification cursor: watch delivery is off,
|
|
2095
|
-
// the reconcile guard still skips them in recovery, and comment
|
|
2096
|
-
// events must not stall channel-wide until an operator re-enables
|
|
2097
|
-
// watch. Re-enabling drains the pendings and re-resolves them.
|
|
2098
|
-
try {
|
|
2099
|
-
for (const task of this.readInboundTasks()) {
|
|
2100
|
-
if (this.isRecoverableInboundTask(task) &&
|
|
2101
|
-
task.backpressure !== true &&
|
|
2102
|
-
task.envelope?.messageId?.startsWith('watch:') === true) {
|
|
2103
|
-
this.transitionInboundTask(task.id, 'failed', {
|
|
2104
|
-
error: 'watch subscriptions disabled; parked until re-enabled',
|
|
2105
|
-
attempts: task.attempts ?? 0,
|
|
2106
|
-
deferCount: task.deferCount ?? 0,
|
|
2107
|
-
backpressure: true,
|
|
2108
|
-
});
|
|
2109
|
-
}
|
|
2110
|
-
}
|
|
2111
|
-
}
|
|
2112
|
-
catch {
|
|
2113
|
-
// Task store unreadable/unwritable: fail closed, retry next poll.
|
|
2114
|
-
}
|
|
2115
|
-
process.stderr.write(`[Channel:${this.name}] watch subscriptions are disabled but pending watch events remain unreconciled; watch task recovery stays blocked until subscriptions are re-enabled and the pending events reconcile (legacy watch tasks parked as backpressure so the notification cursor keeps flowing)${watchStateError ? ` — the watch state is also unreadable, which alone blocks recovery: ${watchStateError}` : ''}\n`);
|
|
2116
|
-
// Edge-triggered per cause, for the same reason as the reconcile
|
|
2117
|
-
// failure above: this branch runs on every poll until an operator
|
|
2118
|
-
// re-enables watch, but a backlog that turns into a read error (or
|
|
2119
|
-
// back) must re-journal so the row never names a stale remedy.
|
|
2120
|
-
const cause = watchStateError ? 'read_error' : 'pending';
|
|
2121
|
-
if (this.watchReconcileBlockedCause !== cause) {
|
|
2122
|
-
if (watchStateError) {
|
|
2123
|
-
this.recordPollDegraded('watch_reconcile_blocked', undefined, watchStateError);
|
|
2124
|
-
}
|
|
2125
|
-
else {
|
|
2126
|
-
this.recordPollDegraded('watch_pending_unreconciled');
|
|
2127
|
-
}
|
|
2128
|
-
this.watchReconcileBlockedCause = cause;
|
|
2129
|
-
}
|
|
2130
|
-
}
|
|
2131
|
-
else {
|
|
2132
|
-
this.watchReconcileBlockedCause = undefined;
|
|
2133
|
-
if (wasBlocked) {
|
|
2134
|
-
this.recordPollDegraded('watch_reconcile_recovered');
|
|
2135
|
-
}
|
|
2136
|
-
}
|
|
2137
|
-
}
|
|
2138
|
-
// The watch pass runs before generic recovery so detection cannot race
|
|
2139
|
-
// recovery over the same task; pending events were already reconciled.
|
|
2140
|
-
// The comment watch is independent of the state-event subscription, so an
|
|
2141
|
-
// empty prWatchEvents still runs the pass while comment watching is on.
|
|
1880
|
+
// The comment watch runs before generic recovery so a slow fetch cannot
|
|
1881
|
+
// race the tasks its own deliveries create. It is default-on with bound
|
|
1882
|
+
// delivery and independent of the retired state subscription.
|
|
2142
1883
|
const commentWatchActive = this.deliverToBoundSessions && this.prCommentWatchEnabled;
|
|
2143
|
-
if (
|
|
2144
|
-
!this.boundRefreshFailed) {
|
|
1884
|
+
if (commentWatchActive && !this.boundRefreshFailed) {
|
|
2145
1885
|
// Protect the interactive notification lane: the watch runs first and
|
|
2146
1886
|
// is best-effort edge-triggered detection, so when the last known REST
|
|
2147
1887
|
// budget is at or below the reserve, skip the pass this poll rather
|
|
@@ -3321,28 +3061,16 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
3321
3061
|
record.source.messageId === envelope.messageId &&
|
|
3322
3062
|
// Fan-out claims one task per (event, target): the target is part
|
|
3323
3063
|
// of the task identity, while source.messageId stays the pure
|
|
3324
|
-
// event key (
|
|
3064
|
+
// event key (audit key and dedupe ride it).
|
|
3325
3065
|
record.delivery?.sessionId === delivery?.sessionId);
|
|
3326
3066
|
if (existing) {
|
|
3327
|
-
//
|
|
3328
|
-
//
|
|
3329
|
-
//
|
|
3330
|
-
//
|
|
3331
|
-
//
|
|
3332
|
-
|
|
3333
|
-
|
|
3334
|
-
(existing.attempts ?? 0) >= MAX_INBOUND_TASK_ATTEMPTS);
|
|
3335
|
-
// Only watch episode keys legitimately recur. Comment/event/issue-body
|
|
3336
|
-
// keys are stable identifiers that never re-fire: a terminal record
|
|
3337
|
-
// there is a permanent dedupe barrier. Replacing it would revive a
|
|
3338
|
-
// cancelled comment (public reply to a silenced comment) or duplicate
|
|
3339
|
-
// a failed one after a crash leaves the cursor behind the cancel.
|
|
3340
|
-
const recurrible = existing.source.messageId?.startsWith('watch:') === true;
|
|
3341
|
-
if (!terminal || !recurrible) {
|
|
3342
|
-
this.applyTaskDedupe(existing.dedupe);
|
|
3343
|
-
return existing;
|
|
3344
|
-
}
|
|
3345
|
-
this.removeInboundTask(existing.id);
|
|
3067
|
+
// Comment/event/issue-body keys are stable identifiers that never
|
|
3068
|
+
// re-fire: any existing record is a permanent dedupe barrier. Replacing
|
|
3069
|
+
// it would revive a cancelled comment (public reply to a silenced
|
|
3070
|
+
// comment) or duplicate a failed one after a crash leaves the cursor
|
|
3071
|
+
// behind the cancel.
|
|
3072
|
+
this.applyTaskDedupe(existing.dedupe);
|
|
3073
|
+
return existing;
|
|
3346
3074
|
}
|
|
3347
3075
|
const now = new Date().toISOString();
|
|
3348
3076
|
const task = {
|
|
@@ -3493,9 +3221,7 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
3493
3221
|
if (!envelope)
|
|
3494
3222
|
return false;
|
|
3495
3223
|
const bound = task.delivery?.kind === 'bound-session';
|
|
3496
|
-
const isWatch = envelope.messageId?.startsWith('watch:') === true;
|
|
3497
3224
|
if (bound ||
|
|
3498
|
-
isWatch ||
|
|
3499
3225
|
!this.deliverToBoundSessions ||
|
|
3500
3226
|
envelope.threadId?.startsWith('pr:') !== true) {
|
|
3501
3227
|
return false;
|
|
@@ -3525,7 +3251,6 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
3525
3251
|
if (!envelope)
|
|
3526
3252
|
return true;
|
|
3527
3253
|
const bound = task.delivery?.kind === 'bound-session';
|
|
3528
|
-
const isWatch = envelope.messageId?.startsWith('watch:') === true;
|
|
3529
3254
|
// Absence from the map authorizes the irreversible public path ONLY
|
|
3530
3255
|
// on a current complete, successful snapshot. A partial answer cannot
|
|
3531
3256
|
// prove absence for a PR even when every OBSERVED binder is listed and
|
|
@@ -3549,20 +3274,14 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
3549
3274
|
// increment. The backpressure rollback is a second write, and a crash
|
|
3550
3275
|
// between the two would leak one budget per cycle until the event is
|
|
3551
3276
|
// silently dropped. Recovery charges the interrupted attempt instead,
|
|
3552
|
-
// which keeps crash loops terminating.
|
|
3553
|
-
|
|
3554
|
-
this.transitionInboundTask(task.id, 'running', bound || isWatch ? {} : { attempts });
|
|
3277
|
+
// which keeps crash loops terminating.
|
|
3278
|
+
this.transitionInboundTask(task.id, 'running', bound ? {} : { attempts });
|
|
3555
3279
|
let cancelled = false;
|
|
3556
3280
|
// The public path journals its own acceptance and publication; only
|
|
3557
3281
|
// bound delivery needs a verdict to name its terminal outcome.
|
|
3558
3282
|
let boundResult = { kind: 'public' };
|
|
3559
3283
|
try {
|
|
3560
|
-
|
|
3561
|
-
// by the current delivery. A watch task whose delivery was cleared (a
|
|
3562
|
-
// gone session, or a crash/removal failure that left it running with no
|
|
3563
|
-
// target) must never fall through to the public channel path —
|
|
3564
|
-
// deliverToBoundSession retires a targetless watch event privately.
|
|
3565
|
-
if (bound || isWatch) {
|
|
3284
|
+
if (bound) {
|
|
3566
3285
|
boundResult = await this.deliverToBoundSession(task, envelope);
|
|
3567
3286
|
if (boundResult.kind === 'deferred')
|
|
3568
3287
|
return false;
|
|
@@ -3714,14 +3433,12 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
3714
3433
|
this.removeInboundTask(task.id);
|
|
3715
3434
|
return true;
|
|
3716
3435
|
}
|
|
3717
|
-
if (
|
|
3718
|
-
// A
|
|
3719
|
-
//
|
|
3720
|
-
//
|
|
3721
|
-
//
|
|
3722
|
-
//
|
|
3723
|
-
// wedge the retired task — and with it the shared cursor — on an
|
|
3724
|
-
// unrelated file's readability.
|
|
3436
|
+
if (this.privatelyRetiredInboundTaskIds.has(task.id)) {
|
|
3437
|
+
// A role-aware comment task reaches here after a private retire (role
|
|
3438
|
+
// lost its match, siblings already delivered). It published nothing, so
|
|
3439
|
+
// it can have no pending final delivery: reading the public reply lane's
|
|
3440
|
+
// store here would wedge the retired task — and with it the shared
|
|
3441
|
+
// cursor — on an unrelated file's readability.
|
|
3725
3442
|
this.privatelyRetiredInboundTaskIds.delete(task.id);
|
|
3726
3443
|
this.removeInboundTask(task.id);
|
|
3727
3444
|
// After the removal, like the dead-letter site: a throwing removal
|
|
@@ -3813,16 +3530,14 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
3813
3530
|
// in-flight entry is a genuine crash and must still be recovered.
|
|
3814
3531
|
if (this.publicTasksInFlight.has(task.id))
|
|
3815
3532
|
continue;
|
|
3816
|
-
|
|
3817
|
-
|
|
3818
|
-
|
|
3819
|
-
//
|
|
3820
|
-
|
|
3821
|
-
// on-disk pending record for a later drain to claim and deliver a
|
|
3822
|
-
// second time. Keep it queued for the reconcile pass; unrelated
|
|
3823
|
-
// comment recovery continues below.
|
|
3533
|
+
if (task.envelope.messageId?.startsWith('watch:') === true) {
|
|
3534
|
+
// The adapter's state watch is retired. A task left behind by a
|
|
3535
|
+
// failed retirement must never be replayed; its dead-letter record is
|
|
3536
|
+
// the only intended trace. A failed write keeps it for the next pass.
|
|
3537
|
+
this.retireBoundTask(task, 'the adapter PR state watch was retired; the transition is not replayed');
|
|
3824
3538
|
continue;
|
|
3825
3539
|
}
|
|
3540
|
+
this.applyTaskDedupe(task.dedupe);
|
|
3826
3541
|
if (task.deliveredAt !== undefined) {
|
|
3827
3542
|
// The daemon accepted this prompt before the crash; re-injecting
|
|
3828
3543
|
// would deliver the same event twice. Retire without replay — but
|
|
@@ -3963,13 +3678,8 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
3963
3678
|
* deferral horizon, and must not freeze mark-as-read for every unrelated
|
|
3964
3679
|
* PR the channel follows. This covers both bound deliveries and the
|
|
3965
3680
|
* targetless deferrals an incomplete binding snapshot produces (no
|
|
3966
|
-
* delivery yet, same durable retry).
|
|
3967
|
-
*
|
|
3968
|
-
* they cannot make progress — and watch events are detected from PR
|
|
3969
|
-
* state, not notifications, so holding the cursor for them only stalls
|
|
3970
|
-
* unrelated comment traffic until the watch sidecar recovers. Once
|
|
3971
|
-
* reconcile succeeds they count again, and their retry budgets guarantee
|
|
3972
|
-
* they settle instead of freezing the cursor forever.
|
|
3681
|
+
* delivery yet, same durable retry). Every entry here settles through its
|
|
3682
|
+
* own retry budget, so it cannot freeze the cursor forever.
|
|
3973
3683
|
*/
|
|
3974
3684
|
hasCursorBlockingTasks() {
|
|
3975
3685
|
return this.readInboundTasks().some((task) => this.isCursorBlockingTask(task));
|
|
@@ -3992,10 +3702,13 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
3992
3702
|
return this.pollStartHeldThreads.has(`${chatId}|${threadId}`);
|
|
3993
3703
|
}
|
|
3994
3704
|
isCursorBlockingTask(task) {
|
|
3705
|
+
// A retired `watch:` task that the dead-letter write keeps retrying is
|
|
3706
|
+
// never replayed, so it must not freeze the shared notification cursor:
|
|
3707
|
+
// with the dead-letter path unwritable, holding it would stop
|
|
3708
|
+
// markNotificationsAsRead for the daemon's lifetime.
|
|
3995
3709
|
return (this.isRecoverableInboundTask(task) &&
|
|
3996
3710
|
task.backpressure !== true &&
|
|
3997
|
-
|
|
3998
|
-
task.envelope?.messageId?.startsWith('watch:') === true));
|
|
3711
|
+
task.envelope?.messageId?.startsWith('watch:') !== true);
|
|
3999
3712
|
}
|
|
4000
3713
|
/** Whether one of the thread's own tasks holds the cursor, as last seen. */
|
|
4001
3714
|
threadTaskHoldsCursor(chatId, threadId) {
|
|
@@ -4261,64 +3974,6 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
4261
3974
|
return this.lastBindings.find((binding) => binding.sessionId === sessionId)
|
|
4262
3975
|
?.workspaceCwd;
|
|
4263
3976
|
}
|
|
4264
|
-
/**
|
|
4265
|
-
* Whether a message key already has a durable dead-letter record. Loads the
|
|
4266
|
-
* never-rotated file's keys once, then serves from the cache this process
|
|
4267
|
-
* keeps current on append. A read failure yields an empty cache: nothing is
|
|
4268
|
-
* known to be dead-lettered, so the caller appends (a possible duplicate is
|
|
4269
|
-
* benign) rather than silently skipping the exhaustion surface.
|
|
4270
|
-
*/
|
|
4271
|
-
isDeadLettered(messageKey) {
|
|
4272
|
-
if (this.deadLetteredKeys === undefined) {
|
|
4273
|
-
const keys = new Set();
|
|
4274
|
-
try {
|
|
4275
|
-
const raw = readFileSync(this.channelFilePath('github-bound-deadletter.jsonl'), 'utf-8');
|
|
4276
|
-
for (const line of raw.split('\n')) {
|
|
4277
|
-
if (!line)
|
|
4278
|
-
continue;
|
|
4279
|
-
try {
|
|
4280
|
-
const rec = JSON.parse(line);
|
|
4281
|
-
if (typeof rec.source?.messageId === 'string') {
|
|
4282
|
-
keys.add(rec.source.messageId);
|
|
4283
|
-
}
|
|
4284
|
-
}
|
|
4285
|
-
catch {
|
|
4286
|
-
// A malformed line names no key; skip it.
|
|
4287
|
-
}
|
|
4288
|
-
}
|
|
4289
|
-
}
|
|
4290
|
-
catch {
|
|
4291
|
-
// No file yet, or unreadable: nothing known to be dead-lettered.
|
|
4292
|
-
}
|
|
4293
|
-
this.deadLetteredKeys = keys;
|
|
4294
|
-
}
|
|
4295
|
-
return this.deadLetteredKeys.has(messageKey);
|
|
4296
|
-
}
|
|
4297
|
-
/**
|
|
4298
|
-
* The overflow retire's journal trace, written only after the retire is
|
|
4299
|
-
* durable. Identifiers only — the dead-letter record's `text` (the body)
|
|
4300
|
-
* must never be copied here. Carries the frozen target and its workspace so
|
|
4301
|
-
* the row links to the session the event lost, even in another workspace.
|
|
4302
|
-
*/
|
|
4303
|
-
recordWatchOverflowSkip(pending) {
|
|
4304
|
-
const sessionId = pending.delivery?.kind === 'bound-session'
|
|
4305
|
-
? pending.delivery.sessionId
|
|
4306
|
-
: undefined;
|
|
4307
|
-
const workspaceCwd = sessionId
|
|
4308
|
-
? this.sessionWorkspaceFor(sessionId)
|
|
4309
|
-
: undefined;
|
|
4310
|
-
this.recordChannelEvent({
|
|
4311
|
-
type: 'inbound',
|
|
4312
|
-
outcome: 'skipped',
|
|
4313
|
-
reason: 'watch_pending_overflow',
|
|
4314
|
-
repository: pending.envelope.chatId,
|
|
4315
|
-
thread: pending.envelope.threadId,
|
|
4316
|
-
number: pending.issueNumber,
|
|
4317
|
-
messageId: pending.key,
|
|
4318
|
-
...(sessionId ? { sessionId } : {}),
|
|
4319
|
-
...(workspaceCwd ? { sessionWorkspaceCwd: workspaceCwd } : {}),
|
|
4320
|
-
});
|
|
4321
|
-
}
|
|
4322
3977
|
removeInboundTask(taskId) {
|
|
4323
3978
|
this.updateInboundTasks((records) => records.filter((record) => record.id !== taskId));
|
|
4324
3979
|
}
|
|
@@ -4427,12 +4082,7 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
4427
4082
|
* covers a wrong estimate or a secondary limit.
|
|
4428
4083
|
*/
|
|
4429
4084
|
watchBudgetExhausted() {
|
|
4430
|
-
const reserve =
|
|
4431
|
-
// A reserve of 0 disables the gate outright. Without this, a remaining
|
|
4432
|
-
// of 0 would still satisfy `0 <= 0` and skip the watch the operator
|
|
4433
|
-
// explicitly opted out of protecting.
|
|
4434
|
-
if (reserve === 0)
|
|
4435
|
-
return false;
|
|
4085
|
+
const reserve = PR_WATCH_BUDGET_RESERVE;
|
|
4436
4086
|
if (this.lastRateLimitRemaining === undefined)
|
|
4437
4087
|
return false;
|
|
4438
4088
|
if (this.lastRateLimitResetAt !== undefined &&
|
|
@@ -4453,9 +4103,9 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
4453
4103
|
this.watchBudgetLow = true;
|
|
4454
4104
|
this.recordPollDegraded('watch_budget_low', {
|
|
4455
4105
|
remaining: this.lastRateLimitRemaining ?? 0,
|
|
4456
|
-
reserve:
|
|
4106
|
+
reserve: PR_WATCH_BUDGET_RESERVE,
|
|
4457
4107
|
});
|
|
4458
|
-
process.stderr.write(`[Channel:${this.name}] PR
|
|
4108
|
+
process.stderr.write(`[Channel:${this.name}] PR watch skipped: REST budget ${this.lastRateLimitRemaining} at or below reserve ${PR_WATCH_BUDGET_RESERVE}; preserving budget for the notification lane\n`);
|
|
4459
4109
|
}
|
|
4460
4110
|
/**
|
|
4461
4111
|
* Close the episode once the budget is no longer exhausted. A still-low
|
|
@@ -5155,19 +4805,11 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
5155
4805
|
return followers;
|
|
5156
4806
|
}
|
|
5157
4807
|
/**
|
|
5158
|
-
* The event class a bound delivery resolves templates against: the
|
|
5159
|
-
*
|
|
5160
|
-
*
|
|
5161
|
-
* An envelope with neither has no class and resolves through `default`.
|
|
4808
|
+
* The event class a bound delivery resolves templates against: the
|
|
4809
|
+
* notification trigger reason. An envelope with none has no class and
|
|
4810
|
+
* resolves through `default`.
|
|
5162
4811
|
*/
|
|
5163
4812
|
boundEventClass(envelope) {
|
|
5164
|
-
const messageId = envelope.messageId ?? '';
|
|
5165
|
-
if (messageId.startsWith('watch:')) {
|
|
5166
|
-
const type = messageId.slice('watch:'.length).split(':')[0];
|
|
5167
|
-
if (type && KNOWN_PR_WATCH_EVENTS.has(type))
|
|
5168
|
-
return `watch:${type}`;
|
|
5169
|
-
return undefined;
|
|
5170
|
-
}
|
|
5171
4813
|
return parseTriggerKind(envelope.metadata);
|
|
5172
4814
|
}
|
|
5173
4815
|
/**
|
|
@@ -5175,7 +4817,7 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
5175
4817
|
* aggregate, identified by their dispatchedComments dedupe) fall back to
|
|
5176
4818
|
* `comment` after the thread's notification reason, so a `fix:comment`
|
|
5177
4819
|
* template catches a comment delivered under `mention`/`subscribed`/
|
|
5178
|
-
* `author` too.
|
|
4820
|
+
* `author` too. A direct-event lane has no lane fallback.
|
|
5179
4821
|
*/
|
|
5180
4822
|
boundLaneClass(dedupe) {
|
|
5181
4823
|
return dedupe?.dispatchedComments !== undefined ? 'comment' : undefined;
|
|
@@ -5564,16 +5206,7 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
5564
5206
|
async deliverToBoundSession(task, envelope) {
|
|
5565
5207
|
const boundSessions = this.boundSessions;
|
|
5566
5208
|
let delivery = task.delivery;
|
|
5567
|
-
const isWatch = envelope.messageId?.startsWith('watch:') === true;
|
|
5568
5209
|
if (!boundSessions || delivery?.kind !== 'bound-session') {
|
|
5569
|
-
// Watch events are operator-facing machine state with no public path:
|
|
5570
|
-
// a channel session's reply would publish the internal prompt text on
|
|
5571
|
-
// the PR. They are only ever delivered privately; without a bound
|
|
5572
|
-
// target they are logged and retired, never fallen back publicly.
|
|
5573
|
-
if (isWatch) {
|
|
5574
|
-
process.stderr.write(`[Channel:${this.name}] watch event ${envelope.messageId} has no bound delivery target; retiring without public fallback\n`);
|
|
5575
|
-
return { kind: 'retired', reason: 'watch_no_target' };
|
|
5576
|
-
}
|
|
5577
5210
|
if (this.boundRoleAware && this.boundEventAlreadyDelivered(envelope)) {
|
|
5578
5211
|
// Defensive: a sibling role already accepted this event privately, so
|
|
5579
5212
|
// a targetless retry must not answer it publicly (durable delivery
|
|
@@ -5618,27 +5251,25 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
5618
5251
|
delivery = current;
|
|
5619
5252
|
}
|
|
5620
5253
|
else if (!current &&
|
|
5621
|
-
(
|
|
5622
|
-
this.boundRoleAware ||
|
|
5254
|
+
(this.boundRoleAware ||
|
|
5623
5255
|
this.frozenTargetGateExcluded(delivery, envelope.chatId, task.issueNumber))) {
|
|
5624
5256
|
// On a complete snapshot with no candidate left for the task's role,
|
|
5625
|
-
// retire privately.
|
|
5626
|
-
// role
|
|
5627
|
-
//
|
|
5628
|
-
//
|
|
5629
|
-
//
|
|
5630
|
-
//
|
|
5631
|
-
//
|
|
5632
|
-
// target, not the follower set: an exempt fix/untyped target, a
|
|
5257
|
+
// retire privately. A role-aware COMMENT whose role lost its match
|
|
5258
|
+
// (the binding's role changed, or the operator removed the template)
|
|
5259
|
+
// must not keep injecting the obsolete role's instruction into the
|
|
5260
|
+
// frozen session. Under the watch gate a legacy comment retires too,
|
|
5261
|
+
// but ONLY when the gate excluded the FROZEN TARGET itself (it
|
|
5262
|
+
// stopped watching between claim and delivery). The decision is about
|
|
5263
|
+
// the target, not the follower set: an exempt fix/untyped target, a
|
|
5633
5264
|
// merely author-excluded winner, or a REMOVED binding all keep the
|
|
5634
5265
|
// legacy contract — the frozen target stands and the gone path below
|
|
5635
5266
|
// owns the fallback — so the gate never changes behavior for the
|
|
5636
5267
|
// fix/untyped sessions it exempts.
|
|
5637
|
-
process.stderr.write(`[Channel:${this.name}]
|
|
5268
|
+
process.stderr.write(`[Channel:${this.name}] bound event ${envelope.messageId} has no bound candidate left for its role; retiring without public fallback\n`);
|
|
5638
5269
|
this.markPrivatelyRetired(task);
|
|
5639
5270
|
return {
|
|
5640
5271
|
kind: 'retired',
|
|
5641
|
-
reason:
|
|
5272
|
+
reason: 'bound_no_candidate',
|
|
5642
5273
|
sessionId: delivery.sessionId,
|
|
5643
5274
|
};
|
|
5644
5275
|
}
|
|
@@ -5646,29 +5277,26 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
5646
5277
|
// The channel path runs the group/sender/pairing gates inside
|
|
5647
5278
|
// handleInbound → preflightInbound; bound delivery bypasses
|
|
5648
5279
|
// handleInbound, so run the same preflight here (pairing side effects
|
|
5649
|
-
// included).
|
|
5650
|
-
//
|
|
5651
|
-
|
|
5652
|
-
|
|
5653
|
-
|
|
5654
|
-
|
|
5655
|
-
|
|
5656
|
-
|
|
5657
|
-
|
|
5658
|
-
|
|
5659
|
-
|
|
5660
|
-
|
|
5661
|
-
|
|
5662
|
-
|
|
5663
|
-
|
|
5664
|
-
|
|
5665
|
-
|
|
5666
|
-
|
|
5667
|
-
|
|
5668
|
-
|
|
5669
|
-
process.stderr.write(`[Channel:${this.name}] bound event ${envelope.messageId} rejected by the channel preflight (sender/route gates); retiring without delivery\n`);
|
|
5670
|
-
return { kind: 'retired', reason: 'preflight_rejected' };
|
|
5671
|
-
}
|
|
5280
|
+
// included).
|
|
5281
|
+
// A first-contact body is the PR's own description, not a comment
|
|
5282
|
+
// for the session: it keeps the mention requirement.
|
|
5283
|
+
const preflight = this.preflightInbound(envelope, {
|
|
5284
|
+
waiveGroupMention: !envelope.messageId?.startsWith('issue-body-') &&
|
|
5285
|
+
this.waivesBoundMention(envelope.chatId, envelope.senderId),
|
|
5286
|
+
// The comment watch delivers the channel account's own comments (the
|
|
5287
|
+
// notification lanes filter that login out, so this can only be the
|
|
5288
|
+
// watch). The sender allowlist guidance excludes that account, which
|
|
5289
|
+
// would otherwise retire every watched comment as preflight_rejected.
|
|
5290
|
+
waiveGroupSender: this.botUsername != null &&
|
|
5291
|
+
envelope.senderId === this.botUsername.toLowerCase(),
|
|
5292
|
+
});
|
|
5293
|
+
const admitted = typeof preflight === 'boolean' ? preflight : await preflight;
|
|
5294
|
+
if (!admitted) {
|
|
5295
|
+
// The bound path inherits the channel gates (sender allowlist,
|
|
5296
|
+
// message routes); a rejection retires the event without delivering
|
|
5297
|
+
// it, so surface it instead of consuming it silently.
|
|
5298
|
+
process.stderr.write(`[Channel:${this.name}] bound event ${envelope.messageId} rejected by the channel preflight (sender/route gates); retiring without delivery\n`);
|
|
5299
|
+
return { kind: 'retired', reason: 'preflight_rejected' };
|
|
5672
5300
|
}
|
|
5673
5301
|
const prompt = this.buildBoundSessionPrompt(envelope, delivery.role, this.boundLaneClass(task.dedupe), task.boundText);
|
|
5674
5302
|
// The idempotency identity is the EVENT (chat + source message), not the
|
|
@@ -5755,19 +5383,6 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
5755
5383
|
next = this.resolveBoundDeliveryExcluding(envelope.chatId, task.issueNumber, goneSessions, roleFilter);
|
|
5756
5384
|
}
|
|
5757
5385
|
}
|
|
5758
|
-
if (isWatch) {
|
|
5759
|
-
// Private-only: no public fallback for watch events (a channel
|
|
5760
|
-
// session would publish the operator-facing prompt as a PR comment
|
|
5761
|
-
// and re-gate it through the sender allowlist). Log and retire.
|
|
5762
|
-
process.stderr.write(`[Channel:${this.name}] watch event ${envelope.messageId} lost its bound session; retiring without public fallback\n`);
|
|
5763
|
-
this.transitionInboundTask(task.id, 'running', { delivery: undefined });
|
|
5764
|
-
task.delivery = undefined;
|
|
5765
|
-
return {
|
|
5766
|
-
kind: 'retired',
|
|
5767
|
-
reason: 'watch_session_gone',
|
|
5768
|
-
sessionId: lastTarget.sessionId,
|
|
5769
|
-
};
|
|
5770
|
-
}
|
|
5771
5386
|
// Role-aware fan-out: a partially delivered event never ALSO goes
|
|
5772
5387
|
// public. While any role still follows the PR, the event is (or will
|
|
5773
5388
|
// be) delivered privately through that role's own task; a public
|
|
@@ -5849,6 +5464,79 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
5849
5464
|
}
|
|
5850
5465
|
return { kind: 'delivered' };
|
|
5851
5466
|
}
|
|
5467
|
+
/**
|
|
5468
|
+
* One-time retirement of the adapter's persisted state watch. The watch
|
|
5469
|
+
* file stays (the comment cursors and the last title live in it), but the
|
|
5470
|
+
* transition baseline and queue are stripped, and persisted `watch:`
|
|
5471
|
+
* tasks are retired privately rather than replayed. A sentinel makes the
|
|
5472
|
+
* count a once-only line and lets a failed retirement retry instead of
|
|
5473
|
+
* being skipped.
|
|
5474
|
+
*/
|
|
5475
|
+
retireLegacyPrWatchState() {
|
|
5476
|
+
const sentinel = this.channelFilePath('github-pr-watch-retired');
|
|
5477
|
+
if (existsSync(sentinel))
|
|
5478
|
+
return;
|
|
5479
|
+
try {
|
|
5480
|
+
// Tasks first: a failure here must not lose the count, which is only
|
|
5481
|
+
// observable while the state file still holds the queue.
|
|
5482
|
+
const tasks = this.readInboundTasks().filter((task) => task.envelope?.messageId?.startsWith('watch:') === true);
|
|
5483
|
+
for (const task of tasks) {
|
|
5484
|
+
this.retireBoundTask(task, 'the adapter PR state watch was retired; the transition is not replayed');
|
|
5485
|
+
}
|
|
5486
|
+
const remaining = this.readInboundTasks().some((task) => task.envelope?.messageId?.startsWith('watch:') === true);
|
|
5487
|
+
if (remaining) {
|
|
5488
|
+
process.stderr.write(`[Channel:${this.name}] PR state watch retirement could not retire every persisted watch task; will retry on the next connect\n`);
|
|
5489
|
+
return;
|
|
5490
|
+
}
|
|
5491
|
+
this.loadPrWatchState();
|
|
5492
|
+
let undelivered = 0;
|
|
5493
|
+
const entries = {};
|
|
5494
|
+
for (const [key, entry] of Object.entries(this.prWatchState.entries)) {
|
|
5495
|
+
// The retired watch wrote fields this type no longer declares; read
|
|
5496
|
+
// only the queue length once, before stripping the entry.
|
|
5497
|
+
const legacy = entry;
|
|
5498
|
+
undelivered += Array.isArray(legacy.pending)
|
|
5499
|
+
? legacy.pending.length
|
|
5500
|
+
: 0;
|
|
5501
|
+
const kept = {};
|
|
5502
|
+
if (entry.title !== undefined)
|
|
5503
|
+
kept.title = entry.title;
|
|
5504
|
+
if (entry.commentBaseline !== undefined) {
|
|
5505
|
+
kept.commentBaseline = entry.commentBaseline;
|
|
5506
|
+
}
|
|
5507
|
+
if (entry.commentSince !== undefined) {
|
|
5508
|
+
kept.commentSince = entry.commentSince;
|
|
5509
|
+
}
|
|
5510
|
+
if (entry.commentLastFetchAt !== undefined) {
|
|
5511
|
+
kept.commentLastFetchAt = entry.commentLastFetchAt;
|
|
5512
|
+
}
|
|
5513
|
+
entries[key] = kept;
|
|
5514
|
+
}
|
|
5515
|
+
this.prWatchState = { version: 1, entries };
|
|
5516
|
+
// A fresh install has no file: do not create one just to write the
|
|
5517
|
+
// emptied state.
|
|
5518
|
+
if (existsSync(this.prWatchStatePath())) {
|
|
5519
|
+
this.savePrWatchState();
|
|
5520
|
+
}
|
|
5521
|
+
process.stderr.write(`[Channel:${this.name}] PR state watch retired: ${undelivered} undelivered transition${undelivered === 1 ? '' : 's'} dropped (not replayed); comment cursors and the last observed title preserved\n`);
|
|
5522
|
+
mkdirSync(dirname(sentinel), { recursive: true, mode: 0o700 });
|
|
5523
|
+
writeFileSync(sentinel, '', { mode: 0o600 });
|
|
5524
|
+
}
|
|
5525
|
+
catch (err) {
|
|
5526
|
+
// Leave the sentinel unwritten so the next connect retries. Reload the
|
|
5527
|
+
// file then: a failed save leaves the on-disk state intact.
|
|
5528
|
+
this.prWatchStateLoaded = false;
|
|
5529
|
+
process.stderr.write(`[Channel:${this.name}] PR state watch retirement failed, will retry on the next connect: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
|
|
5530
|
+
}
|
|
5531
|
+
finally {
|
|
5532
|
+
// The pass must read the file it will maintain, whether or not a file
|
|
5533
|
+
// existed before this retirement.
|
|
5534
|
+
if (existsSync(sentinel)) {
|
|
5535
|
+
this.prWatchState = { version: 1, entries: {} };
|
|
5536
|
+
this.prWatchStateLoaded = false;
|
|
5537
|
+
}
|
|
5538
|
+
}
|
|
5539
|
+
}
|
|
5852
5540
|
prWatchStatePath() {
|
|
5853
5541
|
return this.channelFilePath('github-pr-watch.json');
|
|
5854
5542
|
}
|
|
@@ -5914,37 +5602,6 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
5914
5602
|
}
|
|
5915
5603
|
this.prWatchStateLoaded = true;
|
|
5916
5604
|
}
|
|
5917
|
-
/**
|
|
5918
|
-
* Whether any persisted watch entry still holds pending events. Keeps
|
|
5919
|
-
* recovery blocked while watch subscriptions are disabled: an accepted
|
|
5920
|
-
* task whose pending record is unreconciled must not be delivered and
|
|
5921
|
-
* removed ahead of a later re-enabled drain. Fail-closed on read errors.
|
|
5922
|
-
*/
|
|
5923
|
-
hasUnreconciledWatchPending() {
|
|
5924
|
-
try {
|
|
5925
|
-
this.loadPrWatchState();
|
|
5926
|
-
}
|
|
5927
|
-
catch {
|
|
5928
|
-
return true;
|
|
5929
|
-
}
|
|
5930
|
-
return Object.values(this.prWatchState.entries).some((entry) => (entry.pending?.length ?? 0) > 0);
|
|
5931
|
-
}
|
|
5932
|
-
/**
|
|
5933
|
-
* PR keys whose earlier watch transition still has a recoverable inbound
|
|
5934
|
-
* task. Undefined when the task store cannot be read: the caller must
|
|
5935
|
-
* not prune or evict watch memory it cannot cross-check (fail-closed).
|
|
5936
|
-
*/
|
|
5937
|
-
survivingWatchPrKeys() {
|
|
5938
|
-
try {
|
|
5939
|
-
return new Set(this.readInboundTasks()
|
|
5940
|
-
.filter((task) => this.isRecoverableInboundTask(task) &&
|
|
5941
|
-
task.envelope?.messageId?.startsWith('watch:') === true)
|
|
5942
|
-
.map((task) => this.prBindingKey(task.source.chatId, task.issueNumber)));
|
|
5943
|
-
}
|
|
5944
|
-
catch {
|
|
5945
|
-
return undefined;
|
|
5946
|
-
}
|
|
5947
|
-
}
|
|
5948
5605
|
savePrWatchState() {
|
|
5949
5606
|
// Never overwrite on-disk state with memory that failed to load: a
|
|
5950
5607
|
// transient read error must not destroy pending events / fired rings.
|
|
@@ -5979,72 +5636,20 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
5979
5636
|
}
|
|
5980
5637
|
}
|
|
5981
5638
|
/**
|
|
5982
|
-
*
|
|
5983
|
-
*
|
|
5984
|
-
*
|
|
5985
|
-
*
|
|
5986
|
-
*
|
|
5987
|
-
* both records on disk).
|
|
5988
|
-
*/
|
|
5989
|
-
async reconcilePendingWatch() {
|
|
5990
|
-
if (!this.boundSessions || this.prWatchEvents.size === 0)
|
|
5991
|
-
return;
|
|
5992
|
-
this.loadPrWatchState();
|
|
5993
|
-
for (const [key, entry] of Object.entries(this.prWatchState.entries)) {
|
|
5994
|
-
if (!entry.pending?.length)
|
|
5995
|
-
continue;
|
|
5996
|
-
await this.drainPendingWatch(key, entry);
|
|
5997
|
-
}
|
|
5998
|
-
}
|
|
5999
|
-
/**
|
|
6000
|
-
* Open-PR watch fan-out per poll (terminal-pending bindings drain in an
|
|
6001
|
-
* additional slice outside it). Clamped like pollInterval: unset or
|
|
6002
|
-
* invalid keeps the default; a fractional count rounds up so the
|
|
6003
|
-
* configured budget is never silently smaller than requested.
|
|
6004
|
-
*/
|
|
6005
|
-
get prWatchLimit() {
|
|
6006
|
-
const configured = this.config.prWatchLimit;
|
|
6007
|
-
if (typeof configured === 'number' &&
|
|
6008
|
-
Number.isFinite(configured) &&
|
|
6009
|
-
configured > 0) {
|
|
6010
|
-
return Math.min(Math.max(Math.ceil(configured), 1), MAX_PR_WATCH_LIMIT);
|
|
6011
|
-
}
|
|
6012
|
-
return DEFAULT_PR_WATCH_LIMIT;
|
|
6013
|
-
}
|
|
6014
|
-
/**
|
|
6015
|
-
* Requests reserved for the notification lane: at or below this remaining
|
|
6016
|
-
* budget the watch pass yields. Clamped like prWatchLimit; a configured 0
|
|
6017
|
-
* is honoured (disables the gate) so an operator can opt out, while unset
|
|
6018
|
-
* or invalid keeps the default. Rounds up so the reserve is never silently
|
|
6019
|
-
* smaller than requested.
|
|
6020
|
-
*/
|
|
6021
|
-
get prWatchBudgetReserve() {
|
|
6022
|
-
const configured = this.config
|
|
6023
|
-
.prWatchBudgetReserve;
|
|
6024
|
-
if (typeof configured === 'number' &&
|
|
6025
|
-
Number.isFinite(configured) &&
|
|
6026
|
-
configured >= 0) {
|
|
6027
|
-
return Math.min(Math.ceil(configured), MAX_PR_WATCH_BUDGET_RESERVE);
|
|
6028
|
-
}
|
|
6029
|
-
return DEFAULT_PR_WATCH_BUDGET_RESERVE;
|
|
6030
|
-
}
|
|
6031
|
-
/**
|
|
6032
|
-
* Edge-triggered state watch over the PRs bound to live sessions. Runs
|
|
6033
|
-
* inside the existing poll loop; detection is API-level and costs no model
|
|
6034
|
-
* tokens until a real transition fires.
|
|
5639
|
+
* The comment-watch pass over the PRs bound to live sessions. Runs inside
|
|
5640
|
+
* the existing poll loop. The state-transition watch that used to share
|
|
5641
|
+
* this pass moved to the daemon (master §7), so an empty state
|
|
5642
|
+
* subscription no longer skips it: only the comment subscription and the
|
|
5643
|
+
* bound-session handle decide.
|
|
6035
5644
|
*/
|
|
6036
5645
|
async runPrStateWatch() {
|
|
6037
|
-
// The comment watch is default-on with deliverToBoundSessions and is
|
|
6038
|
-
// independent of the state-event subscription, so an empty prWatchEvents
|
|
6039
|
-
// must not skip the pass while comment watching is enabled.
|
|
6040
|
-
const commentWatchActive = this.deliverToBoundSessions && this.prCommentWatchEnabled;
|
|
6041
5646
|
if (!this.boundSessions ||
|
|
6042
|
-
|
|
5647
|
+
!this.deliverToBoundSessions ||
|
|
5648
|
+
!this.prCommentWatchEnabled) {
|
|
6043
5649
|
return;
|
|
6044
5650
|
}
|
|
6045
5651
|
this.loadPrWatchState();
|
|
6046
5652
|
const candidates = new Map();
|
|
6047
|
-
const active = new Map();
|
|
6048
5653
|
for (const summary of this.lastBindings) {
|
|
6049
5654
|
if (summary.sourceType === 'channel')
|
|
6050
5655
|
continue;
|
|
@@ -6052,162 +5657,79 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
6052
5657
|
const identity = this.parsePrBindingUrl(pr.url);
|
|
6053
5658
|
if (!identity || identity.number !== pr.number)
|
|
6054
5659
|
continue;
|
|
5660
|
+
// A merged or closed binding has no new comments to fetch, but it
|
|
5661
|
+
// still belongs to the snapshot: the entry is the only home of the
|
|
5662
|
+
// comment cursor and the title, and the prune below deletes every key
|
|
5663
|
+
// the snapshot does not claim. Skipping the fetch, not the candidate,
|
|
5664
|
+
// keeps a reopen from re-baselining past the merged window.
|
|
5665
|
+
const terminal = pr.state === 'merged' || pr.state === 'closed';
|
|
6055
5666
|
const key = this.prBindingKey(identity.chatId, identity.number);
|
|
6056
5667
|
const updatedAt = summary.updatedAt ?? '';
|
|
6057
5668
|
const existing = candidates.get(key);
|
|
6058
|
-
if (!existing
|
|
5669
|
+
if (!existing) {
|
|
6059
5670
|
candidates.set(key, {
|
|
6060
5671
|
chatId: identity.chatId,
|
|
6061
5672
|
number: identity.number,
|
|
6062
5673
|
updatedAt,
|
|
5674
|
+
terminal,
|
|
6063
5675
|
});
|
|
6064
5676
|
}
|
|
6065
|
-
|
|
6066
|
-
|
|
6067
|
-
|
|
6068
|
-
|
|
6069
|
-
|
|
6070
|
-
|
|
6071
|
-
|
|
6072
|
-
// terminal record. Binding retention and active polling are
|
|
6073
|
-
// separate concerns. A comment-only channel subscribes no state
|
|
6074
|
-
// event, so there is no state_change to observe and watchOnePr (the
|
|
6075
|
-
// only prState writer) never runs: drain on the binding's terminal
|
|
6076
|
-
// state alone, else merged/closed bindings would be comment-fetched
|
|
6077
|
-
// forever. A reopened binding flips back to open and resumes.
|
|
6078
|
-
if ((pr.state === 'merged' || pr.state === 'closed') &&
|
|
6079
|
-
(this.prWatchState.entries[key]?.prState === 'closed' ||
|
|
6080
|
-
this.prWatchEvents.size === 0)) {
|
|
6081
|
-
continue;
|
|
6082
|
-
}
|
|
6083
|
-
const existingActive = active.get(key);
|
|
6084
|
-
if (!existingActive || updatedAt > existingActive.updatedAt) {
|
|
6085
|
-
active.set(key, {
|
|
6086
|
-
chatId: identity.chatId,
|
|
6087
|
-
number: identity.number,
|
|
6088
|
-
updatedAt,
|
|
6089
|
-
// Tiering only — observation stays API-authoritative. A binding
|
|
6090
|
-
// still saying open while the watch already observed closed must
|
|
6091
|
-
// not hold an open-tier slot (stale registry, e.g. refresh
|
|
6092
|
-
// disabled); a genuinely reopened PR gets one leftover-budget
|
|
6093
|
-
// observation and returns to the open tier, self-correcting.
|
|
6094
|
-
terminal: pr.state === 'merged' ||
|
|
6095
|
-
pr.state === 'closed' ||
|
|
6096
|
-
this.prWatchState.entries[key]?.prState === 'closed',
|
|
6097
|
-
});
|
|
5677
|
+
else {
|
|
5678
|
+
// Any open binding wins: its session still follows the PR, so the
|
|
5679
|
+
// fetch stays on even when another summary already reads terminal.
|
|
5680
|
+
if (!terminal)
|
|
5681
|
+
existing.terminal = false;
|
|
5682
|
+
if (updatedAt > existing.updatedAt)
|
|
5683
|
+
existing.updatedAt = updatedAt;
|
|
6098
5684
|
}
|
|
6099
5685
|
}
|
|
6100
5686
|
}
|
|
6101
|
-
// Prune only against a complete snapshot: a partial answer
|
|
6102
|
-
//
|
|
6103
|
-
// the edge-triggered memory of PRs it failed to list. Prune against the
|
|
6104
|
-
// full candidate set, not the capped watch set, so PRs rotating out of
|
|
6105
|
-
// the cap keep their baseline. Never delete an entry that still holds
|
|
6106
|
-
// undelivered pending events (a failed claim keeps its queue) OR whose
|
|
6107
|
-
// earlier transition still has a surviving inbound task: keep the
|
|
6108
|
-
// baseline and ciFiredSha pin while the old transition is in flight so
|
|
6109
|
-
// a rebind does not re-fire the same red head.
|
|
5687
|
+
// Prune only against a complete snapshot: a partial answer must not
|
|
5688
|
+
// destroy cursors for PRs it failed to list.
|
|
6110
5689
|
if (!this.lastBindingsPartial) {
|
|
6111
|
-
|
|
6112
|
-
|
|
6113
|
-
const survivingWatchPrs = this.survivingWatchPrKeys();
|
|
6114
|
-
if (survivingWatchPrs !== undefined) {
|
|
6115
|
-
for (const key of Object.keys(this.prWatchState.entries)) {
|
|
6116
|
-
if (candidates.has(key))
|
|
6117
|
-
continue;
|
|
6118
|
-
if (this.prWatchState.entries[key]?.pending?.length)
|
|
6119
|
-
continue;
|
|
6120
|
-
if (survivingWatchPrs.has(key))
|
|
6121
|
-
continue;
|
|
5690
|
+
for (const key of Object.keys(this.prWatchState.entries)) {
|
|
5691
|
+
if (!candidates.has(key))
|
|
6122
5692
|
delete this.prWatchState.entries[key];
|
|
6123
|
-
}
|
|
6124
5693
|
}
|
|
6125
5694
|
}
|
|
6126
|
-
//
|
|
6127
|
-
//
|
|
6128
|
-
//
|
|
6129
|
-
//
|
|
6130
|
-
// complete-snapshot prune. An evicted entry belongs to a PR with no
|
|
6131
|
-
// delivery target: a later rebind re-baselines silently like any first
|
|
6132
|
-
// observation, so eviction bounds memory without losing a deliverable
|
|
6133
|
-
// event. Surfaced on stderr, never silent.
|
|
5695
|
+
// Cap the entry map so an unscannable workspace cannot grow it without
|
|
5696
|
+
// bound. Evict only idle entries no retained binding still claims; an
|
|
5697
|
+
// evicted entry re-baselines silently on a later rebind. Surfaced on
|
|
5698
|
+
// stderr, never silent.
|
|
6134
5699
|
const entryKeys = Object.keys(this.prWatchState.entries);
|
|
6135
5700
|
if (entryKeys.length > MAX_PARTIAL_RETAINED) {
|
|
6136
|
-
const
|
|
6137
|
-
|
|
6138
|
-
|
|
6139
|
-
|
|
6140
|
-
|
|
6141
|
-
|
|
6142
|
-
|
|
6143
|
-
|
|
6144
|
-
|
|
6145
|
-
|
|
6146
|
-
delete this.prWatchState.entries[evictable[i]];
|
|
6147
|
-
}
|
|
6148
|
-
if (evictCount > 0) {
|
|
6149
|
-
process.stderr.write(`[Channel:${this.name}] PR watch entry cap exceeded: evicted ${evictCount} idle entries (oldest first) to bound memory under a partial binding snapshot\n`);
|
|
6150
|
-
}
|
|
5701
|
+
const evictable = entryKeys
|
|
5702
|
+
.filter((key) => !candidates.has(key))
|
|
5703
|
+
.sort((a, b) => (this.prWatchState.entries[a]?.commentLastFetchAt ?? 0) -
|
|
5704
|
+
(this.prWatchState.entries[b]?.commentLastFetchAt ?? 0));
|
|
5705
|
+
const evictCount = Math.min(evictable.length, entryKeys.length - MAX_PARTIAL_RETAINED);
|
|
5706
|
+
for (let i = 0; i < evictCount; i++) {
|
|
5707
|
+
delete this.prWatchState.entries[evictable[i]];
|
|
5708
|
+
}
|
|
5709
|
+
if (evictCount > 0) {
|
|
5710
|
+
process.stderr.write(`[Channel:${this.name}] PR watch entry cap exceeded: evicted ${evictCount} idle entries (oldest first) to bound memory under a partial binding snapshot\n`);
|
|
6151
5711
|
}
|
|
6152
|
-
}
|
|
6153
|
-
// Open bindings take the FULL watch budget: a merged or closed PR that
|
|
6154
|
-
// the watch has not observed yet must never crowd a live PR out of it,
|
|
6155
|
-
// even when open bindings fill the limit. Terminal-pending bindings
|
|
6156
|
-
// drain in an ADDITIONAL slice outside the open budget (20% of the
|
|
6157
|
-
// limit, at least one, plus any leftover open budget): without it they
|
|
6158
|
-
// would never receive their one terminal observation when open PRs
|
|
6159
|
-
// fill the limit, and the active set would grow with every merge. The
|
|
6160
|
-
// extra slice costs at most ceil(limit*0.2) additional pulls.get per
|
|
6161
|
-
// poll while a backlog drains; each drained binding leaves the active
|
|
6162
|
-
// set for good, so the fan-out returns to the open budget once the
|
|
6163
|
-
// backlog clears.
|
|
6164
|
-
const limit = this.prWatchLimit;
|
|
6165
|
-
const byRecency = (a, b) => b[1].updatedAt.localeCompare(a[1].updatedAt);
|
|
6166
|
-
const openEntries = [...active.entries()]
|
|
6167
|
-
.filter(([, candidate]) => !candidate.terminal)
|
|
6168
|
-
.sort(byRecency);
|
|
6169
|
-
const terminalEntries = [...active.entries()]
|
|
6170
|
-
.filter(([, candidate]) => candidate.terminal)
|
|
6171
|
-
.sort(byRecency);
|
|
6172
|
-
const terminalReserved = terminalEntries.length > 0
|
|
6173
|
-
? Math.min(terminalEntries.length, Math.max(1, Math.ceil(limit * 0.2)))
|
|
6174
|
-
: 0;
|
|
6175
|
-
const watched = openEntries.slice(0, limit);
|
|
6176
|
-
const terminalSlots = Math.max(terminalReserved, limit - watched.length);
|
|
6177
|
-
watched.push(...terminalEntries.slice(0, Math.min(terminalEntries.length, terminalSlots)));
|
|
6178
|
-
if (watched.length < active.size) {
|
|
6179
|
-
// The cap deterministically excludes the oldest bindings every poll.
|
|
6180
|
-
// Surface it (dead-letter principle: surfaced, never silently
|
|
6181
|
-
// consumed) so an operator knows some bound PRs are not watched this
|
|
6182
|
-
// pass.
|
|
6183
|
-
const watchedKeys = new Set(watched.map(([key]) => key));
|
|
6184
|
-
const excluded = [...active.keys()].filter((key) => !watchedKeys.has(key));
|
|
6185
|
-
process.stderr.write(`[Channel:${this.name}] PR watch cap exceeded: watching ${watched.length}/${active.size} bound PRs (open first, most recent; open limit ${limit}); not watched: ${excluded.join(', ')}\n`);
|
|
6186
5712
|
}
|
|
6187
5713
|
// One burst budget for the whole pass: after an outage every watched PR
|
|
6188
5714
|
// can be due at once, and a per-PR cap would claim up to cap × watched-PR
|
|
6189
5715
|
// durable tasks in a single poll. PRs that find it spent keep their cursor
|
|
6190
5716
|
// and resume next pass.
|
|
6191
5717
|
const commentBudget = { remaining: MAX_WATCH_COMMENTS_PER_PASS };
|
|
6192
|
-
for (const [key, candidate] of
|
|
5718
|
+
for (const [key, candidate] of candidates) {
|
|
5719
|
+
if (candidate.terminal)
|
|
5720
|
+
continue;
|
|
6193
5721
|
// Yield at the spend site, not only at the poll boundary: one pass can
|
|
6194
5722
|
// issue several requests per watched PR, so a pass entered just above
|
|
6195
5723
|
// the reserve would otherwise spend the whole reserve before the
|
|
6196
|
-
// notification lane runs. Break (not return) so the
|
|
6197
|
-
// so far still
|
|
5724
|
+
// notification lane runs. Break (not return) so the cursors observed
|
|
5725
|
+
// so far still reach savePrWatchState below.
|
|
6198
5726
|
if (this.watchBudgetExhausted()) {
|
|
6199
5727
|
this.noteWatchBudgetLow();
|
|
6200
5728
|
break;
|
|
6201
5729
|
}
|
|
6202
5730
|
try {
|
|
6203
|
-
// The state observation costs a pulls.get per watched PR per poll; skip
|
|
6204
|
-
// it when no state event is subscribed so a comment-only channel does
|
|
6205
|
-
// not pay for transitions it never emits.
|
|
6206
|
-
if (this.prWatchEvents.size > 0) {
|
|
6207
|
-
await this.watchOnePr(key, candidate.chatId, candidate.number);
|
|
6208
|
-
}
|
|
6209
5731
|
// Additive comment watch: isolates its own failures so a comment
|
|
6210
|
-
// fetch problem never skips the
|
|
5732
|
+
// fetch problem never skips the next PR.
|
|
6211
5733
|
await this.watchPrComments(key, candidate.chatId, candidate.number, commentBudget);
|
|
6212
5734
|
}
|
|
6213
5735
|
catch (err) {
|
|
@@ -6223,305 +5745,6 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
6223
5745
|
}
|
|
6224
5746
|
this.savePrWatchState();
|
|
6225
5747
|
}
|
|
6226
|
-
async watchOnePr(key, chatId, number) {
|
|
6227
|
-
const copy = BOUND_DELIVERY_COPY[this.locale];
|
|
6228
|
-
const [owner, repo] = chatId.split('/');
|
|
6229
|
-
// Rate-limited watch calls fail fast instead of sleeping out the reset
|
|
6230
|
-
// window: the watch pass runs before notification processing, and a
|
|
6231
|
-
// blocking cooldown here would pin the whole notification lane (the
|
|
6232
|
-
// design promises notifications are unaffected by watch rate limiting).
|
|
6233
|
-
const { data: pr } = await this.githubApi(() => this.octokit.rest.pulls.get({
|
|
6234
|
-
owner,
|
|
6235
|
-
repo,
|
|
6236
|
-
pull_number: number,
|
|
6237
|
-
}), `pulls.get(watch ${key})`, 3, (err) => !isWatchFailFastError(err));
|
|
6238
|
-
const entry = this.prWatchState.entries[key] ?? {};
|
|
6239
|
-
const firstObservation = entry.headSha === undefined && entry.prState === undefined;
|
|
6240
|
-
const headSha = pr.head?.sha;
|
|
6241
|
-
const headChanged = headSha !== undefined &&
|
|
6242
|
-
entry.headSha !== undefined &&
|
|
6243
|
-
headSha !== entry.headSha;
|
|
6244
|
-
const events = [];
|
|
6245
|
-
if (headChanged && this.prWatchEvents.has('head_change')) {
|
|
6246
|
-
events.push({
|
|
6247
|
-
type: 'head_change',
|
|
6248
|
-
summary: copy.headChange(entry.headSha, headSha),
|
|
6249
|
-
});
|
|
6250
|
-
}
|
|
6251
|
-
// Check fetches are conditional and gated on the ci_failure subscription
|
|
6252
|
-
// (the other three events come from pulls.get fields alone). A
|
|
6253
|
-
// steady-state green PR costs one pulls.get per poll. A new head always
|
|
6254
|
-
// re-checks; a pending aggregate re-checks on the
|
|
6255
|
-
// CI_PENDING_RECHECK_INTERVAL_MS period until it settles; an advanced
|
|
6256
|
-
// updated_at re-checks a settled head. updated_at is NOT a reliable
|
|
6257
|
-
// re-run signal (GitHub does not bump it on check activity), so settled
|
|
6258
|
-
// heads — including 'none' past the grace window — also re-check on the
|
|
6259
|
-
// CI_RECHECK_INTERVAL_MS period to catch re-runs that turn red and CI
|
|
6260
|
-
// that appears late (manual workflow_dispatch).
|
|
6261
|
-
const prUpdatedAt = typeof pr.updated_at === 'string' ? pr.updated_at : undefined;
|
|
6262
|
-
let ciResult;
|
|
6263
|
-
let ciFetchAttempted = false;
|
|
6264
|
-
if (headSha &&
|
|
6265
|
-
this.prWatchEvents.has('ci_failure') &&
|
|
6266
|
-
(headChanged ||
|
|
6267
|
-
((entry.ci === undefined || entry.ci === 'pending') &&
|
|
6268
|
-
(entry.lastCiFetchAt === undefined ||
|
|
6269
|
-
Date.now() - entry.lastCiFetchAt >=
|
|
6270
|
-
CI_PENDING_RECHECK_INTERVAL_MS)) ||
|
|
6271
|
-
(prUpdatedAt !== undefined && prUpdatedAt !== entry.prUpdatedAt) ||
|
|
6272
|
-
(entry.ci === 'none' &&
|
|
6273
|
-
entry.headObservedAt !== undefined &&
|
|
6274
|
-
Date.now() - entry.headObservedAt < CI_NONE_GRACE_MS) ||
|
|
6275
|
-
(entry.lastCiFetchAt !== undefined &&
|
|
6276
|
-
Date.now() - entry.lastCiFetchAt >= CI_RECHECK_INTERVAL_MS))) {
|
|
6277
|
-
ciFetchAttempted = true;
|
|
6278
|
-
try {
|
|
6279
|
-
ciResult = await this.fetchCiAggregate(owner, repo, headSha);
|
|
6280
|
-
}
|
|
6281
|
-
catch (err) {
|
|
6282
|
-
// CI is a conditional refinement of the pulls.get baseline, not a
|
|
6283
|
-
// dependency of it: a persistent Checks-endpoint failure (a classic
|
|
6284
|
-
// PAT without Checks permission, an enterprise policy) must not
|
|
6285
|
-
// suppress merge_conflict / state_change, whose data already arrived
|
|
6286
|
-
// in pulls.get. Leave ciResult undefined so entry.ci is preserved
|
|
6287
|
-
// (writing 'none' would re-fire ci_failure when the endpoint heals).
|
|
6288
|
-
// The attempt still advances lastCiFetchAt below: without it, a
|
|
6289
|
-
// persistent failure would leave the interval conditions true every
|
|
6290
|
-
// poll and degrade to one doomed request per PR per poll.
|
|
6291
|
-
process.stderr.write(`[Channel:${this.name}] CI fetch failed for ${key}, continuing without CI state this poll: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
|
|
6292
|
-
}
|
|
6293
|
-
}
|
|
6294
|
-
const ci = ciResult?.aggregate;
|
|
6295
|
-
const prevCiForThisHead = headChanged ? undefined : entry.ci;
|
|
6296
|
-
if (!firstObservation &&
|
|
6297
|
-
ci === 'failure' &&
|
|
6298
|
-
prevCiForThisHead !== 'failure' &&
|
|
6299
|
-
this.prWatchEvents.has('ci_failure')) {
|
|
6300
|
-
const failedChecks = ciResult && ciResult.failedChecks.length > 0
|
|
6301
|
-
? copy.failedChecks(ciResult.failedChecks.join(', '), ciResult.namesIncomplete)
|
|
6302
|
-
: '';
|
|
6303
|
-
events.push({
|
|
6304
|
-
type: 'ci_failure',
|
|
6305
|
-
// ciResult is assigned only inside the headSha-guarded fetch block,
|
|
6306
|
-
// so ci === 'failure' proves headSha is defined.
|
|
6307
|
-
summary: `${copy.ciFailure(headSha)}${failedChecks}`,
|
|
6308
|
-
});
|
|
6309
|
-
}
|
|
6310
|
-
// mergeable === null means GitHub is still computing; never overwrite
|
|
6311
|
-
// the last known state with it.
|
|
6312
|
-
const mergeableState = pr.mergeable !== null && typeof pr.mergeable_state === 'string'
|
|
6313
|
-
? pr.mergeable_state
|
|
6314
|
-
: undefined;
|
|
6315
|
-
if (!firstObservation &&
|
|
6316
|
-
mergeableState === 'dirty' &&
|
|
6317
|
-
entry.mergeableState !== 'dirty' &&
|
|
6318
|
-
this.prWatchEvents.has('merge_conflict')) {
|
|
6319
|
-
events.push({
|
|
6320
|
-
type: 'merge_conflict',
|
|
6321
|
-
summary: copy.mergeConflict,
|
|
6322
|
-
});
|
|
6323
|
-
}
|
|
6324
|
-
const prState = pr.state;
|
|
6325
|
-
if (!firstObservation &&
|
|
6326
|
-
prState === 'closed' &&
|
|
6327
|
-
entry.prState !== 'closed' &&
|
|
6328
|
-
this.prWatchEvents.has('state_change')) {
|
|
6329
|
-
events.push({
|
|
6330
|
-
type: 'state_change',
|
|
6331
|
-
summary: pr.merged ? copy.prMerged : copy.prClosed,
|
|
6332
|
-
});
|
|
6333
|
-
}
|
|
6334
|
-
const next = {
|
|
6335
|
-
...(headSha !== undefined ? { headSha } : {}),
|
|
6336
|
-
...(ci !== undefined
|
|
6337
|
-
? { ci }
|
|
6338
|
-
: headChanged
|
|
6339
|
-
? {}
|
|
6340
|
-
: entry.ci !== undefined
|
|
6341
|
-
? { ci: entry.ci }
|
|
6342
|
-
: {}),
|
|
6343
|
-
...(mergeableState !== undefined
|
|
6344
|
-
? { mergeableState }
|
|
6345
|
-
: entry.mergeableState !== undefined
|
|
6346
|
-
? { mergeableState: entry.mergeableState }
|
|
6347
|
-
: {}),
|
|
6348
|
-
...(prState !== undefined ? { prState } : {}),
|
|
6349
|
-
...(pr.title !== undefined
|
|
6350
|
-
? { title: pr.title }
|
|
6351
|
-
: entry.title !== undefined
|
|
6352
|
-
? { title: entry.title }
|
|
6353
|
-
: {}),
|
|
6354
|
-
...(prUpdatedAt !== undefined ? { prUpdatedAt } : {}),
|
|
6355
|
-
...(firstObservation || headChanged
|
|
6356
|
-
? { headObservedAt: Date.now() }
|
|
6357
|
-
: entry.headObservedAt !== undefined
|
|
6358
|
-
? { headObservedAt: entry.headObservedAt }
|
|
6359
|
-
: {}),
|
|
6360
|
-
...(ciFetchAttempted
|
|
6361
|
-
? { lastCiFetchAt: Date.now() }
|
|
6362
|
-
: entry.lastCiFetchAt !== undefined
|
|
6363
|
-
? { lastCiFetchAt: entry.lastCiFetchAt }
|
|
6364
|
-
: {}),
|
|
6365
|
-
...(entry.seq !== undefined ? { seq: entry.seq } : {}),
|
|
6366
|
-
...(entry.pending !== undefined ? { pending: entry.pending } : {}),
|
|
6367
|
-
...(entry.fired !== undefined ? { fired: entry.fired } : {}),
|
|
6368
|
-
...(!headChanged && entry.ciFiredSha !== undefined
|
|
6369
|
-
? { ciFiredSha: entry.ciFiredSha }
|
|
6370
|
-
: {}),
|
|
6371
|
-
// The comment watch cursor is independent of head/CI transitions; carry
|
|
6372
|
-
// it through so the state baseline write does not drop it.
|
|
6373
|
-
...(entry.commentBaseline !== undefined
|
|
6374
|
-
? { commentBaseline: entry.commentBaseline }
|
|
6375
|
-
: {}),
|
|
6376
|
-
...(entry.commentSince !== undefined
|
|
6377
|
-
? { commentSince: entry.commentSince }
|
|
6378
|
-
: {}),
|
|
6379
|
-
...(entry.commentLastFetchAt !== undefined
|
|
6380
|
-
? { commentLastFetchAt: entry.commentLastFetchAt }
|
|
6381
|
-
: {}),
|
|
6382
|
-
};
|
|
6383
|
-
// Bake the PR number and detection time into every watch key. The
|
|
6384
|
-
// delivery idempotency key is chatId + messageId only, so without the
|
|
6385
|
-
// PR number two PRs of one repo bound to the same session would issue
|
|
6386
|
-
// identical first-episode keys and the daemon ring would silently
|
|
6387
|
-
// dedupe the second PR's event. The timestamp survives episode-counter
|
|
6388
|
-
// resets (prune, corruption recovery): the daemon ring outlives the
|
|
6389
|
-
// worker, and a re-issued bare seq key would dedupe into the old
|
|
6390
|
-
// admission instead of delivering the new transition. The identity is
|
|
6391
|
-
// instance-local by design: two channel configurations watching the
|
|
6392
|
-
// same repo each deliver their own watch notifications (at-least-once
|
|
6393
|
-
// per subscription) — the ring dedupes retries of ONE delivery, not
|
|
6394
|
-
// independent subscriptions. Comment events still dedupe across
|
|
6395
|
-
// instances via their stable GitHub ids.
|
|
6396
|
-
const detectedAt = Date.now();
|
|
6397
|
-
// Overflow retires sliced during this pass; their skip rows are journalled
|
|
6398
|
-
// only after the end-of-pass save commits the baseline and queue together.
|
|
6399
|
-
const overflowRetires = [];
|
|
6400
|
-
for (const event of events) {
|
|
6401
|
-
// ci_failure dedupes per head SHA: once per head even when the
|
|
6402
|
-
// aggregate flaps back to success and fails again. The other three
|
|
6403
|
-
// identify the transition INSTANCE with a monotonic episode counter,
|
|
6404
|
-
// so a legitimate recurrence fires again: dirty -> clean -> dirty,
|
|
6405
|
-
// close -> reopen -> close, and a force-push revisit of a recent SHA.
|
|
6406
|
-
// A state-valued key (the old `open`/`closed`/target-SHA shape) would
|
|
6407
|
-
// suppress those forever within the fired ring's window, contradicting
|
|
6408
|
-
// the documented edge-triggered semantics.
|
|
6409
|
-
let dedupeKey;
|
|
6410
|
-
if (event.type === 'ci_failure') {
|
|
6411
|
-
dedupeKey = `watch:ci_failure:${number}:${headSha ?? 'unknown'}:${detectedAt}`;
|
|
6412
|
-
}
|
|
6413
|
-
else {
|
|
6414
|
-
next.seq = (next.seq ?? 0) + 1;
|
|
6415
|
-
dedupeKey = `watch:${event.type}:${number}:${next.seq}:${detectedAt}`;
|
|
6416
|
-
}
|
|
6417
|
-
// The fired ring is the durable once-per-transition record: inbound
|
|
6418
|
-
// tasks are removed on success, so task-level dedupe alone would let
|
|
6419
|
-
// a flapping aggregate re-fire the same head after a restart.
|
|
6420
|
-
// ci_failure matches by PR+SHA PREFIX: the nonce suffix makes every
|
|
6421
|
-
// detection key unique, but once-per-head must survive head changes
|
|
6422
|
-
// (the ciFiredSha pin drops on a head change) and flaps while an
|
|
6423
|
-
// earlier episode is still pending.
|
|
6424
|
-
const ciPrefix = event.type === 'ci_failure'
|
|
6425
|
-
? `watch:ci_failure:${number}:${headSha ?? 'unknown'}:`
|
|
6426
|
-
: undefined;
|
|
6427
|
-
const recorded = (key) => ciPrefix !== undefined ? key.startsWith(ciPrefix) : key === dedupeKey;
|
|
6428
|
-
if (next.fired?.some(recorded))
|
|
6429
|
-
continue;
|
|
6430
|
-
// The fired ring is capped: 64 non-ci episodes on a long-lived head
|
|
6431
|
-
// can evict the ci_failure key. The ciFiredSha pin keeps ci_failure
|
|
6432
|
-
// once-per-head even after that eviction (a flapping aggregate must
|
|
6433
|
-
// not re-fire on the same head).
|
|
6434
|
-
if (event.type === 'ci_failure' &&
|
|
6435
|
-
headSha !== undefined &&
|
|
6436
|
-
next.ciFiredSha === headSha) {
|
|
6437
|
-
continue;
|
|
6438
|
-
}
|
|
6439
|
-
if (next.pending?.some((p) => recorded(p.key)))
|
|
6440
|
-
continue;
|
|
6441
|
-
const envelope = {
|
|
6442
|
-
channelName: this.name,
|
|
6443
|
-
senderId: 'github',
|
|
6444
|
-
senderName: 'GitHub',
|
|
6445
|
-
chatId,
|
|
6446
|
-
threadId: `pr:${number}`,
|
|
6447
|
-
messageId: dedupeKey,
|
|
6448
|
-
text: event.summary,
|
|
6449
|
-
isGroup: true,
|
|
6450
|
-
isMentioned: true,
|
|
6451
|
-
isReplyToBot: false,
|
|
6452
|
-
metadata: `${this.buildMetadata(chatId, `pr:${number}`, pr.title ?? '')}\nEvent: ${event.type}.`,
|
|
6453
|
-
};
|
|
6454
|
-
(next.pending ??= []).push({
|
|
6455
|
-
key: dedupeKey,
|
|
6456
|
-
issueNumber: number,
|
|
6457
|
-
envelope,
|
|
6458
|
-
delivery: this.resolveBoundDelivery(chatId, number),
|
|
6459
|
-
});
|
|
6460
|
-
if (next.pending.length > MAX_PENDING_WATCH_PER_ENTRY) {
|
|
6461
|
-
const oldest = next.pending[0];
|
|
6462
|
-
if (!this.isDeadLettered(oldest.key)) {
|
|
6463
|
-
const record = {
|
|
6464
|
-
retiredAt: new Date().toISOString(),
|
|
6465
|
-
issueNumber: oldest.issueNumber,
|
|
6466
|
-
source: {
|
|
6467
|
-
chatId,
|
|
6468
|
-
threadId: `pr:${number}`,
|
|
6469
|
-
messageId: oldest.key,
|
|
6470
|
-
},
|
|
6471
|
-
delivery: oldest.delivery,
|
|
6472
|
-
reason: `watch pending queue overflow (cap ${MAX_PENDING_WATCH_PER_ENTRY}); oldest event retired undelivered`,
|
|
6473
|
-
text: oldest.envelope.text,
|
|
6474
|
-
};
|
|
6475
|
-
try {
|
|
6476
|
-
const path = this.channelFilePath('github-bound-deadletter.jsonl');
|
|
6477
|
-
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
6478
|
-
appendFileSync(path, `${JSON.stringify(record)}\n`, {
|
|
6479
|
-
encoding: 'utf-8',
|
|
6480
|
-
mode: 0o600,
|
|
6481
|
-
});
|
|
6482
|
-
this.deadLetteredKeys.add(oldest.key);
|
|
6483
|
-
}
|
|
6484
|
-
catch (err) {
|
|
6485
|
-
// The exhaustion surface cannot be written: keep the event queued
|
|
6486
|
-
// (over cap) and retry the overflow on the next detection instead
|
|
6487
|
-
// of dropping it. The body has nowhere else to go, so dump it to
|
|
6488
|
-
// stderr — sanitized without truncation, like retireBoundTask.
|
|
6489
|
-
const payload = JSON.stringify(record);
|
|
6490
|
-
process.stderr.write(`[Channel:${this.name}] failed to write watch pending overflow dead-letter (${oldest.key}): ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}; payload: ${sanitizeLogText(payload, payload.length)}\n`);
|
|
6491
|
-
}
|
|
6492
|
-
}
|
|
6493
|
-
if (this.isDeadLettered(oldest.key)) {
|
|
6494
|
-
// The dead-letter record is the retire's commit point. Slice in
|
|
6495
|
-
// memory ONLY: the end-of-pass save below commits the advanced
|
|
6496
|
-
// baseline and the full queue in one write. A mid-pass save here
|
|
6497
|
-
// would persist the baseline before this pass's later events are
|
|
6498
|
-
// queued, so a crash would never re-derive them. The skip row is
|
|
6499
|
-
// journalled after that save, never before; if the save throws, the
|
|
6500
|
-
// drain completes the retire next poll (the head is dead-lettered,
|
|
6501
|
-
// so it is never delivered).
|
|
6502
|
-
next.pending = next.pending.slice(1);
|
|
6503
|
-
this.prWatchState.entries[key] = next;
|
|
6504
|
-
overflowRetires.push(oldest);
|
|
6505
|
-
process.stderr.write(`[Channel:${this.name}] watch pending overflow for ${key}: retired ${oldest.key} to dead-letter (cap ${MAX_PENDING_WATCH_PER_ENTRY})\n`);
|
|
6506
|
-
}
|
|
6507
|
-
}
|
|
6508
|
-
if (event.type === 'ci_failure' && headSha !== undefined) {
|
|
6509
|
-
next.ciFiredSha = headSha;
|
|
6510
|
-
}
|
|
6511
|
-
}
|
|
6512
|
-
this.prWatchState.entries[key] = next;
|
|
6513
|
-
// Baseline and pending queue commit in one write: a crash from here on
|
|
6514
|
-
// either finds the pending event (drained next poll) or the claimed
|
|
6515
|
-
// task (recovery), never a consumed transition with nothing to retry.
|
|
6516
|
-
this.savePrWatchState();
|
|
6517
|
-
// The overflow retires are durable only now. Journal their skip rows after
|
|
6518
|
-
// the save: a throwing save leaves no claim for an event still queued on
|
|
6519
|
-
// disk, and the drain completes the retire next poll instead.
|
|
6520
|
-
for (const retired of overflowRetires) {
|
|
6521
|
-
this.recordWatchOverflowSkip(retired);
|
|
6522
|
-
}
|
|
6523
|
-
await this.drainPendingWatch(key, next);
|
|
6524
|
-
}
|
|
6525
5748
|
/**
|
|
6526
5749
|
* Bound PR comment watch (docs/design/2026-11-08-bound-pr-comment-watch.md).
|
|
6527
5750
|
* Poll conversation + inline review comments on a bound PR and deliver each
|
|
@@ -6533,7 +5756,7 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
6533
5756
|
* what prevents a fix session's own reply from re-triggering it.
|
|
6534
5757
|
*
|
|
6535
5758
|
* Default-on with deliverToBoundSessions; `prCommentWatch: false` disables
|
|
6536
|
-
* it. Failures are isolated here so
|
|
5759
|
+
* it. Failures are isolated here so one PR's fetch never skips the next.
|
|
6537
5760
|
*/
|
|
6538
5761
|
async watchPrComments(key, chatId, number, budget) {
|
|
6539
5762
|
if (!this.deliverToBoundSessions ||
|
|
@@ -6868,402 +6091,6 @@ export class GithubChannel extends PollingChannelBase {
|
|
|
6868
6091
|
: nowIso);
|
|
6869
6092
|
}
|
|
6870
6093
|
}
|
|
6871
|
-
/**
|
|
6872
|
-
* Deliver queued watch events. Order per event: claim the inbound task
|
|
6873
|
-
* (durable), move the key from pending to fired (durable), then run the
|
|
6874
|
-
* task. A crash at any point leaves either a pending event or a claimed
|
|
6875
|
-
* task for the next poll / recovery, and the fired ring prevents a second
|
|
6876
|
-
* delivery of the same transition.
|
|
6877
|
-
*/
|
|
6878
|
-
async drainPendingWatch(key, entry) {
|
|
6879
|
-
if (this.boundRoleAware) {
|
|
6880
|
-
return this.drainPendingWatchRoleAware(key, entry);
|
|
6881
|
-
}
|
|
6882
|
-
// Per-PR ordering across passes: an earlier watch transition that is
|
|
6883
|
-
// still unsettled (a failed/backpressure/running task from a previous
|
|
6884
|
-
// attempt) must settle via recovery BEFORE any later pending event
|
|
6885
|
-
// drains — the watch pass re-drains after reconcile, and the next
|
|
6886
|
-
// poll's reconcile runs before recovery, so a per-pass break alone
|
|
6887
|
-
// would still let the later event arrive first. Skip the whole entry
|
|
6888
|
-
// until recovery settles the predecessor; nothing is lost (pending
|
|
6889
|
-
// and fired are persisted). A task whose key EQUALS the pending head
|
|
6890
|
-
// is that same event's own claim (the crash window between claim and
|
|
6891
|
-
// fire-save), not a predecessor — draining reuses it, so let it pass.
|
|
6892
|
-
const headKey = entry.pending?.[0]?.key;
|
|
6893
|
-
const unsettledPredecessor = this.readInboundTasks().some((task) => this.isRecoverableInboundTask(task) &&
|
|
6894
|
-
task.envelope?.messageId?.startsWith('watch:') === true &&
|
|
6895
|
-
task.source.messageId !== headKey &&
|
|
6896
|
-
this.prBindingKey(task.source.chatId, task.issueNumber) === key);
|
|
6897
|
-
if (unsettledPredecessor)
|
|
6898
|
-
return;
|
|
6899
|
-
while (entry.pending && entry.pending.length > 0) {
|
|
6900
|
-
const pending = entry.pending[0];
|
|
6901
|
-
if (this.isDeadLettered(pending.key)) {
|
|
6902
|
-
// This head already carries a durable "retired undelivered" record
|
|
6903
|
-
// (an overflow whose end-of-pass save failed, or a crash before it).
|
|
6904
|
-
// Complete the retire instead of delivering: a delivered event must
|
|
6905
|
-
// never also stand in the dead-letter file as retired undelivered.
|
|
6906
|
-
const pendingBefore = entry.pending;
|
|
6907
|
-
entry.pending = entry.pending.slice(1);
|
|
6908
|
-
this.prWatchState.entries[key] = entry;
|
|
6909
|
-
try {
|
|
6910
|
-
this.savePrWatchState();
|
|
6911
|
-
}
|
|
6912
|
-
catch (err) {
|
|
6913
|
-
entry.pending = pendingBefore;
|
|
6914
|
-
this.prWatchState.entries[key] = entry;
|
|
6915
|
-
throw err;
|
|
6916
|
-
}
|
|
6917
|
-
this.recordWatchOverflowSkip(pending);
|
|
6918
|
-
continue;
|
|
6919
|
-
}
|
|
6920
|
-
// Re-validate the frozen recipient against the latest COMPLETE
|
|
6921
|
-
// snapshot: a live rebind must not misdeliver to the old session. On
|
|
6922
|
-
// a partial/failed scan the persisted target stands (fail-closed).
|
|
6923
|
-
// With no candidate left on a complete snapshot the watch event is
|
|
6924
|
-
// private-only: retire it with a log rather than queue a delivery
|
|
6925
|
-
// that would retire publicly anyway.
|
|
6926
|
-
let delivery = pending.delivery;
|
|
6927
|
-
if (this.boundSnapshotTrusted &&
|
|
6928
|
-
!this.lastBindingsPartial &&
|
|
6929
|
-
!this.boundRefreshFailed) {
|
|
6930
|
-
const current = this.resolveBoundDelivery(pending.envelope.chatId, pending.issueNumber);
|
|
6931
|
-
if (current) {
|
|
6932
|
-
delivery = current;
|
|
6933
|
-
this.gateGraceClear(pending.key);
|
|
6934
|
-
}
|
|
6935
|
-
else {
|
|
6936
|
-
// One grace cycle when the gate is the cause: a watch installed
|
|
6937
|
-
// after the snapshot was fetched surfaces on the next refresh, and
|
|
6938
|
-
// the transition it was installed to catch must not retire first.
|
|
6939
|
-
// The grace is scoped to the snapshot generation, so a second drain
|
|
6940
|
-
// of the same PR in the same poll does not spend it.
|
|
6941
|
-
if (this.gateExcludedAllFollowers(pending.envelope.chatId, pending.issueNumber) &&
|
|
6942
|
-
this.gateGraceShouldHold(pending.key)) {
|
|
6943
|
-
return;
|
|
6944
|
-
}
|
|
6945
|
-
this.gateGraceClear(pending.key);
|
|
6946
|
-
process.stderr.write(`[Channel:${this.name}] watch event ${pending.key} has no bound candidate left; retiring without public fallback\n`);
|
|
6947
|
-
const pendingBefore = entry.pending;
|
|
6948
|
-
entry.pending = entry.pending.slice(1);
|
|
6949
|
-
this.prWatchState.entries[key] = entry;
|
|
6950
|
-
try {
|
|
6951
|
-
this.savePrWatchState();
|
|
6952
|
-
}
|
|
6953
|
-
catch (err) {
|
|
6954
|
-
// The slice already mutated the loaded state, and a failed save
|
|
6955
|
-
// does not clear prWatchStateLoaded — without this rollback the
|
|
6956
|
-
// next poll skips the entry and the end-of-pass save persists the
|
|
6957
|
-
// truncation, losing the event with no trace at all. Mirrors the
|
|
6958
|
-
// claim path's rollback below.
|
|
6959
|
-
entry.pending = pendingBefore;
|
|
6960
|
-
this.prWatchState.entries[key] = entry;
|
|
6961
|
-
throw err;
|
|
6962
|
-
}
|
|
6963
|
-
// Retired before any task was claimed, so there is no task row to
|
|
6964
|
-
// close: the skip is the event's only journal trace. After the
|
|
6965
|
-
// durable save — the rollback above keeps the event queued when the
|
|
6966
|
-
// save throws, and the journal must not claim a retire that did not
|
|
6967
|
-
// happen.
|
|
6968
|
-
const lostTarget = pending.delivery?.kind === 'bound-session'
|
|
6969
|
-
? pending.delivery.sessionId
|
|
6970
|
-
: undefined;
|
|
6971
|
-
const lostWorkspace = lostTarget
|
|
6972
|
-
? this.sessionWorkspaceFor(lostTarget)
|
|
6973
|
-
: undefined;
|
|
6974
|
-
this.recordChannelEvent({
|
|
6975
|
-
type: 'inbound',
|
|
6976
|
-
outcome: 'skipped',
|
|
6977
|
-
reason: 'watch_no_candidate',
|
|
6978
|
-
repository: pending.envelope.chatId,
|
|
6979
|
-
thread: pending.envelope.threadId,
|
|
6980
|
-
number: pending.issueNumber,
|
|
6981
|
-
messageId: pending.key,
|
|
6982
|
-
// The frozen target is in hand; this retire writes no dead-letter
|
|
6983
|
-
// record (only the overflow retire does), so the skip row is the
|
|
6984
|
-
// event's only trace — without the target it cannot say whether
|
|
6985
|
-
// the retired event ever belonged to a session.
|
|
6986
|
-
...(lostTarget ? { sessionId: lostTarget } : {}),
|
|
6987
|
-
...(lostWorkspace ? { sessionWorkspaceCwd: lostWorkspace } : {}),
|
|
6988
|
-
});
|
|
6989
|
-
continue;
|
|
6990
|
-
}
|
|
6991
|
-
}
|
|
6992
|
-
// A partial/failed scan keeps the frozen target — which may be absent
|
|
6993
|
-
// because the gate filtered the map at detection time. Give that state
|
|
6994
|
-
// the same one grace cycle before claiming a task that would retire
|
|
6995
|
-
// targetless at run time.
|
|
6996
|
-
if (delivery === undefined &&
|
|
6997
|
-
this.gateExcludedAllFollowers(pending.envelope.chatId, pending.issueNumber) &&
|
|
6998
|
-
this.gateGraceShouldHold(pending.key)) {
|
|
6999
|
-
return;
|
|
7000
|
-
}
|
|
7001
|
-
let task;
|
|
7002
|
-
try {
|
|
7003
|
-
task = this.claimInboundTask(pending.envelope, pending.issueNumber, {}, delivery);
|
|
7004
|
-
}
|
|
7005
|
-
catch (err) {
|
|
7006
|
-
// Claim persistence failed: keep the event queued and retry on the
|
|
7007
|
-
// next poll instead of consuming the transition. Propagate so the
|
|
7008
|
-
// reconcile pass fails and sets watchReconcileBlocked: a swallowed
|
|
7009
|
-
// failure would let recovery deliver an accepted watch task whose
|
|
7010
|
-
// pending record is still unreconciled on disk.
|
|
7011
|
-
process.stderr.write(`[Channel:${this.name}] failed to claim watch event ${pending.key}, will retry: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
|
|
7012
|
-
throw err;
|
|
7013
|
-
}
|
|
7014
|
-
const firedBefore = entry.fired;
|
|
7015
|
-
const pendingBefore = entry.pending;
|
|
7016
|
-
entry.fired = [...(entry.fired ?? []), pending.key].slice(-MAX_FIRED_KEYS);
|
|
7017
|
-
entry.pending = entry.pending.slice(1);
|
|
7018
|
-
this.prWatchState.entries[key] = entry;
|
|
7019
|
-
try {
|
|
7020
|
-
this.savePrWatchState();
|
|
7021
|
-
}
|
|
7022
|
-
catch (err) {
|
|
7023
|
-
// The claim is durable but the pending->fired save failed (watch
|
|
7024
|
-
// file unwritable while the task file is writable). Roll the claim
|
|
7025
|
-
// back so the event stays queued: otherwise same-poll recovery would
|
|
7026
|
-
// deliver and remove the task while the on-disk pending survives,
|
|
7027
|
-
// and a restart would re-claim and deliver the same transition twice.
|
|
7028
|
-
entry.fired = firedBefore;
|
|
7029
|
-
entry.pending = pendingBefore;
|
|
7030
|
-
this.prWatchState.entries[key] = entry;
|
|
7031
|
-
this.removeInboundTask(task.id);
|
|
7032
|
-
process.stderr.write(`[Channel:${this.name}] failed to persist watch fire for ${pending.key}, rolled back claim, will retry: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
|
|
7033
|
-
return;
|
|
7034
|
-
}
|
|
7035
|
-
const delivered = await this.runInboundTask(task);
|
|
7036
|
-
if (!delivered) {
|
|
7037
|
-
// Preserve per-PR ordering: a failed/deferred event retries via
|
|
7038
|
-
// recovery next poll; delivering later pendings now would arrive
|
|
7039
|
-
// out of order. Pending and fired are already persisted, so
|
|
7040
|
-
// stopping here loses nothing.
|
|
7041
|
-
return;
|
|
7042
|
-
}
|
|
7043
|
-
}
|
|
7044
|
-
}
|
|
7045
|
-
/**
|
|
7046
|
-
* Role-aware watch drain: one durable task per (event, matched role
|
|
7047
|
-
* winner). The event leaves `pending` for `fired` only after EVERY
|
|
7048
|
-
* matched target is claimed, so a crash mid-fan-out re-claims exactly the
|
|
7049
|
-
* missing targets (claimInboundTask reuses an existing (event, target)
|
|
7050
|
-
* task). Ordering is per (PR, target): a target with an unsettled
|
|
7051
|
-
* predecessor waits while the event's other targets drain — one stuck
|
|
7052
|
-
* role never head-of-line-blocks another.
|
|
7053
|
-
*/
|
|
7054
|
-
async drainPendingWatchRoleAware(key, entry) {
|
|
7055
|
-
while (entry.pending && entry.pending.length > 0) {
|
|
7056
|
-
const pending = entry.pending[0];
|
|
7057
|
-
if (this.isDeadLettered(pending.key)) {
|
|
7058
|
-
// A dead-lettered head is committed to retire; complete it rather than
|
|
7059
|
-
// deliver, so no event is both delivered and filed as retired
|
|
7060
|
-
// undelivered. Mirrors the legacy drain's guard.
|
|
7061
|
-
const pendingBefore = entry.pending;
|
|
7062
|
-
entry.pending = entry.pending.slice(1);
|
|
7063
|
-
this.prWatchState.entries[key] = entry;
|
|
7064
|
-
try {
|
|
7065
|
-
this.savePrWatchState();
|
|
7066
|
-
}
|
|
7067
|
-
catch (err) {
|
|
7068
|
-
entry.pending = pendingBefore;
|
|
7069
|
-
this.prWatchState.entries[key] = entry;
|
|
7070
|
-
throw err;
|
|
7071
|
-
}
|
|
7072
|
-
this.recordWatchOverflowSkip(pending);
|
|
7073
|
-
continue;
|
|
7074
|
-
}
|
|
7075
|
-
const { targets } = this.resolveBoundTargets(pending.envelope.chatId, pending.issueNumber, this.boundEventClass(pending.envelope));
|
|
7076
|
-
if (targets.length === 0) {
|
|
7077
|
-
// An incomplete enumeration is not an absence: defer instead of
|
|
7078
|
-
// retiring while the snapshot cannot prove no role matches.
|
|
7079
|
-
if (!this.boundSnapshotTrusted ||
|
|
7080
|
-
this.lastBindingsPartial ||
|
|
7081
|
-
this.boundRefreshFailed) {
|
|
7082
|
-
return;
|
|
7083
|
-
}
|
|
7084
|
-
// One grace cycle when the gate is the cause: a watch installed
|
|
7085
|
-
// after the snapshot was fetched surfaces on the next refresh. The
|
|
7086
|
-
// grace is scoped to the snapshot generation (a second drain of the
|
|
7087
|
-
// same PR in the same poll must not spend it).
|
|
7088
|
-
if (this.gateExcludedAllFollowers(pending.envelope.chatId, pending.issueNumber) &&
|
|
7089
|
-
this.gateGraceShouldHold(pending.key)) {
|
|
7090
|
-
return;
|
|
7091
|
-
}
|
|
7092
|
-
this.gateGraceClear(pending.key);
|
|
7093
|
-
process.stderr.write(`[Channel:${this.name}] watch event ${pending.key} has no matching role target; retiring without public fallback\n`);
|
|
7094
|
-
entry.pending = entry.pending.slice(1);
|
|
7095
|
-
this.prWatchState.entries[key] = entry;
|
|
7096
|
-
this.savePrWatchState();
|
|
7097
|
-
continue;
|
|
7098
|
-
}
|
|
7099
|
-
this.gateGraceClear(pending.key);
|
|
7100
|
-
const tasksBefore = this.readInboundTasks();
|
|
7101
|
-
const knownIds = new Set(tasksBefore.map((task) => task.id));
|
|
7102
|
-
const claimable = targets.filter((target) => !tasksBefore.some((task) => this.isRecoverableInboundTask(task) &&
|
|
7103
|
-
task.envelope?.messageId?.startsWith('watch:') === true &&
|
|
7104
|
-
task.source.messageId !== pending.key &&
|
|
7105
|
-
task.delivery?.sessionId === target.sessionId &&
|
|
7106
|
-
this.prBindingKey(task.source.chatId, task.issueNumber) === key));
|
|
7107
|
-
if (claimable.length === 0)
|
|
7108
|
-
return;
|
|
7109
|
-
const claimed = [];
|
|
7110
|
-
const newlyClaimed = [];
|
|
7111
|
-
try {
|
|
7112
|
-
for (const target of claimable) {
|
|
7113
|
-
const task = this.claimInboundTask(pending.envelope, pending.issueNumber, {}, {
|
|
7114
|
-
kind: 'bound-session',
|
|
7115
|
-
sessionId: target.sessionId,
|
|
7116
|
-
...(target.role ? { role: target.role } : {}),
|
|
7117
|
-
});
|
|
7118
|
-
claimed.push(task);
|
|
7119
|
-
if (!knownIds.has(task.id))
|
|
7120
|
-
newlyClaimed.push(task.id);
|
|
7121
|
-
}
|
|
7122
|
-
}
|
|
7123
|
-
catch (err) {
|
|
7124
|
-
// Claim persistence failed: keep the event queued and surface the
|
|
7125
|
-
// failure so reconcile blocks recovery (same contract as legacy).
|
|
7126
|
-
process.stderr.write(`[Channel:${this.name}] failed to claim watch event ${pending.key}, will retry: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
|
|
7127
|
-
throw err;
|
|
7128
|
-
}
|
|
7129
|
-
if (claimable.length === targets.length) {
|
|
7130
|
-
const firedBefore = entry.fired;
|
|
7131
|
-
const pendingBefore = entry.pending;
|
|
7132
|
-
entry.fired = [...(entry.fired ?? []), pending.key].slice(-MAX_FIRED_KEYS);
|
|
7133
|
-
entry.pending = entry.pending.slice(1);
|
|
7134
|
-
this.prWatchState.entries[key] = entry;
|
|
7135
|
-
try {
|
|
7136
|
-
this.savePrWatchState();
|
|
7137
|
-
}
|
|
7138
|
-
catch (err) {
|
|
7139
|
-
// Roll back every NEW claim of this event so the pending record
|
|
7140
|
-
// and the task store cannot diverge across a restart; reused
|
|
7141
|
-
// tasks predate this pass and stay.
|
|
7142
|
-
entry.fired = firedBefore;
|
|
7143
|
-
entry.pending = pendingBefore;
|
|
7144
|
-
this.prWatchState.entries[key] = entry;
|
|
7145
|
-
for (const id of newlyClaimed)
|
|
7146
|
-
this.removeInboundTask(id);
|
|
7147
|
-
process.stderr.write(`[Channel:${this.name}] failed to persist watch fire for ${pending.key}, rolled back claims, will retry: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
|
|
7148
|
-
return;
|
|
7149
|
-
}
|
|
7150
|
-
}
|
|
7151
|
-
for (const task of claimed) {
|
|
7152
|
-
const delivered = await this.runInboundTask(task);
|
|
7153
|
-
if (!delivered)
|
|
7154
|
-
return;
|
|
7155
|
-
}
|
|
7156
|
-
if (claimable.length !== targets.length) {
|
|
7157
|
-
// Blocked targets keep the event pending; their predecessors
|
|
7158
|
-
// settle via recovery, and the next drain re-claims only them
|
|
7159
|
-
// (delivered siblings dedupe at admission if re-listed).
|
|
7160
|
-
return;
|
|
7161
|
-
}
|
|
7162
|
-
}
|
|
7163
|
-
}
|
|
7164
|
-
async fetchCiAggregate(owner, repo, sha) {
|
|
7165
|
-
// The observation is accumulated per ATTEMPT, inside the retried
|
|
7166
|
-
// closure: githubApi retries the whole pagination, and state carried
|
|
7167
|
-
// over from an attempt that died on a later page would let its partial
|
|
7168
|
-
// pending/success readings decide the retry's aggregate.
|
|
7169
|
-
const checks = await this.githubApi(async () => {
|
|
7170
|
-
let sawFailure = false;
|
|
7171
|
-
let sawPending = false;
|
|
7172
|
-
let sawSuccess = false;
|
|
7173
|
-
let namesIncomplete = false;
|
|
7174
|
-
const failedChecks = [];
|
|
7175
|
-
await this.octokit.paginate(this.octokit.rest.checks.listForRef, {
|
|
7176
|
-
owner,
|
|
7177
|
-
repo,
|
|
7178
|
-
ref: sha,
|
|
7179
|
-
per_page: 100,
|
|
7180
|
-
}, (response, done) => {
|
|
7181
|
-
// Octokit's conclusion union omits 'startup_failure', which the
|
|
7182
|
-
// API does return and this aggregate must count as a failure.
|
|
7183
|
-
const runs = response.data;
|
|
7184
|
-
for (const run of runs) {
|
|
7185
|
-
if (run.status !== 'completed') {
|
|
7186
|
-
sawPending = true;
|
|
7187
|
-
continue;
|
|
7188
|
-
}
|
|
7189
|
-
if (run.conclusion === 'failure' ||
|
|
7190
|
-
run.conclusion === 'timed_out' ||
|
|
7191
|
-
run.conclusion === 'action_required' ||
|
|
7192
|
-
// A workflow that fails at startup (e.g. a broken workflow
|
|
7193
|
-
// file) never runs a single job; missing it would certify a
|
|
7194
|
-
// broken CI as 'none' or even 'success'. A deliberate SUBSET
|
|
7195
|
-
// of core's FAILING_CHECK_RUN_CONCLUSIONS: core also counts
|
|
7196
|
-
// cancelled/stale, which the design excludes as
|
|
7197
|
-
// concurrency-cancel noise (a superseded run's cancellation
|
|
7198
|
-
// is not a CI failure of this head).
|
|
7199
|
-
run.conclusion === 'startup_failure') {
|
|
7200
|
-
sawFailure = true;
|
|
7201
|
-
if (typeof run.name === 'string' &&
|
|
7202
|
-
run.name.length > 0 &&
|
|
7203
|
-
failedChecks.length < MAX_REPORTED_FAILED_CHECKS) {
|
|
7204
|
-
failedChecks.push(run.name);
|
|
7205
|
-
}
|
|
7206
|
-
}
|
|
7207
|
-
else if (run.conclusion === 'success') {
|
|
7208
|
-
sawSuccess = true;
|
|
7209
|
-
}
|
|
7210
|
-
}
|
|
7211
|
-
// A failure decides the aggregate: no later page can overturn
|
|
7212
|
-
// it, so stop paging instead of spending one request per page
|
|
7213
|
-
// of a head that carries hundreds of check runs. Whole pages are
|
|
7214
|
-
// still read, so a head whose failures all fit in the pages read
|
|
7215
|
-
// reports the same names as before.
|
|
7216
|
-
if (sawFailure) {
|
|
7217
|
-
// Only unread pages make the list partial: stopping on the
|
|
7218
|
-
// LAST page read everything. The iterator follows this same
|
|
7219
|
-
// header, so its presence is exactly "a page went unread".
|
|
7220
|
-
namesIncomplete = /<[^<>]+>;\s*rel="next"/.test(response.headers?.link ?? '');
|
|
7221
|
-
done();
|
|
7222
|
-
}
|
|
7223
|
-
return [];
|
|
7224
|
-
});
|
|
7225
|
-
return {
|
|
7226
|
-
sawFailure,
|
|
7227
|
-
sawPending,
|
|
7228
|
-
sawSuccess,
|
|
7229
|
-
failedChecks,
|
|
7230
|
-
namesIncomplete,
|
|
7231
|
-
};
|
|
7232
|
-
}, `checks.listForRef(${sha})`, 3, (err) => !isWatchFailFastError(err));
|
|
7233
|
-
let { sawFailure, sawPending, sawSuccess } = checks;
|
|
7234
|
-
const { failedChecks, namesIncomplete } = checks;
|
|
7235
|
-
// A check run already failed, so the combined status could only confirm
|
|
7236
|
-
// 'failure' — skip the request rather than pay for a decided aggregate.
|
|
7237
|
-
if (!sawFailure) {
|
|
7238
|
-
const { data: combined } = await this.githubApi(() => this.octokit.rest.repos.getCombinedStatusForRef({
|
|
7239
|
-
owner,
|
|
7240
|
-
repo,
|
|
7241
|
-
ref: sha,
|
|
7242
|
-
}), `combinedStatus(${sha})`, 3, (err) => !isWatchFailFastError(err));
|
|
7243
|
-
// GitHub returns {state:"pending", total_count:0, statuses:[]} for a
|
|
7244
|
-
// SHA with no legacy commit statuses; an empty combined status must not
|
|
7245
|
-
// count as active CI (it would keep every poll re-fetching forever).
|
|
7246
|
-
if (combined.total_count > 0) {
|
|
7247
|
-
if (combined.state === 'failure' || combined.state === 'error') {
|
|
7248
|
-
sawFailure = true;
|
|
7249
|
-
}
|
|
7250
|
-
else if (combined.state === 'pending') {
|
|
7251
|
-
sawPending = true;
|
|
7252
|
-
}
|
|
7253
|
-
else {
|
|
7254
|
-
sawSuccess = true;
|
|
7255
|
-
}
|
|
7256
|
-
}
|
|
7257
|
-
}
|
|
7258
|
-
const aggregate = sawFailure
|
|
7259
|
-
? 'failure'
|
|
7260
|
-
: sawPending
|
|
7261
|
-
? 'pending'
|
|
7262
|
-
: sawSuccess
|
|
7263
|
-
? 'success'
|
|
7264
|
-
: 'none';
|
|
7265
|
-
return { aggregate, failedChecks, namesIncomplete };
|
|
7266
|
-
}
|
|
7267
6094
|
async markNotificationsAsRead(lastReadAt) {
|
|
7268
6095
|
await this.githubApi(() => this.octokit.rest.activity.markNotificationsAsRead({
|
|
7269
6096
|
last_read_at: lastReadAt,
|