@hearsay-tools/squawk 0.18.0-dev.8291 → 0.18.0-dev.8304

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.
Files changed (64) hide show
  1. package/dist/runners/antigravity/acp/events.d.ts +1 -1
  2. package/dist/runners/antigravity/acp/events.js +1 -1
  3. package/dist/runners/antigravity/acp/events.js.map +1 -1
  4. package/dist/runners/antigravity/acp/protocol.d.ts +1 -2
  5. package/dist/runners/antigravity/acp/protocol.js +1 -1
  6. package/dist/runners/antigravity/acp/protocol.js.map +1 -1
  7. package/dist/runners/antigravity/acp/session.d.ts +1 -1
  8. package/dist/runners/antigravity/acp/session.js +1 -1
  9. package/dist/runners/antigravity/acp/session.js.map +1 -1
  10. package/dist/runners/antigravity/acp/transport.d.ts +1 -1
  11. package/dist/runners/antigravity/acp/transport.js +1 -1
  12. package/dist/runners/antigravity/acp/transport.js.map +1 -1
  13. package/dist/runners/antigravity/antigravity-model-catalog.js +2 -4
  14. package/dist/runners/antigravity/antigravity-model-catalog.js.map +1 -1
  15. package/dist/runners/antigravity/antigravity-runner.js +3 -2
  16. package/dist/runners/antigravity/antigravity-runner.js.map +1 -1
  17. package/dist/runners/antigravity/antigravity-session.js +1 -2
  18. package/dist/runners/antigravity/antigravity-session.js.map +1 -1
  19. package/dist/runners/antigravity/antigravity-skill-catalog.js +4 -5
  20. package/dist/runners/antigravity/antigravity-skill-catalog.js.map +1 -1
  21. package/dist/runners/antigravity/antigravity-ui-mapper.d.ts +1 -1
  22. package/dist/runners/antigravity/antigravity-ui-mapper.js +1 -1
  23. package/dist/runners/antigravity/antigravity-ui-mapper.js.map +1 -1
  24. package/dist/runners/antigravity/ask-question.d.ts +1 -1
  25. package/dist/runners/antigravity/ask-question.js +1 -1
  26. package/dist/runners/antigravity/ask-question.js.map +1 -1
  27. package/dist/runners/antigravity/client-files.d.ts +1 -1
  28. package/dist/runners/antigravity/client-files.js +1 -1
  29. package/dist/runners/antigravity/client-files.js.map +1 -1
  30. package/dist/runners/antigravity/http-mcp.d.ts +1 -1
  31. package/dist/runners/antigravity/http-mcp.js +1 -1
  32. package/dist/runners/antigravity/http-mcp.js.map +1 -1
  33. package/dist/runners/antigravity/permissions.d.ts +1 -1
  34. package/dist/runners/antigravity/permissions.js +1 -1
  35. package/dist/runners/antigravity/permissions.js.map +1 -1
  36. package/dist/runners/antigravity/tool-normalization.d.ts +1 -1
  37. package/dist/runners/antigravity/tool-normalization.js +1 -1
  38. package/dist/runners/antigravity/tool-normalization.js.map +1 -1
  39. package/dist/runners/antigravity/tool-transcript.d.ts +1 -2
  40. package/dist/runners/antigravity/tool-transcript.js +1 -1
  41. package/dist/runners/antigravity/tool-transcript.js.map +1 -1
  42. package/dist/runners/antigravity/usage.d.ts +1 -1
  43. package/dist/runners/antigravity/usage.js +1 -1
  44. package/dist/runners/antigravity/usage.js.map +1 -1
  45. package/dist/runners/antigravity/wire-updates.js +1 -1
  46. package/dist/runners/antigravity/wire-updates.js.map +1 -1
  47. package/dist/server/forge/github-comments.d.ts +25 -0
  48. package/dist/server/forge/github-comments.js +486 -0
  49. package/dist/server/forge/github-comments.js.map +1 -0
  50. package/dist/server/forge/github-mutations.d.ts +19 -0
  51. package/dist/server/forge/github-mutations.js +295 -0
  52. package/dist/server/forge/github-mutations.js.map +1 -0
  53. package/dist/server/forge/github-ref-status-derive.d.ts +54 -0
  54. package/dist/server/forge/github-ref-status-derive.js +202 -0
  55. package/dist/server/forge/github-ref-status-derive.js.map +1 -0
  56. package/dist/server/forge/github-ref-status.d.ts +23 -0
  57. package/dist/server/forge/github-ref-status.js +224 -0
  58. package/dist/server/forge/github-ref-status.js.map +1 -0
  59. package/dist/server/forge/github.d.ts +9 -196
  60. package/dist/server/forge/github.js +20 -1454
  61. package/dist/server/forge/github.js.map +1 -1
  62. package/dist/server/provider-sign-in-routes.d.ts +2 -2
  63. package/dist/server/server.d.ts +4 -4
  64. package/package.json +4 -4
@@ -1,1412 +1,38 @@
1
+ import { refNumberFromUrl } from '../../contract/index.js';
1
2
  import { productEnv } from '../../core/product-env.js';
3
+ import { mergedPullRequestObservations } from '../../merge-observations.js';
2
4
  import { createDraftPr } from './draft-pr.js';
5
+ import { gh } from './github-cli.js';
6
+ import { canonicalRepoRef, discoverRepoHandle, resolveRepoHandle } from './github-repo-handle.js';
7
+ import { fetchGithubChecks } from './github-checks.js';
8
+ import { fetchGithubCommentCounts, fetchGithubComments, fetchGithubItem, forgetGithubItem } from './github-comments.js';
9
+ import { fetchGithub, fetchGithubProjects, searchGithubItems, viewGithubItem } from './github-list.js';
10
+ import { fetchPrMergeState, lookupMergedPullRequests, mergePullRequest, readyPullRequest } from './github-mutations.js';
11
+ import { fetchGithubPrDiff } from './github-pr-diff.js';
12
+ import { fetchGithubRefStatus, forgetRefStatus, readCachedRefStatuses } from './github-ref-status.js';
13
+ import { detectGithub, detectGithubCached, ghPrViewSchema, rollupToChecks, } from './github-shared.js';
3
14
  export { createDraftPr, buildPrBody } from './draft-pr.js';
4
- import { defined } from '../../core/defined.js';
5
- import { activeWorkflowRunsArgs, parseActiveWorkflowRuns } from '../../ci-wait/github.js';
6
- import { pullRequestKey } from '../../runs/pull-requests.js';
7
- import { matchesGithubPullRequest, mergedPullRequestObservations } from '../../merge-observations.js';
8
- import { z } from 'zod';
9
- import { githubRequestGate } from './github-request-gate.js';
10
- import { refStatusQuery } from './github-ref-status-query.js';
11
- import { mergedPullRequestChunk } from './github-merged-pr-chunk.js';
12
- import { reviewerKey, reviewerRefSchema } from './github-reviewer-ref.js';
13
- import { gh, githubContext } from './github-cli.js';
14
- import { canonicalRepoRef, discoverRepoHandle, forgetRepoHandle, resolveRepoHandle } from './github-repo-handle.js';
15
15
  export { parseOwnerName } from './github-cli.js';
16
16
  export { __clearRepoHandleCacheForTests, discoverRepoHandle, forgetRepoHandle, resolveRepoHandle } from './github-repo-handle.js';
17
- import { GITHUB_COMMENT_COUNTS_MAX, REFERENCE_STATUS_MAX } from '../../contract/index.js';
18
- import { fetchGithubMergeRequirements } from './github-merge-requirements.js';
19
- import { mergePrSchema, normalizeMergeState } from './github-merge-state.js';
20
- import { fetchTimelinePages, normalizeEvents, TIMELINE_PER_PAGE } from './github-timeline.js';
21
17
  export { normalizeMergeState } from './github-merge-state.js';
22
18
  export { fetchTimelinePages, ghTimelineEventSchema, normalizeEvents, TIMELINE_BUDGET_MS, TIMELINE_EVENT_CAP, TIMELINE_EVENT_KINDS, TIMELINE_MAX_PAGES, TIMELINE_MIN_PAGE_MS, } from './github-timeline.js';
23
- import { refNumberFromUrl } from '../../contract/index.js';
24
- import { CACHE_MS, detectGithub, detectGithubCached, firstLine, ghFailureReason, ghGraphqlArgs, ghMergeResultSchema, ghPrViewSchema, mockGithub, refStatusGraphql, resolveRepoHandleStrict, rollupToChecks, } from './github-shared.js';
19
+ export { refNumberFromUrl } from '../../contract/index.js';
25
20
  export { detectGithubCached, ghCheckRunSchema, ghFailureReason, ghGraphqlArgs, HEALTH_AVAILABILITY_TTL_MS, rollupToChecks, } from './github-shared.js';
26
- import { fetchGithubPrDiff } from './github-pr-diff.js';
27
21
  export { fetchGithubPrDiff, fetchPrFilePages, GH_PR_DIFF_FILE_CAP, GH_PR_DIFF_JSON_CAP, GH_PR_PATCH_CAP, GithubPrNotFoundError, } from './github-pr-diff.js';
28
- import { evictGithubListCaches, fetchGithub, fetchGithubProjects, searchGithubItems, viewGithubItem, } from './github-list.js';
29
22
  export { fetchGithub, fetchGithubProjects, fetchListConnection, GH_GRAPHQL_PAGE_MAX, GH_MAX_LIMIT, GH_SEARCH_MAX, searchGithubItems, viewGithubItem, } from './github-list.js';
30
- import { CHECKS_CACHE_MAX, fetchCommitChecks, fetchGithubChecks, } from './github-checks.js';
31
23
  export { __clearChecksCacheForTests, COMMIT_CHECKS_CHUNK, fetchCommitChecks, fetchGithubChecks, fetchPrChecks, GH_CHECKS_MAX, } from './github-checks.js';
