@qwen-code/channel-github 0.28.0 → 0.28.1-preview.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/managed-github-adapter.d.ts +238 -0
- package/dist/managed-github-adapter.d.ts.map +1 -0
- package/dist/managed-github-adapter.js +1621 -0
- package/dist/managed-github-adapter.js.map +1 -0
- package/dist/managed-github-deps.d.ts +24 -0
- package/dist/managed-github-deps.d.ts.map +1 -0
- package/dist/managed-github-deps.js +365 -0
- package/dist/managed-github-deps.js.map +1 -0
- package/dist/managed-state.d.ts +202 -0
- package/dist/managed-state.d.ts.map +1 -0
- package/dist/managed-state.js +411 -0
- package/dist/managed-state.js.map +1 -0
- package/package.json +6 -3
|
@@ -0,0 +1,1621 @@
|
|
|
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, options.controlPlane.destinationKey ?? '');
|
|
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
|
+
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 ?? {
|
|
329
|
+
version: 1,
|
|
330
|
+
generation: 1,
|
|
331
|
+
cursor: { lastProcessedAt: null, dispatchedComments: [] },
|
|
332
|
+
pending: [],
|
|
333
|
+
outbound: [],
|
|
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
|
+
}
|
|
388
|
+
if (this.state.pending.some((entry) => entry.held)) {
|
|
389
|
+
this.instanceStalled = true;
|
|
390
|
+
this.state.instanceRefusals = Math.max(this.state.instanceRefusals ?? 0, INSTANCE_REFUSAL_DROP_LIMIT + 1);
|
|
391
|
+
}
|
|
392
|
+
this.persist();
|
|
393
|
+
this.abort = new AbortController();
|
|
394
|
+
this.running = true;
|
|
395
|
+
this.loggedNoClaimSlot = false;
|
|
396
|
+
this.registeredGeneration = undefined;
|
|
397
|
+
this.client = await this.deps.createClient(this.settings);
|
|
398
|
+
// The first identity failure must surface: a bad token creates no
|
|
399
|
+
// usable client, and swallowing it would report a healthy start that
|
|
400
|
+
// is permanently deaf. The deps redact the credential from the error.
|
|
401
|
+
this.accountId = await this.client.resolveIdentity();
|
|
402
|
+
if (!this.running)
|
|
403
|
+
throw new Error('Managed GitHub adapter stopped during connection.');
|
|
404
|
+
await this.ensureRegistered(this.state);
|
|
405
|
+
await this.reportOrphanedOutbound();
|
|
406
|
+
// A lock compromise can land during the awaits above. Re-check so
|
|
407
|
+
// connect() rejects rather than resolving a healthy-looking start for
|
|
408
|
+
// a stopped, deaf adapter the CLI would then park on.
|
|
409
|
+
if (!this.running || this.ownershipLost)
|
|
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
|
+
}
|
|
430
|
+
// The first window starts at connect time: no historical backlog.
|
|
431
|
+
this.startedAt = new Date((this.deps.now ?? Date.now)()).toISOString();
|
|
432
|
+
if (this.pollLoop)
|
|
433
|
+
this.loop = this.runLoop();
|
|
434
|
+
}
|
|
435
|
+
catch (error) {
|
|
436
|
+
this.stop();
|
|
437
|
+
await this.release();
|
|
438
|
+
throw error;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
async disconnect() {
|
|
442
|
+
this.stop();
|
|
443
|
+
await this.loop;
|
|
444
|
+
await this.controlPlane.disconnect().catch(() => undefined);
|
|
445
|
+
await this.release();
|
|
446
|
+
}
|
|
447
|
+
/** One admission re-drive, one inbound poll, one outbox pull, one PR watch. */
|
|
448
|
+
async tick() {
|
|
449
|
+
await this.ensureRegistered(this.state);
|
|
450
|
+
await this.resubmitPending();
|
|
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.
|
|
455
|
+
await this.reportOrphanedOutbound();
|
|
456
|
+
await this.pullOutbox();
|
|
457
|
+
await this.watchPrs();
|
|
458
|
+
}
|
|
459
|
+
async runLoop() {
|
|
460
|
+
try {
|
|
461
|
+
while (this.running) {
|
|
462
|
+
try {
|
|
463
|
+
await this.tick();
|
|
464
|
+
}
|
|
465
|
+
catch (error) {
|
|
466
|
+
this.log(`Managed GitHub tick failed: ${String(error)}`);
|
|
467
|
+
}
|
|
468
|
+
if (this.running) {
|
|
469
|
+
const floor = this.client?.pollIntervalFloorMs() ?? 0;
|
|
470
|
+
await delay(Math.max(this.settings.pollInterval, floor), undefined, {
|
|
471
|
+
signal: this.abort.signal,
|
|
472
|
+
}).catch(() => { });
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
finally {
|
|
477
|
+
this.stop();
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
senderAllowed(sender) {
|
|
481
|
+
switch (this.policy.senderPolicy) {
|
|
482
|
+
case 'disabled':
|
|
483
|
+
return false;
|
|
484
|
+
case 'open':
|
|
485
|
+
return true;
|
|
486
|
+
default:
|
|
487
|
+
return this.policy.allowedSenders.includes(sender);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
repoAllowed(chatId) {
|
|
491
|
+
return (!this.settings.repoFilter || this.settings.repoFilter.includes(chatId));
|
|
492
|
+
}
|
|
493
|
+
async pollInbound() {
|
|
494
|
+
const state = this.state;
|
|
495
|
+
if (!this.running || this.instanceStalled || !this.client)
|
|
496
|
+
return;
|
|
497
|
+
if (state.pending.length >= MANAGED_GITHUB_PENDING_LIMIT) {
|
|
498
|
+
if (!this.loggedNoClaimSlot) {
|
|
499
|
+
this.loggedNoClaimSlot = true;
|
|
500
|
+
this.log('Managed GitHub has no durable claim slot; the inbound poll waits for pending admissions to settle.');
|
|
501
|
+
}
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
this.loggedNoClaimSlot = false;
|
|
505
|
+
// The watermark steps back one second because GitHub timestamps are
|
|
506
|
+
// second-granular; the overlap is absorbed by the dispatched ring and,
|
|
507
|
+
// ultimately, by the control plane's platformEventId idempotency.
|
|
508
|
+
const since = state.cursor.lastProcessedAt
|
|
509
|
+
? new Date(Date.parse(state.cursor.lastProcessedAt) - 1000).toISOString()
|
|
510
|
+
: this.startedAt;
|
|
511
|
+
let notifications;
|
|
512
|
+
try {
|
|
513
|
+
notifications = await this.client.listNotifications(since);
|
|
514
|
+
}
|
|
515
|
+
catch (error) {
|
|
516
|
+
// A failed read holds the window; the next poll re-lists it.
|
|
517
|
+
this.log(`Managed GitHub notification poll failed: ${String(error)}`);
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
const kept = notifications.filter((notification) => {
|
|
521
|
+
if (notification.reason !== 'mention')
|
|
522
|
+
return false;
|
|
523
|
+
const type = notification.subject.type;
|
|
524
|
+
if (type !== 'Issue' && type !== 'PullRequest')
|
|
525
|
+
return false;
|
|
526
|
+
const target = extractSubjectUrl(notification.subject.url ?? '');
|
|
527
|
+
return !!target && this.repoAllowed(target.chatId);
|
|
528
|
+
});
|
|
529
|
+
// A thread whose comments cannot be read, whose collection was cut short
|
|
530
|
+
// by the claim cap, or whose mark-read fails freezes the whole window:
|
|
531
|
+
// the watermark advances only on a complete pass, and a thread is marked
|
|
532
|
+
// read only when every comment it produced was fully collected.
|
|
533
|
+
let windowComplete = true;
|
|
534
|
+
const processedThreads = new Set();
|
|
535
|
+
const droppedThreads = new Set();
|
|
536
|
+
for (const notification of kept) {
|
|
537
|
+
if (!this.running)
|
|
538
|
+
return;
|
|
539
|
+
if (state.pending.length >= MANAGED_GITHUB_PENDING_LIMIT)
|
|
540
|
+
break;
|
|
541
|
+
const target = extractSubjectUrl(notification.subject.url ?? '');
|
|
542
|
+
let comments;
|
|
543
|
+
try {
|
|
544
|
+
comments = await this.client.listComments(target.owner, target.repo, target.issueNumber, since);
|
|
545
|
+
}
|
|
546
|
+
catch (error) {
|
|
547
|
+
if (isDefinitiveGithubReadFailure(error)) {
|
|
548
|
+
// Poison escape: a deleted or inaccessible thread answers the same
|
|
549
|
+
// refusal forever; without this it freezes the watermark for the
|
|
550
|
+
// life of the channel. Drop it visibly — its mentions are
|
|
551
|
+
// unrecoverable — and skip its mark-read (which would also fail).
|
|
552
|
+
droppedThreads.add(notification.id);
|
|
553
|
+
this.log(`Managed GitHub drops unreadable thread ${target.chatId}#${target.issueNumber}: ${String(error)}`);
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
windowComplete = false;
|
|
557
|
+
this.log(`Managed GitHub could not read comments for ${target.chatId}#${target.issueNumber}: ${String(error)}`);
|
|
558
|
+
continue;
|
|
559
|
+
}
|
|
560
|
+
let capped = false;
|
|
561
|
+
for (const comment of comments) {
|
|
562
|
+
if (state.pending.length >= MANAGED_GITHUB_PENDING_LIMIT) {
|
|
563
|
+
capped = true;
|
|
564
|
+
break;
|
|
565
|
+
}
|
|
566
|
+
const login = comment.user?.login;
|
|
567
|
+
const body = comment.body;
|
|
568
|
+
if (!login || !body || !body.trim())
|
|
569
|
+
continue;
|
|
570
|
+
if (login.toLowerCase() === this.accountId.toLowerCase())
|
|
571
|
+
continue;
|
|
572
|
+
if (!testBotMention(body, this.accountId))
|
|
573
|
+
continue;
|
|
574
|
+
// node_id is globally unique; the numeric id fallback is only unique
|
|
575
|
+
// per repo, so scope it by thread — two repos' comment #555 must stay
|
|
576
|
+
// two platform events, not one replayed away.
|
|
577
|
+
const key = comment.node_id ??
|
|
578
|
+
`${target.chatId}/${target.threadId}/${comment.id}`;
|
|
579
|
+
const eventId = `${GITHUB_EVENT_PREFIX}${key}`;
|
|
580
|
+
if (state.cursor.dispatchedComments.includes(key) ||
|
|
581
|
+
state.pending.some((entry) => entry.eventId === eventId)) {
|
|
582
|
+
continue;
|
|
583
|
+
}
|
|
584
|
+
const senderId = login.toLowerCase();
|
|
585
|
+
if (!this.senderAllowed(senderId)) {
|
|
586
|
+
this.log(`Managed GitHub sender ${senderId} is not allowed; comment ${key} skipped.`);
|
|
587
|
+
this.recordDispatched(key);
|
|
588
|
+
try {
|
|
589
|
+
this.persist();
|
|
590
|
+
}
|
|
591
|
+
catch (error) {
|
|
592
|
+
// The skip is already applied in memory; disk keeps no claim, so a
|
|
593
|
+
// restart re-lists the comment and skips it again. Never abort the
|
|
594
|
+
// poll over the failed write.
|
|
595
|
+
this.log(`Managed GitHub could not persist the sender skip of ${key}: ${persistErrorText(error)}; a restart re-lists and skips it again.`);
|
|
596
|
+
}
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
const event = {
|
|
600
|
+
accountGeneration: state.generation,
|
|
601
|
+
platformEventId: eventId,
|
|
602
|
+
semanticRevision: 1,
|
|
603
|
+
scope: {
|
|
604
|
+
kind: 'chat_thread',
|
|
605
|
+
senderId: null,
|
|
606
|
+
chatId: target.chatId,
|
|
607
|
+
threadId: target.threadId,
|
|
608
|
+
},
|
|
609
|
+
senderId,
|
|
610
|
+
chatId: target.chatId,
|
|
611
|
+
threadId: target.threadId,
|
|
612
|
+
subject: fitSubject(notification.subject.title),
|
|
613
|
+
text: fitInboundText(body),
|
|
614
|
+
attachments: [],
|
|
615
|
+
replyContext: {
|
|
616
|
+
owner: target.owner,
|
|
617
|
+
repo: target.repo,
|
|
618
|
+
issueNumber: target.issueNumber,
|
|
619
|
+
senderId,
|
|
620
|
+
},
|
|
621
|
+
};
|
|
622
|
+
const previousPending = state.pending;
|
|
623
|
+
state.pending = [
|
|
624
|
+
...state.pending,
|
|
625
|
+
{ eventId, event, notificationThreadId: notification.id },
|
|
626
|
+
].slice(-MANAGED_GITHUB_PENDING_LIMIT);
|
|
627
|
+
try {
|
|
628
|
+
this.persist();
|
|
629
|
+
}
|
|
630
|
+
catch (error) {
|
|
631
|
+
// A failed save must not leave the claim in memory: the dedupe arm
|
|
632
|
+
// would then skip a re-listed comment for a claim the store never
|
|
633
|
+
// accepted. Roll back so the next poll re-stages it.
|
|
634
|
+
state.pending = previousPending;
|
|
635
|
+
throw error;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
// A capped collection leaves comments uncollected: marking this thread
|
|
639
|
+
// read would consume notifications whose mentions were never staged.
|
|
640
|
+
if (!capped)
|
|
641
|
+
processedThreads.add(notification.id);
|
|
642
|
+
}
|
|
643
|
+
await this.resubmitPending();
|
|
644
|
+
// Mark a thread read only after every event it produced has left pending
|
|
645
|
+
// (admitted, replayed or visibly dropped). A thread still holding a claim
|
|
646
|
+
// keeps the window frozen so the next poll re-drives it.
|
|
647
|
+
const heldThreads = new Set(state.pending.map((entry) => entry.notificationThreadId));
|
|
648
|
+
for (const notification of kept) {
|
|
649
|
+
if (!this.running)
|
|
650
|
+
return;
|
|
651
|
+
if (droppedThreads.has(notification.id))
|
|
652
|
+
continue;
|
|
653
|
+
if (!processedThreads.has(notification.id)) {
|
|
654
|
+
windowComplete = false;
|
|
655
|
+
continue;
|
|
656
|
+
}
|
|
657
|
+
if (heldThreads.has(notification.id)) {
|
|
658
|
+
windowComplete = false;
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
try {
|
|
662
|
+
await this.client.markThreadRead(notification.id);
|
|
663
|
+
}
|
|
664
|
+
catch (error) {
|
|
665
|
+
windowComplete = false;
|
|
666
|
+
this.log(`Managed GitHub could not mark notification ${notification.id} read: ${String(error)}; the window holds.`);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
if (windowComplete && notifications.length > 0) {
|
|
670
|
+
let watermark = state.cursor.lastProcessedAt;
|
|
671
|
+
// The outer windowComplete was already evaluated to enter this block;
|
|
672
|
+
// a local flag is what actually gates the persist below.
|
|
673
|
+
let unparseable = false;
|
|
674
|
+
for (const notification of notifications) {
|
|
675
|
+
const updated = Date.parse(notification.updated_at);
|
|
676
|
+
if (Number.isNaN(updated)) {
|
|
677
|
+
// Persisting an unparseable watermark would throw RangeError on
|
|
678
|
+
// every later tick's since computation and fail load() on restart.
|
|
679
|
+
// Hold the window instead; outbound keeps moving.
|
|
680
|
+
unparseable = true;
|
|
681
|
+
this.log(`Managed GitHub notification ${notification.id} has an unparseable updated_at; the window holds.`);
|
|
682
|
+
continue;
|
|
683
|
+
}
|
|
684
|
+
if (!watermark || updated > Date.parse(watermark)) {
|
|
685
|
+
watermark = notification.updated_at;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
if (!unparseable &&
|
|
689
|
+
watermark &&
|
|
690
|
+
watermark !== state.cursor.lastProcessedAt) {
|
|
691
|
+
state.cursor.lastProcessedAt = watermark;
|
|
692
|
+
this.persist();
|
|
693
|
+
}
|
|
694
|
+
}
|
|
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
|
+
}
|
|
1205
|
+
recordDispatched(key) {
|
|
1206
|
+
const state = this.state;
|
|
1207
|
+
if (!state.cursor.dispatchedComments.includes(key)) {
|
|
1208
|
+
state.cursor.dispatchedComments = [
|
|
1209
|
+
...state.cursor.dispatchedComments,
|
|
1210
|
+
key,
|
|
1211
|
+
].slice(-DISPATCHED_COMMENTS_LIMIT);
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
async submit(eventId, event) {
|
|
1215
|
+
const state = this.state;
|
|
1216
|
+
try {
|
|
1217
|
+
const admitted = await this.controlPlane.submitInbound(event);
|
|
1218
|
+
const wasHeld = state.pending.some((entry) => entry.eventId === eventId && entry.held === true);
|
|
1219
|
+
const previousPending = state.pending;
|
|
1220
|
+
const previousDispatched = state.cursor.dispatchedComments;
|
|
1221
|
+
const previousRefusals = state.instanceRefusals;
|
|
1222
|
+
const previousStalled = this.instanceStalled;
|
|
1223
|
+
state.pending = state.pending.filter((entry) => entry.eventId !== eventId);
|
|
1224
|
+
this.recordDispatched(eventId.slice(GITHUB_EVENT_PREFIX.length));
|
|
1225
|
+
if (!admitted.replayed && wasHeld) {
|
|
1226
|
+
state.instanceRefusals = 0;
|
|
1227
|
+
this.instanceStalled = false;
|
|
1228
|
+
}
|
|
1229
|
+
else {
|
|
1230
|
+
this.liftStallWhenNothingHeld();
|
|
1231
|
+
}
|
|
1232
|
+
try {
|
|
1233
|
+
this.persist();
|
|
1234
|
+
this.loggedSettleFailure = false;
|
|
1235
|
+
}
|
|
1236
|
+
catch (error) {
|
|
1237
|
+
// The admission answer arrived but the settle never reached disk.
|
|
1238
|
+
// Roll back everything the settle touched so the next tick re-drives
|
|
1239
|
+
// the identical event into the idempotent replayed answer; a
|
|
1240
|
+
// half-settled memory state would drop the claim from this process's
|
|
1241
|
+
// re-drive while disk still holds it (the DingTalk discipline).
|
|
1242
|
+
state.pending = previousPending;
|
|
1243
|
+
state.cursor.dispatchedComments = previousDispatched;
|
|
1244
|
+
state.instanceRefusals = previousRefusals;
|
|
1245
|
+
this.instanceStalled = previousStalled;
|
|
1246
|
+
// Latched: the rollback keeps the claim pending, so every tick
|
|
1247
|
+
// re-drives it and an unlatched line would re-log per claim per tick.
|
|
1248
|
+
if (!this.loggedSettleFailure) {
|
|
1249
|
+
this.loggedSettleFailure = true;
|
|
1250
|
+
this.log(`Managed GitHub could not persist the admission of ${eventId}: ${persistErrorText(error)}; it re-drives on the next tick.`);
|
|
1251
|
+
}
|
|
1252
|
+
return;
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
catch (error) {
|
|
1256
|
+
const status = error.status;
|
|
1257
|
+
const code = error.code;
|
|
1258
|
+
if (this.isRegistrationRefusal(error)) {
|
|
1259
|
+
this.registeredGeneration = 0;
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
if (typeof status === 'number' &&
|
|
1263
|
+
(status === 400 ||
|
|
1264
|
+
status === 403 ||
|
|
1265
|
+
status === 409 ||
|
|
1266
|
+
(status === 404 && INSTANCE_SCOPED_REFUSALS.has(String(code))))) {
|
|
1267
|
+
if (INSTANCE_SCOPED_REFUSALS.has(String(code))) {
|
|
1268
|
+
state.instanceRefusals = (state.instanceRefusals ?? 0) + 1;
|
|
1269
|
+
const entry = state.pending.find((p) => p.eventId === eventId);
|
|
1270
|
+
if (entry?.held ||
|
|
1271
|
+
state.instanceRefusals > INSTANCE_REFUSAL_DROP_LIMIT) {
|
|
1272
|
+
if (!entry?.held) {
|
|
1273
|
+
state.pending = state.pending.map((p) => p.eventId === eventId ? { ...p, held: true } : p);
|
|
1274
|
+
try {
|
|
1275
|
+
this.persist();
|
|
1276
|
+
}
|
|
1277
|
+
catch (error) {
|
|
1278
|
+
// The hold stays armed in memory for this process; a restart
|
|
1279
|
+
// before the write lands re-arms it after one refusal, which
|
|
1280
|
+
// is the bounded first-occurrence tradeoff, never a loss.
|
|
1281
|
+
this.log(`Managed GitHub could not persist the held claim ${eventId}: ${persistErrorText(error)}; the stall stays armed in memory.`);
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
if (!this.instanceStalled) {
|
|
1285
|
+
this.instanceStalled = true;
|
|
1286
|
+
this.log(`Managed GitHub stopped admitting: every comment is refused with ${status} ${String(code)}; check the instance's --workspace and --actor flags.`);
|
|
1287
|
+
}
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
this.log(`Managed GitHub admission of ${eventId} was refused (${status}); the comment is skipped.`);
|
|
1292
|
+
state.pending = state.pending.filter((p) => p.eventId !== eventId);
|
|
1293
|
+
this.recordDispatched(eventId.slice(GITHUB_EVENT_PREFIX.length));
|
|
1294
|
+
this.liftStallWhenNothingHeld();
|
|
1295
|
+
try {
|
|
1296
|
+
this.persist();
|
|
1297
|
+
}
|
|
1298
|
+
catch (error) {
|
|
1299
|
+
// The drop is already applied in memory; disk keeps the claim, so a
|
|
1300
|
+
// restart re-drives it into the same deterministic refusal and drops
|
|
1301
|
+
// it again. Never abort the batch over the failed write.
|
|
1302
|
+
this.log(`Managed GitHub could not persist the refused admission of ${eventId}: ${persistErrorText(error)}; a restart re-drives it into the same refusal.`);
|
|
1303
|
+
}
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
// A lost answer or a transient refusal: the claim, with its persisted
|
|
1307
|
+
// event, stays in pending so the next tick re-drives the identical
|
|
1308
|
+
// event, never a rebuilt one.
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* The stall exists to be lifted by the held claim's probe: when the last
|
|
1313
|
+
* held claim leaves without proving the binding, no probe remains, and a
|
|
1314
|
+
* flag kept armed would gate every later tick. The refusal streak is NOT
|
|
1315
|
+
* reset here: only the held claim's fresh admission proves the binding.
|
|
1316
|
+
*/
|
|
1317
|
+
liftStallWhenNothingHeld() {
|
|
1318
|
+
if (this.instanceStalled &&
|
|
1319
|
+
!this.state.pending.some((entry) => entry.held === true)) {
|
|
1320
|
+
this.instanceStalled = false;
|
|
1321
|
+
this.log('Managed GitHub admission resumed; no claim remains held, and the refusal streak still stands for the next instance-scoped refusal.');
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
async resubmitPending() {
|
|
1325
|
+
const state = this.state;
|
|
1326
|
+
if (!state)
|
|
1327
|
+
return;
|
|
1328
|
+
// Probe held claims first: the stall lifts only on a held claim's fresh
|
|
1329
|
+
// admission, and push order lets an earlier claim whose answer never
|
|
1330
|
+
// comes shadow the one probe per tick. The sort is stable.
|
|
1331
|
+
const ordered = [...state.pending].sort((a, b) => Number(b.held === true) - Number(a.held === true));
|
|
1332
|
+
for (const entry of ordered) {
|
|
1333
|
+
if (!this.running)
|
|
1334
|
+
return;
|
|
1335
|
+
if (!this.senderAllowed(entry.event.senderId) ||
|
|
1336
|
+
!this.repoAllowed(entry.event.chatId)) {
|
|
1337
|
+
// The policy moved on since the claim: the persisted event drops
|
|
1338
|
+
// visibly rather than drive a Session the current policy forbids.
|
|
1339
|
+
// The repo allowlist gets the same re-check as the sender policy —
|
|
1340
|
+
// a claim staged under a wider filter must not post into a repo the
|
|
1341
|
+
// operator has since excluded.
|
|
1342
|
+
this.log(`Managed GitHub event ${entry.eventId} is refused by the current sender policy or repo allowlist; its claim drops.`);
|
|
1343
|
+
state.pending = state.pending.filter((p) => p.eventId !== entry.eventId);
|
|
1344
|
+
this.recordDispatched(entry.eventId.slice(GITHUB_EVENT_PREFIX.length));
|
|
1345
|
+
this.liftStallWhenNothingHeld();
|
|
1346
|
+
try {
|
|
1347
|
+
this.persist();
|
|
1348
|
+
}
|
|
1349
|
+
catch (error) {
|
|
1350
|
+
// Same shape as the refusal drop: memory applied, disk keeps the
|
|
1351
|
+
// claim, a restart re-drives it into the same policy refusal.
|
|
1352
|
+
this.log(`Managed GitHub could not persist the policy drop of ${entry.eventId}: ${persistErrorText(error)}; a restart re-drives it into the same refusal.`);
|
|
1353
|
+
}
|
|
1354
|
+
continue;
|
|
1355
|
+
}
|
|
1356
|
+
await this.submit(entry.eventId, entry.event);
|
|
1357
|
+
if (this.registeredGeneration === 0 || this.instanceStalled)
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
isRegistrationRefusal(error) {
|
|
1362
|
+
const status = error.status;
|
|
1363
|
+
const code = error.code;
|
|
1364
|
+
return ((status === 404 && String(code) === CHANNEL_NOT_FOUND) ||
|
|
1365
|
+
(status === 409 &&
|
|
1366
|
+
(code === 'channel_generation_unregistered' ||
|
|
1367
|
+
code === 'channel_disconnected')));
|
|
1368
|
+
}
|
|
1369
|
+
async ensureRegistered(state) {
|
|
1370
|
+
if (this.registeredGeneration === state.generation)
|
|
1371
|
+
return;
|
|
1372
|
+
try {
|
|
1373
|
+
await this.controlPlane.register({
|
|
1374
|
+
platform: 'github',
|
|
1375
|
+
accountId: this.accountId,
|
|
1376
|
+
accountGeneration: state.generation,
|
|
1377
|
+
policy: this.policy,
|
|
1378
|
+
});
|
|
1379
|
+
this.registeredGeneration = state.generation;
|
|
1380
|
+
}
|
|
1381
|
+
catch (error) {
|
|
1382
|
+
this.registeredGeneration = 0;
|
|
1383
|
+
throw error;
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
async pullOutbox() {
|
|
1387
|
+
// Guard before the claim, not in the per-delivery loop: the claim itself
|
|
1388
|
+
// moves up to CLAIM_BATCH deliveries to sending server-side, so a stop
|
|
1389
|
+
// that lands mid-tick must not claim a batch it would then abandon.
|
|
1390
|
+
if (!this.running || !this.state)
|
|
1391
|
+
return;
|
|
1392
|
+
let claimed;
|
|
1393
|
+
try {
|
|
1394
|
+
claimed = await this.controlPlane.claimDeliveries(CLAIM_BATCH);
|
|
1395
|
+
}
|
|
1396
|
+
catch (error) {
|
|
1397
|
+
if (this.isRegistrationRefusal(error)) {
|
|
1398
|
+
this.registeredGeneration = 0;
|
|
1399
|
+
return;
|
|
1400
|
+
}
|
|
1401
|
+
throw error;
|
|
1402
|
+
}
|
|
1403
|
+
for (const delivery of claimed) {
|
|
1404
|
+
if (!this.running)
|
|
1405
|
+
return;
|
|
1406
|
+
await this.send(delivery);
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
async send(delivery) {
|
|
1410
|
+
const state = this.state;
|
|
1411
|
+
const context = delivery.replyContext;
|
|
1412
|
+
const owner = context?.owner;
|
|
1413
|
+
const repo = context?.repo;
|
|
1414
|
+
const issueNumber = context?.issueNumber;
|
|
1415
|
+
const chatId = typeof owner === 'string' && typeof repo === 'string'
|
|
1416
|
+
? `${owner}/${repo}`.toLowerCase()
|
|
1417
|
+
: '';
|
|
1418
|
+
if (typeof owner !== 'string' ||
|
|
1419
|
+
!owner ||
|
|
1420
|
+
typeof repo !== 'string' ||
|
|
1421
|
+
!repo ||
|
|
1422
|
+
!Number.isSafeInteger(issueNumber) ||
|
|
1423
|
+
issueNumber < 1 ||
|
|
1424
|
+
// Re-check the current policy before posting, mirroring the DingTalk /
|
|
1425
|
+
// email send-time re-check: a sender or repo the operator has since
|
|
1426
|
+
// excluded must not receive the reply even though it was admitted.
|
|
1427
|
+
!this.senderAllowed(context?.senderId ?? '') ||
|
|
1428
|
+
!this.repoAllowed(chatId)) {
|
|
1429
|
+
// One delivery's unreportable rejection receipt must never abort the
|
|
1430
|
+
// claimed batch: the deliveries behind it were already moved to sending
|
|
1431
|
+
// server-side and would settle unknown (lost) if the tick escaped here.
|
|
1432
|
+
try {
|
|
1433
|
+
await this.controlPlane.receipt(delivery.deliveryId, {
|
|
1434
|
+
outcome: 'rejected',
|
|
1435
|
+
});
|
|
1436
|
+
}
|
|
1437
|
+
catch (error) {
|
|
1438
|
+
if (this.isRegistrationRefusal(error)) {
|
|
1439
|
+
this.registeredGeneration = 0;
|
|
1440
|
+
return;
|
|
1441
|
+
}
|
|
1442
|
+
this.log(`Managed GitHub rejection receipt for ${delivery.deliveryId} could not be reported (${String(error)}); the rest of the batch still sends.`);
|
|
1443
|
+
}
|
|
1444
|
+
return;
|
|
1445
|
+
}
|
|
1446
|
+
for (const segment of delivery.segments) {
|
|
1447
|
+
if (!this.running)
|
|
1448
|
+
return;
|
|
1449
|
+
const previousOutbound = state.outbound;
|
|
1450
|
+
state.outbound = [
|
|
1451
|
+
...state.outbound,
|
|
1452
|
+
{ deliveryId: delivery.deliveryId, ordinal: segment.ordinal },
|
|
1453
|
+
].slice(-MANAGED_OUTBOUND_LIMIT);
|
|
1454
|
+
try {
|
|
1455
|
+
this.persist();
|
|
1456
|
+
}
|
|
1457
|
+
catch (error) {
|
|
1458
|
+
// The ledger entry is the double-send guard: without it on disk, a
|
|
1459
|
+
// crash after the comment post would re-send on restart. Roll back
|
|
1460
|
+
// and abandon this delivery before the side effect; the lease
|
|
1461
|
+
// reconciler settles it unknown (the DingTalk discipline).
|
|
1462
|
+
state.outbound = previousOutbound;
|
|
1463
|
+
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.`);
|
|
1464
|
+
return;
|
|
1465
|
+
}
|
|
1466
|
+
let outcome;
|
|
1467
|
+
try {
|
|
1468
|
+
// One ledger segment is one comment: the producer's 48 KiB UTF-8
|
|
1469
|
+
// segment cap is below GitHub's 65,536-character body cap, so no
|
|
1470
|
+
// provider-side chunking exists here.
|
|
1471
|
+
const posted = await this.client.postComment(owner, repo, issueNumber, segment.text);
|
|
1472
|
+
outcome = {
|
|
1473
|
+
outcome: 'accepted',
|
|
1474
|
+
ordinal: segment.ordinal,
|
|
1475
|
+
providerMessageId: String(posted.id),
|
|
1476
|
+
acceptedAt: (this.deps.now ?? Date.now)(),
|
|
1477
|
+
};
|
|
1478
|
+
}
|
|
1479
|
+
catch (error) {
|
|
1480
|
+
const definitive = error.definitive;
|
|
1481
|
+
outcome = definitive ? { outcome: 'rejected' } : { outcome: 'unknown' };
|
|
1482
|
+
}
|
|
1483
|
+
const entry = state.outbound.find((candidate) => candidate.deliveryId === delivery.deliveryId &&
|
|
1484
|
+
candidate.ordinal === segment.ordinal);
|
|
1485
|
+
if (entry)
|
|
1486
|
+
entry.receipt = outcome;
|
|
1487
|
+
try {
|
|
1488
|
+
this.persist();
|
|
1489
|
+
}
|
|
1490
|
+
catch (error) {
|
|
1491
|
+
// The send already happened: report the outcome to the control plane
|
|
1492
|
+
// even if the local write failed — the server-side settle is the
|
|
1493
|
+
// durable record, and the orphan re-drive replays the in-memory
|
|
1494
|
+
// receipt until the local write lands (the DingTalk discipline).
|
|
1495
|
+
this.log(`Managed GitHub could not persist the receipt for ${delivery.deliveryId}: ${persistErrorText(error)}; it is still reported and re-driven locally.`);
|
|
1496
|
+
}
|
|
1497
|
+
try {
|
|
1498
|
+
await this.controlPlane.receipt(delivery.deliveryId, outcome);
|
|
1499
|
+
}
|
|
1500
|
+
catch (error) {
|
|
1501
|
+
// One delivery's unreportable receipt never aborts the claimed
|
|
1502
|
+
// batch: the entry stays outbound with the outcome persisted, so
|
|
1503
|
+
// every later tick re-drives exactly this receipt — never the send.
|
|
1504
|
+
this.log(`Managed GitHub receipt for ${delivery.deliveryId} could not be reported (${String(error)}); it re-drives on the next tick.`);
|
|
1505
|
+
return;
|
|
1506
|
+
}
|
|
1507
|
+
state.outbound = state.outbound.filter((candidate) => !(candidate.deliveryId === delivery.deliveryId &&
|
|
1508
|
+
candidate.ordinal === segment.ordinal));
|
|
1509
|
+
try {
|
|
1510
|
+
this.persist();
|
|
1511
|
+
}
|
|
1512
|
+
catch (error) {
|
|
1513
|
+
// The receipt is already reported; disk keeps the entry, so the next
|
|
1514
|
+
// tick's orphan re-drive replays the receipt and removes it again.
|
|
1515
|
+
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.`);
|
|
1516
|
+
}
|
|
1517
|
+
if (outcome.outcome !== 'accepted')
|
|
1518
|
+
return;
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
async reportOrphanedOutbound() {
|
|
1522
|
+
const state = this.state;
|
|
1523
|
+
if (!state)
|
|
1524
|
+
return;
|
|
1525
|
+
for (const entry of [...state.outbound]) {
|
|
1526
|
+
if (!this.running)
|
|
1527
|
+
return;
|
|
1528
|
+
// A segment whose send produced a persisted receipt replays that
|
|
1529
|
+
// receipt — the control plane may already hold it (its answer was
|
|
1530
|
+
// lost) and settles idempotently. Only a segment whose send never
|
|
1531
|
+
// produced an outcome settles unknown.
|
|
1532
|
+
try {
|
|
1533
|
+
await this.controlPlane.receipt(entry.deliveryId, entry.receipt ?? { outcome: 'unknown' });
|
|
1534
|
+
}
|
|
1535
|
+
catch (error) {
|
|
1536
|
+
const status = error.status;
|
|
1537
|
+
const code = error.code;
|
|
1538
|
+
if (this.isRegistrationRefusal(error)) {
|
|
1539
|
+
this.registeredGeneration = 0;
|
|
1540
|
+
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.`);
|
|
1541
|
+
return;
|
|
1542
|
+
}
|
|
1543
|
+
// A deterministic refusal never converges on re-drive, and a held
|
|
1544
|
+
// entry runs before every outbox pull: it would stall every later
|
|
1545
|
+
// delivery. Drop it visibly; the lease reconciler records the
|
|
1546
|
+
// delivery unknown.
|
|
1547
|
+
if (!(status === 400 ||
|
|
1548
|
+
status === 403 ||
|
|
1549
|
+
status === 409 ||
|
|
1550
|
+
(status === 404 && code === 'delivery_not_found'))) {
|
|
1551
|
+
throw error;
|
|
1552
|
+
}
|
|
1553
|
+
this.log(`Managed GitHub receipt for ${entry.deliveryId} was refused (${String(status)}); it is dropped.`);
|
|
1554
|
+
}
|
|
1555
|
+
state.outbound = state.outbound.filter((candidate) => candidate !== entry);
|
|
1556
|
+
try {
|
|
1557
|
+
this.persist();
|
|
1558
|
+
}
|
|
1559
|
+
catch (error) {
|
|
1560
|
+
// Disk keeps the entry; the next tick replays the same idempotent
|
|
1561
|
+
// receipt and retries the removal. Never abort the remaining orphans.
|
|
1562
|
+
this.log(`Managed GitHub could not persist the orphan removal of ${entry.deliveryId}: ${persistErrorText(error)}; it re-drives on the next tick.`);
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
persist() {
|
|
1567
|
+
// Once the lock is compromised the state file belongs to another process;
|
|
1568
|
+
// never rewrite it, even from an in-flight tick's post-await persist.
|
|
1569
|
+
if (this.ownershipLost)
|
|
1570
|
+
return;
|
|
1571
|
+
if (this.state)
|
|
1572
|
+
this.store.save(this.state);
|
|
1573
|
+
}
|
|
1574
|
+
stop() {
|
|
1575
|
+
this.running = false;
|
|
1576
|
+
this.abort?.abort();
|
|
1577
|
+
try {
|
|
1578
|
+
this.client?.disconnect();
|
|
1579
|
+
}
|
|
1580
|
+
catch {
|
|
1581
|
+
// The client may already be closed; stopping is best-effort.
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
async release() {
|
|
1585
|
+
const releaseLock = this.releaseLock;
|
|
1586
|
+
this.releaseLock = undefined;
|
|
1587
|
+
if (releaseLock)
|
|
1588
|
+
await releaseLock().catch(() => undefined);
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
// The store rethrows a fixed sentence (the state file may hold platform data)
|
|
1592
|
+
// but preserves the fs error on `cause`. Log the cause so ENOSPC, EACCES and a
|
|
1593
|
+
// read-only directory are diagnosable instead of hidden behind the sentence.
|
|
1594
|
+
// Mirrors the DingTalk adapter's persistErrorText.
|
|
1595
|
+
function persistErrorText(error) {
|
|
1596
|
+
return String(error.cause ?? error);
|
|
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
|
+
}
|
|
1613
|
+
function fitSubject(title) {
|
|
1614
|
+
if (!title)
|
|
1615
|
+
return null;
|
|
1616
|
+
let bounded = title.slice(0, MAX_SUBJECT_CHARS);
|
|
1617
|
+
if (/[\uD800-\uDBFF]$/.test(bounded))
|
|
1618
|
+
bounded = bounded.slice(0, -1);
|
|
1619
|
+
return bounded;
|
|
1620
|
+
}
|
|
1621
|
+
//# sourceMappingURL=managed-github-adapter.js.map
|