@qwen-code/channel-github 0.27.4 → 0.28.0-nightly.20261119.f8d4f706ea

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.
@@ -0,0 +1,1471 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Qwen Team
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { setTimeout as delay } from 'node:timers/promises';
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
+ import { testBotMention } from './mention.js';
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;
15
+ const DEFAULT_POLL_INTERVAL = 60_000;
16
+ const MIN_POLL_INTERVAL = 1_000;
17
+ const MAX_POLL_INTERVAL = 86_400_000;
18
+ const GITHUB_EVENT_PREFIX = 'github:';
19
+ const INSTANCE_SCOPED_REFUSALS = new Set([
20
+ 'workspace_not_found',
21
+ 'workspace_forbidden',
22
+ 'actor_scope_mismatch',
23
+ 'workspace_unavailable',
24
+ ]);
25
+ const INSTANCE_REFUSAL_DROP_LIMIT = 1;
26
+ const CHANNEL_NOT_FOUND = 'channel_not_found';
27
+ // The wire's subject bound (InboundEventRequest.subject @Size(max = 200)).
28
+ const MAX_SUBJECT_CHARS = 200;
29
+ export function githubSettings(config) {
30
+ if (config['useLocalGh'] === true) {
31
+ // The gh CLI login is a machine-level identity; a tenant-scoped managed
32
+ // deployment authenticates with its own token.
33
+ throw new Error('The managed GitHub path does not support useLocalGh; configure a token.');
34
+ }
35
+ const token = config['token'];
36
+ if (!validCredential(token))
37
+ throw new Error('GitHub channel requires a token.');
38
+ const rawBaseUrl = config['baseUrl'];
39
+ const baseUrlRaw = typeof rawBaseUrl === 'string' && rawBaseUrl.trim()
40
+ ? rawBaseUrl.trim()
41
+ : 'https://api.github.com';
42
+ let parsedBase;
43
+ try {
44
+ parsedBase = new URL(baseUrlRaw);
45
+ }
46
+ catch {
47
+ throw new Error('GitHub channel baseUrl is not a valid URL.');
48
+ }
49
+ // WHATWG parses a scheme-less "host:port/path" with an empty hostname and a
50
+ // bogus protocol; it would fail identity resolution as "unknown scheme"
51
+ // behind the token-pointing message. Require an absolute http(s) URL.
52
+ if (!/^https?:$/.test(parsedBase.protocol) || !parsedBase.hostname) {
53
+ throw new Error('GitHub channel baseUrl must be an absolute http(s) URL with a host.');
54
+ }
55
+ // Normalize before the state-directory hash: trailing slash and host case
56
+ // are the same endpoint and must key one state directory, not two owners.
57
+ const baseUrl = `${parsedBase.origin}${parsedBase.pathname.replace(/\/+$/, '')}`;
58
+ const rawInterval = config['pollInterval'];
59
+ const pollInterval = Number(rawInterval ?? DEFAULT_POLL_INTERVAL);
60
+ const intervalAccepted = Number.isSafeInteger(pollInterval) &&
61
+ pollInterval >= MIN_POLL_INTERVAL &&
62
+ pollInterval <= MAX_POLL_INTERVAL;
63
+ const rawRepoFilter = config['repoFilter'];
64
+ const repoFilterMode = config['repoFilterMode'];
65
+ let repoFilter;
66
+ // The plugin descriptor defaults repoFilterMode to 'off' and the Web Shell
67
+ // editor seeds 'off' on save, so 'off' — and a blocklist with no list — must
68
+ // start as "no repository filtering", not be refused. Only the invertible
69
+ // and fail-open shapes are refused.
70
+ if (repoFilterMode === 'blocklist' && rawRepoFilter !== undefined) {
71
+ // A blocklist excludes the listed repos; reading it as an allowlist would
72
+ // answer only in the repos the operator blocked. The managed path cannot
73
+ // carry a blocklist, so refuse the invertible shape rather than guess.
74
+ throw new Error("The managed GitHub path supports repoFilter only as an allowlist; a blocklist with a repoFilter list would invert the operator's intent.");
75
+ }
76
+ if (rawRepoFilter !== undefined && repoFilterMode === undefined) {
77
+ // Legacy reads a list with no mode as "filter off"; promoting it to an
78
+ // active allowlist would answer only inside the parked repos. Require the
79
+ // explicit managed spelling instead of guessing.
80
+ throw new Error('GitHub channel repoFilter requires repoFilterMode "allowlist" on the managed path.');
81
+ }
82
+ if (repoFilterMode === 'allowlist') {
83
+ if (rawRepoFilter === undefined) {
84
+ // Declaring an allowlist without a list must not fail open to every repo.
85
+ throw new Error('GitHub channel repoFilterMode "allowlist" requires a non-empty repoFilter array.');
86
+ }
87
+ if (!Array.isArray(rawRepoFilter) ||
88
+ rawRepoFilter.length === 0 ||
89
+ !rawRepoFilter.every((entry) => typeof entry === 'string' &&
90
+ REPOSITORY_FULL_NAME_RE.test(entry.trim()))) {
91
+ // An empty or malformed allowlist would silently drop every event
92
+ // while the adapter reports running (the Legacy validator refuses both
93
+ // for the same reason).
94
+ throw new Error('GitHub channel repoFilter must be a non-empty array of owner/repo strings.');
95
+ }
96
+ repoFilter = rawRepoFilter.map((entry) => entry.trim().toLowerCase());
97
+ }
98
+ // 'off' (the plugin/editor default) and a blocklist without a list leave
99
+ // repoFilter undefined — no repository filtering, nothing to invert.
100
+ return {
101
+ token: token.trim(),
102
+ baseUrl,
103
+ pollInterval: intervalAccepted ? pollInterval : DEFAULT_POLL_INTERVAL,
104
+ pollIntervalRewritten: rawInterval !== undefined && !intervalAccepted,
105
+ repoFilter,
106
+ };
107
+ }
108
+ // Mirror the email/DingTalk credential rule: a copy-paste trailing newline or
109
+ // an embedded CR/LF/NUL must be rejected, not passed through to the API where
110
+ // it surfaces as an auth error pointing at the credential.
111
+ function validCredential(value) {
112
+ return typeof value === 'string' && !!value.trim() && !/[\r\n\0]/.test(value);
113
+ }
114
+ // The Legacy repository full-name shape (GithubAdapter.ts
115
+ // REPOSITORY_FULL_NAME_RE): owner/repo, no whitespace or path separators.
116
+ const REPOSITORY_FULL_NAME_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
117
+ // The Legacy adapter's subject-URL mechanics: one repo + issue/PR number is
118
+ // one chat_thread route. chatId is lowercased like the Legacy group id.
119
+ function extractSubjectUrl(url) {
120
+ const match = url.match(/\/repos\/([^/]+)\/([^/]+)\/(issues|pulls)\/(\d+)/);
121
+ if (!match)
122
+ return null;
123
+ const owner = match[1];
124
+ const repo = match[2];
125
+ const kind = match[3] === 'pulls' ? 'pr' : 'issue';
126
+ const issueNumber = Number(match[4]);
127
+ return {
128
+ chatId: `${owner}/${repo}`.toLowerCase(),
129
+ threadId: `${kind}:${issueNumber}`,
130
+ owner,
131
+ repo,
132
+ issueNumber,
133
+ };
134
+ }
135
+ export class ManagedGithubAdapter {
136
+ settings;
137
+ policy;
138
+ store;
139
+ controlPlane;
140
+ deps;
141
+ log;
142
+ pollLoop;
143
+ state;
144
+ client;
145
+ accountId;
146
+ startedAt;
147
+ releaseLock;
148
+ running = false;
149
+ ownershipLost = false;
150
+ loop;
151
+ abort;
152
+ registeredGeneration;
153
+ instanceStalled = false;
154
+ loggedNoClaimSlot = false;
155
+ loggedSettleFailure = false;
156
+ constructor(options) {
157
+ this.settings = githubSettings(options.config);
158
+ const config = options.config;
159
+ // parseChannelConfig always injects privatePolicy/senderPolicy/groupPolicy
160
+ // defaults into `config`, so an operator's explicit policy choice must be
161
+ // judged on the raw pre-parse entry, not the fully-defaulted parse result.
162
+ const raw = options.rawConfig ?? config;
163
+ const groupPolicy = raw['groupPolicy'];
164
+ if (groupPolicy === 'pairing') {
165
+ // Same "skip every comment while reporting running" hazard as
166
+ // privatePolicy pairing: the managed policy shape has no pairing arm.
167
+ throw new Error('The managed GitHub path does not support groupPolicy "pairing"; use allowedUsers or groupPolicy "open"/"disabled".');
168
+ }
169
+ const groups = config['groups'];
170
+ if (groups &&
171
+ typeof groups === 'object' &&
172
+ Object.keys(groups).length > 0) {
173
+ // Per-repo sender lists cannot be represented by the flat managed
174
+ // policy; silently dropping them would admit senders the operator
175
+ // excluded (or drop ones they allowed).
176
+ throw new Error('The managed GitHub path does not support per-repo "groups"; configure allowedUsers instead.');
177
+ }
178
+ let senderPolicy = resolvePrivatePolicy(config);
179
+ if (senderPolicy === 'pairing') {
180
+ // The managed policy shape has no pairing arm; silently coercing it to
181
+ // an empty allowlist would skip every comment while reporting running.
182
+ throw new Error('The managed GitHub path does not support privatePolicy "pairing"; use allowedUsers, open, or disabled.');
183
+ }
184
+ // The plugin's own schema documents groupPolicy as the GitHub admission
185
+ // gate. Honor an active groupPolicy when the operator did not explicitly
186
+ // choose a managed policy in the RAW entry: a channel configured
187
+ // groupPolicy "open" must not resolve to an empty allowlist and silently
188
+ // consume every mention. Absence is judged on `raw`, not `config` —
189
+ // parseChannelConfig injects privatePolicy/senderPolicy into config for
190
+ // every channel, so a config-based guard would be dead on the production
191
+ // path. groupPolicy "disabled" (the parse default when absent) stays inert
192
+ // — keep the managed resolvePrivatePolicy result — rather than clobber an
193
+ // allowedUsers allowlist into admit-nothing.
194
+ if (raw['privatePolicy'] === undefined &&
195
+ raw['senderPolicy'] === undefined &&
196
+ groupPolicy !== undefined) {
197
+ if (groupPolicy === 'open' || groupPolicy === 'allowlist') {
198
+ senderPolicy = groupPolicy;
199
+ }
200
+ else if (groupPolicy !== 'disabled') {
201
+ throw new Error('GitHub channel groupPolicy must be one of: allowlist, open, disabled.');
202
+ }
203
+ }
204
+ const allowed = config['allowedUsers'];
205
+ this.policy = {
206
+ adapter: 'github',
207
+ senderPolicy: senderPolicy === 'disabled' || senderPolicy === 'open'
208
+ ? senderPolicy
209
+ : 'allowlist',
210
+ allowedSenders: Array.isArray(allowed)
211
+ ? allowed
212
+ .filter((entry) => typeof entry === 'string')
213
+ .map((entry) => entry.trim().toLowerCase())
214
+ : [],
215
+ dispatchMode: config['dispatchMode'] === 'steer' ? 'steer' : 'followup',
216
+ };
217
+ this.store = new ManagedGithubStateStore(options.name, options.cwd, this.settings.baseUrl);
218
+ this.controlPlane = options.controlPlane;
219
+ this.deps = options.deps;
220
+ this.log =
221
+ options.deps.log ?? ((line) => process.stderr.write(`${line}\n`));
222
+ if (this.settings.pollIntervalRewritten) {
223
+ this.log(`Managed GitHub pollInterval ${String(options.config['pollInterval'])} is not an integer in [${MIN_POLL_INTERVAL}, ${MAX_POLL_INTERVAL}]; using ${this.settings.pollInterval} ms.`);
224
+ }
225
+ this.pollLoop = options.pollLoop ?? true;
226
+ }
227
+ get stateFile() {
228
+ return this.store.file;
229
+ }
230
+ get generation() {
231
+ return this.state?.generation;
232
+ }
233
+ async connect() {
234
+ if (this.running || this.releaseLock)
235
+ throw new Error('Managed GitHub adapter is already connected.');
236
+ try {
237
+ this.releaseLock = await this.deps.lock(this.store.directory, () => {
238
+ // A reaped stale lock means a second owner won the state directory.
239
+ // Stop, and stop persisting: an in-flight tick or the shutdown drain
240
+ // must not rewrite the file the new owner now holds.
241
+ this.ownershipLost = true;
242
+ this.log('Managed GitHub state ownership was lost to another process; adapter stopped.');
243
+ this.stop();
244
+ });
245
+ }
246
+ catch {
247
+ throw new Error('GitHub state is owned by another process; managed adapter not started.');
248
+ }
249
+ try {
250
+ this.state = this.store.load() ?? {
251
+ version: 1,
252
+ generation: 1,
253
+ cursor: { lastProcessedAt: null, dispatchedComments: [] },
254
+ pending: [],
255
+ outbound: [],
256
+ };
257
+ if (this.state.pending.some((entry) => entry.held)) {
258
+ this.instanceStalled = true;
259
+ this.state.instanceRefusals = Math.max(this.state.instanceRefusals ?? 0, INSTANCE_REFUSAL_DROP_LIMIT + 1);
260
+ }
261
+ this.persist();
262
+ this.abort = new AbortController();
263
+ this.running = true;
264
+ this.loggedNoClaimSlot = false;
265
+ this.registeredGeneration = undefined;
266
+ this.client = await this.deps.createClient(this.settings);
267
+ // The first identity failure must surface: a bad token creates no
268
+ // usable client, and swallowing it would report a healthy start that
269
+ // is permanently deaf. The deps redact the credential from the error.
270
+ this.accountId = await this.client.resolveIdentity();
271
+ if (!this.running)
272
+ throw new Error('Managed GitHub adapter stopped during connection.');
273
+ await this.ensureRegistered(this.state);
274
+ await this.reportOrphanedOutbound();
275
+ // A lock compromise can land during the awaits above. Re-check so
276
+ // connect() rejects rather than resolving a healthy-looking start for
277
+ // a stopped, deaf adapter the CLI would then park on.
278
+ if (!this.running || this.ownershipLost)
279
+ throw new Error('Managed GitHub adapter stopped during connection.');
280
+ // The first window starts at connect time: no historical backlog.
281
+ this.startedAt = new Date((this.deps.now ?? Date.now)()).toISOString();
282
+ if (this.pollLoop)
283
+ this.loop = this.runLoop();
284
+ }
285
+ catch (error) {
286
+ this.stop();
287
+ await this.release();
288
+ throw error;
289
+ }
290
+ }
291
+ async disconnect() {
292
+ this.stop();
293
+ await this.loop;
294
+ await this.controlPlane.disconnect().catch(() => undefined);
295
+ await this.release();
296
+ }
297
+ /** One admission re-drive, one inbound poll, one outbox pull, one PR watch. */
298
+ async tick() {
299
+ await this.ensureRegistered(this.state);
300
+ await this.resubmitPending();
301
+ await this.pollInbound();
302
+ // The user-visible reply lane runs before the watch pass: the watch is not
303
+ // admission-critical and can spend dozens of sequential GitHub round-trips,
304
+ // which must not delay claiming deliveries and posting comment replies.
305
+ await this.reportOrphanedOutbound();
306
+ await this.pullOutbox();
307
+ await this.watchPrs();
308
+ }
309
+ async runLoop() {
310
+ try {
311
+ while (this.running) {
312
+ try {
313
+ await this.tick();
314
+ }
315
+ catch (error) {
316
+ this.log(`Managed GitHub tick failed: ${String(error)}`);
317
+ }
318
+ if (this.running) {
319
+ const floor = this.client?.pollIntervalFloorMs() ?? 0;
320
+ await delay(Math.max(this.settings.pollInterval, floor), undefined, {
321
+ signal: this.abort.signal,
322
+ }).catch(() => { });
323
+ }
324
+ }
325
+ }
326
+ finally {
327
+ this.stop();
328
+ }
329
+ }
330
+ senderAllowed(sender) {
331
+ switch (this.policy.senderPolicy) {
332
+ case 'disabled':
333
+ return false;
334
+ case 'open':
335
+ return true;
336
+ default:
337
+ return this.policy.allowedSenders.includes(sender);
338
+ }
339
+ }
340
+ repoAllowed(chatId) {
341
+ return (!this.settings.repoFilter || this.settings.repoFilter.includes(chatId));
342
+ }
343
+ async pollInbound() {
344
+ const state = this.state;
345
+ if (!this.running || this.instanceStalled || !this.client)
346
+ return;
347
+ if (state.pending.length >= MANAGED_GITHUB_PENDING_LIMIT) {
348
+ if (!this.loggedNoClaimSlot) {
349
+ this.loggedNoClaimSlot = true;
350
+ this.log('Managed GitHub has no durable claim slot; the inbound poll waits for pending admissions to settle.');
351
+ }
352
+ return;
353
+ }
354
+ this.loggedNoClaimSlot = false;
355
+ // The watermark steps back one second because GitHub timestamps are
356
+ // second-granular; the overlap is absorbed by the dispatched ring and,
357
+ // ultimately, by the control plane's platformEventId idempotency.
358
+ const since = state.cursor.lastProcessedAt
359
+ ? new Date(Date.parse(state.cursor.lastProcessedAt) - 1000).toISOString()
360
+ : this.startedAt;
361
+ let notifications;
362
+ try {
363
+ notifications = await this.client.listNotifications(since);
364
+ }
365
+ catch (error) {
366
+ // A failed read holds the window; the next poll re-lists it.
367
+ this.log(`Managed GitHub notification poll failed: ${String(error)}`);
368
+ return;
369
+ }
370
+ const kept = notifications.filter((notification) => {
371
+ if (notification.reason !== 'mention')
372
+ return false;
373
+ const type = notification.subject.type;
374
+ if (type !== 'Issue' && type !== 'PullRequest')
375
+ return false;
376
+ const target = extractSubjectUrl(notification.subject.url ?? '');
377
+ return !!target && this.repoAllowed(target.chatId);
378
+ });
379
+ // A thread whose comments cannot be read, whose collection was cut short
380
+ // by the claim cap, or whose mark-read fails freezes the whole window:
381
+ // the watermark advances only on a complete pass, and a thread is marked
382
+ // read only when every comment it produced was fully collected.
383
+ let windowComplete = true;
384
+ const processedThreads = new Set();
385
+ const droppedThreads = new Set();
386
+ for (const notification of kept) {
387
+ if (!this.running)
388
+ return;
389
+ if (state.pending.length >= MANAGED_GITHUB_PENDING_LIMIT)
390
+ break;
391
+ const target = extractSubjectUrl(notification.subject.url ?? '');
392
+ let comments;
393
+ try {
394
+ comments = await this.client.listComments(target.owner, target.repo, target.issueNumber, since);
395
+ }
396
+ catch (error) {
397
+ if (isDefinitiveGithubReadFailure(error)) {
398
+ // Poison escape: a deleted or inaccessible thread answers the same
399
+ // refusal forever; without this it freezes the watermark for the
400
+ // life of the channel. Drop it visibly — its mentions are
401
+ // unrecoverable — and skip its mark-read (which would also fail).
402
+ droppedThreads.add(notification.id);
403
+ this.log(`Managed GitHub drops unreadable thread ${target.chatId}#${target.issueNumber}: ${String(error)}`);
404
+ continue;
405
+ }
406
+ windowComplete = false;
407
+ this.log(`Managed GitHub could not read comments for ${target.chatId}#${target.issueNumber}: ${String(error)}`);
408
+ continue;
409
+ }
410
+ let capped = false;
411
+ for (const comment of comments) {
412
+ if (state.pending.length >= MANAGED_GITHUB_PENDING_LIMIT) {
413
+ capped = true;
414
+ break;
415
+ }
416
+ const login = comment.user?.login;
417
+ const body = comment.body;
418
+ if (!login || !body || !body.trim())
419
+ continue;
420
+ if (login.toLowerCase() === this.accountId.toLowerCase())
421
+ continue;
422
+ if (!testBotMention(body, this.accountId))
423
+ continue;
424
+ // node_id is globally unique; the numeric id fallback is only unique
425
+ // per repo, so scope it by thread — two repos' comment #555 must stay
426
+ // two platform events, not one replayed away.
427
+ const key = comment.node_id ??
428
+ `${target.chatId}/${target.threadId}/${comment.id}`;
429
+ const eventId = `${GITHUB_EVENT_PREFIX}${key}`;
430
+ if (state.cursor.dispatchedComments.includes(key) ||
431
+ state.pending.some((entry) => entry.eventId === eventId)) {
432
+ continue;
433
+ }
434
+ const senderId = login.toLowerCase();
435
+ if (!this.senderAllowed(senderId)) {
436
+ this.log(`Managed GitHub sender ${senderId} is not allowed; comment ${key} skipped.`);
437
+ this.recordDispatched(key);
438
+ try {
439
+ this.persist();
440
+ }
441
+ catch (error) {
442
+ // The skip is already applied in memory; disk keeps no claim, so a
443
+ // restart re-lists the comment and skips it again. Never abort the
444
+ // poll over the failed write.
445
+ this.log(`Managed GitHub could not persist the sender skip of ${key}: ${persistErrorText(error)}; a restart re-lists and skips it again.`);
446
+ }
447
+ continue;
448
+ }
449
+ const event = {
450
+ accountGeneration: state.generation,
451
+ platformEventId: eventId,
452
+ semanticRevision: 1,
453
+ scope: {
454
+ kind: 'chat_thread',
455
+ senderId: null,
456
+ chatId: target.chatId,
457
+ threadId: target.threadId,
458
+ },
459
+ senderId,
460
+ chatId: target.chatId,
461
+ threadId: target.threadId,
462
+ subject: fitSubject(notification.subject.title),
463
+ text: fitInboundText(body),
464
+ attachments: [],
465
+ replyContext: {
466
+ owner: target.owner,
467
+ repo: target.repo,
468
+ issueNumber: target.issueNumber,
469
+ senderId,
470
+ },
471
+ };
472
+ const previousPending = state.pending;
473
+ state.pending = [
474
+ ...state.pending,
475
+ { eventId, event, notificationThreadId: notification.id },
476
+ ].slice(-MANAGED_GITHUB_PENDING_LIMIT);
477
+ try {
478
+ this.persist();
479
+ }
480
+ catch (error) {
481
+ // A failed save must not leave the claim in memory: the dedupe arm
482
+ // would then skip a re-listed comment for a claim the store never
483
+ // accepted. Roll back so the next poll re-stages it.
484
+ state.pending = previousPending;
485
+ throw error;
486
+ }
487
+ }
488
+ // A capped collection leaves comments uncollected: marking this thread
489
+ // read would consume notifications whose mentions were never staged.
490
+ if (!capped)
491
+ processedThreads.add(notification.id);
492
+ }
493
+ await this.resubmitPending();
494
+ // Mark a thread read only after every event it produced has left pending
495
+ // (admitted, replayed or visibly dropped). A thread still holding a claim
496
+ // keeps the window frozen so the next poll re-drives it.
497
+ const heldThreads = new Set(state.pending.map((entry) => entry.notificationThreadId));
498
+ for (const notification of kept) {
499
+ if (!this.running)
500
+ return;
501
+ if (droppedThreads.has(notification.id))
502
+ continue;
503
+ if (!processedThreads.has(notification.id)) {
504
+ windowComplete = false;
505
+ continue;
506
+ }
507
+ if (heldThreads.has(notification.id)) {
508
+ windowComplete = false;
509
+ continue;
510
+ }
511
+ try {
512
+ await this.client.markThreadRead(notification.id);
513
+ }
514
+ catch (error) {
515
+ windowComplete = false;
516
+ this.log(`Managed GitHub could not mark notification ${notification.id} read: ${String(error)}; the window holds.`);
517
+ }
518
+ }
519
+ if (windowComplete && notifications.length > 0) {
520
+ let watermark = state.cursor.lastProcessedAt;
521
+ // The outer windowComplete was already evaluated to enter this block;
522
+ // a local flag is what actually gates the persist below.
523
+ let unparseable = false;
524
+ for (const notification of notifications) {
525
+ const updated = Date.parse(notification.updated_at);
526
+ if (Number.isNaN(updated)) {
527
+ // Persisting an unparseable watermark would throw RangeError on
528
+ // every later tick's since computation and fail load() on restart.
529
+ // Hold the window instead; outbound keeps moving.
530
+ unparseable = true;
531
+ this.log(`Managed GitHub notification ${notification.id} has an unparseable updated_at; the window holds.`);
532
+ continue;
533
+ }
534
+ if (!watermark || updated > Date.parse(watermark)) {
535
+ watermark = notification.updated_at;
536
+ }
537
+ }
538
+ if (!unparseable &&
539
+ watermark &&
540
+ watermark !== state.cursor.lastProcessedAt) {
541
+ state.cursor.lastProcessedAt = watermark;
542
+ this.persist();
543
+ }
544
+ }
545
+ }
546
+ /**
547
+ * PR-watch pass (D3 of the bound-session design): observe the bound PRs,
548
+ * derive transitions with the daemon's semantics, and inject them privately
549
+ * into the binding's Session through the control plane. Never posts
550
+ * publicly. Every failure is contained here so the outbound lane keeps
551
+ * moving. See docs/design/2026-11-17-managed-github-pr-watch-bound-session.md.
552
+ */
553
+ async watchPrs() {
554
+ const state = this.state;
555
+ const plane = this.deps.prWatchControlPlane;
556
+ if (!this.running ||
557
+ this.instanceStalled ||
558
+ !state ||
559
+ !this.client ||
560
+ !plane)
561
+ return;
562
+ const watch = (state.watch ??= { prs: {} });
563
+ // Durable pending re-drives before new detection: a restart replays the
564
+ // same events into the control plane's idempotent injection.
565
+ await this.drainPrWatchPending();
566
+ if (!this.running)
567
+ return;
568
+ let bindings;
569
+ try {
570
+ bindings = await plane.listPrWatchBindings();
571
+ }
572
+ catch (error) {
573
+ if (this.isRegistrationRefusal(error)) {
574
+ this.registeredGeneration = 0;
575
+ return;
576
+ }
577
+ this.log(`Managed GitHub PR watch binding list failed: ${String(error)}`);
578
+ return;
579
+ }
580
+ const byKey = new Map();
581
+ let folded = 0;
582
+ let excluded = 0;
583
+ for (const binding of bindings) {
584
+ if (typeof binding.owner !== 'string' ||
585
+ !binding.owner ||
586
+ typeof binding.repo !== 'string' ||
587
+ !binding.repo ||
588
+ !Number.isSafeInteger(binding.prNumber) ||
589
+ binding.prNumber < 1 ||
590
+ !Array.isArray(binding.events))
591
+ continue;
592
+ const events = binding.events.filter((event) => MANAGED_GITHUB_PR_TRANSITIONS.includes(event));
593
+ // A binding with no recognized event costs no observation (the retired
594
+ // watch skipped pulls.get for a comment-only channel for the same reason).
595
+ if (events.length === 0)
596
+ continue;
597
+ const key = prWatchKey(binding.owner, binding.repo, binding.prNumber);
598
+ // The allowlist gates the watch lane exactly like the inbound lane: a
599
+ // binding created while the filter was wider must not observe or drive a
600
+ // Session for a repository the operator has since excluded (the
601
+ // resubmitPending rule). Nothing prunes bindings when the config
602
+ // narrows, so without this gate every rotation window would spend
603
+ // GitHub/wake budget on the excluded PR and inject a pr_event into its
604
+ // bound Session. Compare on the lowercased owner/repo chat-id form, the
605
+ // same normalization repoAllowed and the folded key use.
606
+ if (!this.repoAllowed(`${binding.owner}/${binding.repo}`.toLowerCase())) {
607
+ excluded += 1;
608
+ continue;
609
+ }
610
+ // This key lowercases owner/repo, so case-variant spellings of one PR
611
+ // fold onto one observation. The control plane's binding identity hashes
612
+ // the raw owner/repo, so those variants are two accepted rows and only
613
+ // the first listed one is served here; any other difference (whitespace,
614
+ // punctuation) names a different PR to both.
615
+ if (!byKey.has(key))
616
+ byKey.set(key, { ...binding, events });
617
+ else
618
+ folded += 1;
619
+ }
620
+ if (excluded > 0) {
621
+ this.log(`Managed GitHub PR watch skipped ${excluded} listed binding(s) excluded by repoFilter; they are not observed and their Sessions receive no events.`);
622
+ }
623
+ if (folded > 0) {
624
+ // The folded rows are inert: their Session never receives an event and
625
+ // the binding keeps consuming a slot. Name the fold instead of leaving
626
+ // the operator to discover a silently deaf binding.
627
+ this.log(`Managed GitHub PR watch skipped ${folded} listed binding(s) whose PR an earlier row already binds; they receive no events until retired.`);
628
+ }
629
+ // Prune unbound entries only once their pending drained: an in-flight
630
+ // transition keeps its baseline so a rebind does not re-fire it.
631
+ let pruned = false;
632
+ for (const key of Object.keys(watch.prs)) {
633
+ if (!byKey.has(key) && !watch.prs[key].pending?.length) {
634
+ delete watch.prs[key];
635
+ pruned = true;
636
+ }
637
+ }
638
+ if (pruned) {
639
+ try {
640
+ this.persist();
641
+ }
642
+ catch (error) {
643
+ this.log(`Managed GitHub could not persist the PR watch prune: ${persistErrorText(error)}; it retries on the next tick.`);
644
+ }
645
+ }
646
+ // Rotate the observation window across the stably-ordered binding list:
647
+ // each tick observes a capped window starting at the durable sweep offset
648
+ // and advances it, so every binding is observed across successive ticks
649
+ // rather than only the first cap (the daemon watch's sweepStart). A plain
650
+ // break would starve every binding past the cap for the life of the list.
651
+ const entries = [...byKey.entries()];
652
+ const start = entries.length > 0 ? (watch.sweepStart ?? 0) % entries.length : 0;
653
+ let observed = 0;
654
+ for (let i = 0; i < entries.length && observed < PR_WATCH_LIMIT; i++) {
655
+ if (!this.running)
656
+ return;
657
+ const [key, binding] = entries[(start + i) % entries.length];
658
+ observed += 1;
659
+ try {
660
+ await this.observePr(key, binding);
661
+ }
662
+ catch (error) {
663
+ if (this.isRegistrationRefusal(error)) {
664
+ this.registeredGeneration = 0;
665
+ return;
666
+ }
667
+ if (isWatchPassAbort(error)) {
668
+ // A shared credential/rate-limit failure condemns the whole pass:
669
+ // walking the rest would issue one doomed request per watched PR.
670
+ this.log(`Managed GitHub PR watch pass aborted at ${key} (credential/rate limit): ${String(error)}`);
671
+ break;
672
+ }
673
+ if (isDefinitiveGithubReadFailure(error)) {
674
+ // Per-PR permanent failure: a deleted or inaccessible PR answers
675
+ // the same refusal forever; isolate it, keep watching the rest.
676
+ this.log(`Managed GitHub PR watch skips unreadable PR ${key}: ${String(error)}`);
677
+ continue;
678
+ }
679
+ this.log(`Managed GitHub PR watch failed for ${key}: ${String(error)}`);
680
+ }
681
+ }
682
+ if (entries.length > PR_WATCH_LIMIT) {
683
+ 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.`);
684
+ }
685
+ const nextSweepStart = entries.length > 0 ? (start + observed) % entries.length : 0;
686
+ if (watch.sweepStart !== nextSweepStart) {
687
+ watch.sweepStart = nextSweepStart;
688
+ try {
689
+ this.persist();
690
+ }
691
+ catch (error) {
692
+ this.log(`Managed GitHub could not persist the PR watch sweep offset: ${persistErrorText(error)}; it retries on the next tick.`);
693
+ }
694
+ }
695
+ await this.drainPrWatchPending();
696
+ }
697
+ /**
698
+ * One PR observation: compare against the persisted baseline, queue the
699
+ * detected transitions, and commit baseline + pending in one write BEFORE
700
+ * any injection side effect (the retired watch's atomicity discipline).
701
+ */
702
+ async observePr(key, binding) {
703
+ const watch = this.state.watch;
704
+ const client = this.client;
705
+ const previous = watch.prs[key];
706
+ const pr = await client.getPullRequest(binding.owner, binding.repo, binding.prNumber);
707
+ const firstObservation = previous === undefined;
708
+ // The baseline tick is deliberately silent, even for a PR that is already
709
+ // failing or conflicted when bound: only an edge observed after the
710
+ // binding fires, so a bind never replays pre-existing state into the
711
+ // Session. The baseline is still stored, and a head already red at bind
712
+ // time is pinned below so the CI read gate closes.
713
+ // A missing head never overwrites the last known one (the daemon's
714
+ // UNKNOWN no-overwrite rule).
715
+ const headSha = pr.headSha ?? previous?.headSha;
716
+ const headChanged = pr.headSha !== undefined &&
717
+ previous?.headSha !== undefined &&
718
+ pr.headSha !== previous.headSha;
719
+ // A merged/closed PR is terminal (the daemon's "merged is terminal" rule):
720
+ // it must not drive a CI-failure turn for a check that concludes after the
721
+ // merge, and its binding is retired below so it stops consuming a slot.
722
+ const terminal = pr.state === 'closed';
723
+ const detected = [];
724
+ if (!firstObservation &&
725
+ !terminal &&
726
+ headChanged &&
727
+ binding.events.includes('head_change')) {
728
+ detected.push({
729
+ transition: 'head_change',
730
+ evidence: `New commits pushed: head moved from ${previous.headSha} to ${pr.headSha}.`,
731
+ });
732
+ }
733
+ // The CI read is gated on the ci_failure subscription and skipped once
734
+ // this head already fired: no ci_failure can result, so the request would
735
+ // be pure budget. A head change resets the pin and re-checks.
736
+ let ci;
737
+ if (!terminal &&
738
+ pr.headSha &&
739
+ binding.events.includes('ci_failure') &&
740
+ previous?.ciFiredSha !== pr.headSha) {
741
+ try {
742
+ ci = await client.getCiStatus(binding.owner, binding.repo, pr.headSha);
743
+ }
744
+ catch (error) {
745
+ if (isWatchPassAbort(error))
746
+ throw error;
747
+ // CI is a refinement of the pulls.get baseline, not a dependency: a
748
+ // persistent Checks-endpoint failure must not suppress head_change /
749
+ // merge_conflict, whose data already arrived. Keep the stored ci.
750
+ this.log(`Managed GitHub CI read failed for ${key}; continuing without CI this tick: ${String(error)}`);
751
+ }
752
+ }
753
+ const prevCiForThisHead = headChanged ? undefined : previous?.ci;
754
+ if (!firstObservation &&
755
+ ci?.aggregate === 'failing' &&
756
+ prevCiForThisHead !== 'failing' &&
757
+ binding.events.includes('ci_failure')) {
758
+ const names = ci.failedChecks.length > 0
759
+ ? ` Failed checks: ${ci.failedChecks.join(', ')}.`
760
+ : '';
761
+ const incomplete = ci.namesIncomplete
762
+ ? ' The failed-check list may be incomplete.'
763
+ : '';
764
+ detected.push({
765
+ transition: 'ci_failure',
766
+ evidence: `CI failed on head ${pr.headSha}.${names}${incomplete}`,
767
+ });
768
+ }
769
+ if (!firstObservation &&
770
+ !terminal &&
771
+ pr.mergeableState === 'dirty' &&
772
+ previous?.mergeableState !== 'dirty' &&
773
+ binding.events.includes('merge_conflict')) {
774
+ detected.push({
775
+ transition: 'merge_conflict',
776
+ evidence: 'Merge conflicts detected (mergeable_state: dirty).',
777
+ });
778
+ }
779
+ const next = {
780
+ ...(headSha !== undefined ? { headSha } : {}),
781
+ ...(ci !== undefined
782
+ ? { ci: ci.aggregate }
783
+ : headChanged
784
+ ? {}
785
+ : previous?.ci !== undefined
786
+ ? { ci: previous.ci }
787
+ : {}),
788
+ ...(pr.mergeableState !== undefined
789
+ ? { mergeableState: pr.mergeableState }
790
+ : previous?.mergeableState !== undefined
791
+ ? { mergeableState: previous.mergeableState }
792
+ : {}),
793
+ ...(previous?.seq !== undefined ? { seq: previous.seq } : {}),
794
+ ...(previous?.episode !== undefined ? { episode: previous.episode } : {}),
795
+ ...(previous?.fired !== undefined ? { fired: previous.fired } : {}),
796
+ // Copy the queue: the rollback below must restore an untouched array.
797
+ ...(previous?.pending !== undefined
798
+ ? { pending: [...previous.pending] }
799
+ : {}),
800
+ // The pin drops on a head change: the new head's ci_failure is fresh.
801
+ ...(!headChanged && previous?.ciFiredSha !== undefined
802
+ ? { ciFiredSha: previous.ciFiredSha }
803
+ : {}),
804
+ };
805
+ // An observation with no head identity cannot produce a deliverable event
806
+ // (the inject identity needs one). Do not let it advance the mergeability
807
+ // baseline: a dirty value would swallow the merge_conflict edge, and the
808
+ // next headed observation would compare against 'dirty' and never fire for
809
+ // that episode. The first observation is exempt — it detects nothing by
810
+ // design, so the value it records is the baseline itself.
811
+ if (!firstObservation && headSha === undefined) {
812
+ if (previous?.mergeableState !== undefined)
813
+ next.mergeableState = previous.mergeableState;
814
+ else
815
+ delete next.mergeableState;
816
+ }
817
+ // A head already failing when the PR was bound derives no event, but it is
818
+ // pinned exactly like a fired one: the CI read gate stops on the
819
+ // once-per-head pin, so without this pin a PR bound while red re-reads its
820
+ // checks on every tick until the head moves. Pinning injects nothing — the
821
+ // baseline tick stays silent.
822
+ if (firstObservation && ci?.aggregate === 'failing' && pr.headSha) {
823
+ next.ciFiredSha = pr.headSha;
824
+ }
825
+ const detectedAt = (this.deps.now ?? Date.now)();
826
+ const prId = `${binding.owner}/${binding.repo}#${binding.prNumber}`;
827
+ // The occurrence watermark is durable per PR and outlives prune/rebind:
828
+ // the admission ledger is permanent and keyed without a binding
829
+ // discriminant, so a rebind must resume the counter, not restart it and
830
+ // re-derive an already-admitted input id. Seed from the watermark (which
831
+ // survives the baseline prune), falling back to the entry for old state.
832
+ let episode = watch.episodes?.[key] ?? previous?.episode ?? 0;
833
+ for (const event of detected) {
834
+ // The inject identity needs a head; an observation without one cannot
835
+ // produce a deliverable event.
836
+ if (headSha === undefined)
837
+ continue;
838
+ let dedupeKey;
839
+ if (event.transition === 'ci_failure') {
840
+ dedupeKey = `prw:ci_failure:${prId}:${headSha}:${detectedAt}`;
841
+ }
842
+ else {
843
+ next.seq = (next.seq ?? 0) + 1;
844
+ dedupeKey = `prw:${event.transition}:${prId}:${next.seq}:${detectedAt}`;
845
+ }
846
+ // ci_failure matches by PR+SHA prefix: once per head across flaps and
847
+ // pending episodes; the other transitions match their exact episode key.
848
+ const ciPrefix = event.transition === 'ci_failure'
849
+ ? `prw:ci_failure:${prId}:${headSha}:`
850
+ : undefined;
851
+ const recorded = (k) => ciPrefix !== undefined ? k.startsWith(ciPrefix) : k === dedupeKey;
852
+ // The carried pin from a prior tick: this head already fired ci_failure.
853
+ if (event.transition === 'ci_failure' && next.ciFiredSha === headSha)
854
+ continue;
855
+ // Pin any failing head we evaluated even when the ring/pending suppress
856
+ // the event (a force-push back to a fired head), so the CI read gate
857
+ // stops re-issuing checks on a head that can never fire again.
858
+ if (event.transition === 'ci_failure')
859
+ next.ciFiredSha = headSha;
860
+ if (next.fired?.some(recorded))
861
+ continue;
862
+ if (next.pending?.some((p) => recorded(p.key)))
863
+ continue;
864
+ // A new occurrence gets a fresh durable episode; it is persisted with the
865
+ // pending entry so a crash-replay derives the same control-plane input id.
866
+ episode += 1;
867
+ next.episode = episode;
868
+ (watch.episodes ??= {})[key] = episode;
869
+ (next.pending ??= []).push({
870
+ key: dedupeKey,
871
+ episode,
872
+ owner: binding.owner,
873
+ repo: binding.repo,
874
+ prNumber: binding.prNumber,
875
+ transition: event.transition,
876
+ headSha,
877
+ evidence: sanitizePromptText(event.evidence),
878
+ detectedAt: new Date(detectedAt).toISOString(),
879
+ });
880
+ if (next.pending.length > MANAGED_GITHUB_PR_WATCH_PENDING_LIMIT) {
881
+ const dropped = next.pending.shift();
882
+ this.log(`Managed GitHub PR watch pending overflow for ${key}: dropped ${dropped.key} undelivered (cap ${MANAGED_GITHUB_PR_WATCH_PENDING_LIMIT}).`);
883
+ }
884
+ }
885
+ // Bound the watermark map separately from the prunable baselines; evict the
886
+ // oldest watermarks past the cap (a rebind of an evicted PR restarts its
887
+ // counter, the bounded-state tradeoff for a permanent admission ledger).
888
+ const episodes = watch.episodes;
889
+ if (episodes) {
890
+ const keys = Object.keys(episodes);
891
+ for (let i = 0; i < keys.length - MANAGED_GITHUB_PR_WATCH_EPISODE_LIMIT; i++) {
892
+ delete episodes[keys[i]];
893
+ }
894
+ }
895
+ // Persist only when the observation actually changed the entry: an
896
+ // all-quiet tick must not pay one full-state write + fsync per binding.
897
+ const entryChanged = previous === undefined ||
898
+ JSON.stringify(next) !== JSON.stringify(previous);
899
+ watch.prs[key] = next;
900
+ if (entryChanged) {
901
+ try {
902
+ this.persist();
903
+ }
904
+ catch (error) {
905
+ // A failed save must not leave the detection in memory: roll back so
906
+ // the next tick re-observes and re-derives it (the pollInbound discipline).
907
+ if (previous === undefined)
908
+ delete watch.prs[key];
909
+ else
910
+ watch.prs[key] = previous;
911
+ throw error;
912
+ }
913
+ }
914
+ // A terminal (merged/closed) PR's binding is retired so it stops consuming
915
+ // an observation slot and the PR can be bound to another Session.
916
+ // Best-effort and idempotent: while the PR stays terminal the next tick
917
+ // re-drives the retire; the episode watermark survives the later prune.
918
+ if (terminal) {
919
+ // Same post-await side-effect discipline as the rest of the pass: a
920
+ // process that lost the state-file lock or was stopped must not delete
921
+ // a binding another owner now serves.
922
+ if (!this.running || this.ownershipLost)
923
+ return;
924
+ const plane = this.deps.prWatchControlPlane;
925
+ if (plane) {
926
+ try {
927
+ await plane.retirePrWatchBinding({
928
+ owner: binding.owner,
929
+ repo: binding.repo,
930
+ prNumber: binding.prNumber,
931
+ });
932
+ }
933
+ catch (error) {
934
+ if (this.isRegistrationRefusal(error)) {
935
+ this.registeredGeneration = 0;
936
+ return;
937
+ }
938
+ this.log(`Managed GitHub could not retire the terminal PR binding ${key}: ${String(error)}; it retries on the next tick.`);
939
+ }
940
+ }
941
+ }
942
+ }
943
+ /**
944
+ * Drain the durable pending queue oldest-first. Injection is the only side
945
+ * effect: success records the fired key and removes the entry in one write;
946
+ * a transient failure keeps the entry for the next tick; a deterministic
947
+ * refusal drops it visibly. Never posts a public comment.
948
+ */
949
+ async drainPrWatchPending() {
950
+ const watch = this.state.watch;
951
+ const plane = this.deps.prWatchControlPlane;
952
+ if (!watch || !plane)
953
+ return;
954
+ for (const [key, entry] of Object.entries(watch.prs)) {
955
+ // A pending event staged while the filter was wider must not drive a
956
+ // Session for a repository the operator has since excluded (the
957
+ // resubmitPending rule). Drop it visibly so the watch prune removes the
958
+ // baseline instead of re-injecting it every tick. The key is the
959
+ // lowercased owner/repo#prNumber; strip the PR suffix to the chat-id
960
+ // form repoAllowed compares.
961
+ if (!this.repoAllowed(key.slice(0, key.lastIndexOf('#')))) {
962
+ if (entry.pending && entry.pending.length > 0) {
963
+ this.log(`Managed GitHub PR watch dropped ${entry.pending.length} pending event(s) for ${key}: the repository is excluded by repoFilter.`);
964
+ entry.pending = [];
965
+ }
966
+ continue;
967
+ }
968
+ while (entry.pending && entry.pending.length > 0) {
969
+ if (!this.running)
970
+ return;
971
+ const pending = entry.pending[0];
972
+ try {
973
+ await plane.injectPrEvent({
974
+ owner: pending.owner,
975
+ repo: pending.repo,
976
+ prNumber: pending.prNumber,
977
+ transition: pending.transition,
978
+ headSha: pending.headSha,
979
+ evidence: pending.evidence,
980
+ episode: pending.episode,
981
+ });
982
+ }
983
+ catch (error) {
984
+ if (this.isRegistrationRefusal(error)) {
985
+ this.registeredGeneration = 0;
986
+ return;
987
+ }
988
+ const status = error.status;
989
+ if (status === 400 ||
990
+ status === 403 ||
991
+ status === 404 ||
992
+ status === 409) {
993
+ // A deterministic refusal never converges on re-drive (the
994
+ // binding or its Session is gone, or the request is refused):
995
+ // drop visibly, the submit() refusal discipline.
996
+ this.log(`Managed GitHub PR event ${pending.key} injection was refused (${status}); the event drops.`);
997
+ // A pump-less bound Session can never run a pr_event turn: retire
998
+ // the binding rather than leave it listed to drop every future
999
+ // transition (the Harness refusal itself stays — R1-4).
1000
+ if (error.code === 'pr_event_wake_unavailable') {
1001
+ if (!this.running || this.ownershipLost)
1002
+ return;
1003
+ try {
1004
+ await plane.retirePrWatchBinding({
1005
+ owner: pending.owner,
1006
+ repo: pending.repo,
1007
+ prNumber: pending.prNumber,
1008
+ });
1009
+ }
1010
+ catch (retireError) {
1011
+ if (this.isRegistrationRefusal(retireError)) {
1012
+ this.registeredGeneration = 0;
1013
+ return;
1014
+ }
1015
+ this.log(`Managed GitHub could not retire the pump-less PR binding ${pending.key}: ${String(retireError)}.`);
1016
+ }
1017
+ }
1018
+ entry.pending = entry.pending.slice(1);
1019
+ try {
1020
+ this.persist();
1021
+ }
1022
+ catch (persistError) {
1023
+ 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.`);
1024
+ }
1025
+ continue;
1026
+ }
1027
+ // A lost answer or transient refusal: the entry stays pending so
1028
+ // the next tick re-drives the identical event into the control
1029
+ // plane's derived-id idempotency. Isolate the failure to this PR's
1030
+ // queue (break) and keep draining the other bindings — a single
1031
+ // unhealthy Session (e.g. history maintenance answering 503) must
1032
+ // not starve every other bound PR in the channel.
1033
+ this.log(`Managed GitHub PR event ${pending.key} injection failed (${String(error)}); it stays pending for the next tick.`);
1034
+ break;
1035
+ }
1036
+ // Success: record fired and remove pending in one durable write. A
1037
+ // failed write rolls both back so the next tick re-drives the same
1038
+ // event into the idempotent replay — never a half-settled memory.
1039
+ const previousPending = entry.pending;
1040
+ const previousFired = entry.fired;
1041
+ entry.pending = entry.pending.slice(1);
1042
+ entry.fired = [...(entry.fired ?? []), pending.key].slice(-MANAGED_GITHUB_PR_WATCH_FIRED_LIMIT);
1043
+ try {
1044
+ this.persist();
1045
+ }
1046
+ catch (error) {
1047
+ entry.pending = previousPending;
1048
+ entry.fired = previousFired;
1049
+ this.log(`Managed GitHub could not persist the fired PR event ${pending.key}: ${persistErrorText(error)}; it re-drives on the next tick.`);
1050
+ return;
1051
+ }
1052
+ }
1053
+ }
1054
+ }
1055
+ recordDispatched(key) {
1056
+ const state = this.state;
1057
+ if (!state.cursor.dispatchedComments.includes(key)) {
1058
+ state.cursor.dispatchedComments = [
1059
+ ...state.cursor.dispatchedComments,
1060
+ key,
1061
+ ].slice(-DISPATCHED_COMMENTS_LIMIT);
1062
+ }
1063
+ }
1064
+ async submit(eventId, event) {
1065
+ const state = this.state;
1066
+ try {
1067
+ const admitted = await this.controlPlane.submitInbound(event);
1068
+ const wasHeld = state.pending.some((entry) => entry.eventId === eventId && entry.held === true);
1069
+ const previousPending = state.pending;
1070
+ const previousDispatched = state.cursor.dispatchedComments;
1071
+ const previousRefusals = state.instanceRefusals;
1072
+ const previousStalled = this.instanceStalled;
1073
+ state.pending = state.pending.filter((entry) => entry.eventId !== eventId);
1074
+ this.recordDispatched(eventId.slice(GITHUB_EVENT_PREFIX.length));
1075
+ if (!admitted.replayed && wasHeld) {
1076
+ state.instanceRefusals = 0;
1077
+ this.instanceStalled = false;
1078
+ }
1079
+ else {
1080
+ this.liftStallWhenNothingHeld();
1081
+ }
1082
+ try {
1083
+ this.persist();
1084
+ this.loggedSettleFailure = false;
1085
+ }
1086
+ catch (error) {
1087
+ // The admission answer arrived but the settle never reached disk.
1088
+ // Roll back everything the settle touched so the next tick re-drives
1089
+ // the identical event into the idempotent replayed answer; a
1090
+ // half-settled memory state would drop the claim from this process's
1091
+ // re-drive while disk still holds it (the DingTalk discipline).
1092
+ state.pending = previousPending;
1093
+ state.cursor.dispatchedComments = previousDispatched;
1094
+ state.instanceRefusals = previousRefusals;
1095
+ this.instanceStalled = previousStalled;
1096
+ // Latched: the rollback keeps the claim pending, so every tick
1097
+ // re-drives it and an unlatched line would re-log per claim per tick.
1098
+ if (!this.loggedSettleFailure) {
1099
+ this.loggedSettleFailure = true;
1100
+ this.log(`Managed GitHub could not persist the admission of ${eventId}: ${persistErrorText(error)}; it re-drives on the next tick.`);
1101
+ }
1102
+ return;
1103
+ }
1104
+ }
1105
+ catch (error) {
1106
+ const status = error.status;
1107
+ const code = error.code;
1108
+ if (this.isRegistrationRefusal(error)) {
1109
+ this.registeredGeneration = 0;
1110
+ return;
1111
+ }
1112
+ if (typeof status === 'number' &&
1113
+ (status === 400 ||
1114
+ status === 403 ||
1115
+ status === 409 ||
1116
+ (status === 404 && INSTANCE_SCOPED_REFUSALS.has(String(code))))) {
1117
+ if (INSTANCE_SCOPED_REFUSALS.has(String(code))) {
1118
+ state.instanceRefusals = (state.instanceRefusals ?? 0) + 1;
1119
+ const entry = state.pending.find((p) => p.eventId === eventId);
1120
+ if (entry?.held ||
1121
+ state.instanceRefusals > INSTANCE_REFUSAL_DROP_LIMIT) {
1122
+ if (!entry?.held) {
1123
+ state.pending = state.pending.map((p) => p.eventId === eventId ? { ...p, held: true } : p);
1124
+ try {
1125
+ this.persist();
1126
+ }
1127
+ catch (error) {
1128
+ // The hold stays armed in memory for this process; a restart
1129
+ // before the write lands re-arms it after one refusal, which
1130
+ // is the bounded first-occurrence tradeoff, never a loss.
1131
+ this.log(`Managed GitHub could not persist the held claim ${eventId}: ${persistErrorText(error)}; the stall stays armed in memory.`);
1132
+ }
1133
+ }
1134
+ if (!this.instanceStalled) {
1135
+ this.instanceStalled = true;
1136
+ this.log(`Managed GitHub stopped admitting: every comment is refused with ${status} ${String(code)}; check the instance's --workspace and --actor flags.`);
1137
+ }
1138
+ return;
1139
+ }
1140
+ }
1141
+ this.log(`Managed GitHub admission of ${eventId} was refused (${status}); the comment is skipped.`);
1142
+ state.pending = state.pending.filter((p) => p.eventId !== eventId);
1143
+ this.recordDispatched(eventId.slice(GITHUB_EVENT_PREFIX.length));
1144
+ this.liftStallWhenNothingHeld();
1145
+ try {
1146
+ this.persist();
1147
+ }
1148
+ catch (error) {
1149
+ // The drop is already applied in memory; disk keeps the claim, so a
1150
+ // restart re-drives it into the same deterministic refusal and drops
1151
+ // it again. Never abort the batch over the failed write.
1152
+ this.log(`Managed GitHub could not persist the refused admission of ${eventId}: ${persistErrorText(error)}; a restart re-drives it into the same refusal.`);
1153
+ }
1154
+ return;
1155
+ }
1156
+ // A lost answer or a transient refusal: the claim, with its persisted
1157
+ // event, stays in pending so the next tick re-drives the identical
1158
+ // event, never a rebuilt one.
1159
+ }
1160
+ }
1161
+ /**
1162
+ * The stall exists to be lifted by the held claim's probe: when the last
1163
+ * held claim leaves without proving the binding, no probe remains, and a
1164
+ * flag kept armed would gate every later tick. The refusal streak is NOT
1165
+ * reset here: only the held claim's fresh admission proves the binding.
1166
+ */
1167
+ liftStallWhenNothingHeld() {
1168
+ if (this.instanceStalled &&
1169
+ !this.state.pending.some((entry) => entry.held === true)) {
1170
+ this.instanceStalled = false;
1171
+ this.log('Managed GitHub admission resumed; no claim remains held, and the refusal streak still stands for the next instance-scoped refusal.');
1172
+ }
1173
+ }
1174
+ async resubmitPending() {
1175
+ const state = this.state;
1176
+ if (!state)
1177
+ return;
1178
+ // Probe held claims first: the stall lifts only on a held claim's fresh
1179
+ // admission, and push order lets an earlier claim whose answer never
1180
+ // comes shadow the one probe per tick. The sort is stable.
1181
+ const ordered = [...state.pending].sort((a, b) => Number(b.held === true) - Number(a.held === true));
1182
+ for (const entry of ordered) {
1183
+ if (!this.running)
1184
+ return;
1185
+ if (!this.senderAllowed(entry.event.senderId) ||
1186
+ !this.repoAllowed(entry.event.chatId)) {
1187
+ // The policy moved on since the claim: the persisted event drops
1188
+ // visibly rather than drive a Session the current policy forbids.
1189
+ // The repo allowlist gets the same re-check as the sender policy —
1190
+ // a claim staged under a wider filter must not post into a repo the
1191
+ // operator has since excluded.
1192
+ this.log(`Managed GitHub event ${entry.eventId} is refused by the current sender policy or repo allowlist; its claim drops.`);
1193
+ state.pending = state.pending.filter((p) => p.eventId !== entry.eventId);
1194
+ this.recordDispatched(entry.eventId.slice(GITHUB_EVENT_PREFIX.length));
1195
+ this.liftStallWhenNothingHeld();
1196
+ try {
1197
+ this.persist();
1198
+ }
1199
+ catch (error) {
1200
+ // Same shape as the refusal drop: memory applied, disk keeps the
1201
+ // claim, a restart re-drives it into the same policy refusal.
1202
+ this.log(`Managed GitHub could not persist the policy drop of ${entry.eventId}: ${persistErrorText(error)}; a restart re-drives it into the same refusal.`);
1203
+ }
1204
+ continue;
1205
+ }
1206
+ await this.submit(entry.eventId, entry.event);
1207
+ if (this.registeredGeneration === 0 || this.instanceStalled)
1208
+ return;
1209
+ }
1210
+ }
1211
+ isRegistrationRefusal(error) {
1212
+ const status = error.status;
1213
+ const code = error.code;
1214
+ return ((status === 404 && String(code) === CHANNEL_NOT_FOUND) ||
1215
+ (status === 409 &&
1216
+ (code === 'channel_generation_unregistered' ||
1217
+ code === 'channel_disconnected')));
1218
+ }
1219
+ async ensureRegistered(state) {
1220
+ if (this.registeredGeneration === state.generation)
1221
+ return;
1222
+ try {
1223
+ await this.controlPlane.register({
1224
+ platform: 'github',
1225
+ accountId: this.accountId,
1226
+ accountGeneration: state.generation,
1227
+ policy: this.policy,
1228
+ });
1229
+ this.registeredGeneration = state.generation;
1230
+ }
1231
+ catch (error) {
1232
+ this.registeredGeneration = 0;
1233
+ throw error;
1234
+ }
1235
+ }
1236
+ async pullOutbox() {
1237
+ // Guard before the claim, not in the per-delivery loop: the claim itself
1238
+ // moves up to CLAIM_BATCH deliveries to sending server-side, so a stop
1239
+ // that lands mid-tick must not claim a batch it would then abandon.
1240
+ if (!this.running || !this.state)
1241
+ return;
1242
+ let claimed;
1243
+ try {
1244
+ claimed = await this.controlPlane.claimDeliveries(CLAIM_BATCH);
1245
+ }
1246
+ catch (error) {
1247
+ if (this.isRegistrationRefusal(error)) {
1248
+ this.registeredGeneration = 0;
1249
+ return;
1250
+ }
1251
+ throw error;
1252
+ }
1253
+ for (const delivery of claimed) {
1254
+ if (!this.running)
1255
+ return;
1256
+ await this.send(delivery);
1257
+ }
1258
+ }
1259
+ async send(delivery) {
1260
+ const state = this.state;
1261
+ const context = delivery.replyContext;
1262
+ const owner = context?.owner;
1263
+ const repo = context?.repo;
1264
+ const issueNumber = context?.issueNumber;
1265
+ const chatId = typeof owner === 'string' && typeof repo === 'string'
1266
+ ? `${owner}/${repo}`.toLowerCase()
1267
+ : '';
1268
+ if (typeof owner !== 'string' ||
1269
+ !owner ||
1270
+ typeof repo !== 'string' ||
1271
+ !repo ||
1272
+ !Number.isSafeInteger(issueNumber) ||
1273
+ issueNumber < 1 ||
1274
+ // Re-check the current policy before posting, mirroring the DingTalk /
1275
+ // email send-time re-check: a sender or repo the operator has since
1276
+ // excluded must not receive the reply even though it was admitted.
1277
+ !this.senderAllowed(context?.senderId ?? '') ||
1278
+ !this.repoAllowed(chatId)) {
1279
+ // One delivery's unreportable rejection receipt must never abort the
1280
+ // claimed batch: the deliveries behind it were already moved to sending
1281
+ // server-side and would settle unknown (lost) if the tick escaped here.
1282
+ try {
1283
+ await this.controlPlane.receipt(delivery.deliveryId, {
1284
+ outcome: 'rejected',
1285
+ });
1286
+ }
1287
+ catch (error) {
1288
+ if (this.isRegistrationRefusal(error)) {
1289
+ this.registeredGeneration = 0;
1290
+ return;
1291
+ }
1292
+ this.log(`Managed GitHub rejection receipt for ${delivery.deliveryId} could not be reported (${String(error)}); the rest of the batch still sends.`);
1293
+ }
1294
+ return;
1295
+ }
1296
+ for (const segment of delivery.segments) {
1297
+ if (!this.running)
1298
+ return;
1299
+ const previousOutbound = state.outbound;
1300
+ state.outbound = [
1301
+ ...state.outbound,
1302
+ { deliveryId: delivery.deliveryId, ordinal: segment.ordinal },
1303
+ ].slice(-MANAGED_OUTBOUND_LIMIT);
1304
+ try {
1305
+ this.persist();
1306
+ }
1307
+ catch (error) {
1308
+ // The ledger entry is the double-send guard: without it on disk, a
1309
+ // crash after the comment post would re-send on restart. Roll back
1310
+ // and abandon this delivery before the side effect; the lease
1311
+ // reconciler settles it unknown (the DingTalk discipline).
1312
+ state.outbound = previousOutbound;
1313
+ this.log(`Managed GitHub could not persist the outbound ledger for ${delivery.deliveryId}: ${persistErrorText(error)}; the send is abandoned and the lease reconciler settles it.`);
1314
+ return;
1315
+ }
1316
+ let outcome;
1317
+ try {
1318
+ // One ledger segment is one comment: the producer's 48 KiB UTF-8
1319
+ // segment cap is below GitHub's 65,536-character body cap, so no
1320
+ // provider-side chunking exists here.
1321
+ const posted = await this.client.postComment(owner, repo, issueNumber, segment.text);
1322
+ outcome = {
1323
+ outcome: 'accepted',
1324
+ ordinal: segment.ordinal,
1325
+ providerMessageId: String(posted.id),
1326
+ acceptedAt: (this.deps.now ?? Date.now)(),
1327
+ };
1328
+ }
1329
+ catch (error) {
1330
+ const definitive = error.definitive;
1331
+ outcome = definitive ? { outcome: 'rejected' } : { outcome: 'unknown' };
1332
+ }
1333
+ const entry = state.outbound.find((candidate) => candidate.deliveryId === delivery.deliveryId &&
1334
+ candidate.ordinal === segment.ordinal);
1335
+ if (entry)
1336
+ entry.receipt = outcome;
1337
+ try {
1338
+ this.persist();
1339
+ }
1340
+ catch (error) {
1341
+ // The send already happened: report the outcome to the control plane
1342
+ // even if the local write failed — the server-side settle is the
1343
+ // durable record, and the orphan re-drive replays the in-memory
1344
+ // receipt until the local write lands (the DingTalk discipline).
1345
+ this.log(`Managed GitHub could not persist the receipt for ${delivery.deliveryId}: ${persistErrorText(error)}; it is still reported and re-driven locally.`);
1346
+ }
1347
+ try {
1348
+ await this.controlPlane.receipt(delivery.deliveryId, outcome);
1349
+ }
1350
+ catch (error) {
1351
+ // One delivery's unreportable receipt never aborts the claimed
1352
+ // batch: the entry stays outbound with the outcome persisted, so
1353
+ // every later tick re-drives exactly this receipt — never the send.
1354
+ this.log(`Managed GitHub receipt for ${delivery.deliveryId} could not be reported (${String(error)}); it re-drives on the next tick.`);
1355
+ return;
1356
+ }
1357
+ state.outbound = state.outbound.filter((candidate) => !(candidate.deliveryId === delivery.deliveryId &&
1358
+ candidate.ordinal === segment.ordinal));
1359
+ try {
1360
+ this.persist();
1361
+ }
1362
+ catch (error) {
1363
+ // The receipt is already reported; disk keeps the entry, so the next
1364
+ // tick's orphan re-drive replays the receipt and removes it again.
1365
+ this.log(`Managed GitHub could not persist the settled segment of ${delivery.deliveryId}: ${persistErrorText(error)}; the orphan re-drive removes it on the next tick.`);
1366
+ }
1367
+ if (outcome.outcome !== 'accepted')
1368
+ return;
1369
+ }
1370
+ }
1371
+ async reportOrphanedOutbound() {
1372
+ const state = this.state;
1373
+ if (!state)
1374
+ return;
1375
+ for (const entry of [...state.outbound]) {
1376
+ if (!this.running)
1377
+ return;
1378
+ // A segment whose send produced a persisted receipt replays that
1379
+ // receipt — the control plane may already hold it (its answer was
1380
+ // lost) and settles idempotently. Only a segment whose send never
1381
+ // produced an outcome settles unknown.
1382
+ try {
1383
+ await this.controlPlane.receipt(entry.deliveryId, entry.receipt ?? { outcome: 'unknown' });
1384
+ }
1385
+ catch (error) {
1386
+ const status = error.status;
1387
+ const code = error.code;
1388
+ if (this.isRegistrationRefusal(error)) {
1389
+ this.registeredGeneration = 0;
1390
+ this.log(`Managed GitHub receipt for ${entry.deliveryId} was refused as not registered (${String(status)} ${String(code)}); it re-drives after the next tick re-registers.`);
1391
+ return;
1392
+ }
1393
+ // A deterministic refusal never converges on re-drive, and a held
1394
+ // entry runs before every outbox pull: it would stall every later
1395
+ // delivery. Drop it visibly; the lease reconciler records the
1396
+ // delivery unknown.
1397
+ if (!(status === 400 ||
1398
+ status === 403 ||
1399
+ status === 409 ||
1400
+ (status === 404 && code === 'delivery_not_found'))) {
1401
+ throw error;
1402
+ }
1403
+ this.log(`Managed GitHub receipt for ${entry.deliveryId} was refused (${String(status)}); it is dropped.`);
1404
+ }
1405
+ state.outbound = state.outbound.filter((candidate) => candidate !== entry);
1406
+ try {
1407
+ this.persist();
1408
+ }
1409
+ catch (error) {
1410
+ // Disk keeps the entry; the next tick replays the same idempotent
1411
+ // receipt and retries the removal. Never abort the remaining orphans.
1412
+ this.log(`Managed GitHub could not persist the orphan removal of ${entry.deliveryId}: ${persistErrorText(error)}; it re-drives on the next tick.`);
1413
+ }
1414
+ }
1415
+ }
1416
+ persist() {
1417
+ // Once the lock is compromised the state file belongs to another process;
1418
+ // never rewrite it, even from an in-flight tick's post-await persist.
1419
+ if (this.ownershipLost)
1420
+ return;
1421
+ if (this.state)
1422
+ this.store.save(this.state);
1423
+ }
1424
+ stop() {
1425
+ this.running = false;
1426
+ this.abort?.abort();
1427
+ try {
1428
+ this.client?.disconnect();
1429
+ }
1430
+ catch {
1431
+ // The client may already be closed; stopping is best-effort.
1432
+ }
1433
+ }
1434
+ async release() {
1435
+ const releaseLock = this.releaseLock;
1436
+ this.releaseLock = undefined;
1437
+ if (releaseLock)
1438
+ await releaseLock().catch(() => undefined);
1439
+ }
1440
+ }
1441
+ // The store rethrows a fixed sentence (the state file may hold platform data)
1442
+ // but preserves the fs error on `cause`. Log the cause so ENOSPC, EACCES and a
1443
+ // read-only directory are diagnosable instead of hidden behind the sentence.
1444
+ // Mirrors the DingTalk adapter's persistErrorText.
1445
+ function persistErrorText(error) {
1446
+ return String(error.cause ?? error);
1447
+ }
1448
+ // One baseline per PR, lowercased like the Legacy group id so two spellings
1449
+ // of one repository share one watch.
1450
+ function prWatchKey(owner, repo, prNumber) {
1451
+ return `${owner}/${repo}#${prNumber}`.toLowerCase();
1452
+ }
1453
+ // Fail-fast statuses that condemn the WHOLE watch pass, not just one PR: a
1454
+ // bad credential or an exhausted rate budget is shared by every watched PR
1455
+ // (the retired watch's isWatchPassAbortError). A bare permission 403 stays
1456
+ // per-PR so it cannot starve the other watched PRs.
1457
+ function isWatchPassAbort(error) {
1458
+ const status = error.status;
1459
+ return (status === 401 ||
1460
+ status === 429 ||
1461
+ (status === 403 && isRateLimitAnswer(error)));
1462
+ }
1463
+ function fitSubject(title) {
1464
+ if (!title)
1465
+ return null;
1466
+ let bounded = title.slice(0, MAX_SUBJECT_CHARS);
1467
+ if (/[\uD800-\uDBFF]$/.test(bounded))
1468
+ bounded = bounded.slice(0, -1);
1469
+ return bounded;
1470
+ }
1471
+ //# sourceMappingURL=managed-github-adapter.js.map