32
- // ---- comment threads (#499 Phase 2) ----------------------------------------
33
- // A lazy per-thread fetch behind `GET /api/github/comments/:kind/:number`: the
34
- // conversation comments (issues endpoint — GitHub serves PR conversation
35
- // comments there too), plus submitted reviews for PRs, normalized into one
36
- // chronological `ForgeComment[]`. Its own bounded 60 s cache keeps an open
37
- // detail view from re-fetching on every focus. Degrades to `available: false`
38
- // exactly like the list fetch — never a 5xx.
39
- const ghCommentUser = z.object({ login: z.string(), avatar_url: z.string().nullish() }).nullish();
40
- const ghIssueCommentSchema = z.object({
41
- id: z.number(),
42
- user: ghCommentUser,
43
- created_at: z.string(),
44
- body: z.string().nullish(),
45
- html_url: z.string(),
46
- });
47
- const ghReviewSchema = z.object({
48
- id: z.number(),
49
- user: ghCommentUser,
50
- body: z.string().nullish(),
51
- state: z.string(),
52
- submitted_at: z.string().nullish(),
53
- html_url: z.string(),
54
- });
55
- const REVIEW_STATE = {
56
- APPROVED: 'approved',
57
- CHANGES_REQUESTED: 'changes_requested',
58
- COMMENTED: 'commented',
59
- DISMISSED: 'dismissed',
60
- };
61
- /** First 200 thread entries, then `truncated`; each body sliced to 8 000 chars (same cap as
62
- * item bodies). */
63
- export const THREAD_ENTRY_CAP = 200;
64
- const COMMENT_BODY_CAP = 8_000;
65
- /** `gh api …/issues/{n}/comments` JSON → `ForgeComment[]`. Exported for unit tests. */
66
- export function normalizeComments(raw) {
67
- return z.array(ghIssueCommentSchema).parse(raw).map((c) => defined({
68
- id: c.id,
69
- author: c.user?.login ?? '?',
70
- avatarUrl: c.user?.avatar_url ?? undefined,
71
- createdAt: c.created_at,
72
- body: (c.body ?? '').slice(0, COMMENT_BODY_CAP),
73
- kind: 'comment',
74
- url: c.html_url,
75
- }));
76
- }
77
- /** `gh api …/pulls/{n}/reviews` JSON → `ForgeComment[]`. Reviews with an empty body AND state
78
- * COMMENTED/PENDING carry no signal in a flat thread and are dropped; the rest map to
79
- * `kind: 'review'` (Q4). Exported for unit tests. */
80
- export function normalizeReviews(raw) {
81
- return z
82
- .array(ghReviewSchema)
83
- .parse(raw)
84
- .filter((r) => {
85
- const state = r.state.toUpperCase();
86
- const emptyBody = (r.body ?? '').trim().length === 0;
87
- return !(emptyBody && (state === 'COMMENTED' || state === 'PENDING'));
88
- })
89
- .map((r) => defined({
90
- id: r.id,
91
- author: r.user?.login ?? '?',
92
- avatarUrl: r.user?.avatar_url ?? undefined,
93
- createdAt: r.submitted_at ?? '',
94
- body: (r.body ?? '').slice(0, COMMENT_BODY_CAP),
95
- kind: 'review',
96
- reviewState: REVIEW_STATE[r.state.toUpperCase()],
97
- url: r.html_url,
98
- }));
99
- }
100
- /** Merge comment/review lists chronologically (oldest first) and apply the entry cap. Exported
101
- * for unit tests. */
102
- export function mergeThread(parts, cap = THREAD_ENTRY_CAP) {
103
- const all = parts.flat().sort((a, b) => a.createdAt.localeCompare(b.createdAt));
104
- const truncated = all.length > cap;
105
- return { comments: truncated ? all.slice(0, cap) : all, truncated };
106
- }
107
- // Per-thread cache: keyed `repoRoot␀kind#number` (the root scopes the key — two projects each
108
- // having a PR #42 must not collide; step 2.6), same 60 s TTL as the list cache but BOUNDED — a
109
- // long browsing session can't grow it without limit (Map preserves insertion order → oldest
110
- // first).
111
- const commentsCache = new Map();
112
- const COMMENTS_CACHE_MAX = 50;
113
- function cacheComments(key, data) {
114
- commentsCache.delete(key); // re-insert so this key becomes the newest
115
- commentsCache.set(key, { at: Date.now(), data });
116
- while (commentsCache.size > COMMENTS_CACHE_MAX) {
117
- const oldest = commentsCache.keys().next().value;
118
- if (oldest === undefined)
119
- break;
120
- commentsCache.delete(oldest);
121
- }
122
- }
123
- /** Test-only: drop the per-thread cache so cases don't leak state into each other. */
124
- export function __clearCommentsCacheForTests() {
125
- commentsCache.clear();
126
- }
127
- // Single-item cache (#692): same key shape, TTL and LRU bound as `commentsCache`. Only a real
128
- // answer (an item or a confirmed absence) is cached, never an unavailable one.
129
- const itemCache = new Map();
130
- function itemCacheKey(repoRoot, kind, number) {
131
- return `${githubContext(repoRoot).key}\0${kind}#${number}`;
132
- }
133
- export function forgetGithubItem(repoRoot, kind, number) {
134
- itemCache.delete(itemCacheKey(repoRoot, kind, number));
135
- }
136
- /** Test-only: drop the single-item cache. */
137
- export function __clearGithubItemCacheForTests() {
138
- itemCache.clear();
139
- }
140
- export async function fetchGithubItem(repoRoot, kind, number, refresh = false) {
141
- if (productEnv('DRY_RUN') === '1') {
142
- const mock = mockGithub();
143
- const item = (kind === 'issue' ? mock.issues : mock.prs).find((i) => i.number === number);
144
- return item
145
- ? { available: true, item, labelColors: mock.labelColors ?? {} }
146
- : { available: true, item: null };
147
- }
148
- const key = itemCacheKey(repoRoot, kind, number);
149
- const hit = itemCache.get(key);
150
- if (!refresh && hit && Date.now() - hit.at < CACHE_MS)
151
- return hit.data;
152
- try {
153
- const forge = await detectGithub(repoRoot);
154
- if (!forge.available)
155
- return { available: false, reason: forge.reason ?? 'GitHub is unavailable' };
156
- const labelColors = {};
157
- const item = await viewGithubItem(repoRoot, kind, number, labelColors);
158
- const data = {
159
- available: true, item, ...(item ? { labelColors } : {}),
160
- };
161
- itemCache.delete(key); // re-insert so this key becomes the newest
162
- itemCache.set(key, { at: Date.now(), data });
163
- while (itemCache.size > COMMENTS_CACHE_MAX) {
164
- const oldest = itemCache.keys().next().value;
165
- if (oldest === undefined)
166
- break;
167
- itemCache.delete(oldest);
168
- }
169
- return data;
170
- }
171
- catch (err) {
172
- const message = err instanceof Error ? err.message : String(err);
173
- return {
174
- available: false,
175
- reason: /ENOENT/.test(message)
176
- ? 'gh CLI not found — install it and run `gh auth login`'
177
- : firstLine(message),
178
- };
179
- }
180
- }
181
- const itemDetailSchema = z.object({
182
- body: z.string().nullish(),
183
- additions: z.number().int().nonnegative().optional(),
184
- deletions: z.number().int().nonnegative().optional(),
185
- });
186
- /** One item's body (and a PR's diffstat), or `undefined` on any failure. */
187
- async function fetchItemDetail(repoRoot, kind, number) {
188
- try {
189
- const out = await gh(repoRoot, [kind, 'view', String(number), '--json', kind === 'pr' ? 'body,additions,deletions' : 'body']);
190
- const parsed = itemDetailSchema.parse(JSON.parse(out));
191
- return {
192
- body: (parsed.body ?? '').slice(0, COMMENT_BODY_CAP),
193
- ...(kind === 'pr' && parsed.additions !== undefined ? { additions: parsed.additions } : {}),
194
- ...(kind === 'pr' && parsed.deletions !== undefined ? { deletions: parsed.deletions } : {}),
195
- };
196
- }
197
- catch {
198
- return undefined;
199
- }
200
- }
201
- // Per-item comment counts (hearsay-tools/cezarion#1183): the list defers them, and the cockpit
202
- // asks for its loaded rows after paint. Keyed `context␀kind␀number`, same TTL and bound as checks.
203
- const commentCountsCache = new Map();
204
- const commentCountsSchema = z.object({
205
- data: z.object({
206
- repository: z.record(z.string(), z.object({ comments: z.object({ totalCount: z.number().int().nonnegative() }) }).nullable()),
207
- }),
208
- });
209
- /**
210
- * Comment counts for the given issue or PR numbers, in one aliased GraphQL query. A number GitHub
211
- * does not know is absent (unknown), never 0. Degrades to `{ available: false, reason }` — never a
212
- * throw. Numbers are de-duplicated, validated and capped at `GITHUB_COMMENT_COUNTS_MAX`.
213
- */
214
- export async function fetchGithubCommentCounts(repoRoot, kind, numbers, refresh = false) {
215
- if (productEnv('DRY_RUN') === '1')
216
- return mockGithubCommentCounts(kind, numbers);
217
- const context = githubContext(repoRoot);
218
- const wanted = [...new Set(numbers)].filter((n) => Number.isSafeInteger(n) && n > 0).slice(0, GITHUB_COMMENT_COUNTS_MAX);
219
- const counts = {};
220
- const misses = [];
221
- const now = Date.now();
222
- const keyOf = (n) => `${context.key}\0${kind}\0${n}`;
223
- for (const n of wanted) {
224
- const hit = commentCountsCache.get(keyOf(n));
225
- if (!refresh && hit && now - hit.at < CACHE_MS)
226
- counts[n] = hit.count;
227
- else
228
- misses.push(n);
229
- }
230
- if (misses.length === 0)
231
- return { available: true, counts };
232
- try {
233
- const handle = await resolveRepoHandleStrict(repoRoot, context);
234
- if (!handle)
235
- return { available: false, reason: 'Could not resolve this repository on GitHub.' };
236
- // Integers only in the aliases; owner and name travel as variables.
237
- const fields = misses.map((n) => `n${n}: issueOrPullRequest(number: ${n}) {
238
- ... on Issue { comments { totalCount } }
239
- ... on PullRequest { comments { totalCount } }
240
- }`).join('\n');
241
- // A number GitHub does not know comes back NOT_FOUND and makes `gh` exit 1 with the rest of
242
- // the batch on stdout; `refStatusGraphql` keeps that partial answer.
243
- const raw = await refStatusGraphql(repoRoot, context)(`query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${fields} } }`, { owner: handle.owner, name: handle.name });
244
- const rows = commentCountsSchema.parse(JSON.parse(raw)).data.repository;
245
- for (const n of misses) {
246
- const count = rows[`n${n}`]?.comments.totalCount;
247
- if (count === undefined)
248
- continue; // unknown number: absent, and asked again next time
249
- counts[n] = count;
250
- commentCountsCache.delete(keyOf(n));
251
- commentCountsCache.set(keyOf(n), { at: now, count });
252
- }
253
- while (commentCountsCache.size > CHECKS_CACHE_MAX) {
254
- const oldest = commentCountsCache.keys().next().value;
255
- if (oldest === undefined)
256
- break;
257
- commentCountsCache.delete(oldest);
258
- }
259
- return { available: true, counts };
260
- }
261
- catch (err) {
262
- return { available: false, reason: ghFailureReason(err) };
263
- }
264
- }
265
- /** CEZ_DRY_RUN=1 — the catalog's own counts, so the offline list shows its badges. */
266
- function mockGithubCommentCounts(kind, numbers) {
267
- const rows = kind === 'pr' ? mockGithub().prs : mockGithub().issues;
268
- const counts = {};
269
- for (const n of numbers) {
270
- const row = rows.find((item) => item.number === n);
271
- if (row)
272
- counts[n] = row.comments;
273
- }
274
- return { available: true, counts };
275
- }
276
- /** Numbers per kind in one ref-status query — the same bound, and for the same reasons, as
277
- * `GH_CHECKS_MAX`: aliases resolve independently, and the query size stays finite. Taken from the
278
- * contract rather than restated, because the cockpit caps its batches by the same number and a
279
- * client that guessed high would have every chip in a batch 400 instead of losing its tail. */
280
- export const GH_REF_STATUS_MAX = REFERENCE_STATUS_MAX;
281
- const ghRefStatusPrSchema = z
282
- .object({
283
- state: z.string(),
284
- url: z.unknown().optional(),
285
- mergedAt: z.unknown().optional(),
286
- isDraft: z.boolean().nullish(),
287
- reviewDecision: z.string().nullish(),
288
- /** `MERGEABLE` | `CONFLICTING` | `UNKNOWN` — GitHub computes it in the background, so
289
- * `UNKNOWN` is normal on a PR that was just pushed and must never read as "clean". */
290
- mergeable: z.string().nullish(),
291
- commits: z
292
- .object({
293
- nodes: z.array(z.object({
294
- commit: z.object({
295
- committedDate: z.string().nullish(),
296
- /** `totalCount` says whether the head is a merge; the first parent is the branch's
297
- * previous tip, which is the newest commit that is actual WORK when it is. */
298
- parents: z
299
- .object({
300
- totalCount: z.number(),
301
- nodes: z.array(z.object({ committedDate: z.string().nullish() }).nullish()).nullish(),
302
- })
303
- .nullish(),
304
- statusCheckRollup: z.object({ state: z.string().nullish() }).nullish(),
305
- }),
306
- })),
307
- })
308
- .nullish(),
309
- reviews: z.object({ nodes: z.array(z.object({ submittedAt: z.string().nullish() })) }).nullish(),
310
- /** Who is on the hook RIGHT NOW. The reviewers are carried, not just the count, because a
311
- * request's date has to be matched to a request that still stands — see `reviewRequestedAt`. */
312
- reviewRequests: z
313
- .object({
314
- totalCount: z.number(),
315
- nodes: z.array(z.object({ requestedReviewer: reviewerRefSchema }).nullish()).nullish(),
316
- })
317
- .nullish(),
318
- timelineItems: z
319
- .object({
320
- nodes: z
321
- .array(z.object({ createdAt: z.string().nullish(), requestedReviewer: reviewerRefSchema }).nullish())
322
- .nullish(),
323
- })
324
- .nullish(),
325
- })
326
- .nullish();
327
- /**
328
- * When was the newest STILL-STANDING review request made?
329
- *
330
- * The two connections answer different halves and neither answers both: `reviewRequests` says who
331
- * is on the hook right now but carries no date, while a `ReviewRequestedEvent` carries the date and
332
- * survives the request being withdrawn. Reading the newest event on its own therefore dates a
333
- * request that may no longer exist — and a request added after a review and then removed would make
334
- * a live rejection read as answered, which is the exact bug the precedence above exists to fix.
335
- * Matching the two by reviewer is what keeps the date attached to a request that is really there.
336
- *
337
- * `null` when nothing matches, which the precedence reads as an undated request and treats
338
- * conservatively: the review stands rather than being dismissed on a guess.
339
- */
340
- function standingReviewRequestedAt(requests, timeline) {
341
- const standing = new Set();
342
- for (const node of requests?.nodes ?? []) {
343
- const key = reviewerKey(node?.requestedReviewer);
344
- if (key)
345
- standing.add(key);
346
- }
347
- if (standing.size === 0)
348
- return null;
349
- let newest = null;
350
- for (const node of timeline?.nodes ?? []) {
351
- if (!node?.createdAt)
352
- continue;
353
- const key = reviewerKey(node.requestedReviewer);
354
- if (!key || !standing.has(key))
355
- continue;
356
- if (!newest || isAfter(node.createdAt, newest))
357
- newest = node.createdAt;
358
- }
359
- return newest;
360
- }
361
- const ghRefStatusIssueSchema = z.object({ state: z.string(), stateReason: z.string().nullish() }).nullish();
362
- // The aliases hold two DIFFERENT shapes, so the record stays unvalidated here and each alias is
363
- // parsed by its own schema below. A union at this level would be wrong, not merely loose: zod
364
- // strips unknown keys, so a PR node matched by the issue arm would come back with `isDraft` and
365
- // `commits` silently removed.
366
- const ghRefStatusSchema = z.record(z.string(), z.unknown());
367
- /**
368
- * Derive whose action is pending: terminal, draft, pending checks, current requested changes,
369
- * failing checks, review, then ready. Use dated review/work evidence; mergeability remains a
370
- * separate axis.
371
- */
372
- export function derivePrReferenceStatus(pr) {
373
- const state = pr.state.toUpperCase();
374
- if (state === 'MERGED')
375
- return 'merged';
376
- if (state === 'CLOSED')
377
- return 'closed';
378
- if (pr.isDraft)
379
- return 'draft';
380
- if (pr.checks === 'pending')
381
- return 'checks-pending';
382
- const decision = (pr.reviewDecision ?? '').toUpperCase();
383
- const changesRequested = decision === 'CHANGES_REQUESTED';
384
- // Has the author already answered the review — by asking for another look, or by pushing?
385
- // A standing request counts as the ask only if it POSTDATES the review; one made before it is a
386
- // reviewer who has not got to the PR yet, and on a PR where someone else rejected it that
387
- // request would otherwise mask the rejection indefinitely. With no review date at all it still
388
- // counts — that is the empty-`reviews` case above, where it is the only signal there is.
389
- const reRequested = pr.reviewRequested === true && (!pr.changesRequestedAt || isAfter(pr.reviewRequestedAt, pr.changesRequestedAt));
390
- // A push counts as the answer, judged by the newest commit that is actual WORK. GitHub's "Update
391
- // branch" button (and this cockpit's own "Resolve conflicts") writes `Merge branch 'main' into
392
- // <branch>` dated NOW, newer than any review while addressing none of it: the click people make
393
- // reflexively on a stale PR must not wipe a rejection off the chip. Two parents is what tells
394
- // that commit apart from work.
395
- //
396
- // Which is why a merge is not simply DISQUALIFYING: it is transparent. Reading only the head
397
- // would let a merge landing on top of a genuine fix erase that fix's answer and flip the chip
398
- // back to red, blaming an author who already responded — the same misattribution this whole
399
- // function exists to prevent, just pointed the other way. The merge's FIRST parent is the
400
- // branch's previous tip, so it carries the date of the work the merge sat on top of.
401
- const workCommittedAt = (pr.headParentCount ?? 1) < 2 ? pr.headCommittedAt : pr.headFirstParentCommittedAt;
402
- const pushed = isAfter(workCommittedAt, pr.changesRequestedAt);
403
- const answered = reRequested || pushed;
404
- if (changesRequested && !answered)
405
- return 'changes-requested';
406
- if (pr.checks === 'failing')
407
- return 'checks-failing';
408
- // `APPROVED` is the forge saying the review requirement IS MET, and it outranks a pending
409
- // request: a reviewer left on the list after someone else approved is a courtesy ask, not an
410
- // unmet gate. (A repo needing two approvals reports `REVIEW_REQUIRED` until it has both, so
411
- // `APPROVED` never arrives early.) Without this, an approved, green, mergeable pull request
412
- // reads "waiting for review" for as long as anyone stays listed — which is indefinitely.
413
- if (decision === 'APPROVED')
414
- return 'ready';
415
- if (changesRequested || decision === 'REVIEW_REQUIRED' || pr.reviewRequested === true) {
416
- return 'review-required';
417
- }
418
- return 'ready';
419
- }
420
- export function mergeabilityOf(state, mergeable) {
421
- if (state.toUpperCase() !== 'OPEN')
422
- return undefined;
423
- switch (mergeable?.toUpperCase()) {
424
- case 'MERGEABLE':
425
- return 'mergeable';
426
- case 'CONFLICTING':
427
- return 'conflicting';
428
- default:
429
- // Includes a field GitHub omitted entirely: not being told is not being told.
430
- return 'unknown';
431
- }
432
- }
433
- /** Did `later` happen AFTER `earlier` — a commit, or a re-request, landing past the review?
434
- * Unparseable or missing dates answer `false`, which is the conservative direction for both
435
- * callers: they only ever use a `true` to demote a review, so no answer must keep the review
436
- * current rather than silently dismiss one. */
437
- function isAfter(later, earlier) {
438
- const a = later ? Date.parse(later) : NaN;
439
- const b = earlier ? Date.parse(earlier) : NaN;
440
- return Number.isFinite(a) && Number.isFinite(b) && a > b;
441
- }
442
- /**
443
- * An issue's two signals as one word. `NOT_PLANNED` is kept apart from `completed` because they
444
- * are opposite outcomes — "we did it" vs "we won't" — and a task whose issue was declined must
445
- * not read as a task that landed.
446
- */
447
- export function deriveIssueReferenceStatus(issue) {
448
- if (issue.state.toUpperCase() !== 'CLOSED')
449
- return 'open';
450
- return (issue.stateReason ?? '').toUpperCase() === 'NOT_PLANNED' ? 'not-planned' : 'completed';
451
- }
452
- function refStatusGraphqlClean(raw, repository, owner, name) {
453
- return (!raw.errors || (Array.isArray(raw.errors) && raw.errors.length === 0)) &&
454
- typeof repository.nameWithOwner === 'string' && repository.nameWithOwner.toLowerCase() === `${owner}/${name}`.toLowerCase();
455
- }
456
- function prHeadCommit(pr) {
457
- return pr.commits?.nodes[0]?.commit;
458
- }
459
- function prRollupChecks(head) {
460
- const rollup = head?.statusCheckRollup;
461
- // Adapt the single rollup state into the array shape `rollupToChecks` expects,
462
- // reusing the FAILURE/PENDING/SUCCESS vocabulary rather than duplicating it.
463
- return rollup ? rollupToChecks([{ state: rollup.state, status: null, conclusion: null }]) ?? null : null;
464
- }
465
- function resolvePrReference(pr, raw, repository, owner, name, number) {
466
- if (refStatusGraphqlClean(raw, repository, owner, name)) {
467
- mergedPullRequestObservations.observe({ owner, repo: name, number }, { ...pr, number });
468
- }
469
- const head = prHeadCommit(pr);
470
- const mergeability = mergeabilityOf(pr.state, pr.mergeable);
471
- return {
472
- kind: 'pr',
473
- status: derivePrReferenceStatus({
474
- state: pr.state,
475
- isDraft: pr.isDraft,
476
- reviewDecision: pr.reviewDecision,
477
- checks: prRollupChecks(head),
478
- headCommittedAt: head?.committedDate,
479
- // Two parents = "Update branch", which is dated now and answers nothing on its own —
480
- // so the first parent's date, the work it sat on top of, is carried with it.
481
- headParentCount: head?.parents?.totalCount,
482
- headFirstParentCommittedAt: head?.parents?.nodes?.[0]?.committedDate,
483
- // `reviews(last: 1, states: CHANGES_REQUESTED)` — the timestamp only. WHETHER changes
484
- // are requested stays `reviewDecision`'s answer, which is the one that accounts for
485
- // dismissed and superseded reviews.
486
- changesRequestedAt: pr.reviews?.nodes[0]?.submittedAt,
487
- reviewRequested: (pr.reviewRequests?.totalCount ?? 0) > 0,
488
- // WHEN that standing request was made. `reviewRequests` carries no date of its own,
489
- // and without one an old request looks exactly like a re-request.
490
- reviewRequestedAt: standingReviewRequestedAt(pr.reviewRequests, pr.timelineItems),
491
- }),
492
- // The tri-state, not a boolean: `unknown` has to survive as far as the cache, which
493
- // is what decides to ask again in seconds rather than in a minute.
494
- ...(mergeability ? { mergeable: mergeability } : {}),
495
- };
496
- }
497
- function applyRefStatusNode(out, node, raw, repository, owner, name, number) {
498
- // Absent alias → the number is not in this repository at all. Left out of the map, which
499
- // is what the route reports as "not found" and the chip paints as neutral.
500
- if (!node)
501
- return;
502
- if (node.__typename === 'PullRequest') {
503
- const pr = ghRefStatusPrSchema.parse(node);
504
- if (!pr)
505
- return;
506
- out.resolved[number] = resolvePrReference(pr, raw, repository, owner, name, number);
507
- return;
508
- }
509
- if (node.__typename === 'Issue') {
510
- const issue = ghRefStatusIssueSchema.parse(node);
511
- if (!issue)
512
- return;
513
- out.resolved[number] = { kind: 'issue', status: deriveIssueReferenceStatus(issue) };
514
- }
515
- }
516
- async function fetchRefStatusChunk(runGraphql, owner, name, chunk, out) {
517
- try {
518
- const raw = JSON.parse(await runGraphql(refStatusQuery(chunk), { owner, name }));
519
- const repository = ghRefStatusSchema.parse(raw?.data?.repository ?? {});
520
- chunk.forEach((number, index) => {
521
- applyRefStatusNode(out, repository[`r${index}`], raw, repository, owner, name, number);
522
- });
523
- }
524
- catch (err) {
525
- // A failed chunk costs only its own numbers; the rest still resolve. They are recorded as
526
- // FAILED rather than left absent, so nothing downstream mistakes them for "no such number".
527
- out.failed.push(...chunk);
528
- out.reason ??= firstLine(err instanceof Error ? err.message : String(err));
529
- }
530
- }
531
- /**
532
- * Status per NUMBER, resolved to whatever that number actually is.
533
- *
534
- * Batched and aliased like `fetchPrChecks`: one subprocess per chunk, each alias resolving
535
- * independently, and a number the forge does not have simply staying absent from `resolved` (its
536
- * chip then renders neutral, as it did before this seam existed). A failed chunk costs only its
537
- * own numbers, and says so rather than letting them look absent. Exported for tests; `runGraphql`
538
- * is injected so this is testable without shelling out.
539
- */
540
- export async function fetchRefStatuses(runGraphql, owner, name, numbers, chunkSize = GH_REF_STATUS_MAX) {
541
- const out = { resolved: {}, failed: [] };
542
- if (numbers.length === 0)
543
- return out;
544
- for (let i = 0; i < numbers.length; i += chunkSize) {
545
- await fetchRefStatusChunk(runGraphql, owner, name, numbers.slice(i, i + chunkSize), out);
546
- }
547
- return out;
548
- }
549
- // Per-reference cache: keyed `repoRoot␀number` — by NUMBER, not by kind, because the kind is now
550
- // something the forge answers rather than something the caller asserts. Same 60 s TTL and bounded
551
- // shape as the checks cache; `null` is a cached "this repository has no such number", so a
552
- // transcript-scraped number from another repo is not re-queried on every table repaint.
553
- //
554
- // `unknownSince` is when this reference FIRST came back with its mergeability still being
555
- // computed, carried across refreshes so the fast recheck below is bounded to that first window
556
- // rather than restarting on every answer that is still `unknown`.
557
- const refStatusCache = new Map();
558
- const REF_STATUS_CACHE_MAX = 500;
559
- /** Test-only: drop the per-reference cache so cases don't leak state into each other. */
560
- export function __clearRefStatusCacheForTests() {
561
- refStatusCache.clear();
562
- refStatusFlights.clear();
563
- }
564
- /** Test-only: warm the cache the way the lazy route would have, so a reader can be tested
565
- * without a forge behind it. */
566
- export function __seedRefStatusCacheForTests(repoRoot, entries) {
567
- for (const [number, resolved] of entries) {
568
- refStatusCache.set(refStatusKey(repoRoot, number), { at: Date.now(), resolved });
569
- }
570
- }
571
- /**
572
- * Invalidate one reference after a known mutation. Let the next forge read establish status
573
- * rather than caching a guessed result.
574
- */
575
- export function forgetRefStatus(repoRoot, number) {
576
- refStatusCache.delete(refStatusKey(repoRoot, number));
577
- refStatusFlights.delete(refStatusKey(repoRoot, number));
578
- }
579
- /**
580
- * Everything the cache ALREADY knows about these numbers. Never spawns `gh`, never awaits.
581
- *
582
- * This is what lets a status ride along with the rows that carry the references, instead of the
583
- * cockpit fetching it separately a moment later: the run index reads whatever is warm and ships
584
- * it, and a cold entry is simply absent — the lazy `/github/ref-status` route stays the thing that
585
- * actually goes and asks.
586
- *
587
- * Because it cannot cost anything, the caller may pass a SUPERSET of the numbers it will really
588
- * display. That matters: deciding which of a run's references a chip shows is the cockpit's rule
589
- * (#407, #526), deliberately not duplicated server-side, and a cache read does not need to know —
590
- * it can look up every number a run mentions and let the client pick.
591
- */
592
- export function readCachedRefStatuses(repoRoot, numbers) {
593
- const out = { prs: {}, issues: {} };
594
- const now = Date.now();
595
- for (const number of new Set(numbers)) {
596
- const hit = refStatusCache.get(refStatusKey(repoRoot, number));
597
- if (!hit || !hit.resolved || now - hit.at >= refStatusTtl(hit.resolved, hit.unknownSince, now))
598
- continue;
599
- out[hit.resolved.kind === 'pr' ? 'prs' : 'issues'][number] = hit.resolved.status;
600
- }
601
- return out;
602
- }
603
- // The `#N` in a forge URL. Defined beside the run search matcher, which reads it too (#864).
604
- export { refNumberFromUrl } from '../../contract/index.js';
605
- /** A closed issue or an abandoned PR can be REOPENED, so this is long rather than forever — but
606
- * it is the rare event, and re-asking a hundred settled references every minute to catch it is
607
- * the wrong trade. */
608
- const REF_STATUS_CLOSED_TTL = 10 * 60_000;
609
- /** A merged pull request is merged forever: GitHub has no un-merge. Capped at a day only so a
610
- * long-lived server eventually re-reads rather than trusting a value from another era. */
611
- const REF_STATUS_MERGED_TTL = 24 * 60 * 60_000;
612
- /**
613
- * How long a cached answer stays fresh — by how changeable that answer IS.
614
- *
615
- * One TTL for everything gets both ends wrong: it re-asks about a merged PR (which cannot change)
616
- * every minute, and it is the only thing standing between a running CI job and a stale chip. What
617
- * a reader wants rechecked is precisely what is still moving.
618
- *
619
- * A number the repository does not have keeps the short TTL: it is usually a wrong number, but it
620
- * is also what a reference to a not-yet-created PR looks like, and re-asking is cheap.
621
- */
622
- function refStatusTtl(entry, unknownSince, now = Date.now()) {
623
- if (!entry)
624
- return CACHE_MS;
625
- // Mergeability GitHub has not finished computing is not an answer to cache for a minute. It is
626
- // the normal reply for the first seconds after a push, and holding it that long is what let a
627
- // conflicting pull request read "Ready to merge" until the page was reloaded. Ask again in
628
- // seconds instead — and only while it is still plausibly being computed, so a repository that
629
- // answers `UNKNOWN` indefinitely settles back to the ordinary cadence rather than spawning `gh`
630
- // every few seconds forever.
631
- if (entry.mergeable === 'unknown' &&
632
- unknownSince !== undefined &&
633
- now - unknownSince < MERGEABILITY_UNKNOWN_WINDOW_MS) {
634
- return MERGEABILITY_UNKNOWN_TTL_MS;
635
- }
636
- switch (entry.status) {
637
- case 'merged':
638
- return REF_STATUS_MERGED_TTL;
639
- case 'closed':
640
- case 'completed':
641
- case 'not-planned':
642
- return REF_STATUS_CLOSED_TTL;
643
- default:
644
- return CACHE_MS;
645
- }
646
- }
647
- /** How long a status can be trusted to stay put — `null` when it can never change again. The
648
- * cadence half of `refStatusTtl`, and deliberately the same function: a value the cache would
649
- * still be serving is a value there is no point asking for, and a value it would NOT serve —
650
- * mergeability still being computed — is one the cockpit should come back for just as soon. */
651
- function refStatusRecheckAfter(entry, unknownSince, now = Date.now()) {
652
- if (entry?.status === 'merged')
653
- return null; // GitHub has no un-merge
654
- return refStatusTtl(entry, unknownSince, now);
655
- }
656
- /** How long the WHOLE answer holds — the soonest any single reference in it could differ. `null`
657
- * only when every one of them is immutable, which is what tells the cockpit to stop scheduling.
658
- * Taking the per-reference values rather than the entries, because one of them may be on the fast
659
- * mergeability cadence and the batch has to travel at the speed of its most impatient member. */
660
- function batchRecheckAfter(rechecks) {
661
- let soonest = null;
662
- for (const after of rechecks) {
663
- if (after === null)
664
- continue;
665
- soonest = soonest === null ? after : Math.min(soonest, after);
666
- }
667
- return soonest;
668
- }
669
- /**
670
- * How long a still-computing mergeability holds, and for how long that fast cadence applies.
671
- *
672
- * Five seconds because that is the shape of the thing being waited for: GitHub kicks off the
673
- * merge-base computation when asked and usually has it by the next request. Bounded to a minute
674
- * because a value that is STILL unknown after that is not a computation in flight any more — it is
675
- * a repository that will not answer, and re-asking it every five seconds forever costs a `gh`
676
- * subprocess a second for nothing.
677
- */
678
- const MERGEABILITY_UNKNOWN_TTL_MS = 5_000;
679
- const MERGEABILITY_UNKNOWN_WINDOW_MS = 60_000;
680
- /** A forge that could not be reached is worth retrying, and worth not hammering: a workspace with
681
- * no `gh` installed would otherwise spawn a subprocess a minute, forever, to be told the same
682
- * thing. Five minutes is the same order as the cockpit's own reconnect cadence. */
683
- const REF_STATUS_RETRY_MS = 5 * 60_000;
684
- // Ownership is per reference, before discovery starts. Overlapping requests join just the
685
- // numbers they need; extra numbers form their own batch without a batching timer or new delay.
686
- // At capacity, untracked work answers its callers without caching: it has no ownership token
687
- // to protect publication against invalidation or newer requests. Retained ownership is at most 500.
688
- const refStatusFlights = new Map();
689
- async function sharedRefStatusMisses(repoRoot, numbers, context) {
690
- const pending = new Map();
691
- const owned = [];
692
- for (const n of numbers) {
693
- const flight = refStatusFlights.get(refStatusKey(repoRoot, n, context));
694
- if (flight)
695
- pending.set(n, flight);
696
- else
697
- owned.push(n);
698
- }
699
- if (owned.length) {
700
- const batch = (async () => {
701
- const handle = await resolveRepoHandleStrict(repoRoot, context);
702
- if (!handle)
703
- throw new Error('repository handle unavailable');
704
- return fetchRefStatuses(refStatusGraphql(repoRoot, context), handle.owner, handle.name, owned);
705
- })();
706
- for (const n of owned) {
707
- const key = refStatusKey(repoRoot, n, context);
708
- const tracked = refStatusFlights.size < REF_STATUS_CACHE_MAX;
709
- const promise = batch.then(result => {
710
- if (result.failed.includes(n))
711
- return { reason: result.reason ?? 'GitHub could not be reached' };
712
- // Date fresh results at arrival; keep the original unknown-mergeability retry window.
713
- const storedAt = Date.now();
714
- const entry = result.resolved[n] ?? null;
715
- const unknownSince = entry?.mergeable === 'unknown'
716
- ? (refStatusCache.get(key)?.unknownSince ?? storedAt) : undefined;
717
- const value = { resolved: entry, ...(unknownSince === undefined ? {} : { unknownSince }) };
718
- if (tracked && refStatusFlights.get(key) === promise) {
719
- refStatusCache.set(key, { at: storedAt, ...value });
720
- while (refStatusCache.size > REF_STATUS_CACHE_MAX)
721
- refStatusCache.delete(refStatusCache.keys().next().value);
722
- }
723
- return value;
724
- }).finally(() => {
725
- if (refStatusFlights.get(key) === promise)
726
- refStatusFlights.delete(key);
727
- });
728
- if (tracked)
729
- refStatusFlights.set(key, promise);
730
- pending.set(n, promise);
731
- }
732
- }
733
- return Promise.all(numbers.map(async (n) => [n, await pending.get(n)]));
734
- }
735
- /**
736
- * Route-facing reference status. Resolves the repo handle once, serves fresh cache entries,
737
- * queries only the misses, and degrades to `{ available: false, reason }` when `gh` or the handle
738
- * is unavailable — never a throw, never a 5xx.
739
- *
740
- * The two request lists are merged into ONE set of numbers: issues and pull requests share a
741
- * repository's numbering space, so a number is one thing and asking about it twice would be asking
742
- * the same question twice. What comes back is filed by what each number turned out to BE, which is
743
- * why a chip whose kind the cockpit guessed wrong still gets the right status.
744
- */
745
- export async function fetchGithubRefStatus(repoRoot, input) {
746
- const context = githubContext(repoRoot);
747
- const asPrs = sanitizeRefNumbers(input.prs);
748
- const asIssues = sanitizeRefNumbers(input.issues);
749
- if (productEnv('DRY_RUN') === '1')
750
- return mockGithubRefStatus(asPrs, asIssues);
751
- const wanted = [...new Set([...asPrs, ...asIssues])];
752
- const resolved = { prs: {}, issues: {} };
753
- // How soon each reference in the answer could differ — what the batch's cadence is the minimum
754
- // of. Per reference rather than per batch because mergeability still being computed is worth
755
- // coming back for in seconds while everything else holds for a minute.
756
- const rechecks = [];
757
- // The second axis, and a list rather than a map because it is nearly always empty: only the
758
- // pull requests the forge actively called CONFLICTING are named (see `mergeabilityOf`).
759
- const conflicts = [];
760
- const file = (number, entry, unknownSince) => {
761
- rechecks.push(refStatusRecheckAfter(entry, unknownSince));
762
- if (!entry)
763
- return;
764
- resolved[entry.kind === 'pr' ? 'prs' : 'issues'][number] = entry.status;
765
- if (entry.mergeable === 'conflicting')
766
- conflicts.push(number);
767
- };
768
- const misses = [];
769
- const now = Date.now();
770
- for (const n of wanted) {
771
- const hit = refStatusCache.get(refStatusKey(repoRoot, n, context));
772
- if (!hit || now - hit.at >= refStatusTtl(hit.resolved, hit.unknownSince, now))
773
- misses.push(n);
774
- else
775
- file(n, hit.resolved, hit.unknownSince);
776
- }
777
- if (misses.length === 0) {
778
- return {
779
- available: true,
780
- prs: resolved.prs,
781
- issues: resolved.issues,
782
- conflicts,
783
- recheckAfterMs: batchRecheckAfter(rechecks),
784
- };
785
- }
786
- try {
787
- const entries = await sharedRefStatusMisses(repoRoot, misses, context);
788
- let failure;
789
- for (const [n, result] of entries) {
790
- if ('reason' in result)
791
- failure ??= result.reason;
792
- else
793
- file(n, result.resolved, result.unknownSince);
794
- }
795
- // Anything unasked makes the whole answer `unavailable`, deliberately. The alternative is a
796
- // payload where a number we could not reach is indistinguishable from one that does not exist,
797
- // and the cockpit would paint "not found on this repository" over a perfectly good PR — the
798
- // exact defect this route was reported for. The successes are cached either way, so the next
799
- // request costs only the numbers that failed and usually answers in full.
800
- if (failure !== undefined) {
801
- return {
802
- available: false,
803
- reason: failure,
804
- recheckAfterMs: REF_STATUS_RETRY_MS,
805
- };
806
- }
807
- return {
808
- available: true,
809
- prs: resolved.prs,
810
- issues: resolved.issues,
811
- conflicts,
812
- recheckAfterMs: batchRecheckAfter(rechecks),
813
- };
814
- }
815
- catch (err) {
816
- const message = err instanceof Error ? err.message : String(err);
817
- return {
818
- available: false,
819
- reason: /ENOENT/.test(message)
820
- ? 'gh CLI not found — install it and run `gh auth login`'
821
- : firstLine(message),
822
- recheckAfterMs: REF_STATUS_RETRY_MS,
823
- };
824
- }
825
- }
826
- /** NUL separator, as everywhere else here: two projects each having a #42 must not collide. */
827
- function refStatusKey(repoRoot, number, context = githubContext(repoRoot)) {
828
- return `${context.key}\0#${number}`;
829
- }
830
- function sanitizeRefNumbers(numbers) {
831
- return [...new Set(numbers ?? [])].filter((n) => Number.isInteger(n) && n > 0).slice(0, GH_REF_STATUS_MAX);
832
- }
833
- /** CEZ_DRY_RUN=1 — statuses derived from the mock catalog so the offline demo paints real chips. */
834
- function mockGithubRefStatus(prs, issues) {
835
- const catalog = mockGithub();
836
- const byPr = new Map(catalog.prs.map((p) => [p.number, p]));
837
- const byIssue = new Set(catalog.issues.map((i) => i.number));
838
- const out = { available: true, prs: {}, issues: {}, recheckAfterMs: CACHE_MS };
839
- for (const n of prs) {
840
- const pr = byPr.get(n);
841
- if (pr) {
842
- out.prs[n] = derivePrReferenceStatus({
843
- state: 'OPEN',
844
- isDraft: pr.isDraft,
845
- reviewDecision: null,
846
- checks: (pr.checks ?? null),
847
- });
848
- }
849
- }
850
- for (const n of issues)
851
- if (byIssue.has(n))
852
- out.issues[n] = 'open';
853
- return out;
854
- }
855
- /**
856
- * The conversation thread for one issue/PR, lazily. `{owner}`/`{repo}` in the gh api paths are
857
- * filled from the worktree's remote by gh itself, so no extra handle lookup. Everything degrades:
858
- * gh missing/offline → `{ available: false, reason }`, a 404 → a "not found" hint — never a throw.
859
- *
860
- * Since #525 the thread is sourced from `/issues/{n}/timeline`, which returns comments AND events
861
- * in one stream: `commented` rows go through the unchanged `normalizeComments`, the rest through
862
- * `normalizeEvents`. `comments[]` therefore keeps its exact pre-#525 shape, contents and cap;
863
- * see the top-up below for the one case that needed defending.
864
- */
865
- function commentsCacheKey(repoRoot, kind, number) {
866
- // NUL separator: cannot appear in a filesystem path, so roots can never alias.
867
- return `${githubContext(repoRoot).key}\0${kind}#${number}`;
868
- }
869
- function cachedGithubComments(key, refresh) {
870
- const hit = commentsCache.get(key);
871
- if (!refresh && hit && Date.now() - hit.at < CACHE_MS)
872
- return hit.data;
873
- return undefined;
874
- }
875
- function legacyIssueComments(repoRoot, number) {
876
- // PR conversation comments live on the issues endpoint too — always use it for the body thread.
877
- return () => gh(repoRoot, ['api', `repos/{owner}/{repo}/issues/${number}/comments`, '--paginate']);
878
- }
879
- function parseUnknownRows(raw) {
880
- return z.array(z.unknown()).parse(JSON.parse(raw));
881
- }
882
- function commentedTimelineRows(rows) {
883
- return rows.filter((row) => row?.event === 'commented');
884
- }
885
- async function fetchIssueTimelinePages(repoRoot, number) {
886
- return fetchTimelinePages((page, timeoutMs) => gh(repoRoot, [
887
- 'api',
888
- '-H',
889
- 'Accept: application/vnd.github+json',
890
- `repos/{owner}/{repo}/issues/${number}/timeline?per_page=${TIMELINE_PER_PAGE}&page=${page}`,
891
- ], timeoutMs));
892
- }
893
- async function topUpTimelineComments(commentRows, stoppedShort, legacyComments) {
894
- // Comments top-up. The two ENTRY caps are independent, but the FETCH budget is not: today's
895
- // call is an unbounded --paginate over a comments-only endpoint, so every comment is fetched
896
- // and mergeThread picks the oldest 200 from the complete set. Under the timeline those same
897
- // 200 slots are filled from at most 1000 rows in which events compete with comments — so on
898
- // a 1500-row thread with 250 interleaved comments, comments[] would return ~167 where today
899
- // it returns 200. Same §2 defect class as a combined entry cap, arriving via the source set.
900
- //
901
- // The trigger deliberately over-fires: it cannot distinguish "comments were cut off" from
902
- // "this thread just has few comments", because the second is only knowable by fetching them.
903
- // So on an event-heavy thread with 30 comments it re-fetches 30 complete comments. Accepted
904
- // — it fires only past ~1000 timeline rows, behind the 60 s LRU, and the alternative is a §2
905
- // regression. In the other direction the threshold is provably sound: with ≥200 commented
906
- // rows already in the oldest-first prefix, mergeThread's oldest-200 cut lies inside it.
907
- if (!(stoppedShort && commentRows.length < THREAD_ENTRY_CAP))
908
- return commentRows;
909
- // Its OWN nested catch. The inner handler's remedy is the fallback — which is this very
910
- // call — and the outer handler returns { available: false, comments: [] }, emptying a
911
- // thread that was about to render. So a thrown top-up is swallowed: keep the commented
912
- // rows the timeline already returned and carry on. That is at worst the short list the
913
- // safeguard existed to avoid, never worse than not having attempted it.
914
- try {
915
- return parseUnknownRows(await legacyComments());
916
- }
917
- catch {
918
- // keep the timeline's own commented rows
919
- return commentRows;
920
- }
921
- }
922
- async function loadGithubThreadSource(repoRoot, number, legacyComments) {
923
- const source = {
924
- commentRows: [],
925
- events: undefined,
926
- eventsTruncated: false,
927
- stoppedShort: false,
928
- };
929
- try {
930
- const pages = await fetchIssueTimelinePages(repoRoot, number);
931
- source.stoppedShort = pages.stoppedShort;
932
- source.commentRows = commentedTimelineRows(pages.rows);
933
- const normalized = normalizeEvents(pages.rows);
934
- source.events = normalized.events;
935
- source.eventsTruncated = normalized.truncated;
936
- source.commentRows = await topUpTimelineComments(source.commentRows, source.stoppedShort, legacyComments);
937
- return source;
938
- }
939
- catch (timelineErr) {
940
- // Scoped INSIDE the existing outer catch on purpose: the outer handler's /404|not found/i
941
- // branch would otherwise turn a timeline 404 into an empty thread. ENOENT is the one failure
942
- // the fallback cannot rescue — nothing will work, and a second spawn fails identically.
943
- const message = timelineErr instanceof Error ? timelineErr.message : String(timelineErr);
944
- if (/ENOENT/.test(message))
945
- throw timelineErr;
946
- // Every other endpoint-level failure substitutes the legacy comments call. It is a
947
- // substitution, not a retry — a different endpoint, which typically still answers. (A 403
948
- // attaches to the token rather than the endpoint, so it cannot succeed either; not
949
- // special-cased, since rate-limit replies are immediate and it costs one fast spawn.)
950
- source.commentRows = parseUnknownRows(await legacyComments());
951
- source.events = undefined;
952
- return source;
953
- }
954
- }
955
- function applyCommitChecks(events, checks) {
956
- for (const event of events) {
957
- if (event.kind !== 'committed' || !event.sha)
958
- continue;
959
- if (event.sha in checks) {
960
- delete event.checks;
961
- Object.assign(event, defined({ checks: checks[event.sha] }));
962
- }
963
- }
964
- }
965
- async function attachCommitChecks(repoRoot, events) {
966
- // Per-commit CI (#525 Phase 2). One extra subprocess per opened thread that contains commits,
967
- // behind the same 60 s LRU — a per-thread-open cost, not per-render. Every failure path here
968
- // leaves `checks` ABSENT rather than null, so commits simply render unglyphed: the fetch
969
- // degrades to "no data" and the render decides what absence looks like.
970
- const commitShas = (events ?? []).flatMap((event) => (event.kind === 'committed' && event.sha ? [event.sha] : []));
971
- if (commitShas.length === 0)
972
- return;
973
- const handle = await resolveRepoHandle(repoRoot);
974
- if (!handle)
975
- return;
976
- const runGraphql = (query, variables) => {
977
- const args = ghGraphqlArgs(query, variables);
978
- return gh(repoRoot, args);
979
- };
980
- applyCommitChecks(events ?? [], await fetchCommitChecks(runGraphql, handle.owner, handle.name, commitShas));
981
- }
982
- async function mergeGithubThread(repoRoot, kind, number, commentRows) {
983
- const parts = [normalizeComments(commentRows)];
984
- if (kind === 'pr') {
985
- const reviewsOut = await gh(repoRoot, ['api', `repos/{owner}/{repo}/pulls/${number}/reviews`, '--paginate']);
986
- parts.push(normalizeReviews(JSON.parse(reviewsOut)));
987
- }
988
- return mergeThread(parts);
989
- }
990
- function commentsFailureReason(err) {
991
- const message = err instanceof Error ? err.message : String(err);
992
- if (/ENOENT/.test(message))
993
- return 'gh CLI not found — install it and run `gh auth login`';
994
- if (/404|not found/i.test(message))
995
- return 'not found on GitHub — it may be closed or deleted';
996
- return firstLine(message);
997
- }
998
- async function loadGithubComments(repoRoot, kind, number, key) {
999
- const legacyComments = legacyIssueComments(repoRoot, number);
1000
- // The detail tier (hearsay-tools/cezarion#1183): the list no longer has to carry a body, so
1001
- // the pane asks for it here, in parallel with the thread. It is attached only to a thread
1002
- // that loaded, and a failed view never costs the thread.
1003
- const detail = fetchItemDetail(repoRoot, kind, number);
1004
- try {
1005
- const source = await loadGithubThreadSource(repoRoot, number, legacyComments);
1006
- await attachCommitChecks(repoRoot, source.events);
1007
- const { comments, truncated } = await mergeGithubThread(repoRoot, kind, number, source.commentRows);
1008
- const data = defined({
1009
- available: true,
1010
- comments,
1011
- // OR-folded exactly as before, so the pre-existing >200-comments trigger is preserved
1012
- // rather than replaced.
1013
- truncated: truncated || source.eventsTruncated || source.stoppedShort || undefined,
1014
- });
1015
- if (source.events)
1016
- data.events = source.events;
1017
- const itemDetail = await detail;
1018
- if (itemDetail)
1019
- data.detail = itemDetail;
1020
- cacheComments(key, data);
1021
- return data;
1022
- }
1023
- catch (err) {
1024
- return { available: false, reason: commentsFailureReason(err), comments: [] };
1025
- }
1026
- }
1027
- export async function fetchGithubComments(repoRoot, kind, number, refresh = false) {
1028
- if (productEnv('DRY_RUN') === '1')
1029
- return mockGithubComments(kind, number);
1030
- const key = commentsCacheKey(repoRoot, kind, number);
1031
- const cached = cachedGithubComments(key, refresh);
1032
- if (cached)
1033
- return cached;
1034
- return loadGithubComments(repoRoot, kind, number, key);
1035
- }
1036
- /** CEZ_DRY_RUN=1 — a small fixed thread (one image-bearing comment, plus a review for PRs) so
1037
- * the whole feature is demoable and e2e-testable offline. */
1038
- function mockGithubComments(kind, number) {
1039
- const base = Date.now() - 3_600_000;
1040
- const at = (offset) => new Date(base + offset).toISOString();
1041
- const comments = [
1042
- {
1043
- id: 1,
1044
- author: 'ada',
1045
- avatarUrl: 'https://avatars.githubusercontent.com/u/1?v=4',
1046
- createdAt: at(0),
1047
- body: 'Thanks for the report — I can reproduce. Which browser were you on?\n\n```\nchrome 126, macOS\n```',
1048
- kind: 'comment',
1049
- url: 'https://github.com/mock/repo/issues/1#issuecomment-1',
1050
- },
1051
- {
1052
- id: 2,
1053
- author: 'lin',
1054
- createdAt: at(600_000),
1055
- body: 'Here is the failing screen:\n\n![failure](https://avatars.githubusercontent.com/u/2?v=4)',
1056
- kind: 'comment',
1057
- url: 'https://github.com/mock/repo/issues/1#issuecomment-2',
1058
- },
1059
- ];
1060
- if (kind === 'pr') {
1061
- comments.push({
1062
- id: 3,
1063
- author: 'grace',
1064
- avatarUrl: 'https://avatars.githubusercontent.com/u/3?v=4',
1065
- createdAt: at(1_200_000),
1066
- body: 'Looks good overall — please add a regression test before this lands.',
1067
- kind: 'review',
1068
- reviewState: 'changes_requested',
1069
- url: 'https://github.com/mock/repo/pull/1#pullrequestreview-3',
1070
- });
1071
- }
1072
- // Timeline events (#525) so the whole feature is demoable and e2e-testable offline. Deliberately
1073
- // covers the cases that are easy to get wrong rather than one of each: a multi-commit run by ONE
1074
- // author (exercises the client-side grouping) with MIXED check states (passing/failing/pending
1075
- // plus one `null` = no CI configured), a label change, a cross-reference, and — for PRs — a
1076
- // merge. SHAs are full 40-char because the rollup query's `oid` rejects abbreviated ones, and a
1077
- // fixture that cheated there would not survive being pasted into a real query.
1078
- const sha = (seed) => seed.repeat(40).slice(0, 40);
1079
- const events = [
1080
- {
1081
- id: 'evt-100',
1082
- kind: 'labeled',
1083
- actor: 'ada',
1084
- avatarUrl: 'https://avatars.githubusercontent.com/u/1?v=4',
1085
- createdAt: at(300_000),
1086
- label: { name: 'bug', color: 'd73a4a' },
1087
- },
1088
- {
1089
- id: `evt-${sha('a')}`,
1090
- kind: 'committed',
1091
- actor: 'Lin Zhao',
1092
- createdAt: at(900_000),
1093
- sha: sha('a'),
1094
- message: 'fix(session): keep the refresh token on reload',
1095
- checks: 'passing',
1096
- },
1097
- {
1098
- id: `evt-${sha('b')}`,
1099
- kind: 'committed',
1100
- actor: 'Lin Zhao',
1101
- createdAt: at(960_000),
1102
- sha: sha('b'),
1103
- message: 'test(session): cover the reload path',
1104
- checks: 'failing',
1105
- },
1106
- {
1107
- id: `evt-${sha('c')}`,
1108
- kind: 'committed',
1109
- actor: 'Lin Zhao',
1110
- createdAt: at(1_020_000),
1111
- sha: sha('c'),
1112
- message: 'chore: appease the linter',
1113
- checks: 'pending',
1114
- },
1115
- {
1116
- id: `evt-${sha('d')}`,
1117
- kind: 'committed',
1118
- actor: 'Lin Zhao',
1119
- createdAt: at(1_080_000),
1120
- sha: sha('d'),
1121
- message: 'docs: note the new behavior',
1122
- checks: null, // no CI configured — renders no glyph, distinct from absent
1123
- },
1124
- {
1125
- id: 'evt-101',
1126
- kind: 'cross-referenced',
1127
- actor: 'grace',
1128
- avatarUrl: 'https://avatars.githubusercontent.com/u/3?v=4',
1129
- createdAt: at(1_500_000),
1130
- refNumber: 42,
1131
- refTitle: 'Session handling rewrite',
1132
- refIsPr: true,
1133
- url: 'https://github.com/mock/repo/pull/42',
1134
- },
1135
- ];
1136
- if (kind === 'pr') {
1137
- events.push({
1138
- id: 'evt-102',
1139
- kind: 'merged',
1140
- actor: 'grace',
1141
- avatarUrl: 'https://avatars.githubusercontent.com/u/3?v=4',
1142
- createdAt: at(1_800_000),
1143
- });
1144
- }
1145
- // The detail tier (hearsay-tools/cezarion#1183): the catalog row's own body and diffstat.
1146
- const row = number === undefined ? undefined
1147
- : (kind === 'pr' ? mockGithub().prs : mockGithub().issues).find((item) => item.number === number);
1148
- const detail = row ? {
1149
- body: row.body ?? '',
1150
- ...(kind === 'pr' ? { additions: row.additions ?? 0, deletions: row.deletions ?? 0 } : {}),
1151
- } : undefined;
1152
- return { available: true, comments, events, ...(detail ? { detail } : {}) };
1153
- }
1154
- // ---- the driver -------------------------------------------------------------
1155
- const mergeStateCache = new Map();
1156
- const mergeInflight = new Set();
1157
- const MERGE_CACHE_MS = 15_000;
1158
- async function fetchPrMergeState(repoRoot, repoRef, number, refresh = false) {
1159
- if (productEnv('DRY_RUN') === '1') {
1160
- return {
1161
- available: true,
1162
- mergeState: normalizeMergeState({
1163
- number,
1164
- title: 'Dry-run pull request',
1165
- url: `https://github.com/mock/repo/pull/${number}`,
1166
- state: 'OPEN',
1167
- isDraft: false,
1168
- headRefName: 'feat/dry-run',
1169
- baseRefName: 'main',
1170
- headRefOid: '0123456789abcdef0123456789abcdef01234567',
1171
- mergeable: 'MERGEABLE',
1172
- mergeStateStatus: 'CLEAN',
1173
- reviewDecision: 'APPROVED',
1174
- statusCheckRollup: [{ name: 'test', conclusion: 'SUCCESS', detailsUrl: 'https://github.com/mock/repo/actions' }],
1175
- }, { allow_merge_commit: true, allow_squash_merge: true, allow_rebase_merge: true }, { readable: true, requiredChecks: ['test'] }),
1176
- };
1177
- }
1178
- if (!repoRef)
1179
- return { available: false, reason: 'GitHub remote could not be resolved' };
1180
- const key = `${repoRoot}:${number}`;
1181
- const hit = mergeStateCache.get(key);
1182
- if (!refresh && hit && Date.now() - hit.at < MERGE_CACHE_MS)
1183
- return hit.value;
1184
- try {
1185
- const prOut = await gh(repoRoot, [
1186
- 'pr', 'view', String(number), '--json',
1187
- 'number,title,url,state,isDraft,headRefName,baseRefName,headRefOid,mergeable,mergeStateStatus,reviewDecision,statusCheckRollup,mergedAt',
1188
- ]);
1189
- const parsedPr = mergePrSchema.parse(JSON.parse(prOut));
1190
- // A pull request under another name is a redirect after a rename: look the name up again.
1191
- if (!matchesGithubPullRequest({ ...repoRef, number }, parsedPr)) {
1192
- forgetRepoHandle(repoRoot);
1193
- return { available: false, reason: 'GitHub returned a different pull request.' };
1194
- }
1195
- mergedPullRequestObservations.observe({ ...repoRef, number }, parsedPr);
1196
- const [policyOut, requirements] = await Promise.all([
1197
- gh(repoRoot, ['api', `repos/${repoRef.owner}/${repoRef.repo}`]),
1198
- fetchGithubMergeRequirements((args) => gh(repoRoot, args), repoRef.owner, repoRef.repo, parsedPr.baseRefName, number),
1199
- ]);
1200
- const value = {
1201
- available: true,
1202
- mergeState: normalizeMergeState(parsedPr, JSON.parse(policyOut), requirements),
1203
- };
1204
- mergeStateCache.set(key, { at: Date.now(), value });
1205
- return value;
1206
- }
1207
- catch (error) {
1208
- return { available: false, reason: firstLine(error instanceof Error ? error.message : String(error)) };
1209
- }
1210
- }
1211
- export function evictGithubProjectCaches(repoRoot) {
1212
- const contextKey = githubContext(repoRoot).key;
1213
- evictGithubListCaches(contextKey);
1214
- commentCountsCache.forEach((_value, key) => {
1215
- if (key.startsWith(`${contextKey}\0`))
1216
- commentCountsCache.delete(key);
1217
- });
1218
- mergeStateCache.forEach((_value, key) => {
1219
- if (key.startsWith(`${repoRoot}:`))
1220
- mergeStateCache.delete(key);
1221
- });
1222
- commentsCache.forEach((_value, key) => {
1223
- if (key.startsWith(`${contextKey}\0`))
1224
- commentsCache.delete(key);
1225
- });
1226
- itemCache.forEach((_value, key) => {
1227
- if (key.startsWith(`${contextKey}\0`))
1228
- itemCache.delete(key);
1229
- });
1230
- }
1231
- function mergeCancelledResult() {
1232
- return { merged: false, status: 409, error: 'Automatic merging was cancelled.', code: 'cancelled' };
1233
- }
1234
- function mergeConflictResult(error, code, current) {
1235
- return { merged: false, status: 409, error, code, current };
1236
- }
1237
- function mergePullRequestPreflight(current, input) {
1238
- if (current.headSha !== input.expectedHeadSha) {
1239
- return mergeConflictResult('The pull request head changed. Review the new commits before merging.', 'stale-head', current);
1240
- }
1241
- if (input.expectedHeadRef !== undefined && current.headRef !== input.expectedHeadRef) {
1242
- return mergeConflictResult('The pull request branch changed.', 'stale-branch', current);
1243
- }
1244
- if (input.requirePassingChecks && (current.checks.length === 0 || current.checks.some(check => check.state !== 'passing'))) {
1245
- return mergeConflictResult('Automatic merging requires at least one check and every current-head check passing.', 'checks-not-passing', current);
1246
- }
1247
- if (!current.methods.includes(input.method)) {
1248
- return mergeConflictResult('That merge method is no longer enabled.', 'disabled-method', current);
1249
- }
1250
- if (!mergePreflightAllowed(current, !input.requirePassingChecks && input.overrideRules)) {
1251
- return mergeConflictResult(current.blockers[0]?.message ?? 'The pull request is not eligible to merge.', current.eligibility, current);
1252
- }
1253
- return null;
1254
- }
1255
- async function mergeActiveCiConflict(repoRoot, repoRef, current, input) {
1256
- if (!(input.requirePassingChecks && productEnv('DRY_RUN') !== '1'))
1257
- return null;
1258
- if (!repoRef)
1259
- return { merged: false, status: 404, error: 'GitHub repository not found.' };
1260
- const active = parseActiveWorkflowRuns(await gh(repoRoot, activeWorkflowRunsArgs({
1261
- repository: `${repoRef.owner}/${repoRef.repo}`, headSha: current.headSha,
1262
- })));
1263
- if (input.canProceed?.() === false)
1264
- return mergeCancelledResult();
1265
- if (active)
1266
- return mergeConflictResult('Waiting for active CI workflows on the current PR head.', 'checks-active', current);
1267
- return null;
1268
- }
1269
- async function executeGithubMerge(repoRoot, repoRef, number, input, current) {
1270
- if (productEnv('DRY_RUN') === '1') {
1271
- evictGithubProjectCaches(repoRoot);
1272
- return { merged: true, number, url: current.url, method: input.method, mergeCommitSha: 'abcdef0123456789abcdef0123456789abcdef01' };
1273
- }
1274
- if (!repoRef)
1275
- return { merged: false, status: 404, error: 'GitHub repository not found.' };
1276
- if (input.canProceed?.() === false)
1277
- return mergeCancelledResult();
1278
- const out = await gh(repoRoot, [
1279
- 'api', '--method', 'PUT', `repos/${repoRef.owner}/${repoRef.repo}/pulls/${number}/merge`,
1280
- '-f', `merge_method=${input.method}`, '-f', `sha=${input.expectedHeadSha}`,
1281
- ]);
1282
- // Once GitHub accepted the mutation, report its real outcome even if intent changed in flight.
1283
- const result = ghMergeResultSchema.parse(JSON.parse(out));
1284
- if (!result.merged)
1285
- return mergeConflictResult(result.message ?? 'GitHub refused the merge.', 'github-blocked', current);
1286
- evictGithubProjectCaches(repoRoot);
1287
- return { merged: true, number, url: current.url, method: input.method, ...(result.sha ? { mergeCommitSha: result.sha } : {}) };
1288
- }
1289
- function mergePullRequestFailure(error) {
1290
- const message = firstLine(error instanceof Error ? error.message : String(error));
1291
- const status = /403|permission|forbidden/i.test(message) ? 403 : /404|not found/i.test(message) ? 404 : 502;
1292
- return { merged: false, status, error: status === 403 ? 'GitHub permission denied.' : status === 404 ? 'Pull request or repository not found.' : 'GitHub could not complete the merge.' };
1293
- }
1294
- async function mergePullRequest(repoRoot, repoRef, number, input) {
1295
- const key = `${repoRoot}:${number}`;
1296
- if (mergeInflight.has(key))
1297
- return { merged: false, status: 409, error: 'A merge is already in progress.', code: 'concurrent' };
1298
- mergeInflight.add(key);
1299
- try {
1300
- if (input.canProceed?.() === false)
1301
- return mergeCancelledResult();
1302
- const ref = await canonicalRepoRef(repoRoot, repoRef);
1303
- const fresh = await fetchPrMergeState(repoRoot, ref, number, true);
1304
- if (input.canProceed?.() === false)
1305
- return mergeCancelledResult();
1306
- if (!fresh.available)
1307
- return { merged: false, status: 502, error: fresh.reason };
1308
- const current = fresh.mergeState;
1309
- const preflight = mergePullRequestPreflight(current, input);
1310
- if (preflight)
1311
- return preflight;
1312
- const ciConflict = await mergeActiveCiConflict(repoRoot, ref, current, input);
1313
- if (ciConflict)
1314
- return ciConflict;
1315
- return await executeGithubMerge(repoRoot, ref, number, input, current);
1316
- }
1317
- catch (error) {
1318
- return mergePullRequestFailure(error);
1319
- }
1320
- finally {
1321
- mergeInflight.delete(key);
1322
- }
1323
- }
1324
- export function mergePreflightAllowed(current, overrideRules = false) {
1325
- return current.canMerge || (overrideRules && current.canOverride);
1326
- }
1327
- function readyCancelledResult() {
1328
- return { available: false, reason: 'Marking the pull request ready was cancelled.' };
1329
- }
1330
- function readyPullRequestInputInvalid(number, input) {
1331
- return !Number.isSafeInteger(number) || number < 1 || !/^[0-9a-f]{40}$/.test(input.expectedHeadSha) || !input.expectedHeadRef;
1332
- }
1333
- function readyPullRequestIdentityConflict(pr, repoRef, number, input) {
1334
- if (!matchesGithubPullRequest({ ...repoRef, number }, pr))
1335
- return { available: false, reason: 'GitHub returned a different pull request.' };
1336
- if (pr.headRefOid !== input.expectedHeadSha)
1337
- return { available: false, reason: 'The pull request head changed.' };
1338
- if (pr.headRefName !== input.expectedHeadRef)
1339
- return { available: false, reason: 'The pull request branch changed.' };
1340
- if (pr.state !== 'OPEN')
1341
- return { available: false, reason: 'The pull request is no longer open.' };
1342
- return null;
1343
- }
1344
- async function markDraftPullRequestReady(repoRoot, repoRef, number, input) {
1345
- if (input.canProceed?.() === false)
1346
- return readyCancelledResult();
1347
- await gh(repoRoot, ['pr', 'ready', String(number), '--repo', `github.com/${repoRef.owner}/${repoRef.repo}`]);
1348
- evictGithubProjectCaches(repoRoot);
1349
- if (input.canProceed?.() === false)
1350
- return readyCancelledResult();
1351
- return null;
1352
- }
1353
- async function readyPullRequestOwnership(repoRoot, repoRef, number, input) {
1354
- if (!repoRef)
1355
- return { available: false, reason: 'GitHub remote could not be resolved' };
1356
- const pr = mergePrSchema.pick({ number: true, url: true, state: true, isDraft: true, headRefName: true, headRefOid: true }).parse(JSON.parse(await gh(repoRoot, [
1357
- 'pr', 'view', String(number), '--json', 'number,url,state,isDraft,headRefName,headRefOid',
1358
- ])));
1359
- if (input.canProceed?.() === false)
1360
- return readyCancelledResult();
1361
- const identity = readyPullRequestIdentityConflict(pr, repoRef, number, input);
1362
- if (identity)
1363
- return identity;
1364
- if (!pr.isDraft)
1365
- return null;
1366
- return markDraftPullRequestReady(repoRoot, repoRef, number, input);
1367
- }
1368
- async function refreshReadyPullRequestState(repoRoot, repoRef, number, input) {
1369
- const fresh = await fetchPrMergeState(repoRoot, repoRef, number, true);
1370
- if (input.canProceed?.() === false)
1371
- return readyCancelledResult();
1372
- if (fresh.available && fresh.mergeState.headSha !== input.expectedHeadSha)
1373
- return { available: false, reason: 'The pull request head changed.' };
1374
- if (fresh.available && fresh.mergeState.headRef !== input.expectedHeadRef)
1375
- return { available: false, reason: 'The pull request branch changed.' };
1376
- return fresh;
1377
- }
1378
- /** gh has no compare-and-swap ready operation. Check ownership immediately before marking ready,
1379
- * then refresh again; the later merge has its own head guard and GitHub's atomic SHA check. */
1380
- async function readyPullRequest(repoRoot, repoRef, number, input) {
1381
- if (readyPullRequestInputInvalid(number, input)) {
1382
- return { available: false, reason: 'A valid pull request, head SHA and task branch are required.' };
1383
- }
1384
- const key = `${repoRoot}:${number}`;
1385
- if (mergeInflight.has(key))
1386
- return { available: false, reason: 'A pull request mutation is already in progress.' };
1387
- mergeInflight.add(key);
1388
- try {
1389
- if (input.canProceed?.() === false)
1390
- return readyCancelledResult();
1391
- const ref = await canonicalRepoRef(repoRoot, repoRef);
1392
- if (productEnv('DRY_RUN') !== '1') {
1393
- const ownership = await readyPullRequestOwnership(repoRoot, ref, number, input);
1394
- if (ownership)
1395
- return ownership;
1396
- }
1397
- return await refreshReadyPullRequestState(repoRoot, ref, number, input);
1398
- }
1399
- catch {
1400
- return { available: false, reason: 'GitHub could not mark the pull request ready for review.' };
1401
- }
1402
- finally {
1403
- mergeInflight.delete(key);
1404
- }
1405
- }
24
+ export { __clearCommentsCacheForTests, __clearGithubItemCacheForTests, fetchGithubCommentCounts, fetchGithubComments, fetchGithubItem, forgetGithubItem, mergeThread, normalizeComments, normalizeReviews, THREAD_ENTRY_CAP, } from './github-comments.js';
25
+ export { deriveIssueReferenceStatus, derivePrReferenceStatus, fetchRefStatuses, GH_REF_STATUS_MAX, mergeabilityOf, } from './github-ref-status-derive.js';
26
+ export { __clearRefStatusCacheForTests, __seedRefStatusCacheForTests, fetchGithubRefStatus, forgetRefStatus, readCachedRefStatuses, } from './github-ref-status.js';
27
+ export { evictGithubProjectCaches, fetchMergedPullRequests, lookupMergedPullRequests, mergePreflightAllowed, } from './github-mutations.js';
1406
28
  const GH_PR_STATES = {
1407
29
  MERGED: 'merged',
1408
30
  CLOSED: 'closed',
1409
31
  };
