@qwen-code/channel-github 0.28.1-preview.0 → 0.28.2

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.
@@ -4,11 +4,14 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
  import { setTimeout as delay } from 'node:timers/promises';
7
- import { MANAGED_OUTBOUND_LIMIT, resolvePrivatePolicy, } from '@qwen-code/channel-base';
8
- import { DISPATCHED_COMMENTS_LIMIT, MANAGED_GITHUB_PENDING_LIMIT, ManagedGithubStateStore, } from './managed-state.js';
9
- import { isDefinitiveGithubReadFailure } from './managed-github-deps.js';
7
+ import { fitInboundText, MANAGED_OUTBOUND_LIMIT, resolvePrivatePolicy, sanitizePromptText, } from '@qwen-code/channel-base';
8
+ import { DISPATCHED_COMMENTS_LIMIT, MANAGED_GITHUB_PENDING_LIMIT, MANAGED_GITHUB_PR_TRANSITIONS, MANAGED_GITHUB_PR_WATCH_EPISODE_LIMIT, MANAGED_GITHUB_PR_WATCH_FIRED_LIMIT, MANAGED_GITHUB_PR_WATCH_PENDING_LIMIT, ManagedGithubStateStore, } from './managed-state.js';
9
+ import { isDefinitiveGithubReadFailure, isRateLimitAnswer, } from './managed-github-deps.js';
10
10
  import { testBotMention } from './mention.js';
11
11
  const CLAIM_BATCH = 16;
12
+ // The retired channel watch's per-pass cap (prWatchLimit default) and the
13
+ // daemon's per-sweep view cap: both bound the pulls.get fan-out at 30.
14
+ const PR_WATCH_LIMIT = 30;
12
15
  const DEFAULT_POLL_INTERVAL = 60_000;
13
16
  const MIN_POLL_INTERVAL = 1_000;
14
17
  const MAX_POLL_INTERVAL = 86_400_000;
@@ -21,12 +24,6 @@ const INSTANCE_SCOPED_REFUSALS = new Set([
21
24
  ]);
22
25
  const INSTANCE_REFUSAL_DROP_LIMIT = 1;
23
26
  const CHANNEL_NOT_FOUND = 'channel_not_found';
24
- // The wire's text bound (the control plane's Jakarta @Size) and the Harness
25
- // envelope's byte line, mirrored locally to keep this package free of core
26
- // imports. Both match the DingTalk reference adapter's clamp.
27
- const MAX_WIRE_TEXT_CHARS = 32_000;
28
- const ENVELOPE_BYTE_LIMIT = 64 * 1024;
29
- const TEXT_ENVELOPE_OVERHEAD_BYTES = 4096;
30
27
  // The wire's subject bound (InboundEventRequest.subject @Size(max = 200)).
31
28
  const MAX_SUBJECT_CHARS = 200;
