@hearsay-tools/squawk 0.18.0-dev.8274 → 0.18.0-dev.8291
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/delegation/transport.d.ts +65 -65
- package/dist/runners/claude/claude-executable.js +3 -9
- package/dist/runners/claude/claude-executable.js.map +1 -1
- package/dist/runners/claude/claude-model-catalog.d.ts +1 -1
- package/dist/runners/claude/claude-model-catalog.js +1 -1
- package/dist/runners/claude/claude-model-catalog.js.map +1 -1
- package/dist/runners/claude/claude-skill-catalog.d.ts +1 -1
- package/dist/runners/claude/claude-skill-catalog.js +1 -1
- package/dist/runners/claude/claude-skill-catalog.js.map +1 -1
- package/dist/runners/codex/codex-app-server-transport.js +3 -3
- package/dist/runners/codex/codex-app-server-transport.js.map +1 -1
- package/dist/runners/codex/codex-approvals.d.ts +1 -1
- package/dist/runners/codex/codex-approvals.js +1 -1
- package/dist/runners/codex/codex-approvals.js.map +1 -1
- package/dist/runners/codex/codex-model-catalog.d.ts +1 -1
- package/dist/runners/codex/codex-model-catalog.js +1 -1
- package/dist/runners/codex/codex-model-catalog.js.map +1 -1
- package/dist/runners/codex/codex-permissions.js +1 -1
- package/dist/runners/codex/codex-permissions.js.map +1 -1
- package/dist/runners/codex/codex-skill-catalog.d.ts +1 -1
- package/dist/runners/codex/codex-skill-catalog.js +1 -1
- package/dist/runners/codex/codex-skill-catalog.js.map +1 -1
- package/dist/server/forge/github-checks.d.ts +31 -0
- package/dist/server/forge/github-checks.js +155 -0
- package/dist/server/forge/github-checks.js.map +1 -0
- package/dist/server/forge/github-list.d.ts +77 -0
- package/dist/server/forge/github-list.js +541 -0
- package/dist/server/forge/github-list.js.map +1 -0
- package/dist/server/forge/github-pr-diff.d.ts +10 -0
- package/dist/server/forge/github-pr-diff.js +126 -0
- package/dist/server/forge/github-pr-diff.js.map +1 -0
- package/dist/server/forge/github-shared.d.ts +119 -0
- package/dist/server/forge/github-shared.js +225 -0
- package/dist/server/forge/github-shared.js.map +1 -0
- package/dist/server/forge/github.d.ts +8 -192
- package/dist/server/forge/github.js +12 -1166
- package/dist/server/forge/github.js.map +1 -1
- package/dist/server/reports-api.d.ts +2 -2
- package/dist/server/runner-install-routes.d.ts +10 -10
- package/dist/server/server.d.ts +60 -60
- package/package.json +4 -4
|
@@ -5,878 +5,30 @@ import { defined } from '../../core/defined.js';
|
|
|
5
5
|
import { activeWorkflowRunsArgs, parseActiveWorkflowRuns } from '../../ci-wait/github.js';
|
|
6
6
|
import { pullRequestKey } from '../../runs/pull-requests.js';
|
|
7
7
|
import { matchesGithubPullRequest, mergedPullRequestObservations } from '../../merge-observations.js';
|
|
8
|
-
import { randomUUID } from 'node:crypto';
|
|
9
8
|
import { z } from 'zod';
|
|
10
9
|
import { githubRequestGate } from './github-request-gate.js';
|
|
11
10
|
import { refStatusQuery } from './github-ref-status-query.js';
|
|
12
11
|
import { mergedPullRequestChunk } from './github-merged-pr-chunk.js';
|
|
13
12
|
import { reviewerKey, reviewerRefSchema } from './github-reviewer-ref.js';
|
|
14
|
-
import { gh, githubContext
|
|
15
|
-
import { canonicalRepoRef, discoverRepoHandle, forgetRepoHandle,
|
|
13
|
+
import { gh, githubContext } from './github-cli.js';
|
|
14
|
+
import { canonicalRepoRef, discoverRepoHandle, forgetRepoHandle, resolveRepoHandle } from './github-repo-handle.js';
|
|
16
15
|
export { parseOwnerName } from './github-cli.js';
|
|
17
16
|
export { __clearRepoHandleCacheForTests, discoverRepoHandle, forgetRepoHandle, resolveRepoHandle } from './github-repo-handle.js';
|
|
18
|
-
import { GITHUB_COMMENT_COUNTS_MAX,
|
|
19
|
-
import { fetchIssueProjects, fetchRepositoryProjects, fetchViewerLogin } from './github-filters.js';
|
|
17
|
+
import { GITHUB_COMMENT_COUNTS_MAX, REFERENCE_STATUS_MAX } from '../../contract/index.js';
|
|
20
18
|
import { fetchGithubMergeRequirements } from './github-merge-requirements.js';
|
|
21
19
|
import { mergePrSchema, normalizeMergeState } from './github-merge-state.js';
|
|
22
20
|
import { fetchTimelinePages, normalizeEvents, TIMELINE_PER_PAGE } from './github-timeline.js';
|
|
23
21
|
export { normalizeMergeState } from './github-merge-state.js';
|
|
24
22
|
export { fetchTimelinePages, ghTimelineEventSchema, normalizeEvents, TIMELINE_BUDGET_MS, TIMELINE_EVENT_CAP, TIMELINE_EVENT_KINDS, TIMELINE_MAX_PAGES, TIMELINE_MIN_PAGE_MS, } from './github-timeline.js';
|
|
25
23
|
import { refNumberFromUrl } from '../../contract/index.js';
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
export
|
|
34
|
-
export const GH_PR_DIFF_JSON_CAP = 4 * 1024 * 1024;
|
|
35
|
-
const ghPrFileSchema = z.object({
|
|
36
|
-
filename: z.string().min(1),
|
|
37
|
-
previous_filename: z.string().optional(),
|
|
38
|
-
status: z.enum(['added', 'modified', 'removed', 'renamed', 'copied', 'changed']),
|
|
39
|
-
additions: z.number().int().nonnegative(),
|
|
40
|
-
deletions: z.number().int().nonnegative(),
|
|
41
|
-
patch: z.string().optional(),
|
|
42
|
-
});
|
|
43
|
-
const ghPrHeadSchema = z.object({ headRefOid: z.string().regex(/^[0-9a-f]{40}$/i) });
|
|
44
|
-
export class GithubPrNotFoundError extends Error {
|
|
45
|
-
}
|
|
46
|
-
const prDiffCache = new Map();
|
|
47
|
-
/** Fetch no more than the three GitHub pages represented by the public 300-file response cap. */
|
|
48
|
-
export async function fetchPrFilePages(runPage) {
|
|
49
|
-
const rows = [];
|
|
50
|
-
for (let page = 1; page <= GH_PR_DIFF_FILE_CAP / 100; page++) {
|
|
51
|
-
const next = z.array(z.unknown()).parse(JSON.parse(await runPage(page)));
|
|
52
|
-
rows.push(...next);
|
|
53
|
-
if (next.length < 100)
|
|
54
|
-
break;
|
|
55
|
-
}
|
|
56
|
-
return rows;
|
|
57
|
-
}
|
|
58
|
-
export async function fetchGithubPrDiff(repoRoot, number, refresh = false) {
|
|
59
|
-
if (productEnv('DRY_RUN') === '1')
|
|
60
|
-
return mockGithubPrDiff(number);
|
|
61
|
-
try {
|
|
62
|
-
const head = ghPrHeadSchema.parse(JSON.parse(await gh(repoRoot, ['pr', 'view', String(number), '--json', 'headRefOid']))).headRefOid;
|
|
63
|
-
const key = `${repoRoot}\0${number}\0${head}`;
|
|
64
|
-
const hit = prDiffCache.get(key);
|
|
65
|
-
if (!refresh && hit && Date.now() - hit.at < CACHE_MS)
|
|
66
|
-
return hit.data;
|
|
67
|
-
const rows = z.array(ghPrFileSchema).parse(await fetchPrFilePages((page) => gh(repoRoot, ['api', `repos/{owner}/{repo}/pulls/${number}/files?per_page=100&page=${page}`], 30_000)));
|
|
68
|
-
const limited = rows.slice(0, GH_PR_DIFF_FILE_CAP);
|
|
69
|
-
// A full third page may have a successor. Without fetching a 301st file, conservatively call
|
|
70
|
-
// the response partial rather than claiming completeness we cannot prove.
|
|
71
|
-
let responseTruncated = rows.length >= GH_PR_DIFF_FILE_CAP;
|
|
72
|
-
const reasons = responseTruncated ? [`Only the first ${GH_PR_DIFF_FILE_CAP} files are shown.`] : [];
|
|
73
|
-
const files = limited.map((row) => {
|
|
74
|
-
let patch = row.patch;
|
|
75
|
-
let truncated = false;
|
|
76
|
-
let patchUnavailableReason;
|
|
77
|
-
if (patch !== undefined && Buffer.byteLength(patch, 'utf8') > GH_PR_PATCH_CAP) {
|
|
78
|
-
patch = undefined;
|
|
79
|
-
truncated = true;
|
|
80
|
-
patchUnavailableReason = 'too-large';
|
|
81
|
-
responseTruncated = true;
|
|
82
|
-
}
|
|
83
|
-
else if (patch === undefined) {
|
|
84
|
-
patchUnavailableReason = row.additions === 0 && row.deletions === 0 ? 'binary' : 'not-provided';
|
|
85
|
-
}
|
|
86
|
-
return {
|
|
87
|
-
path: row.filename,
|
|
88
|
-
...(row.previous_filename ? { previousPath: row.previous_filename } : {}),
|
|
89
|
-
status: row.status,
|
|
90
|
-
additions: row.additions,
|
|
91
|
-
deletions: row.deletions,
|
|
92
|
-
...(patch !== undefined ? { patch } : {}),
|
|
93
|
-
...(patchUnavailableReason ? { patchUnavailableReason } : {}),
|
|
94
|
-
...(truncated ? { truncated: true } : {}),
|
|
95
|
-
};
|
|
96
|
-
});
|
|
97
|
-
let kept = files;
|
|
98
|
-
while (kept.length > 0 &&
|
|
99
|
-
Buffer.byteLength(JSON.stringify({ available: true, number, headSha: head, files: kept }), 'utf8') >
|
|
100
|
-
GH_PR_DIFF_JSON_CAP) {
|
|
101
|
-
kept = kept.slice(0, -1);
|
|
102
|
-
responseTruncated = true;
|
|
103
|
-
}
|
|
104
|
-
if (kept.length < files.length)
|
|
105
|
-
reasons.push('The response size limit omitted some files.');
|
|
106
|
-
if (files.some((file) => file.truncated))
|
|
107
|
-
reasons.push('One or more patches exceeded the per-file limit.');
|
|
108
|
-
const data = {
|
|
109
|
-
available: true,
|
|
110
|
-
number,
|
|
111
|
-
headSha: head,
|
|
112
|
-
files: kept,
|
|
113
|
-
additions: rows.reduce((sum, row) => sum + row.additions, 0),
|
|
114
|
-
deletions: rows.reduce((sum, row) => sum + row.deletions, 0),
|
|
115
|
-
truncated: responseTruncated,
|
|
116
|
-
...(reasons.length ? { reason: reasons.join(' ') } : {}),
|
|
117
|
-
};
|
|
118
|
-
prDiffCache.set(key, { at: Date.now(), data });
|
|
119
|
-
while (prDiffCache.size > 50)
|
|
120
|
-
prDiffCache.delete(prDiffCache.keys().next().value);
|
|
121
|
-
return data;
|
|
122
|
-
}
|
|
123
|
-
catch (err) {
|
|
124
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
125
|
-
if (/HTTP 404|Could not resolve to a PullRequest|no pull requests found/i.test(message)) {
|
|
126
|
-
throw new GithubPrNotFoundError(`Pull request #${number} was not found`);
|
|
127
|
-
}
|
|
128
|
-
return {
|
|
129
|
-
available: false,
|
|
130
|
-
reason: /ENOENT/.test(message)
|
|
131
|
-
? 'gh CLI not found — install it and run `gh auth login`'
|
|
132
|
-
: firstLine(message),
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
function mockGithubPrDiff(number) {
|
|
137
|
-
return {
|
|
138
|
-
available: true,
|
|
139
|
-
number,
|
|
140
|
-
headSha: '0123456789abcdef0123456789abcdef01234567',
|
|
141
|
-
additions: 15,
|
|
142
|
-
deletions: 4,
|
|
143
|
-
truncated: true,
|
|
144
|
-
reason: 'One or more patches were not provided by GitHub.',
|
|
145
|
-
files: [
|
|
146
|
-
{ path: 'src/session.ts', status: 'modified', additions: 8, deletions: 3, patch: '@@ -1,3 +1,4 @@\n-old\n+new\n context' },
|
|
147
|
-
{ path: 'src/new-name.ts', previousPath: 'src/old-name.ts', status: 'renamed', additions: 7, deletions: 1, patch: '@@ -1 +1 @@\n-old name\n+new name' },
|
|
148
|
-
{ path: 'assets/logo.png', status: 'modified', additions: 0, deletions: 0, patchUnavailableReason: 'binary' },
|
|
149
|
-
{ path: 'generated/output.txt', status: 'modified', additions: 0, deletions: 0, patchUnavailableReason: 'too-large', truncated: true },
|
|
150
|
-
],
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
// `gh … --json` output — validated at the boundary, extras stripped.
|
|
154
|
-
const ghAuthor = z.object({ login: z.string() }).nullish();
|
|
155
|
-
// `color` is the 6-hex GitHub label color (no `#`), '' when gh omits it.
|
|
156
|
-
const ghLabel = z.object({ name: z.string(), color: z.string().default('') });
|
|
157
|
-
const ghIssueSchema = z.object({
|
|
158
|
-
number: z.number(),
|
|
159
|
-
title: z.string(),
|
|
160
|
-
author: ghAuthor,
|
|
161
|
-
createdAt: z.string(),
|
|
162
|
-
labels: z.array(ghLabel).default([]),
|
|
163
|
-
assignees: z.array(z.object({ login: z.string() })).default([]),
|
|
164
|
-
body: z.string().nullish(),
|
|
165
|
-
url: z.string(),
|
|
166
|
-
});
|
|
167
|
-
// One check run's `gh --json statusCheckRollup` entry — every field optional/nullish because
|
|
168
|
-
// gh's shape varies by check provider (exported so #400's unit tests can build fixtures).
|
|
169
|
-
export const ghCheckRunSchema = z.object({
|
|
170
|
-
state: z.string().nullish(),
|
|
171
|
-
status: z.string().nullish(),
|
|
172
|
-
conclusion: z.string().nullish(),
|
|
173
|
-
});
|
|
174
|
-
const ghStatusCheckRollup = z.array(ghCheckRunSchema).nullish();
|
|
175
|
-
const ghPrViewSchema = z.object({
|
|
176
|
-
number: z.number(),
|
|
177
|
-
url: z.string(),
|
|
178
|
-
state: z.string().default('OPEN'),
|
|
179
|
-
mergedAt: z.unknown().optional(),
|
|
180
|
-
isDraft: z.boolean().default(false),
|
|
181
|
-
statusCheckRollup: ghStatusCheckRollup,
|
|
182
|
-
});
|
|
183
|
-
const ghMergeResultSchema = z.object({
|
|
184
|
-
merged: z.boolean(),
|
|
185
|
-
message: z.string().nullish(),
|
|
186
|
-
sha: z.string().nullish(),
|
|
187
|
-
});
|
|
188
|
-
/** Exported for unit tests (#400) — collapses a zod-validated `statusCheckRollup` array down to
|
|
189
|
-
* the single enum the GitHub tab (list rows + detail badge) renders. */
|
|
190
|
-
export function rollupToChecks(rollup) {
|
|
191
|
-
if (!rollup || rollup.length === 0)
|
|
192
|
-
return null;
|
|
193
|
-
const states = rollup.map((r) => (r.conclusion || r.state || r.status || '').toUpperCase());
|
|
194
|
-
if (states.some((s) => ['FAILURE', 'ERROR', 'TIMED_OUT', 'ACTION_REQUIRED'].includes(s)))
|
|
195
|
-
return 'failing';
|
|
196
|
-
if (states.some((s) => ['PENDING', 'IN_PROGRESS', 'QUEUED', 'EXPECTED', ''].includes(s)))
|
|
197
|
-
return 'pending';
|
|
198
|
-
return 'passing';
|
|
199
|
-
}
|
|
200
|
-
/** `gh api graphql` argv. `-f` sends every value as a String, and GitHub rejects a String where
|
|
201
|
-
* the query declares `Int!` ("Could not coerce value to Int", open-mercato/cezar#1366), so a
|
|
202
|
-
* number goes through `-F`. A string never does: `-F` would read `@file` and coerce
|
|
203
|
-
* `true`/numerals, which is not what an opaque cursor or a login means. */
|
|
204
|
-
export function ghGraphqlArgs(query, variables = {}) {
|
|
205
|
-
const args = ['api', 'graphql', '-f', `query=${query}`];
|
|
206
|
-
for (const [key, value] of Object.entries(variables)) {
|
|
207
|
-
args.push(typeof value === 'number' ? '-F' : '-f', `${key}=${value}`);
|
|
208
|
-
}
|
|
209
|
-
return args;
|
|
210
|
-
}
|
|
211
|
-
// Paged open lists defer comment counts; hydrate them through the counts route after paint.
|
|
212
|
-
/** GitHub GraphQL rejects `first` above 100 (EXCESSIVE_PAGINATION); larger limits walk pages. */
|
|
213
|
-
export const GH_GRAPHQL_PAGE_MAX = 100;
|
|
214
|
-
// Labels up to 100, which is what `gh issue list --json labels` read before the GraphQL page.
|
|
215
|
-
const LIST_NODE_FIELDS = 'number title author { login } createdAt url body labels(first: 100) { nodes { name color } }';
|
|
216
|
-
const listQuery = (side) => `
|
|
217
|
-
query ($owner: String!, $name: String!, $first: Int!, $after: String) {
|
|
218
|
-
repository(owner: $owner, name: $name) {
|
|
219
|
-
${side}(first: $first, after: $after, states: OPEN, orderBy: {field: CREATED_AT, direction: DESC}) {
|
|
220
|
-
totalCount
|
|
221
|
-
pageInfo { hasNextPage endCursor }
|
|
222
|
-
nodes { ${LIST_NODE_FIELDS} ${side === 'issues' ? 'assignees(first: 20) { nodes { login } }' : 'isDraft additions deletions'} }
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
}`;
|
|
226
|
-
/** A GraphQL connection (`{ nodes }`) read as the flat array `gh … --json` used to return. */
|
|
227
|
-
const connectionOf = (item) => z.object({ nodes: z.array(item.nullable()).default([]) }).nullish()
|
|
228
|
-
.transform((connection) => (connection?.nodes ?? []).filter((node) => node != null));
|
|
229
|
-
const ghListNodeSchema = z.object({
|
|
230
|
-
number: z.number(),
|
|
231
|
-
title: z.string(),
|
|
232
|
-
author: ghAuthor,
|
|
233
|
-
createdAt: z.string(),
|
|
234
|
-
url: z.string(),
|
|
235
|
-
body: z.string().nullish(),
|
|
236
|
-
labels: connectionOf(ghLabel),
|
|
237
|
-
assignees: connectionOf(z.object({ login: z.string() })),
|
|
238
|
-
isDraft: z.boolean().nullish(),
|
|
239
|
-
additions: z.number().nullish(),
|
|
240
|
-
deletions: z.number().nullish(),
|
|
241
|
-
});
|
|
242
|
-
const ghListConnectionSchema = z.object({
|
|
243
|
-
totalCount: z.number().int().nonnegative(),
|
|
244
|
-
pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullish() }),
|
|
245
|
-
nodes: z.array(ghListNodeSchema.nullable()),
|
|
246
|
-
});
|
|
247
|
-
function parseListConnection(out, side) {
|
|
248
|
-
const parsed = JSON.parse(out);
|
|
249
|
-
const message = parsed.errors?.map((e) => e.message).filter(Boolean).join(' ');
|
|
250
|
-
if (message)
|
|
251
|
-
throw new Error(message);
|
|
252
|
-
if (!parsed.data?.repository)
|
|
253
|
-
throw new Error('GitHub did not resolve this repository');
|
|
254
|
-
return ghListConnectionSchema.parse(parsed.data.repository[side]);
|
|
255
|
-
}
|
|
256
|
-
/**
|
|
257
|
-
* One side of the open list: up to `limit` rows from `cursor`, in requests of at most
|
|
258
|
-
* `GH_GRAPHQL_PAGE_MAX`. `nextCursor` is where the rows stop, or `null` once the side is
|
|
259
|
-
* exhausted. `done` asks for `first: 0`, which still answers `totalCount`, so an exhausted side
|
|
260
|
-
* keeps a fresh total without ever restarting from its first page (open-mercato/cezar#1366
|
|
261
|
-
* restarted it while the other side paged).
|
|
262
|
-
*/
|
|
263
|
-
export async function fetchListConnection(run, owner, name, side, limit, cursor, done = false) {
|
|
264
|
-
const query = listQuery(side);
|
|
265
|
-
if (done) {
|
|
266
|
-
const page = parseListConnection(await run(query, { owner, name, first: 0 }), side);
|
|
267
|
-
return { totalCount: page.totalCount, nodes: [], nextCursor: null };
|
|
268
|
-
}
|
|
269
|
-
const nodes = [];
|
|
270
|
-
let after = cursor;
|
|
271
|
-
for (;;) {
|
|
272
|
-
const first = Math.min(GH_GRAPHQL_PAGE_MAX, limit - nodes.length);
|
|
273
|
-
const page = parseListConnection(await run(query, { owner, name, first, ...(after ? { after } : {}) }), side);
|
|
274
|
-
const rows = page.nodes.filter((node) => node !== null);
|
|
275
|
-
nodes.push(...rows);
|
|
276
|
-
const next = page.pageInfo.hasNextPage ? page.pageInfo.endCursor ?? null : null;
|
|
277
|
-
// An empty page that claims more would loop forever; read it as the end of the side.
|
|
278
|
-
if (next === null || rows.length === 0)
|
|
279
|
-
return { totalCount: page.totalCount, nodes, nextCursor: null };
|
|
280
|
-
if (next === after)
|
|
281
|
-
throw new Error('GitHub list cursor did not advance');
|
|
282
|
-
// A short page with more behind it still ends this request: the cursor resumes it exactly.
|
|
283
|
-
if (nodes.length >= limit || rows.length < first)
|
|
284
|
-
return { totalCount: page.totalCount, nodes, nextCursor: next };
|
|
285
|
-
after = next;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
/* Reads degrade to `available: false` with a hint — never an error (plan rule
|
|
289
|
-
7): no `gh`, no remote, offline all land on the same quiet path. A short
|
|
290
|
-
cache keeps tab switches from hammering the GitHub API; a cached fetch with
|
|
291
|
-
a bigger limit than asked serves fine (it's a superset). Keyed by repository/host/account context
|
|
292
|
-
(multi-project workspace, step 2.6) plus the page asked for: one project's — possibly private —
|
|
293
|
-
issues/PRs must never be served under another project's scope, and page 2 is never page 1.
|
|
294
|
-
Bounded like `commentsCache` so an unbounded workspace can't grow it without limit. */
|
|
295
|
-
let listRequestOrder = 0;
|
|
296
|
-
/** Per context, the order of the newest page-1 refresh. A refresh drops the context's later
|
|
297
|
-
* pages (their cursors were cut from the old first page), and a later page that started before
|
|
298
|
-
* it may answer its caller but never re-enters the cache. Bounded with `listCache`. */
|
|
299
|
-
const listRefreshOrder = new Map();
|
|
300
|
-
const listCache = new Map();
|
|
301
|
-
const LIST_CACHE_MAX = 50;
|
|
302
|
-
const CACHE_MS = 60_000;
|
|
303
|
-
/** Which page key holds a projects generation, so `fetchGithubProjects` never scans the cache.
|
|
304
|
-
* Installed and evicted in step with `listCache`, so it shares its bound. */
|
|
305
|
-
const projectGenerations = new Map();
|
|
306
|
-
/** Board discovery (the `projectsV2` walk) per context: page 2 pays for membership only. A
|
|
307
|
-
* failed discovery is dropped, so the next page or refresh asks again. */
|
|
308
|
-
const repositoryProjectsCache = new Map();
|
|
309
|
-
function dropListEntry(key) {
|
|
310
|
-
const generation = listCache.get(key)?.data.projectsGeneration;
|
|
311
|
-
if (generation && projectGenerations.get(generation) === key)
|
|
312
|
-
projectGenerations.delete(generation);
|
|
313
|
-
listCache.delete(key);
|
|
314
|
-
}
|
|
315
|
-
function discoverRepositoryProjects(contextKey, refresh, start) {
|
|
316
|
-
const hit = repositoryProjectsCache.get(contextKey);
|
|
317
|
-
if (!refresh && hit && Date.now() - hit.at < CACHE_MS)
|
|
318
|
-
return hit.projects;
|
|
319
|
-
const projects = start();
|
|
320
|
-
const entry = { at: Date.now(), projects };
|
|
321
|
-
repositoryProjectsCache.delete(contextKey);
|
|
322
|
-
repositoryProjectsCache.set(contextKey, entry);
|
|
323
|
-
projects.catch(() => {
|
|
324
|
-
if (repositoryProjectsCache.get(contextKey) === entry)
|
|
325
|
-
repositoryProjectsCache.delete(contextKey);
|
|
326
|
-
});
|
|
327
|
-
while (repositoryProjectsCache.size > LIST_CACHE_MAX) {
|
|
328
|
-
const oldest = repositoryProjectsCache.keys().next().value;
|
|
329
|
-
if (oldest === undefined)
|
|
330
|
-
break;
|
|
331
|
-
repositoryProjectsCache.delete(oldest);
|
|
332
|
-
}
|
|
333
|
-
return projects;
|
|
334
|
-
}
|
|
335
|
-
export const GH_MAX_LIMIT = 1000;
|
|
336
|
-
function listPageKey(contextKey, page) {
|
|
337
|
-
return JSON.stringify([contextKey, page.issuesCursor ?? null, page.prsCursor ?? null, !!page.issuesDone, !!page.prsDone]);
|
|
338
|
-
}
|
|
339
|
-
function isFirstGithubPage(page) {
|
|
340
|
-
return !page.issuesCursor && !page.prsCursor && !page.issuesDone && !page.prsDone;
|
|
341
|
-
}
|
|
342
|
-
function cachedGithubPage(hit, refresh, capped) {
|
|
343
|
-
if (!refresh && hit && Date.now() - hit.at < CACHE_MS && hit.limit >= capped)
|
|
344
|
-
return hit.data;
|
|
345
|
-
return undefined;
|
|
346
|
-
}
|
|
347
|
-
function rememberListRefresh(contextKey, order, key) {
|
|
348
|
-
listRefreshOrder.delete(contextKey);
|
|
349
|
-
listRefreshOrder.set(contextKey, order);
|
|
350
|
-
while (listRefreshOrder.size > LIST_CACHE_MAX) {
|
|
351
|
-
const oldest = listRefreshOrder.keys().next().value;
|
|
352
|
-
if (oldest === undefined)
|
|
353
|
-
break;
|
|
354
|
-
listRefreshOrder.delete(oldest);
|
|
355
|
-
}
|
|
356
|
-
for (const [cached, entry] of [...listCache]) {
|
|
357
|
-
if (entry.contextKey === contextKey && cached !== key)
|
|
358
|
-
dropListEntry(cached);
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
function githubProjectGraphql(repoRoot, context) {
|
|
362
|
-
// Optional project queries have one shared wall-clock budget. A missing scope, a cap,
|
|
363
|
-
// or malformed metadata must never turn an otherwise working list into unavailable.
|
|
364
|
-
const deadline = Date.now() + 15_000;
|
|
365
|
-
return (query, variables) => {
|
|
366
|
-
const remaining = deadline - Date.now();
|
|
367
|
-
if (remaining <= 0)
|
|
368
|
-
return Promise.reject(new Error('Project lookup timed out'));
|
|
369
|
-
return gh(repoRoot, ghGraphqlArgs(query, variables), Math.min(remaining, 8_000), undefined, context);
|
|
370
|
-
};
|
|
371
|
-
}
|
|
372
|
-
function recordLabelColor(labelColors, label) {
|
|
373
|
-
if (label.color && !labelColors[label.name])
|
|
374
|
-
labelColors[label.name] = label.color;
|
|
375
|
-
}
|
|
376
|
-
function flattenGithubIssue(issue, recordColor) {
|
|
377
|
-
issue.labels.forEach(recordColor);
|
|
378
|
-
return {
|
|
379
|
-
kind: 'issue',
|
|
380
|
-
number: issue.number,
|
|
381
|
-
title: issue.title,
|
|
382
|
-
author: issue.author?.login ?? '?',
|
|
383
|
-
createdAt: issue.createdAt,
|
|
384
|
-
labels: issue.labels.map((label) => label.name),
|
|
385
|
-
body: (issue.body ?? '').slice(0, 8_000),
|
|
386
|
-
url: issue.url,
|
|
387
|
-
comments: 0,
|
|
388
|
-
assignees: issue.assignees.map((assignee) => assignee.login),
|
|
389
|
-
};
|
|
390
|
-
}
|
|
391
|
-
function flattenGithubPr(pr, recordColor) {
|
|
392
|
-
pr.labels.forEach(recordColor);
|
|
393
|
-
const isDraft = pr.isDraft ?? false;
|
|
394
|
-
return {
|
|
395
|
-
kind: 'pr',
|
|
396
|
-
number: pr.number,
|
|
397
|
-
title: pr.title,
|
|
398
|
-
author: pr.author?.login ?? '?',
|
|
399
|
-
createdAt: pr.createdAt,
|
|
400
|
-
labels: [...pr.labels.map((label) => label.name), ...(isDraft ? ['draft'] : [])],
|
|
401
|
-
body: (pr.body ?? '').slice(0, 8_000),
|
|
402
|
-
url: pr.url,
|
|
403
|
-
comments: 0,
|
|
404
|
-
isDraft,
|
|
405
|
-
additions: pr.additions ?? 0,
|
|
406
|
-
deletions: pr.deletions ?? 0,
|
|
407
|
-
// Hydrated lazily by `fetchGithubChecks` for on-screen rows (#664) — the list no
|
|
408
|
-
// longer pays for the CI rollup of every open PR.
|
|
409
|
-
checks: null,
|
|
410
|
-
};
|
|
411
|
-
}
|
|
412
|
-
function applyPreviousProjectIds(issues, previous) {
|
|
413
|
-
for (const issue of issues) {
|
|
414
|
-
const known = previous?.issues.find((row) => row.number === issue.number)?.projectIds;
|
|
415
|
-
if (known !== undefined)
|
|
416
|
-
issue.projectIds = known;
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
function githubListData(input) {
|
|
420
|
-
return {
|
|
421
|
-
available: true,
|
|
422
|
-
repo: input.repo,
|
|
423
|
-
syncedAt: new Date().toISOString(),
|
|
424
|
-
issues: input.issues,
|
|
425
|
-
prs: input.prs,
|
|
426
|
-
labelColors: input.labelColors,
|
|
427
|
-
...(input.viewerLogin ? { viewerLogin: input.viewerLogin } : {}),
|
|
428
|
-
projectsState: 'refreshing',
|
|
429
|
-
projectsGeneration: input.generation,
|
|
430
|
-
...(input.previous?.projects ? { projects: input.previous.projects } : {}),
|
|
431
|
-
issuesTotal: input.issuesTotal,
|
|
432
|
-
prsTotal: input.prsTotal,
|
|
433
|
-
issuesNextCursor: input.issuesNextCursor,
|
|
434
|
-
prsNextCursor: input.prsNextCursor,
|
|
435
|
-
commentsDeferred: true,
|
|
436
|
-
};
|
|
437
|
-
}
|
|
438
|
-
function applyReadyProjectMembership(current, metadata) {
|
|
439
|
-
current.data = {
|
|
440
|
-
...current.data,
|
|
441
|
-
projectsState: metadata.state,
|
|
442
|
-
projects: metadata.projects,
|
|
443
|
-
issues: current.data.issues.map((issue) => ({ ...issue, projectIds: metadata.membership?.[issue.number] ?? [] })),
|
|
444
|
-
};
|
|
445
|
-
}
|
|
446
|
-
function attachProjectMetadata(projectLookup, generation, key) {
|
|
447
|
-
return projectLookup.then((result) => {
|
|
448
|
-
const metadata = 'membership' in result
|
|
449
|
-
? { generation, state: 'ready', projects: result.projects, membership: result.membership }
|
|
450
|
-
: { generation, state: 'unavailable', reason: result.projectsReason };
|
|
451
|
-
const current = listCache.get(key);
|
|
452
|
-
if (current?.data.projectsGeneration === generation) {
|
|
453
|
-
if (metadata.state === 'ready')
|
|
454
|
-
applyReadyProjectMembership(current, metadata);
|
|
455
|
-
else
|
|
456
|
-
current.data = { ...current.data, projectsState: metadata.state, projectsReason: metadata.reason };
|
|
457
|
-
}
|
|
458
|
-
return metadata;
|
|
459
|
-
});
|
|
460
|
-
}
|
|
461
|
-
function storeGithubPage(key, contextKey, order, capped, data, projects, generation) {
|
|
462
|
-
// Concurrent refreshes may finish in reverse order. An older list must not evict
|
|
463
|
-
// the newer generation (and invalidate the newer client's metadata follow-up).
|
|
464
|
-
if ((listCache.get(key)?.order ?? -1) < order && order >= (listRefreshOrder.get(contextKey) ?? 0)) {
|
|
465
|
-
dropListEntry(key); // re-insert so this key becomes the newest
|
|
466
|
-
listCache.set(key, { contextKey, order, at: Date.now(), limit: capped, data, projects });
|
|
467
|
-
projectGenerations.set(generation, key);
|
|
468
|
-
}
|
|
469
|
-
while (listCache.size > LIST_CACHE_MAX) {
|
|
470
|
-
const oldest = listCache.keys().next().value;
|
|
471
|
-
if (oldest === undefined)
|
|
472
|
-
break;
|
|
473
|
-
dropListEntry(oldest);
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
async function loadGithubPage(repoRoot, context, capped, page, key, hit, order, refresh) {
|
|
477
|
-
// No `statusCheckRollup` (#664): it is hydrated lazily per on-screen PR row via
|
|
478
|
-
// `fetchGithubChecks`. A big aggregate list still gets a little more wall clock.
|
|
479
|
-
const timeout = capped > 100 ? 30_000 : 15_000;
|
|
480
|
-
const ownerName = await resolveRepoHandleStrict(repoRoot, context);
|
|
481
|
-
if (!ownerName)
|
|
482
|
-
return { available: false, reason: 'Could not resolve this repository on GitHub.', issues: [], prs: [] };
|
|
483
|
-
const runGraphql = (query, variables) => forgettingNameOnMiss(repoRoot, () => gh(repoRoot, ghGraphqlArgs(query, variables), timeout, undefined, context));
|
|
484
|
-
const projectGraphql = githubProjectGraphql(repoRoot, context);
|
|
485
|
-
const firstPage = isFirstGithubPage(page);
|
|
486
|
-
const issueSide = fetchListConnection(runGraphql, ownerName.owner, ownerName.name, 'issues', capped, page.issuesCursor, page.issuesDone);
|
|
487
|
-
const projectLookup = fetchIssueProjects(projectGraphql, ownerName.owner, ownerName.name, async () => (await issueSide).nodes.map((node) => node.number), () => discoverRepositoryProjects(context.key, refresh, () => fetchRepositoryProjects(projectGraphql, ownerName.owner, ownerName.name)));
|
|
488
|
-
const [issuesPage, prsPage, viewerLogin] = await Promise.all([
|
|
489
|
-
issueSide,
|
|
490
|
-
fetchListConnection(runGraphql, ownerName.owner, ownerName.name, 'pullRequests', capped, page.prsCursor, page.prsDone),
|
|
491
|
-
// The viewer is the same on every page; only the first one asks.
|
|
492
|
-
firstPage
|
|
493
|
-
? fetchViewerLogin((query) => gh(repoRoot, ghGraphqlArgs(query), 8_000, undefined, context))
|
|
494
|
-
: Promise.resolve(undefined),
|
|
495
|
-
]);
|
|
496
|
-
// One repo-wide label→color map, filled as we flatten each item's labels.
|
|
497
|
-
const labelColors = {};
|
|
498
|
-
const recordColor = (label) => recordLabelColor(labelColors, label);
|
|
499
|
-
const issues = issuesPage.nodes.map((issue) => flattenGithubIssue(issue, recordColor));
|
|
500
|
-
const prs = prsPage.nodes.map((pr) => flattenGithubPr(pr, recordColor));
|
|
501
|
-
// Only verified values from the same repository may survive a refresh.
|
|
502
|
-
const previous = hit?.data.repo === `${ownerName.owner}/${ownerName.name}` ? hit.data : undefined;
|
|
503
|
-
applyPreviousProjectIds(issues, previous);
|
|
504
|
-
const generation = randomUUID();
|
|
505
|
-
const data = githubListData({
|
|
506
|
-
repo: `${ownerName.owner}/${ownerName.name}`,
|
|
507
|
-
issues,
|
|
508
|
-
prs,
|
|
509
|
-
labelColors,
|
|
510
|
-
viewerLogin,
|
|
511
|
-
generation,
|
|
512
|
-
previous,
|
|
513
|
-
issuesTotal: issuesPage.totalCount,
|
|
514
|
-
prsTotal: prsPage.totalCount,
|
|
515
|
-
issuesNextCursor: issuesPage.nextCursor,
|
|
516
|
-
prsNextCursor: prsPage.nextCursor,
|
|
517
|
-
});
|
|
518
|
-
const projects = attachProjectMetadata(projectLookup, generation, key);
|
|
519
|
-
storeGithubPage(key, context.key, order, capped, data, projects, generation);
|
|
520
|
-
return data;
|
|
521
|
-
}
|
|
522
|
-
export async function fetchGithub(repoRoot, refresh = false, limit = 30, page = {}) {
|
|
523
|
-
if (productEnv('DRY_RUN') === '1')
|
|
524
|
-
return mockGithubPage(limit, page);
|
|
525
|
-
const context = githubContext(repoRoot);
|
|
526
|
-
const capped = Math.min(Math.max(limit, 1), GH_MAX_LIMIT);
|
|
527
|
-
const key = listPageKey(context.key, page);
|
|
528
|
-
const hit = listCache.get(key);
|
|
529
|
-
const cached = cachedGithubPage(hit, refresh, capped);
|
|
530
|
-
if (cached)
|
|
531
|
-
return cached;
|
|
532
|
-
const order = ++listRequestOrder;
|
|
533
|
-
if (refresh && isFirstGithubPage(page))
|
|
534
|
-
rememberListRefresh(context.key, order, key);
|
|
535
|
-
try {
|
|
536
|
-
return await loadGithubPage(repoRoot, context, capped, page, key, hit, order, refresh);
|
|
537
|
-
}
|
|
538
|
-
catch (err) {
|
|
539
|
-
return { available: false, reason: ghFailureReason(err), issues: [], prs: [] };
|
|
540
|
-
}
|
|
541
|
-
}
|
|
542
|
-
/** A `gh` failure as one readable line. GitHub's own words come on stderr; the Node message
|
|
543
|
-
* starts with the whole argv, and a GraphQL argv is a multi-line query, so its first line is
|
|
544
|
-
* a fragment of that query rather than the reason (open-mercato/cezar#1366). */
|
|
545
|
-
export function ghFailureReason(err) {
|
|
546
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
547
|
-
if (/ENOENT/.test(message))
|
|
548
|
-
return 'gh CLI not found — install it and run `gh auth login`';
|
|
549
|
-
const failure = (err ?? {});
|
|
550
|
-
const stderr = typeof failure.stderr === 'string' ? failure.stderr : '';
|
|
551
|
-
if (stderr.trim()) {
|
|
552
|
-
const lines = stderr.split('\n').map((line) => line.trim()).filter(Boolean);
|
|
553
|
-
return lines.find((line) => !/^Command failed:/i.test(line)) ?? lines[0];
|
|
554
|
-
}
|
|
555
|
-
if (failure.killed === true || typeof failure.signal === 'string')
|
|
556
|
-
return 'GitHub did not answer in time. Refresh to try again.';
|
|
557
|
-
// Without stderr, everything after "Command failed:" is the argv, which is query text.
|
|
558
|
-
if (/^Command failed:/i.test(message))
|
|
559
|
-
return 'GitHub request failed. Refresh to try again.';
|
|
560
|
-
return message.split('\n').map((line) => line.trim()).find(Boolean) ?? 'gh failed';
|
|
561
|
-
}
|
|
562
|
-
/** Bounded lookup already started by the list. Never launch work for an expired generation. */
|
|
563
|
-
export async function fetchGithubProjects(repoRoot, generation) {
|
|
564
|
-
const key = projectGenerations.get(generation);
|
|
565
|
-
const entry = key === undefined ? undefined : listCache.get(key);
|
|
566
|
-
// A generation from another repository, host or account never resolves here, even when
|
|
567
|
-
// its UUID is known: the context is part of what the generation was issued for.
|
|
568
|
-
if (!entry || entry.contextKey !== githubContext(repoRoot).key || entry.data.projectsGeneration !== generation) {
|
|
569
|
-
return { generation, state: 'unavailable', reason: 'Project metadata expired. Refresh to try again.' };
|
|
570
|
-
}
|
|
571
|
-
return entry.projects;
|
|
572
|
-
}
|
|
573
|
-
function firstLine(s) {
|
|
574
|
-
return s.split('\n').find((l) => l.trim().length > 0)?.trim() ?? 'gh failed';
|
|
575
|
-
}
|
|
576
|
-
// On-demand cross-state search stays separate from the hot open list.
|
|
577
|
-
/** Hits per search. `gh search`'s own default is 30; 50 matches the page size the incremental-
|
|
578
|
-
* loading spec settled on and keeps one search to a single `gh` round-trip. */
|
|
579
|
-
export const GH_SEARCH_MAX = GITHUB_SEARCH_MAX;
|
|
580
|
-
/** The `--json` field set each search path requests. Neither path asks for `additions`/`deletions`
|
|
581
|
-
* or `statusCheckRollup` — the same reason the list tier stopped (#664), those are the expensive
|
|
582
|
-
* per-PR lookups.
|
|
583
|
-
*
|
|
584
|
-
* `isDraft` is added for PRs only, and that is a hard requirement rather than a nicety: `gh search
|
|
585
|
-
* issues` does not define the field at all and rejects the whole call with `Unknown JSON field:
|
|
586
|
-
* "isDraft"`, which would turn every text query on the Issues tab into the "could not be searched"
|
|
587
|
-
* degrade. `gh {issue,pr} view` is the opposite — it tolerates the field for both kinds — so only
|
|
588
|
-
* the search path needs to discriminate. */
|
|
589
|
-
const SEARCH_FIELDS = 'number,title,author,createdAt,labels,body,url';
|
|
590
|
-
/** `gh search {prs,issues} --json` field list for `kind`. See `SEARCH_FIELDS` on why `isDraft`
|
|
591
|
-
* cannot be sent to the issues search. */
|
|
592
|
-
function searchJsonFields(kind) {
|
|
593
|
-
return kind === 'pr'
|
|
594
|
-
? `${SEARCH_FIELDS},isDraft,commentsCount`
|
|
595
|
-
: `${SEARCH_FIELDS},assignees,commentsCount`;
|
|
596
|
-
}
|
|
597
|
-
/** `gh search issues|prs` returns `commentsCount` where the list tier gets its counts from a
|
|
598
|
-
* separate GraphQL walk. Same value, different spelling — normalized into `ForgeItem.comments`. */
|
|
599
|
-
const ghSearchHitSchema = ghIssueSchema.extend({
|
|
600
|
-
assignees: z.array(z.object({ login: z.string() })).optional(),
|
|
601
|
-
isDraft: z.boolean().default(false),
|
|
602
|
-
commentsCount: z.number().default(0),
|
|
603
|
-
});
|
|
604
|
-
/** `gh {issue,pr} view <n> --json …` — the exact-number path. Shares `ghIssueSchema`'s core;
|
|
605
|
-
* `isDraft`/`additions`/`deletions` are PR-only and default harmlessly for issues. */
|
|
606
|
-
const ghViewHitSchema = ghIssueSchema.extend({
|
|
607
|
-
state: z.string().optional(),
|
|
608
|
-
mergedAt: z.unknown().optional(),
|
|
609
|
-
assignees: z.array(z.object({ login: z.string() })).optional(),
|
|
610
|
-
isDraft: z.boolean().default(false),
|
|
611
|
-
additions: z.number().default(0),
|
|
612
|
-
deletions: z.number().default(0),
|
|
613
|
-
});
|
|
614
|
-
/** Flatten one validated hit into the `ForgeItem` the tab's rows already render. `checks: null`
|
|
615
|
-
* is what the list tier ships too since #664 — the glyph hydrates lazily via `/api/github/checks`
|
|
616
|
-
* — so a searched row and a listed row are indistinguishable to the UI. */
|
|
617
|
-
function toSearchItem(kind, hit, labelColors) {
|
|
618
|
-
for (const label of hit.labels) {
|
|
619
|
-
if (label.color && !labelColors[label.name])
|
|
620
|
-
labelColors[label.name] = label.color;
|
|
621
|
-
}
|
|
622
|
-
const item = {
|
|
623
|
-
kind,
|
|
624
|
-
number: hit.number,
|
|
625
|
-
title: hit.title,
|
|
626
|
-
author: hit.author?.login ?? '?',
|
|
627
|
-
createdAt: hit.createdAt,
|
|
628
|
-
labels: hit.labels.map((l) => l.name),
|
|
629
|
-
body: (hit.body ?? '').slice(0, 8_000),
|
|
630
|
-
url: hit.url,
|
|
631
|
-
comments: hit.commentsCount,
|
|
632
|
-
...(kind === 'issue' && hit.assignees ? { assignees: hit.assignees.map(a => a.login) } : {}),
|
|
633
|
-
};
|
|
634
|
-
if (kind === 'pr') {
|
|
635
|
-
item.isDraft = hit.isDraft;
|
|
636
|
-
// Draft is a label on list rows as well as a flag — keep the parity so filtering by the
|
|
637
|
-
// `draft` chip behaves the same on a searched row.
|
|
638
|
-
if (hit.isDraft)
|
|
639
|
-
item.labels = [...item.labels, 'draft'];
|
|
640
|
-
if ('additions' in hit)
|
|
641
|
-
item.additions = hit.additions;
|
|
642
|
-
if ('deletions' in hit)
|
|
643
|
-
item.deletions = hit.deletions;
|
|
644
|
-
item.checks = null;
|
|
645
|
-
}
|
|
646
|
-
return item;
|
|
647
|
-
}
|
|
648
|
-
/** `gh {pr,issue} view <n>` diagnostics that name the REQUESTED item as absent. A bare
|
|
649
|
-
* "not found" / 404 or "Could not resolve to a Repository" also fails a view, but says the
|
|
650
|
-
* repository (or auth) is the problem, not that the number does not exist. */
|
|
651
|
-
const MISSING_ITEM_RE = /could not resolve to an? (?:pullrequest|issue|issueorpullrequest|pull request|issue or pull request)\b|no (?:pull requests|issues) found/i;
|
|
652
|
-
/** The exact `gh view` call plus its parse. `null` only for a confirmed-missing item; anything
|
|
653
|
-
* else (transport, auth, repository, unparseable output) throws. */
|
|
654
|
-
async function viewGithubHit(repoRoot, kind, number) {
|
|
655
|
-
try {
|
|
656
|
-
const out = await gh(repoRoot, [
|
|
657
|
-
kind === 'pr' ? 'pr' : 'issue',
|
|
658
|
-
'view',
|
|
659
|
-
String(number),
|
|
660
|
-
'--json',
|
|
661
|
-
kind === 'pr' ? `${SEARCH_FIELDS},isDraft,additions,deletions,state,mergedAt` : `${SEARCH_FIELDS},assignees`,
|
|
662
|
-
]);
|
|
663
|
-
const hit = ghViewHitSchema.parse(JSON.parse(out));
|
|
664
|
-
if (kind === 'pr' && hit.state === 'MERGED') {
|
|
665
|
-
const handle = await resolveRepoHandle(repoRoot);
|
|
666
|
-
if (handle)
|
|
667
|
-
mergedPullRequestObservations.observe({ owner: handle.owner, repo: handle.name, number }, hit);
|
|
668
|
-
}
|
|
669
|
-
return hit;
|
|
670
|
-
}
|
|
671
|
-
catch (err) {
|
|
672
|
-
if (MISSING_ITEM_RE.test(err instanceof Error ? err.message : String(err)))
|
|
673
|
-
return null;
|
|
674
|
-
throw err;
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
/** `view` exposes comment bodies rather than a count. Read the single issue resource
|
|
678
|
-
* (PRs share this endpoint) instead of paginating a potentially enormous thread.
|
|
679
|
-
* gh resolves placeholders in repoRoot, just as it resolves the preceding view call. */
|
|
680
|
-
async function finishViewHit(repoRoot, kind, number, hit, labelColors) {
|
|
681
|
-
const commentsCount = z.number().int().nonnegative().parse(JSON.parse(await gh(repoRoot, ['api', `repos/{owner}/{repo}/issues/${number}`, '--jq', '.comments'], 8_000)));
|
|
682
|
-
return toSearchItem(kind, { ...hit, commentsCount }, labelColors);
|
|
683
|
-
}
|
|
684
|
-
/**
|
|
685
|
-
* One issue or PR by number, in any state (#692). `null` when `gh` confirms the item is absent;
|
|
686
|
-
* throws on every other failure. `labelColors` is an optional out-param.
|
|
687
|
-
*/
|
|
688
|
-
export async function viewGithubItem(repoRoot, kind, number, labelColors = {}) {
|
|
689
|
-
const hit = await viewGithubHit(repoRoot, kind, number);
|
|
690
|
-
return hit ? finishViewHit(repoRoot, kind, number, hit, labelColors) : null;
|
|
691
|
-
}
|
|
692
|
-
/**
|
|
693
|
-
* Search any state: exact numbers try a direct lookup, then text fallback; text search omits
|
|
694
|
-
* state restriction. Return availability and a reason on failure instead of throwing.
|
|
695
|
-
*/
|
|
696
|
-
export async function searchGithubItems(repoRoot, kind, query, limit = GH_SEARCH_MAX) {
|
|
697
|
-
const trimmed = query.trim();
|
|
698
|
-
if (trimmed === '')
|
|
699
|
-
return { available: true, items: [] };
|
|
700
|
-
const capped = Math.min(Math.max(limit, 1), GH_SEARCH_MAX);
|
|
701
|
-
if (productEnv('DRY_RUN') === '1') {
|
|
702
|
-
const mock = mockGithub();
|
|
703
|
-
const pool = kind === 'issue' ? mock.issues : mock.prs;
|
|
704
|
-
const queryText = trimmed.toLowerCase();
|
|
705
|
-
const numeric = queryText.replace(/^#/, '');
|
|
706
|
-
const idOnly = /^\d+$/.test(numeric);
|
|
707
|
-
// The fixture obeys `limit` and flags `truncated` on the live path's own rule (#838). The
|
|
708
|
-
// catalog is a handful of rows, so the cap never bites in the demo itself — but offline mode
|
|
709
|
-
// is the only place anyone developing without `gh` exercises cap-and-truncate at all, and a
|
|
710
|
-
// dry-run that returned the whole pool unflagged would hide a regression in it.
|
|
711
|
-
const items = pool
|
|
712
|
-
.filter((item) => idOnly
|
|
713
|
-
? String(item.number).includes(numeric)
|
|
714
|
-
: `#${item.number} ${item.title} ${item.author} ${item.body}`.toLowerCase().includes(queryText))
|
|
715
|
-
.slice(0, capped)
|
|
716
|
-
// Search rows defer checks to the same hydration endpoint as live results. Copy rather
|
|
717
|
-
// than mutate: the mock checks endpoint still reads the fixture's passing/failing values.
|
|
718
|
-
.map(item => item.kind === 'pr' ? { ...item, checks: null } : item);
|
|
719
|
-
return { available: true, items, truncated: items.length >= capped };
|
|
720
|
-
}
|
|
721
|
-
const labelColors = {};
|
|
722
|
-
const numeric = trimmed.replace(/^#/, '');
|
|
723
|
-
try {
|
|
724
|
-
if (/^\d+$/.test(numeric)) {
|
|
725
|
-
// `Number()` before interpolation: the regex already guarantees digits, but the number is
|
|
726
|
-
// user input reaching an argv, so it is normalized rather than passed through verbatim.
|
|
727
|
-
const number = Number(numeric);
|
|
728
|
-
// Any failure of the exact view call or its parse (and a missing number) falls through to
|
|
729
|
-
// the text search below. The comment count is outside that guard: its failure reports
|
|
730
|
-
// unavailable rather than an invented zero.
|
|
731
|
-
let hit = null;
|
|
732
|
-
try {
|
|
733
|
-
hit = await viewGithubHit(repoRoot, kind, number);
|
|
734
|
-
}
|
|
735
|
-
catch {
|
|
736
|
-
// fall through
|
|
737
|
-
}
|
|
738
|
-
if (hit) {
|
|
739
|
-
const item = await finishViewHit(repoRoot, kind, number, hit, labelColors);
|
|
740
|
-
return await hydrateSearchProjects(repoRoot, kind, { available: true, items: [item], labelColors });
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
// The memoized handle first (usually a hit). Its `null` is deliberately ambiguous — it swallows
|
|
744
|
-
// "gh is missing" and "no remote" alike — so on a miss, ask once more directly and let the real
|
|
745
|
-
// failure reach the catch below, where it becomes the same honest hint the list tier gives.
|
|
746
|
-
// Only a genuinely unparseable slug reaches the "no remote" reason.
|
|
747
|
-
const handle = (await resolveRepoHandle(repoRoot)) ??
|
|
748
|
-
parseOwnerName(await gh(repoRoot, ['repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner']));
|
|
749
|
-
if (!handle) {
|
|
750
|
-
return { available: false, reason: 'no GitHub remote to search', items: [] };
|
|
751
|
-
}
|
|
752
|
-
const out = await forgettingNameOnMiss(repoRoot, () => gh(repoRoot, [
|
|
753
|
-
'search',
|
|
754
|
-
kind === 'pr' ? 'prs' : 'issues',
|
|
755
|
-
'--repo',
|
|
756
|
-
`${handle.owner}/${handle.name}`,
|
|
757
|
-
'--limit',
|
|
758
|
-
String(capped),
|
|
759
|
-
'--json',
|
|
760
|
-
searchJsonFields(kind),
|
|
761
|
-
// End-of-flags, then the query: `gh` parses a leading `-`/`--` as a flag otherwise, so a
|
|
762
|
-
// flag-shaped query would degrade the tab to "GitHub could not be searched: unknown flag",
|
|
763
|
-
// and the exact text `--web` would match `gh search`'s own `-w, --web` and open a browser
|
|
764
|
-
// on the cockpit's host. Behind `--` it is search text, which is all the box ever means.
|
|
765
|
-
'--',
|
|
766
|
-
trimmed,
|
|
767
|
-
]));
|
|
768
|
-
const hits = z.array(ghSearchHitSchema).parse(JSON.parse(out));
|
|
769
|
-
// Older gh/GHES search treats repeated repo qualifiers as OR. Never hydrate a foreign
|
|
770
|
-
// hit's number with this repository's memberships or expose it as a local detail row.
|
|
771
|
-
const prefix = `/${handle.owner}/${handle.name}/${kind === 'pr' ? 'pull' : 'issues'}/`.toLowerCase();
|
|
772
|
-
if (hits.some(hit => {
|
|
773
|
-
try {
|
|
774
|
-
return new URL(hit.url).pathname.toLowerCase() !== `${prefix}${hit.number}`;
|
|
775
|
-
}
|
|
776
|
-
catch {
|
|
777
|
-
return true;
|
|
778
|
-
}
|
|
779
|
-
}))
|
|
780
|
-
return { available: false, reason: 'GitHub returned results outside this repository. Remove repository qualifiers and try again.', items: [] };
|
|
781
|
-
return await hydrateSearchProjects(repoRoot, kind, {
|
|
782
|
-
available: true,
|
|
783
|
-
items: hits.map((hit) => toSearchItem(kind, hit, labelColors)),
|
|
784
|
-
truncated: hits.length >= capped,
|
|
785
|
-
labelColors,
|
|
786
|
-
});
|
|
787
|
-
}
|
|
788
|
-
catch (err) {
|
|
789
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
790
|
-
const reason = /ENOENT/.test(message)
|
|
791
|
-
? 'gh CLI not found — install it and run `gh auth login`'
|
|
792
|
-
: firstLine(message);
|
|
793
|
-
return { available: false, reason, items: [] };
|
|
794
|
-
}
|
|
795
|
-
}
|
|
796
|
-
/** The list's metadata window contains only open issues. Search must look up its own window,
|
|
797
|
-
* including closed issues, with the same bounds and unknown-on-failure semantics (#90). */
|
|
798
|
-
async function hydrateSearchProjects(repoRoot, kind, data) {
|
|
799
|
-
if (kind !== 'issue' || data.items.length === 0)
|
|
800
|
-
return data;
|
|
801
|
-
const handle = await resolveRepoHandle(repoRoot);
|
|
802
|
-
if (!handle)
|
|
803
|
-
return { ...data, projectsReason: 'Project boards unavailable for this repository.' };
|
|
804
|
-
const deadline = Date.now() + 15_000;
|
|
805
|
-
const run = (query, variables) => {
|
|
806
|
-
const remaining = deadline - Date.now();
|
|
807
|
-
if (remaining <= 0)
|
|
808
|
-
return Promise.reject(new Error('Project lookup timed out'));
|
|
809
|
-
const args = ghGraphqlArgs(query, variables);
|
|
810
|
-
return gh(repoRoot, args, Math.min(remaining, 8_000));
|
|
811
|
-
};
|
|
812
|
-
const projects = await fetchIssueProjects(run, handle.owner, handle.name, data.items.map(item => item.number));
|
|
813
|
-
if ('projectsReason' in projects)
|
|
814
|
-
return { ...data, projectsReason: projects.projectsReason };
|
|
815
|
-
return { ...data, items: data.items.map(item => ({ ...item, projectIds: projects.membership[item.number] ?? [] })) };
|
|
816
|
-
}
|
|
817
|
-
/** The dry-run catalog, paged like the real list: numeric offset cursors per side, done flags
|
|
818
|
-
* honored, exact totals, and counts deferred to the counts route (hearsay-tools/cezarion#1183). */
|
|
819
|
-
function mockGithubPage(limit, page) {
|
|
820
|
-
const full = mockGithub();
|
|
821
|
-
const side = (rows, cursor, done) => {
|
|
822
|
-
const start = done ? rows.length : Number(cursor ?? 0);
|
|
823
|
-
const slice = rows.slice(start, start + Math.max(limit, 1));
|
|
824
|
-
const end = start + slice.length;
|
|
825
|
-
return { rows: slice.map((row) => ({ ...row, comments: 0 })), next: end < rows.length ? String(end) : null };
|
|
826
|
-
};
|
|
827
|
-
const issues = side(full.issues, page.issuesCursor, page.issuesDone);
|
|
828
|
-
const prs = side(full.prs, page.prsCursor, page.prsDone);
|
|
829
|
-
const firstPage = !page.issuesCursor && !page.prsCursor && !page.issuesDone && !page.prsDone;
|
|
830
|
-
const { viewerLogin, ...rest } = full;
|
|
831
|
-
return {
|
|
832
|
-
...rest,
|
|
833
|
-
...(firstPage && viewerLogin ? { viewerLogin } : {}),
|
|
834
|
-
issues: issues.rows,
|
|
835
|
-
prs: prs.rows,
|
|
836
|
-
issuesTotal: full.issues.length,
|
|
837
|
-
prsTotal: full.prs.length,
|
|
838
|
-
issuesNextCursor: issues.next,
|
|
839
|
-
prsNextCursor: prs.next,
|
|
840
|
-
commentsDeferred: true,
|
|
841
|
-
};
|
|
842
|
-
}
|
|
843
|
-
/** CEZ_DRY_RUN=1 — a small fixed catalog so the GitHub tab is demoable offline. */
|
|
844
|
-
function mockGithub() {
|
|
845
|
-
const mk = (over) => ({
|
|
846
|
-
author: 'mock',
|
|
847
|
-
createdAt: new Date(Date.now() - over.number * 3_600_000).toISOString(),
|
|
848
|
-
labels: [],
|
|
849
|
-
url: `https://github.com/mock/repo/${over.kind === 'pr' ? 'pull' : 'issues'}/${over.number}`,
|
|
850
|
-
comments: 0,
|
|
851
|
-
...over,
|
|
852
|
-
});
|
|
853
|
-
return {
|
|
854
|
-
available: true,
|
|
855
|
-
repo: 'mock/repo',
|
|
856
|
-
viewerLogin: 'octocat',
|
|
857
|
-
projects: [{ id: 'mock-delivery', title: 'Delivery', url: 'https://github.com/users/mock/projects/1' }],
|
|
858
|
-
syncedAt: new Date().toISOString(),
|
|
859
|
-
issues: [
|
|
860
|
-
mk({ kind: 'issue', assignees: ['octocat'], projectIds: ['mock-delivery'], number: 142, title: 'Login form drops session on refresh', labels: ['bug', 'auth'], comments: 3, body: 'Repro: log in, hit reload — you land back on /login. The session cookie is set correctly, but the client store rehydrates before the cookie check resolves, so the auth guard redirects.' }),
|
|
861
|
-
mk({ kind: 'issue', assignees: ['ada'], projectIds: [], number: 139, title: 'Add --json flag to cez CLI output', labels: ['enhancement', 'cli'], comments: 1, body: 'For scripting it would help if `cez list` and `cez status` could emit machine-readable JSON instead of the table view.' }),
|
|
862
|
-
mk({ kind: 'issue', assignees: [], projectIds: ['mock-delivery'], number: 135, title: 'Flaky e2e: worktree cleanup race on cancel', labels: ['bug', 'flaky-test'], comments: 6, body: 'Cancelling a run while the agent holds a file lock leaves a dangling worktree. The next run on the same branch then fails with "worktree already exists".' }),
|
|
863
|
-
],
|
|
864
|
-
prs: [
|
|
865
|
-
mk({ kind: 'pr', number: 128, title: 'Fix flaky auth test in CI', labels: ['tests'], checks: 'passing', additions: 6, deletions: 3, body: 'Loosens the timing assertion in refresh.test.ts to a realistic budget.' }),
|
|
866
|
-
mk({ kind: 'pr', number: 124, title: 'Rate limit /api/runs', labels: ['server', 'draft'], isDraft: true, checks: 'failing', additions: 118, deletions: 7, comments: 4, body: 'Draft: token-bucket middleware on the runs router. Still needs the config surface and README docs before review.' }),
|
|
867
|
-
],
|
|
868
|
-
labelColors: {
|
|
869
|
-
bug: 'd73a4a',
|
|
870
|
-
auth: '5319e7',
|
|
871
|
-
enhancement: 'a2eeef',
|
|
872
|
-
cli: '0e8a16',
|
|
873
|
-
'flaky-test': 'fbca04',
|
|
874
|
-
tests: 'c5def5',
|
|
875
|
-
server: '1d76db',
|
|
876
|
-
draft: '6a737d',
|
|
877
|
-
},
|
|
878
|
-
};
|
|
879
|
-
}
|
|
24
|
+
import { CACHE_MS, detectGithub, detectGithubCached, firstLine, ghFailureReason, ghGraphqlArgs, ghMergeResultSchema, ghPrViewSchema, mockGithub, refStatusGraphql, resolveRepoHandleStrict, rollupToChecks, } from './github-shared.js';
|
|
25
|
+
export { detectGithubCached, ghCheckRunSchema, ghFailureReason, ghGraphqlArgs, HEALTH_AVAILABILITY_TTL_MS, rollupToChecks, } from './github-shared.js';
|
|
26
|
+
import { fetchGithubPrDiff } from './github-pr-diff.js';
|
|
27
|
+
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
|
+
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
|
+
export { __clearChecksCacheForTests, COMMIT_CHECKS_CHUNK, fetchCommitChecks, fetchGithubChecks, fetchPrChecks, GH_CHECKS_MAX, } from './github-checks.js';
|
|
880
32
|
// ---- comment threads (#499 Phase 2) ----------------------------------------
|
|
881
33
|
// A lazy per-thread fetch behind `GET /api/github/comments/:kind/:number`: the
|
|
882
34
|
// conversation comments (issues endpoint — GitHub serves PR conversation
|
|
@@ -1026,114 +178,6 @@ export async function fetchGithubItem(repoRoot, kind, number, refresh = false) {
|
|
|
1026
178
|
};
|
|
1027
179
|
}
|
|
1028
180
|
}
|
|
1029
|
-
/** SHAs per rollup query. Aliases resolve independently, so a chunk that fails costs only its own
|
|
1030
|
-
* glyphs — but an unbounded alias list would eventually blow the query size limit. */
|
|
1031
|
-
export const COMMIT_CHECKS_CHUNK = 50;
|
|
1032
|
-
/** One aliased `object(oid:)` per SHA. `oid` requires a FULL 40-char SHA in both literal and
|
|
1033
|
-
* variable form (`Could not coerce value "babda63" to GitObjectID`), which constrains fixtures
|
|
1034
|
-
* rather than production data — the timeline always supplies full SHAs. */
|
|
1035
|
-
function commitChecksQuery(shas) {
|
|
1036
|
-
const aliases = shas
|
|
1037
|
-
.map((sha, i) => ` c${i}: object(oid: "${sha}") { ... on Commit { statusCheckRollup { state } } }`)
|
|
1038
|
-
.join('\n');
|
|
1039
|
-
return `query ($owner: String!, $name: String!) {\n repository(owner: $owner, name: $name) {\n${aliases}\n }\n}`;
|
|
1040
|
-
}
|
|
1041
|
-
const ghCommitChecksSchema = z.record(z.string(), z.object({ statusCheckRollup: z.object({ state: z.string().nullish() }).nullish() }).nullish());
|
|
1042
|
-
/**
|
|
1043
|
-
* Rolled-up CI state per commit SHA, as a `sha → checks` map.
|
|
1044
|
-
*
|
|
1045
|
-
* Batched and aliased so a 40-commit PR costs one subprocess, not forty. Verified against the live
|
|
1046
|
-
* API: each alias resolves independently and an unknown SHA comes back `null` rather than erroring
|
|
1047
|
-
* the batch, so partial results degrade cleanly.
|
|
1048
|
-
*
|
|
1049
|
-
* Degrades to an empty map on any failure — exactly as `fetchCommentCounts` does for counts. The
|
|
1050
|
-
* caller then leaves `checks` **absent**, which the UI renders as no glyph. Exported for tests;
|
|
1051
|
-
* `runGraphql` is injected so this is testable without shelling out.
|
|
1052
|
-
*/
|
|
1053
|
-
export async function fetchCommitChecks(runGraphql, owner, name, shas, chunkSize = COMMIT_CHECKS_CHUNK) {
|
|
1054
|
-
const out = {};
|
|
1055
|
-
if (shas.length === 0)
|
|
1056
|
-
return out;
|
|
1057
|
-
for (let i = 0; i < shas.length; i += chunkSize) {
|
|
1058
|
-
const chunk = shas.slice(i, i + chunkSize);
|
|
1059
|
-
try {
|
|
1060
|
-
const raw = JSON.parse(await runGraphql(commitChecksQuery(chunk), { owner, name }));
|
|
1061
|
-
const repository = ghCommitChecksSchema.parse(raw?.data?.repository ?? {});
|
|
1062
|
-
chunk.forEach((sha, index) => {
|
|
1063
|
-
const node = repository[`c${index}`];
|
|
1064
|
-
if (!node)
|
|
1065
|
-
return; // unknown SHA → alias resolved null; leave `checks` absent
|
|
1066
|
-
// Adapt the single rollup state into the array shape `rollupToChecks` expects, so the
|
|
1067
|
-
// existing FAILURE/PENDING/SUCCESS vocabulary is reused rather than duplicated.
|
|
1068
|
-
out[sha] = node.statusCheckRollup
|
|
1069
|
-
? rollupToChecks([{ state: node.statusCheckRollup.state, status: null, conclusion: null }])
|
|
1070
|
-
: null; // no CI configured — distinct from absent
|
|
1071
|
-
});
|
|
1072
|
-
}
|
|
1073
|
-
catch {
|
|
1074
|
-
// A failed chunk costs only its own glyphs; the rest still resolve.
|
|
1075
|
-
}
|
|
1076
|
-
}
|
|
1077
|
-
return out;
|
|
1078
|
-
}
|
|
1079
|
-
/** PR numbers per checks query. Aliases resolve independently (a failed chunk costs only its own
|
|
1080
|
-
* glyphs); bounded so an unbounded number list can't blow the query size limit. Also the route's
|
|
1081
|
-
* hard cap on how many PRs one request may ask about. */
|
|
1082
|
-
export const GH_CHECKS_MAX = 100;
|
|
1083
|
-
/** One aliased `pullRequest(number:)` per PR; the rolled-up CI state lives on the head commit. */
|
|
1084
|
-
function prChecksQuery(numbers) {
|
|
1085
|
-
const aliases = numbers
|
|
1086
|
-
.map((n, i) => ` p${i}: pullRequest(number: ${n}) { commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } }`)
|
|
1087
|
-
.join('\n');
|
|
1088
|
-
return `query ($owner: String!, $name: String!) {\n repository(owner: $owner, name: $name) {\n${aliases}\n }\n}`;
|
|
1089
|
-
}
|
|
1090
|
-
const ghPrChecksSchema = z.record(z.string(), z
|
|
1091
|
-
.object({
|
|
1092
|
-
commits: z.object({
|
|
1093
|
-
nodes: z.array(z.object({
|
|
1094
|
-
commit: z.object({
|
|
1095
|
-
statusCheckRollup: z.object({ state: z.string().nullish() }).nullish(),
|
|
1096
|
-
}),
|
|
1097
|
-
})),
|
|
1098
|
-
}),
|
|
1099
|
-
})
|
|
1100
|
-
.nullish());
|
|
1101
|
-
/**
|
|
1102
|
-
* Rolled-up CI state per PR number, as a `number → glyph` map.
|
|
1103
|
-
*
|
|
1104
|
-
* Batched and aliased so a 100-PR window costs one subprocess, not a hundred. Each alias resolves
|
|
1105
|
-
* independently and an unknown number comes back `null` (alias resolved null → left absent), so
|
|
1106
|
-
* partial results degrade cleanly. Degrades to an empty map on any failure — exactly as
|
|
1107
|
-
* `fetchCommitChecks` does. Exported for tests; `runGraphql` is injected so this is testable
|
|
1108
|
-
* without shelling out.
|
|
1109
|
-
*/
|
|
1110
|
-
export async function fetchPrChecks(runGraphql, owner, name, numbers, chunkSize = GH_CHECKS_MAX) {
|
|
1111
|
-
const out = {};
|
|
1112
|
-
if (numbers.length === 0)
|
|
1113
|
-
return out;
|
|
1114
|
-
for (let i = 0; i < numbers.length; i += chunkSize) {
|
|
1115
|
-
const chunk = numbers.slice(i, i + chunkSize);
|
|
1116
|
-
try {
|
|
1117
|
-
const raw = JSON.parse(await runGraphql(prChecksQuery(chunk), { owner, name }));
|
|
1118
|
-
const repository = ghPrChecksSchema.parse(raw?.data?.repository ?? {});
|
|
1119
|
-
chunk.forEach((number, index) => {
|
|
1120
|
-
const node = repository[`p${index}`];
|
|
1121
|
-
if (!node)
|
|
1122
|
-
return; // unknown PR → alias resolved null; leave the glyph absent
|
|
1123
|
-
const rollup = node.commits.nodes[0]?.commit.statusCheckRollup;
|
|
1124
|
-
// Adapt the single rollup state into the array shape `rollupToChecks` expects, reusing the
|
|
1125
|
-
// FAILURE/PENDING/SUCCESS vocabulary rather than duplicating it.
|
|
1126
|
-
out[number] = rollup
|
|
1127
|
-
? rollupToChecks([{ state: rollup.state, status: null, conclusion: null }]) ?? null
|
|
1128
|
-
: null; // no CI configured — distinct from absent
|
|
1129
|
-
});
|
|
1130
|
-
}
|
|
1131
|
-
catch {
|
|
1132
|
-
// A failed chunk costs only its own glyphs; the rest still resolve.
|
|
1133
|
-
}
|
|
1134
|
-
}
|
|
1135
|
-
return out;
|
|
1136
|
-
}
|
|
1137
181
|
const itemDetailSchema = z.object({
|
|
1138
182
|
body: z.string().nullish(),
|
|
1139
183
|
additions: z.number().int().nonnegative().optional(),
|
|
@@ -1229,79 +273,6 @@ function mockGithubCommentCounts(kind, numbers) {
|
|
|
1229
273
|
}
|
|
1230
274
|
return { available: true, counts };
|
|
1231
275
|
}
|
|
1232
|
-
// Per-PR checks cache: keyed `githubContext␀number`, same 60 s TTL as the list cache but BOUNDED. Lets
|
|
1233
|
-
// a repeated visible-window hydration within a minute serve cached glyphs instead of re-querying.
|
|
1234
|
-
const checksCache = new Map();
|
|
1235
|
-
const CHECKS_CACHE_MAX = 500;
|
|
1236
|
-
/** Test hook — the per-PR checks cache would otherwise leak state across cases in one process. */
|
|
1237
|
-
export function __clearChecksCacheForTests() {
|
|
1238
|
-
checksCache.clear();
|
|
1239
|
-
}
|
|
1240
|
-
/**
|
|
1241
|
-
* Lazy checks glyphs for the given PR numbers (route-facing). Resolves the repo handle once,
|
|
1242
|
-
* serves fresh cache entries, queries only the misses, and degrades to `{ available: false,
|
|
1243
|
-
* reason }` when `gh` or the handle is unavailable — never a throw, never a 5xx (plan rule 7).
|
|
1244
|
-
* Numbers are de-duplicated, validated, and capped at `GH_CHECKS_MAX`.
|
|
1245
|
-
*/
|
|
1246
|
-
export async function fetchGithubChecks(repoRoot, numbers) {
|
|
1247
|
-
if (productEnv('DRY_RUN') === '1')
|
|
1248
|
-
return mockGithubChecks(numbers);
|
|
1249
|
-
const wanted = [...new Set(numbers)].filter((n) => Number.isInteger(n) && n > 0).slice(0, GH_CHECKS_MAX);
|
|
1250
|
-
const checks = {};
|
|
1251
|
-
const misses = [];
|
|
1252
|
-
const now = Date.now();
|
|
1253
|
-
const context = githubContext(repoRoot);
|
|
1254
|
-
for (const n of wanted) {
|
|
1255
|
-
const hit = checksCache.get(`${context.key}\0${n}`);
|
|
1256
|
-
if (hit && now - hit.at < CACHE_MS)
|
|
1257
|
-
checks[n] = hit.glyph;
|
|
1258
|
-
else
|
|
1259
|
-
misses.push(n);
|
|
1260
|
-
}
|
|
1261
|
-
if (misses.length === 0)
|
|
1262
|
-
return { available: true, checks };
|
|
1263
|
-
try {
|
|
1264
|
-
const repoOut = await gh(repoRoot, ['repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner'], undefined, undefined, context);
|
|
1265
|
-
const ownerName = parseOwnerName(repoOut);
|
|
1266
|
-
if (!ownerName)
|
|
1267
|
-
return { available: false, reason: 'repository handle unavailable' };
|
|
1268
|
-
const runGraphql = (query, variables) => {
|
|
1269
|
-
const args = ghGraphqlArgs(query, variables);
|
|
1270
|
-
return gh(repoRoot, args, undefined, undefined, context);
|
|
1271
|
-
};
|
|
1272
|
-
const fetched = await fetchPrChecks(runGraphql, ownerName.owner, ownerName.name, misses);
|
|
1273
|
-
for (const n of misses) {
|
|
1274
|
-
// Absent (unknown/closed PR) caches as `null` so a nonexistent number isn't re-queried.
|
|
1275
|
-
const glyph = n in fetched ? fetched[n] : null;
|
|
1276
|
-
checks[n] = glyph;
|
|
1277
|
-
checksCache.set(`${context.key}\0${n}`, { at: now, glyph });
|
|
1278
|
-
}
|
|
1279
|
-
while (checksCache.size > CHECKS_CACHE_MAX) {
|
|
1280
|
-
const oldest = checksCache.keys().next().value;
|
|
1281
|
-
if (oldest === undefined)
|
|
1282
|
-
break;
|
|
1283
|
-
checksCache.delete(oldest);
|
|
1284
|
-
}
|
|
1285
|
-
return { available: true, checks };
|
|
1286
|
-
}
|
|
1287
|
-
catch (err) {
|
|
1288
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
1289
|
-
return {
|
|
1290
|
-
available: false,
|
|
1291
|
-
reason: /ENOENT/.test(message)
|
|
1292
|
-
? 'gh CLI not found — install it and run `gh auth login`'
|
|
1293
|
-
: firstLine(message),
|
|
1294
|
-
};
|
|
1295
|
-
}
|
|
1296
|
-
}
|
|
1297
|
-
/** CEZ_DRY_RUN=1 — glyphs straight from the mock catalog so the offline demo shows checks. */
|
|
1298
|
-
function mockGithubChecks(numbers) {
|
|
1299
|
-
const byNumber = new Map(mockGithub().prs.map((p) => [p.number, (p.checks ?? null)]));
|
|
1300
|
-
const checks = {};
|
|
1301
|
-
for (const n of numbers)
|
|
1302
|
-
checks[n] = byNumber.get(n) ?? null;
|
|
1303
|
-
return { available: true, checks };
|
|
1304
|
-
}
|
|
1305
276
|
/** Numbers per kind in one ref-status query — the same bound, and for the same reasons, as
|
|
1306
277
|
* `GH_CHECKS_MAX`: aliases resolve independently, and the query size stays finite. Taken from the
|
|
1307
278
|
* contract rather than restated, because the cockpit caps its batches by the same number and a
|
|
@@ -1710,49 +681,6 @@ const MERGEABILITY_UNKNOWN_WINDOW_MS = 60_000;
|
|
|
1710
681
|
* no `gh` installed would otherwise spawn a subprocess a minute, forever, to be told the same
|
|
1711
682
|
* thing. Five minutes is the same order as the cockpit's own reconnect cadence. */
|
|
1712
683
|
const REF_STATUS_RETRY_MS = 5 * 60_000;
|
|
1713
|
-
/**
|
|
1714
|
-
* Use failed gh GraphQL stdout only when it contains usable data.repository. Preserve successful
|
|
1715
|
-
* aliases in partial responses; rethrow malformed or unresolved-repository failures.
|
|
1716
|
-
*/
|
|
1717
|
-
function refStatusGraphql(repoRoot, context = githubContext(repoRoot)) {
|
|
1718
|
-
return async (query, variables) => {
|
|
1719
|
-
const args = ghGraphqlArgs(query, variables);
|
|
1720
|
-
try {
|
|
1721
|
-
return await gh(repoRoot, args, 15_000, undefined, context);
|
|
1722
|
-
}
|
|
1723
|
-
catch (err) {
|
|
1724
|
-
const stdout = err.stdout;
|
|
1725
|
-
if (typeof stdout === 'string' && hasResolvedRepository(stdout))
|
|
1726
|
-
return stdout;
|
|
1727
|
-
throw err;
|
|
1728
|
-
}
|
|
1729
|
-
};
|
|
1730
|
-
}
|
|
1731
|
-
/**
|
|
1732
|
-
* The repo handle, memoized in the same map `resolveRepoHandle` uses — but rethrowing instead of
|
|
1733
|
-
* answering `null`.
|
|
1734
|
-
*
|
|
1735
|
-
* The memo is the point: without it every recheck tick spawned a second subprocess to re-learn an
|
|
1736
|
-
* `owner/name` that changes approximately never, doubling the cost of the one query that actually
|
|
1737
|
-
* carries information. The difference from `resolveRepoHandle` is the failure: this route turns a
|
|
1738
|
-
* `gh` error into the payload's `reason` — "gh CLI not found — install it and run `gh auth login`"
|
|
1739
|
-
* is what the chip's tooltip now shows a user — and a `null` would erase which failure it was.
|
|
1740
|
-
*/
|
|
1741
|
-
async function resolveRepoHandleStrict(repoRoot, context = githubContext(repoRoot)) {
|
|
1742
|
-
return sharedRepoHandle(repoRoot, undefined, context);
|
|
1743
|
-
}
|
|
1744
|
-
/** Is this a reply we can still read aliases out of? `repository: null` says the handle did not
|
|
1745
|
-
* resolve, which is a real failure and must not be read as "the numbers are all missing". */
|
|
1746
|
-
function hasResolvedRepository(stdout) {
|
|
1747
|
-
try {
|
|
1748
|
-
const parsed = JSON.parse(stdout);
|
|
1749
|
-
const repository = parsed?.data?.repository;
|
|
1750
|
-
return typeof repository === 'object' && repository !== null;
|
|
1751
|
-
}
|
|
1752
|
-
catch {
|
|
1753
|
-
return false;
|
|
1754
|
-
}
|
|
1755
|
-
}
|
|
1756
684
|
// Ownership is per reference, before discovery starts. Overlapping requests join just the
|
|
1757
685
|
// numbers they need; extra numbers form their own batch without a batching timer or new delay.
|
|
1758
686
|
// At capacity, untracked work answers its callers without caching: it has no ownership token
|
|
@@ -2224,84 +1152,6 @@ function mockGithubComments(kind, number) {
|
|
|
2224
1152
|
return { available: true, comments, events, ...(detail ? { detail } : {}) };
|
|
2225
1153
|
}
|
|
2226
1154
|
// ---- the driver -------------------------------------------------------------
|
|
2227
|
-
/**
|
|
2228
|
-
* Cached availability probe so `GET /api/health` never pays a full listing. Keyed by GitHub context (root, host, account):
|
|
2229
|
-
* every registered project reads its own slot, so the boot project's constant health refresh can't
|
|
2230
|
-
* evict another project's answer (a single slot made `GET /automations` flap between "still being
|
|
2231
|
-
* checked" and available). One in-flight probe per context dedupes a burst of reads.
|
|
2232
|
-
*/
|
|
2233
|
-
const DETECT_CACHE_MAX = 64;
|
|
2234
|
-
const detectCache = new Map();
|
|
2235
|
-
const detectInflight = new Map();
|
|
2236
|
-
async function probeGithub(repoRoot, context) {
|
|
2237
|
-
let result;
|
|
2238
|
-
try {
|
|
2239
|
-
await gh(repoRoot, ['repo', 'view', '--json', 'nameWithOwner'], 5_000, undefined, context);
|
|
2240
|
-
result = { available: true };
|
|
2241
|
-
}
|
|
2242
|
-
catch (err) {
|
|
2243
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
2244
|
-
result = {
|
|
2245
|
-
available: false,
|
|
2246
|
-
reason: /ENOENT/.test(message)
|
|
2247
|
-
? 'gh CLI not found — install it and run `gh auth login`'
|
|
2248
|
-
: firstLine(message),
|
|
2249
|
-
};
|
|
2250
|
-
}
|
|
2251
|
-
detectCache.delete(context.key); // re-insert so Map order tracks recency
|
|
2252
|
-
detectCache.set(context.key, { at: Date.now(), result });
|
|
2253
|
-
while (detectCache.size > DETECT_CACHE_MAX) {
|
|
2254
|
-
const oldest = detectCache.keys().next().value;
|
|
2255
|
-
if (oldest === undefined)
|
|
2256
|
-
break;
|
|
2257
|
-
detectCache.delete(oldest);
|
|
2258
|
-
}
|
|
2259
|
-
return result;
|
|
2260
|
-
}
|
|
2261
|
-
async function detectGithub(repoRoot) {
|
|
2262
|
-
if (productEnv('DRY_RUN') === '1')
|
|
2263
|
-
return { available: true };
|
|
2264
|
-
const context = githubContext(repoRoot);
|
|
2265
|
-
const hit = detectCache.get(context.key);
|
|
2266
|
-
if (hit && Date.now() - hit.at < CACHE_MS)
|
|
2267
|
-
return hit.result;
|
|
2268
|
-
const pending = detectInflight.get(context.key);
|
|
2269
|
-
if (pending)
|
|
2270
|
-
return pending;
|
|
2271
|
-
const probe = probeGithub(repoRoot, context).finally(() => detectInflight.delete(context.key));
|
|
2272
|
-
detectInflight.set(context.key, probe);
|
|
2273
|
-
return probe;
|
|
2274
|
-
}
|
|
2275
|
-
/**
|
|
2276
|
-
* How old an availability answer `/health` serves before it probes again. The server rebuilds
|
|
2277
|
-
* health every 5 s while a client reads it, so `CACHE_MS` (60 s) started one `gh repo view` a
|
|
2278
|
-
* minute, and each start forks the server process (hearsay-tools/squawk#3658). The answer depends
|
|
2279
|
-
* on the network and on GitHub access, so no file change can signal it. A direct `detectGithub`
|
|
2280
|
-
* call (automation discovery) still refreshes the shared slot after 60 s.
|
|
2281
|
-
*/
|
|
2282
|
-
export const HEALTH_AVAILABILITY_TTL_MS = 10 * 60_000;
|
|
2283
|
-
/**
|
|
2284
|
-
* Non-blocking availability for `GET /api/health` (#major-health-latency): serves the last-known
|
|
2285
|
-
* probe immediately (stale-while-revalidate) and only returns `null` on a cold start, before the
|
|
2286
|
-
* first probe has ever warmed the cache. It NEVER shells out to `gh` on the request that reads it,
|
|
2287
|
-
* so health stays fast (a `gh repo view` round-trip is ~500–650 ms on its own). `null` is contract-safe — the whole `forge` field is additive, so
|
|
2288
|
-
* "unknown until warm" is a valid answer.
|
|
2289
|
-
*
|
|
2290
|
-
* Serving the stale value while revalidating is what keeps the GitHub nav item from flickering:
|
|
2291
|
-
* without it, every time the cache expired this returned `null` for one 5 s health poll,
|
|
2292
|
-
* dropping `forge.available` and blinking the sidebar item out until the background probe warmed.
|
|
2293
|
-
*/
|
|
2294
|
-
export function detectGithubCached(repoRoot) {
|
|
2295
|
-
if (productEnv('DRY_RUN') === '1')
|
|
2296
|
-
return { available: true };
|
|
2297
|
-
const hit = detectCache.get(githubContext(repoRoot).key);
|
|
2298
|
-
const cached = hit?.result ?? null;
|
|
2299
|
-
const fresh = hit !== undefined && Date.now() - hit.at < HEALTH_AVAILABILITY_TTL_MS;
|
|
2300
|
-
if (!fresh) {
|
|
2301
|
-
void detectGithub(repoRoot).catch(() => { }); // revalidate off the request path
|
|
2302
|
-
}
|
|
2303
|
-
return cached; // last-known value while revalidating; null only until the first probe warms
|
|
2304
|
-
}
|
|
2305
1155
|
const mergeStateCache = new Map();
|
|
2306
1156
|
const mergeInflight = new Set();
|
|
2307
1157
|
const MERGE_CACHE_MS = 15_000;
|
|
@@ -2360,11 +1210,7 @@ async function fetchPrMergeState(repoRoot, repoRef, number, refresh = false) {
|
|
|
2360
1210
|
}
|
|
2361
1211
|
export function evictGithubProjectCaches(repoRoot) {
|
|
2362
1212
|
const contextKey = githubContext(repoRoot).key;
|
|
2363
|
-
|
|
2364
|
-
if (entry.contextKey === contextKey)
|
|
2365
|
-
dropListEntry(key);
|
|
2366
|
-
});
|
|
2367
|
-
repositoryProjectsCache.delete(contextKey);
|
|
1213
|
+
evictGithubListCaches(contextKey);
|
|
2368
1214
|
commentCountsCache.forEach((_value, key) => {
|
|
2369
1215
|
if (key.startsWith(`${contextKey}\0`))
|
|
2370
1216
|
commentCountsCache.delete(key);
|