32
+ /**
33
+ * The GitHub forge driver — coordinates the sibling transport, list, comment, check, ref-status,
34
+ * and mutation modules behind the `ForgeDriver` seam.
35
+ */
1410
36
  export function createGithubDriver(repoRoot, repoRef) {
1411
37
  return {
1412
38
  kind: 'github',
@@ -1422,11 +48,6 @@ export function createGithubDriver(repoRoot, repoRef) {
1422
48
  refStatus: (input) => fetchGithubRefStatus(repoRoot, input),
1423
49
  cachedRefStatuses: (numbers) => readCachedRefStatuses(repoRoot, numbers),
1424
50
  branchPushed: (numbers) => {
1425
- // A push is the event that changes what the chips say about this task's pull requests —
1426
- // its checks start again, and its MERGEABILITY is recomputed from scratch. Both are cached
1427
- // per number, so without this the cockpit would keep showing the pre-push answer (up to a
1428
- // minute of "Ready to merge" for a branch that has just been rewritten) about a push the
1429
- // user watched this server make.
1430
51
  for (const number of numbers)
1431
52
  forgetRefStatus(repoRoot, number);
1432
53
  },
@@ -1434,25 +55,18 @@ export function createGithubDriver(repoRoot, repoRef) {
1434
55
  detectCached: () => detectGithubCached(repoRoot),
1435
56
  listIssues: async (opts) => (await fetchGithub(repoRoot, opts?.refresh, opts?.limit, opts)).issues,
1436
57
  listPRs: async (opts) => (await fetchGithub(repoRoot, opts?.refresh, opts?.limit, opts)).prs,
1437
- // The open-only list tier's escape hatch (#730) — this is the only path that can reach a
1438
- // closed or merged item.
1439
58
  searchItems: (kind, query, opts) => searchGithubItems(repoRoot, kind, query, opts?.limit),
1440
59
  viewItem: (kind, number) => viewGithubItem(repoRoot, kind, number),
1441
60
  prDiff: (number, opts) => fetchGithubPrDiff(repoRoot, number, opts?.refresh),
1442
61
  createPR: async (input) => {
1443
62
  const outcome = await createDraftPr(input);
1444
63
  if (outcome.ok) {
1445
- // A number the cockpit asked about BEFORE the pull request existed is cached as "this
1446
- // repository has no such number" — which is exactly what a `CEZ:PR=901` marker declared
1447
- // ahead of the push looks like. It exists now.
1448
64
  const createdNumber = refNumberFromUrl(outcome.url);
1449
65
  if (createdNumber !== null)
1450
66
  forgetRefStatus(repoRoot, createdNumber);
1451
67
  }
1452
68
  return outcome;
1453
69
  },
1454
- // Null covers everything from "no PR yet" to "gh missing" — the callers
1455
- // (Create PR → View PR flip) treat all of it as "nothing to link".
1456
70
  prStatus: async (branch) => {
1457
71
  if (productEnv('DRY_RUN') === '1')
1458
72
  return null;
@@ -1479,10 +93,6 @@ export function createGithubDriver(repoRoot, repoRef) {
1479
93
  mergePR: async (number, input) => {
1480
94
  const result = await mergePullRequest(repoRoot, repoRef, number, input);
1481
95
  if (result.merged) {
1482
- // We just changed this pull request, so what the ref-status cache holds about it is now
1483
- // known-stale — and its TTL would keep every chip showing the PRE-merge status for up to
1484
- // a minute after the user watched this server merge it. Forget it; the next reader asks
1485
- // the forge, gets `merged`, and then stops polling it at all.
1486
96
  forgetRefStatus(repoRoot, number);
1487
97
  forgetGithubItem(repoRoot, 'pr', number);
1488
98
  }
@@ -1492,7 +102,6 @@ export function createGithubDriver(repoRoot, repoRef) {
1492
102
  if (!repoRef)
1493
103
  return null;
1494
104
  const base = `https://github.com/${repoRef.owner}/${repoRef.repo}`;
1495
- // Branch names may contain '/' — encode per segment, keep the slashes.
1496
105
  const path = String(ref).split('/').map(encodeURIComponent).join('/');
1497
106
  switch (kind) {
1498
107
  case 'repo':
@@ -1509,47 +118,4 @@ export function createGithubDriver(repoRoot, repoRef) {
1509
118
  },
1510
119
  };
1511
120
  }
1512
- /** Strict archive authority: no partial GraphQL success, redirects, guessed identity or date. */
1513
- export async function fetchMergedPullRequests(runGraphql, identities) {
1514
- const repositories = new Map();
1515
- for (const identity of new Map(identities.map(pr => [pullRequestKey(pr), pr])).values()) {
1516
- const key = `${identity.owner}/${identity.repo}`;
1517
- repositories.set(key, [...(repositories.get(key) ?? []), identity]);
1518
- }
1519
- const merged = [];
1520
- for (const [repository, prs] of repositories) {
1521
- for (let offset = 0; offset < prs.length; offset += 25) {
1522
- const chunk = prs.slice(offset, offset + 25);
1523
- const response = await mergedPullRequestChunk(runGraphql, chunk);
1524
- const parsed = z.object({ errors: z.array(z.unknown()).optional(), data: z.object({ repository: z.object({ nameWithOwner: z.string() }).passthrough().nullable() }) }).safeParse(response);
1525
- if (!parsed.success || parsed.data.errors?.length || parsed.data.data.repository?.nameWithOwner.toLowerCase() !== repository.toLowerCase())
1526
- continue;
1527
- for (const pr of chunk) {
1528
- const fact = mergedPullRequestObservations.observe(pr, parsed.data.data.repository[`pr${pr.number}`]);
1529
- if (fact)
1530
- merged.push(fact);
1531
- }
1532
- }
1533
- }
1534
- return merged;
1535
- }
1536
- export async function lookupMergedPullRequests(repoRoot, identities, signal) {
1537
- signal.throwIfAborted();
1538
- if (productEnv('DRY_RUN') === '1')
1539
- return [];
1540
- const unique = [...new Map(identities.map(pr => [pullRequestKey(pr), pr])).values()];
1541
- const known = unique.flatMap(pr => mergedPullRequestObservations.get(pr) ?? []);
1542
- const missing = unique.filter(pr => !mergedPullRequestObservations.get(pr));
1543
- if (missing.length === 0)
1544
- return known;
1545
- const context = githubContext(repoRoot);
1546
- const fetched = await fetchMergedPullRequests(async (query, variables) => {
1547
- const args = ['api', 'graphql', '--hostname', 'github.com', '-f', `query=${query}`];
1548
- for (const [key, value] of Object.entries(variables))
1549
- args.push('-f', `${key}=${value}`);
1550
- // Archive-on-merge is one of the gated pollers: during a pause it refuses at once and skips this tick.
1551
- return githubRequestGate.run(() => gh(repoRoot, args, 15_000, signal, context), { signal, whenPaused: 'throw' });
1552
- }, missing);
1553
- return [...known, ...fetched];
1554
- }
1555
121
  //# sourceMappingURL=github.js.map