32
29
  export function githubSettings(config) {
@@ -217,7 +214,7 @@ export class ManagedGithubAdapter {
217
214
  : [],
218
215
  dispatchMode: config['dispatchMode'] === 'steer' ? 'steer' : 'followup',
219
216
  };
220
- this.store = new ManagedGithubStateStore(options.name, options.cwd, this.settings.baseUrl);
217
+ this.store = new ManagedGithubStateStore(options.name, options.cwd, this.settings.baseUrl, options.controlPlane.destinationKey ?? '');
221
218
  this.controlPlane = options.controlPlane;
222
219
  this.deps = options.deps;
223
220
  this.log =
@@ -250,13 +247,144 @@ export class ManagedGithubAdapter {
250
247
  throw new Error('GitHub state is owned by another process; managed adapter not started.');
251
248
  }
252
249
  try {
253
- this.state = this.store.load() ?? {
250
+ const loaded = this.store.load();
251
+ // The upgrade to per-registration ledgers strands the legacy
252
+ // managed-state.json: make the drop explicit, never silent. Detect it
253
+ // even when a keyed ledger already exists — a rollback to the
254
+ // pre-upgrade build can stage fresh legacy claims after the upgrade. The
255
+ // legacy ledger is not adopted — that would replay one registration's
256
+ // pending into another. It is archived only once the start succeeds
257
+ // (below), so a failed first start leaves the file for a rollback to
258
+ // recover.
259
+ const legacy = this.store.strandedLegacyLedger();
260
+ if (legacy) {
261
+ // An unreadable legacy is not an empty one: its counts are unknown and
262
+ // any claims it held are stranded. Name the inbound and outbound
263
+ // consequences separately so an outbound-only strand does not report
264
+ // lost inbound comments, and a quiescent 0/0 legacy reports no loss.
265
+ // The pending count folds in the legacy watch.prs queues (R3-1): those
266
+ // detected-but-undelivered transitions are stranded work too, so a
267
+ // legacy holding only a queued PR-watch event must not render as a
268
+ // quiescent "0 pending".
269
+ const pendingLabel = legacy.readable
270
+ ? legacy.pending + legacy.watchPending
271
+ : 'unknown';
272
+ const outboundLabel = legacy.readable ? legacy.outbound : 'unknown';
273
+ // The "fresh window" loss claims only hold when the loaded ledger has no
274
+ // watermark of its own. On a roll-forward after a rollback the keyed
275
+ // ledger already has a cursor, so the poll re-lists from it and the
276
+ // legacy watermark's window is NOT skipped — claiming a loss there would
277
+ // page the operator about a loss that does not exist (R1-4 fix-induced).
278
+ const freshWindow = !loaded || loaded.cursor.lastProcessedAt === null;
279
+ let consequence = '';
280
+ if (!legacy.readable) {
281
+ consequence =
282
+ ' Its contents could not be read as a ledger, so any staged-but-unadmitted claims it held are stranded.';
283
+ }
284
+ else {
285
+ if (legacy.pending > 0 && freshWindow)
286
+ consequence +=
287
+ ' Its staged-but-unadmitted claims are stranded; the fresh notification window does not re-list them.';
288
+ // The queued PR-watch transitions are not adopted (R3-1); name that
289
+ // even when the legacy staged no inbound pending/outbound. Whether
290
+ // one can be re-derived depends on the LOADED BASELINES, not the
291
+ // window alone (R5): a roll-forward re-detects the edge only if the
292
+ // loaded ledger holds a watch.prs baseline for the stranded PR. A
293
+ // ledger can have a cursor yet no baseline for it (the PR was bound
294
+ // only during the rollback window, or the earlier run never finished
295
+ // a watch pass) — there the first observation detects nothing and
296
+ // only records a baseline. Decide PER PR (deferred item 11): a mixed
297
+ // queue must not read as wholly lost when a baselined subset can
298
+ // re-derive, and re-detection is conditional on the edge RECURRING —
299
+ // a baseline already past the edge does not re-fire it, so presence
300
+ // alone must not promise re-derivation.
301
+ if (legacy.watchPending > 0) {
302
+ const loadedPrs = loaded?.watch?.prs ?? {};
303
+ const baselined = legacy.watchPendingKeys.filter((key) => loadedPrs[key] !== undefined).length;
304
+ const unbaselined = legacy.watchPendingKeys.length - baselined;
305
+ if (baselined === 0) {
306
+ consequence +=
307
+ ' Its queued PR-watch transitions were dropped; there is no baseline to re-detect them against, so they are neither replayed nor re-derived.';
308
+ }
309
+ else if (unbaselined === 0) {
310
+ consequence += ` Its queued PR-watch transitions were not adopted; this ledger holds their baselines, so ${baselined} may be re-derived if the edge recurs.`;
311
+ }
312
+ else {
313
+ consequence += ` Its queued PR-watch transitions were not adopted; ${baselined} may be re-derived against a loaded baseline if their edge recurs, and ${unbaselined} are dropped with no baseline to re-detect against.`;
314
+ }
315
+ }
316
+ if (legacy.outbound > 0)
317
+ consequence +=
318
+ ' Its outbound segments with an unknown delivery status were dropped.';
319
+ // Even a legacy with no pending/outbound drops the offline backlog:
320
+ // the fresh null cursor restarts the window at connect time, so
321
+ // mentions received after the legacy watermark while the bot was down
322
+ // are never listed. Name that skipped window separately (R1-4).
323
+ if (freshWindow && legacy.watermark !== null)
324
+ consequence += ` Unread notifications updated after ${legacy.watermark} and before this start were never listed, so mentions received since then were not admitted.`;
325
+ }
326
+ this.log(`Managed GitHub upgraded to per-registration ledgers; the legacy ledger ${legacy.path} (${pendingLabel} pending, ${outboundLabel} outbound) is stranded and not replayed.${consequence}`);
327
+ }
328
+ this.state = loaded ?? {
254
329
  version: 1,
255
330
  generation: 1,
256
331
  cursor: { lastProcessedAt: null, dispatchedComments: [] },
257
332
  pending: [],
258
333
  outbound: [],
259
334
  };
335
+ // Carry the durable episode counters into WHATEVER state was loaded
336
+ // (R3-1), not only a fresh object: the admission ledger is permanent, so
337
+ // restarting the counter would re-derive an already-admitted input id and
338
+ // dedupe a genuine post-upgrade recurrence. The counters are entry-scoped
339
+ // — merged Math.max per key from every ledger in the entry directory
340
+ // (live legacy, keyed ledgers, and the .stranded-* archives) — so they
341
+ // survive the first start's archive of the legacy and a roll-forward over
342
+ // an existing keyed ledger. watch.prs re-baselines silently; the queued
343
+ // transitions are NOT adopted (cross-ownership replay).
344
+ const { episodes: entryEpisodes, skipped } = this.store.entryWatchEpisodes();
345
+ // A counter source that could not be read is skipped, not silently
346
+ // dropped: name it so the operator knows the carry may be incomplete
347
+ // (deferred item 8).
348
+ for (const filePath of skipped) {
349
+ this.log(`Managed GitHub could not read the episode-counter source ${filePath}; its counters are not carried this start.`);
350
+ }
351
+ if (entryEpisodes) {
352
+ const watch = this.state.watch ?? { prs: {} };
353
+ const episodes = { ...(watch.episodes ?? {}) };
354
+ // R7-1: the carry is NON-DESTRUCTIVE — persist() writes this map back
355
+ // over the loaded ledger, so evicting the loaded registration's own
356
+ // counters would lose them permanently. Keep every own counter; raise
357
+ // existing ones and add carried ones only while there is room, each
358
+ // floored at the prs baseline so a stale archive can never lower the
359
+ // effective seed (R7-2: the seed `episodes ?? prs.episode ?? 0` lets a
360
+ // watermark shadow the baseline; entryWatchEpisodes already carries the
361
+ // loaded prs baselines, so flooring here is the single guard needed).
362
+ // Iterate sorted so the result is independent of the directory
363
+ // enumeration order. At the hard bound, overflow carried counters are
364
+ // bounded-and-accepted (the same tradeoff as the live watermark
365
+ // eviction): their source files persist and are re-read next start, but
366
+ // they are NOT promised a slot this start — and the overflow is logged,
367
+ // never silent.
368
+ let overflow = 0;
369
+ for (const key of Object.keys(entryEpisodes).sort()) {
370
+ const baseline = watch.prs[key]?.episode;
371
+ const carried = entryEpisodes[key];
372
+ const value = baseline !== undefined ? Math.max(carried, baseline) : carried;
373
+ if (episodes[key] !== undefined) {
374
+ episodes[key] = Math.max(episodes[key], value);
375
+ }
376
+ else if (Object.keys(episodes).length < MANAGED_GITHUB_PR_WATCH_EPISODE_LIMIT) {
377
+ episodes[key] = value;
378
+ }
379
+ else {
380
+ overflow += 1;
381
+ }
382
+ }
383
+ if (overflow > 0) {
384
+ this.log(`Managed GitHub episode carry: ${overflow} counter(s) not carried this start (the loaded ledger holds the ${MANAGED_GITHUB_PR_WATCH_EPISODE_LIMIT}-counter cap); their sources persist and are re-read next start.`);
385
+ }
386
+ this.state.watch = { ...watch, episodes };
387
+ }
260
388
  if (this.state.pending.some((entry) => entry.held)) {
261
389
  this.instanceStalled = true;
262
390
  this.state.instanceRefusals = Math.max(this.state.instanceRefusals ?? 0, INSTANCE_REFUSAL_DROP_LIMIT + 1);
@@ -280,6 +408,25 @@ export class ManagedGithubAdapter {
280
408
  // a stopped, deaf adapter the CLI would then park on.
281
409
  if (!this.running || this.ownershipLost)
282
410
  throw new Error('Managed GitHub adapter stopped during connection.');
411
+ // The start succeeded, so archive the reported legacy: a static legacy is
412
+ // not re-announced on every later start, and a second registration of the
413
+ // entry is not told the first registration's claims were its own. A
414
+ // failed start above leaves it untouched for a rollback to recover; the
415
+ // notice then simply repeats on the retry.
416
+ if (legacy) {
417
+ const archived = this.store.archiveStrandedLegacy();
418
+ // The notice above names the legacy path, which this rename moves; name
419
+ // the archived path too so an operator following the notice can still
420
+ // find the preserved claims instead of hitting ENOENT.
421
+ if (archived) {
422
+ this.log(`Managed GitHub archived the legacy ledger to ${archived}; the claims it held are preserved there for inspection.`);
423
+ }
424
+ else {
425
+ // A failed rename leaves the legacy in place; say so rather than
426
+ // letting the notice name a path with no archive outcome (R7).
427
+ this.log(`Managed GitHub could not archive the legacy ledger ${legacy.path}; it remains in place and will be reported again on the next start.`);
428
+ }
429
+ }
283
430
  // The first window starts at connect time: no historical backlog.
284
431
  this.startedAt = new Date((this.deps.now ?? Date.now)()).toISOString();
285
432
  if (this.pollLoop)
@@ -297,13 +444,17 @@ export class ManagedGithubAdapter {
297
444
  await this.controlPlane.disconnect().catch(() => undefined);
298
445
  await this.release();
299
446
  }
300
- /** One admission re-drive, one inbound poll and one outbound pull. */
447
+ /** One admission re-drive, one inbound poll, one outbox pull, one PR watch. */
301
448
  async tick() {
302
449
  await this.ensureRegistered(this.state);
303
450
  await this.resubmitPending();
304
451
  await this.pollInbound();
452
+ // The user-visible reply lane runs before the watch pass: the watch is not
453
+ // admission-critical and can spend dozens of sequential GitHub round-trips,
454
+ // which must not delay claiming deliveries and posting comment replies.
305
455
  await this.reportOrphanedOutbound();
306
456
  await this.pullOutbox();
457
+ await this.watchPrs();
307
458
  }
308
459
  async runLoop() {
309
460
  try {
@@ -542,6 +693,515 @@ export class ManagedGithubAdapter {
542
693
  }
543
694
  }
544
695
  }
696
+ /**
697
+ * PR-watch pass (D3 of the bound-session design): observe the bound PRs,
698
+ * derive transitions with the daemon's semantics, and inject them privately
699
+ * into the binding's Session through the control plane. Never posts
700
+ * publicly. Every failure is contained here so the outbound lane keeps
701
+ * moving. See docs/design/2026-11-17-managed-github-pr-watch-bound-session.md.
702
+ */
703
+ async watchPrs() {
704
+ const state = this.state;
705
+ const plane = this.deps.prWatchControlPlane;
706
+ if (!this.running ||
707
+ this.instanceStalled ||
708
+ !state ||
709
+ !this.client ||
710
+ !plane)
711
+ return;
712
+ const watch = (state.watch ??= { prs: {} });
713
+ // Durable pending re-drives before new detection: a restart replays the
714
+ // same events into the control plane's idempotent injection.
715
+ await this.drainPrWatchPending();
716
+ if (!this.running)
717
+ return;
718
+ let bindings;
719
+ try {
720
+ bindings = await plane.listPrWatchBindings();
721
+ }
722
+ catch (error) {
723
+ if (this.isRegistrationRefusal(error)) {
724
+ this.registeredGeneration = 0;
725
+ return;
726
+ }
727
+ this.log(`Managed GitHub PR watch binding list failed: ${String(error)}`);
728
+ return;
729
+ }
730
+ const byKey = new Map();
731
+ let folded = 0;
732
+ let excluded = 0;
733
+ for (const binding of bindings) {
734
+ if (typeof binding.owner !== 'string' ||
735
+ !binding.owner ||
736
+ typeof binding.repo !== 'string' ||
737
+ !binding.repo ||
738
+ !Number.isSafeInteger(binding.prNumber) ||
739
+ binding.prNumber < 1 ||
740
+ !Array.isArray(binding.events))
741
+ continue;
742
+ const events = binding.events.filter((event) => MANAGED_GITHUB_PR_TRANSITIONS.includes(event));
743
+ // A binding with no recognized event costs no observation (the retired
744
+ // watch skipped pulls.get for a comment-only channel for the same reason).
745
+ if (events.length === 0)
746
+ continue;
747
+ const key = prWatchKey(binding.owner, binding.repo, binding.prNumber);
748
+ // The allowlist gates the watch lane exactly like the inbound lane: a
749
+ // binding created while the filter was wider must not observe or drive a
750
+ // Session for a repository the operator has since excluded (the
751
+ // resubmitPending rule). Nothing prunes bindings when the config
752
+ // narrows, so without this gate every rotation window would spend
753
+ // GitHub/wake budget on the excluded PR and inject a pr_event into its
754
+ // bound Session. Compare on the lowercased owner/repo chat-id form, the
755
+ // same normalization repoAllowed and the folded key use.
756
+ if (!this.repoAllowed(`${binding.owner}/${binding.repo}`.toLowerCase())) {
757
+ excluded += 1;
758
+ continue;
759
+ }
760
+ // This key lowercases owner/repo, so case-variant spellings of one PR
761
+ // fold onto one observation. The control plane's binding identity hashes
762
+ // the raw owner/repo, so those variants are two accepted rows and only
763
+ // the first listed one is served here; any other difference (whitespace,
764
+ // punctuation) names a different PR to both.
765
+ if (!byKey.has(key))
766
+ byKey.set(key, { ...binding, events });
767
+ else
768
+ folded += 1;
769
+ }
770
+ if (excluded > 0) {
771
+ this.log(`Managed GitHub PR watch skipped ${excluded} listed binding(s) excluded by repoFilter; they are not observed and their Sessions receive no events.`);
772
+ }
773
+ if (folded > 0) {
774
+ // The folded rows are inert: their Session never receives an event and
775
+ // the binding keeps consuming a slot. Name the fold instead of leaving
776
+ // the operator to discover a silently deaf binding.
777
+ this.log(`Managed GitHub PR watch skipped ${folded} listed binding(s) whose PR an earlier row already binds; they receive no events until retired.`);
778
+ }
779
+ // Prune unbound entries only once their pending drained: an in-flight
780
+ // transition keeps its baseline so a rebind does not re-fire it.
781
+ let pruned = false;
782
+ for (const key of Object.keys(watch.prs)) {
783
+ if (!byKey.has(key) && !watch.prs[key].pending?.length) {
784
+ delete watch.prs[key];
785
+ pruned = true;
786
+ }
787
+ }
788
+ if (pruned) {
789
+ try {
790
+ this.persist();
791
+ }
792
+ catch (error) {
793
+ this.log(`Managed GitHub could not persist the PR watch prune: ${persistErrorText(error)}; it retries on the next tick.`);
794
+ }
795
+ }
796
+ // Rotate the observation window across the stably-ordered binding list:
797
+ // each tick observes a capped window starting at the durable sweep offset
798
+ // and advances it, so every binding is observed across successive ticks
799
+ // rather than only the first cap (the daemon watch's sweepStart). A plain
800
+ // break would starve every binding past the cap for the life of the list.
801
+ const entries = [...byKey.entries()];
802
+ const start = entries.length > 0 ? (watch.sweepStart ?? 0) % entries.length : 0;
803
+ let observed = 0;
804
+ for (let i = 0; i < entries.length && observed < PR_WATCH_LIMIT; i++) {
805
+ if (!this.running)
806
+ return;
807
+ const [key, binding] = entries[(start + i) % entries.length];
808
+ observed += 1;
809
+ try {
810
+ await this.observePr(key, binding);
811
+ }
812
+ catch (error) {
813
+ if (this.isRegistrationRefusal(error)) {
814
+ this.registeredGeneration = 0;
815
+ return;
816
+ }
817
+ if (isWatchPassAbort(error)) {
818
+ // A shared credential/rate-limit failure condemns the whole pass:
819
+ // walking the rest would issue one doomed request per watched PR.
820
+ this.log(`Managed GitHub PR watch pass aborted at ${key} (credential/rate limit): ${String(error)}`);
821
+ break;
822
+ }
823
+ if (isDefinitiveGithubReadFailure(error)) {
824
+ // Per-PR permanent failure: a deleted or inaccessible PR answers
825
+ // the same refusal forever; isolate it, keep watching the rest.
826
+ this.log(`Managed GitHub PR watch skips unreadable PR ${key}: ${String(error)}`);
827
+ continue;
828
+ }
829
+ this.log(`Managed GitHub PR watch failed for ${key}: ${String(error)}`);
830
+ }
831
+ }
832
+ if (entries.length > PR_WATCH_LIMIT) {
833
+ this.log(`Managed GitHub PR watch cap: observed ${observed}/${entries.length} bound PRs this tick; the window rotates so the rest are observed on later ticks.`);
834
+ }
835
+ const nextSweepStart = entries.length > 0 ? (start + observed) % entries.length : 0;
836
+ if (watch.sweepStart !== nextSweepStart) {
837
+ watch.sweepStart = nextSweepStart;
838
+ try {
839
+ this.persist();
840
+ }
841
+ catch (error) {
842
+ this.log(`Managed GitHub could not persist the PR watch sweep offset: ${persistErrorText(error)}; it retries on the next tick.`);
843
+ }
844
+ }
845
+ await this.drainPrWatchPending();
846
+ }
847
+ /**
848
+ * One PR observation: compare against the persisted baseline, queue the
849
+ * detected transitions, and commit baseline + pending in one write BEFORE
850
+ * any injection side effect (the retired watch's atomicity discipline).
851
+ */
852
+ async observePr(key, binding) {
853
+ const watch = this.state.watch;
854
+ const client = this.client;
855
+ const previous = watch.prs[key];
856
+ const pr = await client.getPullRequest(binding.owner, binding.repo, binding.prNumber);
857
+ const firstObservation = previous === undefined;
858
+ // The baseline tick is deliberately silent, even for a PR that is already
859
+ // failing or conflicted when bound: only an edge observed after the
860
+ // binding fires, so a bind never replays pre-existing state into the
861
+ // Session. The baseline is still stored, and a head already red at bind
862
+ // time is pinned below so the CI read gate closes.
863
+ // A missing head never overwrites the last known one (the daemon's
864
+ // UNKNOWN no-overwrite rule).
865
+ const headSha = pr.headSha ?? previous?.headSha;
866
+ const headChanged = pr.headSha !== undefined &&
867
+ previous?.headSha !== undefined &&
868
+ pr.headSha !== previous.headSha;
869
+ // A merged/closed PR is terminal (the daemon's "merged is terminal" rule):
870
+ // it must not drive a CI-failure turn for a check that concludes after the
871
+ // merge, and its binding is retired below so it stops consuming a slot.
872
+ const terminal = pr.state === 'closed';
873
+ const detected = [];
874
+ if (!firstObservation &&
875
+ !terminal &&
876
+ headChanged &&
877
+ binding.events.includes('head_change')) {
878
+ detected.push({
879
+ transition: 'head_change',
880
+ evidence: `New commits pushed: head moved from ${previous.headSha} to ${pr.headSha}.`,
881
+ });
882
+ }
883
+ // The CI read is gated on the ci_failure subscription and skipped once
884
+ // this head already fired: no ci_failure can result, so the request would
885
+ // be pure budget. A head change resets the pin and re-checks.
886
+ let ci;
887
+ if (!terminal &&
888
+ pr.headSha &&
889
+ binding.events.includes('ci_failure') &&
890
+ previous?.ciFiredSha !== pr.headSha) {
891
+ try {
892
+ ci = await client.getCiStatus(binding.owner, binding.repo, pr.headSha);
893
+ }
894
+ catch (error) {
895
+ if (isWatchPassAbort(error))
896
+ throw error;
897
+ // CI is a refinement of the pulls.get baseline, not a dependency: a
898
+ // persistent Checks-endpoint failure must not suppress head_change /
899
+ // merge_conflict, whose data already arrived. Keep the stored ci.
900
+ this.log(`Managed GitHub CI read failed for ${key}; continuing without CI this tick: ${String(error)}`);
901
+ }
902
+ }
903
+ const prevCiForThisHead = headChanged ? undefined : previous?.ci;
904
+ if (!firstObservation &&
905
+ ci?.aggregate === 'failing' &&
906
+ prevCiForThisHead !== 'failing' &&
907
+ binding.events.includes('ci_failure')) {
908
+ const names = ci.failedChecks.length > 0
909
+ ? ` Failed checks: ${ci.failedChecks.join(', ')}.`
910
+ : '';
911
+ const incomplete = ci.namesIncomplete
912
+ ? ' The failed-check list may be incomplete.'
913
+ : '';
914
+ detected.push({
915
+ transition: 'ci_failure',
916
+ evidence: `CI failed on head ${pr.headSha}.${names}${incomplete}`,
917
+ });
918
+ }
919
+ if (!firstObservation &&
920
+ !terminal &&
921
+ pr.mergeableState === 'dirty' &&
922
+ previous?.mergeableState !== 'dirty' &&
923
+ binding.events.includes('merge_conflict')) {
924
+ detected.push({
925
+ transition: 'merge_conflict',
926
+ evidence: 'Merge conflicts detected (mergeable_state: dirty).',
927
+ });
928
+ }
929
+ const next = {
930
+ ...(headSha !== undefined ? { headSha } : {}),
931
+ ...(ci !== undefined
932
+ ? { ci: ci.aggregate }
933
+ : headChanged
934
+ ? {}
935
+ : previous?.ci !== undefined
936
+ ? { ci: previous.ci }
937
+ : {}),
938
+ ...(pr.mergeableState !== undefined
939
+ ? { mergeableState: pr.mergeableState }
940
+ : previous?.mergeableState !== undefined
941
+ ? { mergeableState: previous.mergeableState }
942
+ : {}),
943
+ ...(previous?.seq !== undefined ? { seq: previous.seq } : {}),
944
+ ...(previous?.episode !== undefined ? { episode: previous.episode } : {}),
945
+ ...(previous?.fired !== undefined ? { fired: previous.fired } : {}),
946
+ // Copy the queue: the rollback below must restore an untouched array.
947
+ ...(previous?.pending !== undefined
948
+ ? { pending: [...previous.pending] }
949
+ : {}),
950
+ // The pin drops on a head change: the new head's ci_failure is fresh.
951
+ ...(!headChanged && previous?.ciFiredSha !== undefined
952
+ ? { ciFiredSha: previous.ciFiredSha }
953
+ : {}),
954
+ };
955
+ // An observation with no head identity cannot produce a deliverable event
956
+ // (the inject identity needs one). Do not let it advance the mergeability
957
+ // baseline: a dirty value would swallow the merge_conflict edge, and the
958
+ // next headed observation would compare against 'dirty' and never fire for
959
+ // that episode. The first observation is exempt — it detects nothing by
960
+ // design, so the value it records is the baseline itself.
961
+ if (!firstObservation && headSha === undefined) {
962
+ if (previous?.mergeableState !== undefined)
963
+ next.mergeableState = previous.mergeableState;
964
+ else
965
+ delete next.mergeableState;
966
+ }
967
+ // A head already failing when the PR was bound derives no event, but it is
968
+ // pinned exactly like a fired one: the CI read gate stops on the
969
+ // once-per-head pin, so without this pin a PR bound while red re-reads its
970
+ // checks on every tick until the head moves. Pinning injects nothing — the
971
+ // baseline tick stays silent.
972
+ if (firstObservation && ci?.aggregate === 'failing' && pr.headSha) {
973
+ next.ciFiredSha = pr.headSha;
974
+ }
975
+ const detectedAt = (this.deps.now ?? Date.now)();
976
+ const prId = `${binding.owner}/${binding.repo}#${binding.prNumber}`;
977
+ // The occurrence watermark is durable per PR and outlives prune/rebind:
978
+ // the admission ledger is permanent and keyed without a binding
979
+ // discriminant, so a rebind must resume the counter, not restart it and
980
+ // re-derive an already-admitted input id. Seed from the watermark (which
981
+ // survives the baseline prune), falling back to the entry for old state.
982
+ let episode = watch.episodes?.[key] ?? previous?.episode ?? 0;
983
+ for (const event of detected) {
984
+ // The inject identity needs a head; an observation without one cannot
985
+ // produce a deliverable event.
986
+ if (headSha === undefined)
987
+ continue;
988
+ let dedupeKey;
989
+ if (event.transition === 'ci_failure') {
990
+ dedupeKey = `prw:ci_failure:${prId}:${headSha}:${detectedAt}`;
991
+ }
992
+ else {
993
+ next.seq = (next.seq ?? 0) + 1;
994
+ dedupeKey = `prw:${event.transition}:${prId}:${next.seq}:${detectedAt}`;
995
+ }
996
+ // ci_failure matches by PR+SHA prefix: once per head across flaps and
997
+ // pending episodes; the other transitions match their exact episode key.
998
+ const ciPrefix = event.transition === 'ci_failure'
999
+ ? `prw:ci_failure:${prId}:${headSha}:`
1000
+ : undefined;
1001
+ const recorded = (k) => ciPrefix !== undefined ? k.startsWith(ciPrefix) : k === dedupeKey;
1002
+ // The carried pin from a prior tick: this head already fired ci_failure.
1003
+ if (event.transition === 'ci_failure' && next.ciFiredSha === headSha)
1004
+ continue;
1005
+ // Pin any failing head we evaluated even when the ring/pending suppress
1006
+ // the event (a force-push back to a fired head), so the CI read gate
1007
+ // stops re-issuing checks on a head that can never fire again.
1008
+ if (event.transition === 'ci_failure')
1009
+ next.ciFiredSha = headSha;
1010
+ if (next.fired?.some(recorded))
1011
+ continue;
1012
+ if (next.pending?.some((p) => recorded(p.key)))
1013
+ continue;
1014
+ // A new occurrence gets a fresh durable episode; it is persisted with the
1015
+ // pending entry so a crash-replay derives the same control-plane input id.
1016
+ episode += 1;
1017
+ next.episode = episode;
1018
+ (watch.episodes ??= {})[key] = episode;
1019
+ (next.pending ??= []).push({
1020
+ key: dedupeKey,
1021
+ episode,
1022
+ owner: binding.owner,
1023
+ repo: binding.repo,
1024
+ prNumber: binding.prNumber,
1025
+ transition: event.transition,
1026
+ headSha,
1027
+ evidence: sanitizePromptText(event.evidence),
1028
+ detectedAt: new Date(detectedAt).toISOString(),
1029
+ });
1030
+ if (next.pending.length > MANAGED_GITHUB_PR_WATCH_PENDING_LIMIT) {
1031
+ const dropped = next.pending.shift();
1032
+ this.log(`Managed GitHub PR watch pending overflow for ${key}: dropped ${dropped.key} undelivered (cap ${MANAGED_GITHUB_PR_WATCH_PENDING_LIMIT}).`);
1033
+ }
1034
+ }
1035
+ // Bound the watermark map separately from the prunable baselines; evict the
1036
+ // oldest watermarks past the cap (a rebind of an evicted PR restarts its
1037
+ // counter, the bounded-state tradeoff for a permanent admission ledger).
1038
+ const episodes = watch.episodes;
1039
+ if (episodes) {
1040
+ const keys = Object.keys(episodes);
1041
+ for (let i = 0; i < keys.length - MANAGED_GITHUB_PR_WATCH_EPISODE_LIMIT; i++) {
1042
+ delete episodes[keys[i]];
1043
+ }
1044
+ }
1045
+ // Persist only when the observation actually changed the entry: an
1046
+ // all-quiet tick must not pay one full-state write + fsync per binding.
1047
+ const entryChanged = previous === undefined ||
1048
+ JSON.stringify(next) !== JSON.stringify(previous);
1049
+ watch.prs[key] = next;
1050
+ if (entryChanged) {
1051
+ try {
1052
+ this.persist();
1053
+ }
1054
+ catch (error) {
1055
+ // A failed save must not leave the detection in memory: roll back so
1056
+ // the next tick re-observes and re-derives it (the pollInbound discipline).
1057
+ if (previous === undefined)
1058
+ delete watch.prs[key];
1059
+ else
1060
+ watch.prs[key] = previous;
1061
+ throw error;
1062
+ }
1063
+ }
1064
+ // A terminal (merged/closed) PR's binding is retired so it stops consuming
1065
+ // an observation slot and the PR can be bound to another Session.
1066
+ // Best-effort and idempotent: while the PR stays terminal the next tick
1067
+ // re-drives the retire; the episode watermark survives the later prune.
1068
+ if (terminal) {
1069
+ // Same post-await side-effect discipline as the rest of the pass: a
1070
+ // process that lost the state-file lock or was stopped must not delete
1071
+ // a binding another owner now serves.
1072
+ if (!this.running || this.ownershipLost)
1073
+ return;
1074
+ const plane = this.deps.prWatchControlPlane;
1075
+ if (plane) {
1076
+ try {
1077
+ await plane.retirePrWatchBinding({
1078
+ owner: binding.owner,
1079
+ repo: binding.repo,
1080
+ prNumber: binding.prNumber,
1081
+ });
1082
+ }
1083
+ catch (error) {
1084
+ if (this.isRegistrationRefusal(error)) {
1085
+ this.registeredGeneration = 0;
1086
+ return;
1087
+ }
1088
+ this.log(`Managed GitHub could not retire the terminal PR binding ${key}: ${String(error)}; it retries on the next tick.`);
1089
+ }
1090
+ }
1091
+ }
1092
+ }
1093
+ /**
1094
+ * Drain the durable pending queue oldest-first. Injection is the only side
1095
+ * effect: success records the fired key and removes the entry in one write;
1096
+ * a transient failure keeps the entry for the next tick; a deterministic
1097
+ * refusal drops it visibly. Never posts a public comment.
1098
+ */
1099
+ async drainPrWatchPending() {
1100
+ const watch = this.state.watch;
1101
+ const plane = this.deps.prWatchControlPlane;
1102
+ if (!watch || !plane)
1103
+ return;
1104
+ for (const [key, entry] of Object.entries(watch.prs)) {
1105
+ // A pending event staged while the filter was wider must not drive a
1106
+ // Session for a repository the operator has since excluded (the
1107
+ // resubmitPending rule). Drop it visibly so the watch prune removes the
1108
+ // baseline instead of re-injecting it every tick. The key is the
1109
+ // lowercased owner/repo#prNumber; strip the PR suffix to the chat-id
1110
+ // form repoAllowed compares.
1111
+ if (!this.repoAllowed(key.slice(0, key.lastIndexOf('#')))) {
1112
+ if (entry.pending && entry.pending.length > 0) {
1113
+ this.log(`Managed GitHub PR watch dropped ${entry.pending.length} pending event(s) for ${key}: the repository is excluded by repoFilter.`);
1114
+ entry.pending = [];
1115
+ }
1116
+ continue;
1117
+ }
1118
+ while (entry.pending && entry.pending.length > 0) {
1119
+ if (!this.running)
1120
+ return;
1121
+ const pending = entry.pending[0];
1122
+ try {
1123
+ await plane.injectPrEvent({
1124
+ owner: pending.owner,
1125
+ repo: pending.repo,
1126
+ prNumber: pending.prNumber,
1127
+ transition: pending.transition,
1128
+ headSha: pending.headSha,
1129
+ evidence: pending.evidence,
1130
+ episode: pending.episode,
1131
+ });
1132
+ }
1133
+ catch (error) {
1134
+ if (this.isRegistrationRefusal(error)) {
1135
+ this.registeredGeneration = 0;
1136
+ return;
1137
+ }
1138
+ const status = error.status;
1139
+ if (status === 400 ||
1140
+ status === 403 ||
1141
+ status === 404 ||
1142
+ status === 409) {
1143
+ // A deterministic refusal never converges on re-drive (the
1144
+ // binding or its Session is gone, or the request is refused):
1145
+ // drop visibly, the submit() refusal discipline.
1146
+ this.log(`Managed GitHub PR event ${pending.key} injection was refused (${status}); the event drops.`);
1147
+ // A pump-less bound Session can never run a pr_event turn: retire
1148
+ // the binding rather than leave it listed to drop every future
1149
+ // transition (the Harness refusal itself stays — R1-4).
1150
+ if (error.code === 'pr_event_wake_unavailable') {
1151
+ if (!this.running || this.ownershipLost)
1152
+ return;
1153
+ try {
1154
+ await plane.retirePrWatchBinding({
1155
+ owner: pending.owner,
1156
+ repo: pending.repo,
1157
+ prNumber: pending.prNumber,
1158
+ });
1159
+ }
1160
+ catch (retireError) {
1161
+ if (this.isRegistrationRefusal(retireError)) {
1162
+ this.registeredGeneration = 0;
1163
+ return;
1164
+ }
1165
+ this.log(`Managed GitHub could not retire the pump-less PR binding ${pending.key}: ${String(retireError)}.`);
1166
+ }
1167
+ }
1168
+ entry.pending = entry.pending.slice(1);
1169
+ try {
1170
+ this.persist();
1171
+ }
1172
+ catch (persistError) {
1173
+ this.log(`Managed GitHub could not persist the refused PR event drop of ${pending.key}: ${persistErrorText(persistError)}; a restart re-drives it into the same refusal.`);
1174
+ }
1175
+ continue;
1176
+ }
1177
+ // A lost answer or transient refusal: the entry stays pending so
1178
+ // the next tick re-drives the identical event into the control
1179
+ // plane's derived-id idempotency. Isolate the failure to this PR's
1180
+ // queue (break) and keep draining the other bindings — a single
1181
+ // unhealthy Session (e.g. history maintenance answering 503) must
1182
+ // not starve every other bound PR in the channel.
1183
+ this.log(`Managed GitHub PR event ${pending.key} injection failed (${String(error)}); it stays pending for the next tick.`);
1184
+ break;
1185
+ }
1186
+ // Success: record fired and remove pending in one durable write. A
1187
+ // failed write rolls both back so the next tick re-drives the same
1188
+ // event into the idempotent replay — never a half-settled memory.
1189
+ const previousPending = entry.pending;
1190
+ const previousFired = entry.fired;
1191
+ entry.pending = entry.pending.slice(1);
1192
+ entry.fired = [...(entry.fired ?? []), pending.key].slice(-MANAGED_GITHUB_PR_WATCH_FIRED_LIMIT);
1193
+ try {
1194
+ this.persist();
1195
+ }
1196
+ catch (error) {
1197
+ entry.pending = previousPending;
1198
+ entry.fired = previousFired;
1199
+ this.log(`Managed GitHub could not persist the fired PR event ${pending.key}: ${persistErrorText(error)}; it re-drives on the next tick.`);
1200
+ return;
1201
+ }
1202
+ }
1203
+ }
1204
+ }
545
1205
  recordDispatched(key) {
546
1206
  const state = this.state;
547
1207
  if (!state.cursor.dispatchedComments.includes(key)) {
@@ -935,6 +1595,21 @@ export class ManagedGithubAdapter {
935
1595
  function persistErrorText(error) {
936
1596
  return String(error.cause ?? error);
937
1597
  }
1598
+ // One baseline per PR, lowercased like the Legacy group id so two spellings
1599
+ // of one repository share one watch.
1600
+ function prWatchKey(owner, repo, prNumber) {
1601
+ return `${owner}/${repo}#${prNumber}`.toLowerCase();
1602
+ }
1603
+ // Fail-fast statuses that condemn the WHOLE watch pass, not just one PR: a
1604
+ // bad credential or an exhausted rate budget is shared by every watched PR
1605
+ // (the retired watch's isWatchPassAbortError). A bare permission 403 stays
1606
+ // per-PR so it cannot starve the other watched PRs.
1607
+ function isWatchPassAbort(error) {
1608
+ const status = error.status;
1609
+ return (status === 401 ||
1610
+ status === 429 ||
1611
+ (status === 403 && isRateLimitAnswer(error)));
1612
+ }
938
1613
  function fitSubject(title) {
939
1614
  if (!title)
940
1615
  return null;
@@ -943,41 +1618,4 @@ function fitSubject(title) {
943
1618
  bounded = bounded.slice(0, -1);
944
1619
  return bounded;
945
1620
  }
946
- /**
947
- * The wire admits at most MAX_WIRE_TEXT_CHARS characters and the Harness
948
- * envelope at most ENVELOPE_BYTE_LIMIT bytes of event JSON. Clamp to both so
949
- * an over-long comment is admitted truncated instead of meeting a
950
- * deterministic 400 and being dropped whole. Copied from the DingTalk
951
- * adapter's clamp (managed-dingtalk-adapter.ts), not email's raw-UTF-8
952
- * budget: a CJK comment can sit under the character line yet overflow the
953
- * byte envelope, and escape-heavy text inflates the JSON-serialized length.
954
- */
955
- function fitInboundText(text) {
956
- // The cap counts UTF-16 units (the server's maxTextChars does too), so a
957
- // code-point cap could overshoot it; but a UTF-16 slice can land inside a
958
- // surrogate pair, so back off a trailing high surrogate to keep the text
959
- // well-formed.
960
- let bounded = text.slice(0, MAX_WIRE_TEXT_CHARS);
961
- if (/[\uD800-\uDBFF]$/.test(bounded))
962
- bounded = bounded.slice(0, -1);
963
- const byteLimit = ENVELOPE_BYTE_LIMIT - TEXT_ENVELOPE_OVERHEAD_BYTES;
964
- // The bound is enforced on the JSON-serialized envelope, where a control
965
- // character costs six bytes and a quote/backslash two — not on the raw
966
- // UTF-8 length. Budget the escaped length and cut by code points until it
967
- // fits.
968
- const encodedBytes = (s) => Buffer.byteLength(JSON.stringify(s), 'utf8') - 2;
969
- if (encodedBytes(bounded) <= byteLimit)
970
- return bounded;
971
- const chars = Array.from(bounded);
972
- let lo = 0;
973
- let hi = chars.length;
974
- while (lo < hi) {
975
- const mid = Math.ceil((lo + hi) / 2);
976
- if (encodedBytes(chars.slice(0, mid).join('')) <= byteLimit)
977
- lo = mid;
978
- else
979
- hi = mid - 1;
980
- }
981
- return chars.slice(0, lo).join('');
982
- }
983
1621
  //# sourceMappingURL=managed-github-adapter.js.map