send-to-paseo 1.3.0

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/server/gh.ts ADDED
@@ -0,0 +1,864 @@
1
+ import { z } from "zod";
2
+ import {
3
+ BridgeError,
4
+ type PrPayload,
5
+ type PrRef,
6
+ type StackPrState,
7
+ } from "../shared/contracts";
8
+ import { INSTALL_HINT, findGh, ghEnv, runProcess } from "./deps";
9
+ import { setBoundedCache } from "./cache";
10
+
11
+ /**
12
+ * Pull-request lookups through the real `gh` binary.
13
+ *
14
+ * `gh` is a shell *function* in some users' zsh, so this module resolves the
15
+ * executable itself (see `server/deps`) and calls it with `execFile` and an
16
+ * argv array. Nothing here ever goes through a shell, which means the function
17
+ * is bypassed and no part of an HTTP request can become shell syntax.
18
+ *
19
+ * **`gh` IS OPTIONAL.** Everything it provides is metadata: the PR title, the
20
+ * head and base branch names, and stack discovery. Creating a worktree for a PR
21
+ * goes through Paseo's own `checkoutSource: { kind: "change_request" }`, which
22
+ * uses Paseo's forge credentials and never touches `gh`. So a missing,
23
+ * unauthenticated or broken `gh` must degrade — see `lookupPr` — and must never
24
+ * turn "send this instruction to an agent" into an error. The one exception is
25
+ * a `gh` that is working well enough to say the *pull request number* does not
26
+ * exist, which is a real, actionable answer worth reporting.
27
+ */
28
+
29
+ const PR_TIMEOUT_MS = 15_000;
30
+ /** Sibling lookups are best-effort, so they get a much shorter leash. */
31
+ const STACK_TIMEOUT_MS = 8_000;
32
+ const PR_TTL_MS = 60_000;
33
+ const MAX_PR_CACHE_ENTRIES = 512;
34
+ const MAX_REPOSITORY_CACHE_ENTRIES = 128;
35
+
36
+ const GhPrSchema = z.object({
37
+ number: z.number(),
38
+ title: z.string(),
39
+ headRefName: z.string(),
40
+ baseRefName: z.string(),
41
+ state: z.string(),
42
+ url: z.string(),
43
+ });
44
+
45
+ /** One `gh pr list` row: just enough to rebuild the stack graph. */
46
+ const GhPrListItemSchema = z.object({
47
+ number: z.number(),
48
+ headRefName: z.string(),
49
+ baseRefName: z.string(),
50
+ /** Only requested for the merged/closed list; the open list knows its own. */
51
+ state: z.string().optional(),
52
+ });
53
+ const GhPrListSchema = z.array(GhPrListItemSchema);
54
+
55
+ const GhRepoSchema = z.object({
56
+ defaultBranchRef: z.object({ name: z.string() }).nullable().optional(),
57
+ });
58
+
59
+ /**
60
+ * GitHub's own state vocabulary is uppercase and treats `MERGED` as distinct
61
+ * from `CLOSED`; this maps it onto the three values CONTRACT.md's
62
+ * `stackPrState` allows.
63
+ */
64
+ export function normalizeStackPrState(raw: string): StackPrState {
65
+ const value = raw.trim().toUpperCase();
66
+ if (value === "OPEN") return "open";
67
+ if (value === "MERGED") return "merged";
68
+ // Anything else is reported as closed rather than dropped: an unrecognised
69
+ // state must not silently become "open", which is the one value the wire
70
+ // format spells by omission.
71
+ return "closed";
72
+ }
73
+
74
+ /**
75
+ * A branch that belongs to the same stack as the PR being resolved.
76
+ * `distance` is hops through the base->head chain, so 1 is the immediate
77
+ * parent or child. Used to prefer the nearest stack workspace.
78
+ */
79
+ export interface StackMember {
80
+ /**
81
+ * The PR whose head branch this is, or null when the branch has no PR at
82
+ * all. Null is reachable only through the local-ancestry mechanism, which
83
+ * proves stack membership from commit reachability and therefore also
84
+ * recognises a Graphite branch that was never pushed as a PR.
85
+ */
86
+ number: number | null;
87
+ branch: string;
88
+ distance: number;
89
+ /** That PR's state; null exactly when `number` is null. */
90
+ state: StackPrState | null;
91
+ }
92
+
93
+ /** Distance given to a member we know only from the caller's hints. */
94
+ export const UNKNOWN_STACK_DISTANCE = 9_999;
95
+
96
+ /**
97
+ * Distance for a member proved only by local git ancestry.
98
+ *
99
+ * Deliberately its own constant, and deliberately *larger* than
100
+ * `UNKNOWN_STACK_DISTANCE`, so ordering degrades in order of evidence quality:
101
+ * a measured hop count through GitHub's base->head chain first, then a sibling
102
+ * the page itself listed but whose hop count we could not compute, then a
103
+ * purely local inference from commit reachability. Reusing
104
+ * `UNKNOWN_STACK_DISTANCE` would make "GitHub says this is a sibling" and "the
105
+ * commits happen to be an ancestor" sort identically, and they are not equally
106
+ * strong claims. Neither can ever outrank a real hop count, which is 1..n.
107
+ */
108
+ export const ANCESTRY_STACK_DISTANCE = 99_999;
109
+
110
+ const STACK_LIST_LIMIT = 200;
111
+ const STACK_LIST_TIMEOUT_MS = 12_000;
112
+ const STACK_LIST_TTL_MS = 60_000;
113
+
114
+ /**
115
+ * The merged/closed half of stack discovery.
116
+ *
117
+ * A repository's open PRs are naturally bounded; its merged history is not, so
118
+ * this list is capped exactly like the open one and the cap is logged rather
119
+ * than silently truncating. The TTL is longer because the fetch is only ever
120
+ * made on the slow path (see `viewStackGraph`) and because merged history is
121
+ * near-immutable — the one thing a stale entry can cost is up to five minutes
122
+ * where a *just*-merged PR is in neither list (the open list drops it at 60s),
123
+ * and the ancestry mechanism covers that window.
124
+ */
125
+ const CLOSED_STACK_LIST_LIMIT = 200;
126
+ const CLOSED_STACK_LIST_TTL_MS = 5 * 60_000;
127
+ /** `gh repo view` is one field; it does not need the list timeout. */
128
+ const REPO_VIEW_TIMEOUT_MS = 8_000;
129
+ const REPO_TTL_MS = 30 * 60_000;
130
+
131
+ /**
132
+ * How many pull requests may be based on a branch before a *non-open* PR
133
+ * claiming that branch as its head is treated as trunk rather than as a stack
134
+ * node.
135
+ *
136
+ * The exact-name trunk check is the primary guard; this is the backstop for
137
+ * when trunk cannot be named at all, and for a repository with a second
138
+ * long-lived integration branch that back-merges (`main` <- `develop`). Four,
139
+ * not two, because a Graphite stack genuinely can fork: a branch with two or
140
+ * three children is a real shape, a branch with four merged-PR children that
141
+ * is not an integration branch is not.
142
+ */
143
+ const TRUNK_FANOUT = 4;
144
+
145
+ /**
146
+ * Why a `gh` call failed, at the granularity a user can act on. Kept separate
147
+ * from the wire error code because CONTRACT.md's code set is closed and lumps
148
+ * all of these into `forge_unauthenticated`; the distinction lives in the
149
+ * message, the hint and the log line instead.
150
+ */
151
+ export type GhFailureKind =
152
+ | "missing"
153
+ | "unauthenticated"
154
+ | "no_repo_access"
155
+ | "network"
156
+ | "timeout"
157
+ | "pr_missing"
158
+ | "unknown";
159
+
160
+ /** A `gh` failure carrying why, so callers can decide to degrade or report. */
161
+ export class GhError extends BridgeError {
162
+ readonly kind: GhFailureKind;
163
+
164
+ constructor(
165
+ kind: GhFailureKind,
166
+ code: "forge_unauthenticated" | "pr_not_found",
167
+ message: string,
168
+ hint?: string,
169
+ ) {
170
+ super(code, message, hint);
171
+ this.kind = kind;
172
+ }
173
+ }
174
+
175
+ async function ghBinary(): Promise<string> {
176
+ const found = await findGh();
177
+ if (found === null) {
178
+ throw new GhError(
179
+ "missing",
180
+ "forge_unauthenticated",
181
+ "The GitHub CLI (gh) is not installed, so the pull request title, branches and stack could not be read. Sending still works.",
182
+ INSTALL_HINT.gh,
183
+ );
184
+ }
185
+ return found;
186
+ }
187
+
188
+ function looksUnauthenticated(text: string): boolean {
189
+ const lower = text.toLowerCase();
190
+ return (
191
+ lower.includes("gh auth login") ||
192
+ lower.includes("authentication required") ||
193
+ lower.includes("not logged in") ||
194
+ lower.includes("bad credentials") ||
195
+ lower.includes("http 401") ||
196
+ lower.includes("requires authentication")
197
+ );
198
+ }
199
+
200
+ /**
201
+ * gh resolved the repository but not the pull request number. This is the one
202
+ * `gh` failure worth reporting as an error: the answer is real and the user can
203
+ * act on it, and unlike the cases below it does not mean "we could not ask".
204
+ */
205
+ function looksPrMissing(text: string): boolean {
206
+ const lower = text.toLowerCase();
207
+ return (
208
+ lower.includes("could not resolve to a pullrequest") ||
209
+ lower.includes("no pull requests found") ||
210
+ lower.includes("could not find any pull request")
211
+ );
212
+ }
213
+
214
+ /**
215
+ * gh could not see the repository at all. Distinct from "the PR does not
216
+ * exist": a private repo the user's `gh` account cannot read is still a repo
217
+ * Paseo's own forge credentials may well be able to check out, so this degrades
218
+ * rather than failing the request.
219
+ */
220
+ function looksNoRepoAccess(text: string): boolean {
221
+ const lower = text.toLowerCase();
222
+ return (
223
+ lower.includes("could not resolve to a repository") ||
224
+ lower.includes("http 403") ||
225
+ lower.includes("http 404") ||
226
+ lower.includes("not found") ||
227
+ lower.includes("saml enforcement") ||
228
+ lower.includes("resource not accessible")
229
+ );
230
+ }
231
+
232
+ /** No route to github.com. Never let this read as "gh is not installed". */
233
+ function looksNetwork(text: string): boolean {
234
+ const lower = text.toLowerCase();
235
+ return (
236
+ lower.includes("dial tcp") ||
237
+ lower.includes("no such host") ||
238
+ lower.includes("connection refused") ||
239
+ lower.includes("network is unreachable") ||
240
+ lower.includes("temporary failure in name resolution") ||
241
+ lower.includes("tls handshake") ||
242
+ lower.includes("i/o timeout") ||
243
+ lower.includes("proxyconnect") ||
244
+ lower.includes("eof")
245
+ );
246
+ }
247
+
248
+ interface ExecFailure {
249
+ code?: number | string;
250
+ stderr?: string;
251
+ stdout?: string;
252
+ message?: string;
253
+ killed?: boolean;
254
+ }
255
+
256
+ /**
257
+ * Turns a raw `execFile` rejection into a `GhError` whose message names the
258
+ * dependency and whose hint is the exact command to run. The order matters:
259
+ * ENOENT (the binary vanished between lookup and spawn) and an auth failure are
260
+ * both checked before the generic text matches, so neither can be mistaken for
261
+ * the other or for "pull request not found".
262
+ */
263
+ function classify(error: unknown, ref: PrRef): GhError {
264
+ const failure = error as ExecFailure;
265
+ const stderr = (failure.stderr ?? "").trim();
266
+ const text = `${stderr}\n${failure.message ?? ""}`;
267
+ const slug = `${ref.owner}/${ref.repo}#${ref.number}`;
268
+
269
+ // The path resolved but the file is gone (uninstalled while we were running),
270
+ // or is not executable by this user.
271
+ if (failure.code === "ENOENT" || failure.code === "EACCES") {
272
+ return new GhError(
273
+ "missing",
274
+ "forge_unauthenticated",
275
+ "The GitHub CLI (gh) was found but could not be executed, so the pull request title, branches and stack could not be read. Sending still works.",
276
+ INSTALL_HINT.gh,
277
+ );
278
+ }
279
+ // gh exits 4 specifically for an authentication problem.
280
+ if (failure.code === 4 || looksUnauthenticated(text)) {
281
+ return new GhError(
282
+ "unauthenticated",
283
+ "forge_unauthenticated",
284
+ `The GitHub CLI (gh) is installed but not signed in to GitHub, so ${slug} could not be read. Sending still works.`,
285
+ "Run: gh auth login",
286
+ );
287
+ }
288
+ if (failure.killed === true || failure.code === "ETIMEDOUT") {
289
+ return new GhError(
290
+ "timeout",
291
+ "forge_unauthenticated",
292
+ `The GitHub CLI (gh) did not answer in time while reading ${slug}.`,
293
+ "Check your network, then try again.",
294
+ );
295
+ }
296
+ if (looksNetwork(text)) {
297
+ return new GhError(
298
+ "network",
299
+ "forge_unauthenticated",
300
+ `The GitHub CLI (gh) could not reach github.com while reading ${slug}.`,
301
+ "Check your network connection, then try again.",
302
+ );
303
+ }
304
+ if (looksPrMissing(text)) {
305
+ return new GhError(
306
+ "pr_missing",
307
+ "pr_not_found",
308
+ `Pull request ${slug} does not exist on GitHub.`,
309
+ "Check the pull request number.",
310
+ );
311
+ }
312
+ if (looksNoRepoAccess(text)) {
313
+ return new GhError(
314
+ "no_repo_access",
315
+ "forge_unauthenticated",
316
+ `The GitHub account gh is signed in as cannot see ${ref.owner}/${ref.repo}, so ${slug} could not be read. Sending still works.`,
317
+ "Check access with: gh auth status",
318
+ );
319
+ }
320
+ // Unknown gh failures are reported as a forge problem rather than `internal`,
321
+ // because the actionable cause is almost always gh or the network.
322
+ return new GhError(
323
+ "unknown",
324
+ "forge_unauthenticated",
325
+ `The GitHub CLI (gh) could not read ${slug}.`,
326
+ stderr === "" ? undefined : stderr.split("\n")[0],
327
+ );
328
+ }
329
+
330
+ const prCache = new Map<string, { at: number; pr: PrPayload }>();
331
+
332
+ function cacheKey(ref: PrRef): string {
333
+ return `${ref.owner}/${ref.repo}#${ref.number}`;
334
+ }
335
+
336
+ async function viewPrRaw(ref: PrRef, timeoutMs: number): Promise<PrPayload> {
337
+ const bin = await ghBinary();
338
+ const { stdout } = await runProcess(
339
+ bin,
340
+ [
341
+ "pr",
342
+ "view",
343
+ String(ref.number),
344
+ "--repo",
345
+ `${ref.owner}/${ref.repo}`,
346
+ "--json",
347
+ "number,title,headRefName,baseRefName,state,url",
348
+ ],
349
+ { timeoutMs, env: ghEnv() },
350
+ );
351
+ const parsed = GhPrSchema.safeParse(JSON.parse(stdout));
352
+ if (!parsed.success) {
353
+ throw new GhError(
354
+ "unknown",
355
+ "forge_unauthenticated",
356
+ `The GitHub CLI (gh) returned an unexpected shape for ${cacheKey(ref)}.`,
357
+ "Check the gh version with: gh --version",
358
+ );
359
+ }
360
+ return {
361
+ number: parsed.data.number,
362
+ title: parsed.data.title,
363
+ headBranch: parsed.data.headRefName,
364
+ baseBranch: parsed.data.baseRefName,
365
+ state: parsed.data.state,
366
+ url: parsed.data.url,
367
+ };
368
+ }
369
+
370
+ /** PR metadata, cached briefly so opening the popover twice costs one lookup. */
371
+ export async function viewPr(ref: PrRef): Promise<PrPayload> {
372
+ const key = cacheKey(ref);
373
+ const hit = prCache.get(key);
374
+ if (hit !== undefined && Date.now() - hit.at < PR_TTL_MS) return hit.pr;
375
+ try {
376
+ const pr = await viewPrRaw(ref, PR_TIMEOUT_MS);
377
+ setBoundedCache(prCache, key, { at: Date.now(), pr }, {
378
+ maxEntries: MAX_PR_CACHE_ENTRIES,
379
+ expired: (value) => Date.now() - value.at >= PR_TTL_MS,
380
+ });
381
+ return pr;
382
+ } catch (error) {
383
+ if (error instanceof BridgeError) throw error;
384
+ throw classify(error, ref);
385
+ }
386
+ }
387
+
388
+ /* -------------------------------------------------------------------------- */
389
+ /* degraded lookup */
390
+ /* -------------------------------------------------------------------------- */
391
+
392
+ /**
393
+ * The degraded-mode log line is throttled per failure kind. The popover calls
394
+ * resolve on every open, and a user who has simply not installed `gh` would
395
+ * otherwise get an identical line for every PR they look at.
396
+ */
397
+ const OUTAGE_LOG_TTL_MS = 5 * 60_000;
398
+ const outageLoggedAt = new Map<GhFailureKind, number>();
399
+
400
+ /** What was lost, and what the user can do about it. Never on the wire. */
401
+ export interface GhOutage {
402
+ kind: GhFailureKind;
403
+ /** Full sentence, safe to show a user and to put in an agent's prompt. */
404
+ message: string;
405
+ hint: string;
406
+ /** A few words for a picker label, e.g. "gh not installed". */
407
+ short: string;
408
+ }
409
+
410
+ function shortFor(kind: GhFailureKind): string {
411
+ switch (kind) {
412
+ case "missing":
413
+ return "gh not installed";
414
+ case "unauthenticated":
415
+ return "gh not signed in — run gh auth login";
416
+ case "no_repo_access":
417
+ return "gh cannot see this repo";
418
+ case "network":
419
+ return "github.com unreachable";
420
+ case "timeout":
421
+ return "gh timed out";
422
+ default:
423
+ return "gh unavailable";
424
+ }
425
+ }
426
+
427
+ /**
428
+ * The PR as GitHub describes it, or a placeholder plus the reason it is a
429
+ * placeholder.
430
+ *
431
+ * This is the whole graceful-degradation story for `gh`. Only `pr_missing`
432
+ * propagates as an error, because it is the one case where `gh` gave a real
433
+ * answer about a real repository. Everything else — not installed, not signed
434
+ * in, no access, no network, timed out, unparseable output — returns a
435
+ * placeholder so the popover still opens and the user can still send: Paseo
436
+ * creates the worktree from the PR number itself, without `gh`.
437
+ *
438
+ * Callers must surface `outage` (candidate label, prompt note, log line);
439
+ * degrading silently would leave the user wondering why the PR title vanished.
440
+ */
441
+ export async function lookupPr(ref: PrRef): Promise<{ pr: PrPayload; outage: GhOutage | null }> {
442
+ try {
443
+ return { pr: await viewPr(ref), outage: null };
444
+ } catch (error) {
445
+ if (error instanceof GhError && error.kind !== "pr_missing") {
446
+ const outage: GhOutage = {
447
+ kind: error.kind,
448
+ message: error.message,
449
+ hint: error.hint ?? "",
450
+ short: shortFor(error.kind),
451
+ };
452
+ const lastLogged = outageLoggedAt.get(error.kind) ?? 0;
453
+ if (Date.now() - lastLogged > OUTAGE_LOG_TTL_MS) {
454
+ outageLoggedAt.set(error.kind, Date.now());
455
+ console.log(
456
+ `[send-to-paseo] degraded: ${error.message}${outage.hint === "" ? "" : ` (${outage.hint})`}`,
457
+ );
458
+ }
459
+ return { pr: unknownPr(ref), outage };
460
+ }
461
+ throw error;
462
+ }
463
+ }
464
+
465
+ /**
466
+ * A PR payload with only what is knowable without `gh`: the number, and the
467
+ * canonical URL, which is a pure function of the reference.
468
+ *
469
+ * `headBranch` and `baseBranch` are deliberately empty rather than guessed.
470
+ * Empty is what stops `buildCandidates` from claiming an exact branch match and
471
+ * what stops `composePrompt` from telling an agent it is on a branch nobody
472
+ * verified. `title` stays `PR #942` so anything that concatenates it still
473
+ * reads correctly.
474
+ */
475
+ export function unknownPr(ref: PrRef): PrPayload {
476
+ return {
477
+ number: ref.number,
478
+ title: `PR #${ref.number}`,
479
+ headBranch: "",
480
+ baseBranch: "",
481
+ state: "UNKNOWN",
482
+ url: `https://github.com/${ref.owner}/${ref.repo}/pull/${ref.number}`,
483
+ };
484
+ }
485
+
486
+ /* -------------------------------------------------------------------------- */
487
+ /* stack discovery */
488
+ /* -------------------------------------------------------------------------- */
489
+
490
+ interface PrListEntry {
491
+ number: number;
492
+ headRefName: string;
493
+ baseRefName: string;
494
+ state: StackPrState;
495
+ }
496
+
497
+ const prListCache = new Map<string, { at: number; entries: PrListEntry[] }>();
498
+ const closedPrListCache = new Map<string, { at: number; entries: PrListEntry[] }>();
499
+ const repoTrunkCache = new Map<string, { at: number; branch: string | null }>();
500
+
501
+ function repoSlug(ref: Pick<PrRef, "owner" | "repo">): string {
502
+ return `${ref.owner}/${ref.repo}`;
503
+ }
504
+
505
+ /** One `gh pr list` call, parsed and stamped with the state we asked for. */
506
+ async function fetchPrList(
507
+ ref: Pick<PrRef, "owner" | "repo">,
508
+ state: "open" | "closed",
509
+ limit: number,
510
+ ): Promise<PrListEntry[]> {
511
+ const bin = await ghBinary();
512
+ const { stdout } = await runProcess(
513
+ bin,
514
+ [
515
+ "pr",
516
+ "list",
517
+ "--repo",
518
+ repoSlug(ref),
519
+ "--state",
520
+ state,
521
+ "--limit",
522
+ String(limit),
523
+ "--json",
524
+ // `state` is only meaningful on the closed list, where it separates
525
+ // MERGED from CLOSED. Asked for unconditionally so both lists parse
526
+ // through one schema.
527
+ "number,headRefName,baseRefName,state",
528
+ ],
529
+ { timeoutMs: STACK_LIST_TIMEOUT_MS, env: ghEnv() },
530
+ );
531
+ const parsed = GhPrListSchema.safeParse(JSON.parse(stdout));
532
+ if (!parsed.success) {
533
+ throw new GhError(
534
+ "unknown",
535
+ "forge_unauthenticated",
536
+ `The GitHub CLI (gh) returned an unexpected shape listing pull requests for ${repoSlug(ref)}.`,
537
+ "Check the gh version with: gh --version",
538
+ );
539
+ }
540
+ return parsed.data.map((row) => ({
541
+ number: row.number,
542
+ headRefName: row.headRefName,
543
+ baseRefName: row.baseRefName,
544
+ // Trust the row over the filter we asked for: `--state closed` returns
545
+ // MERGED rows too (measured, see `listNonOpenPrs`).
546
+ state:
547
+ row.state === undefined
548
+ ? state === "open"
549
+ ? "open"
550
+ : "closed"
551
+ : normalizeStackPrState(row.state),
552
+ }));
553
+ }
554
+
555
+ /**
556
+ * Every open PR in a repository, as `{number, head, base, state}`.
557
+ *
558
+ * One request instead of one per sibling, cached briefly because the popover
559
+ * calls resolve on every open.
560
+ */
561
+ async function listOpenPrs(ref: Pick<PrRef, "owner" | "repo">): Promise<PrListEntry[]> {
562
+ const key = repoSlug(ref).toLowerCase();
563
+ const hit = prListCache.get(key);
564
+ if (hit !== undefined && Date.now() - hit.at < STACK_LIST_TTL_MS) return hit.entries;
565
+
566
+ const entries = await fetchPrList(ref, "open", STACK_LIST_LIMIT);
567
+ if (entries.length >= STACK_LIST_LIMIT) {
568
+ // Truncation degrades safely — an unfound stack falls back to the create
569
+ // option rather than to a wrong workspace — but it would be an unexplainable
570
+ // mystery in the field, so say it out loud.
571
+ console.log(
572
+ `[send-to-paseo] ${repoSlug(ref)} has at least ${STACK_LIST_LIMIT} open PRs; ` +
573
+ `the stack lookup may be truncated and stack candidates may be missing`,
574
+ );
575
+ }
576
+ setBoundedCache(prListCache, key, { at: Date.now(), entries }, {
577
+ maxEntries: MAX_REPOSITORY_CACHE_ENTRIES,
578
+ expired: (value) => Date.now() - value.at >= STACK_LIST_TTL_MS,
579
+ });
580
+ return entries;
581
+ }
582
+
583
+ /**
584
+ * The merged and closed PRs of a repository, newest first.
585
+ *
586
+ * ONE call, not two: `gh pr list --state closed` returns MERGED rows as well as
587
+ * CLOSED ones — measured on 2026-09-02 against `cli/cli`, where the first five
588
+ * `--state closed` rows were three CLOSED and two MERGED. (GitHub's search
589
+ * semantics: a merged PR *is* closed. `--state merged` is the narrower filter.)
590
+ * So one request covers both, and each row's own `state` field is what
591
+ * distinguishes them.
592
+ *
593
+ * NEVER on the hot path. `/v1/resolve` runs on every popover open while the
594
+ * user types, and the open-PR list already answers the common cases (workspace
595
+ * on this PR's branch, or on an open sibling's). This list is fetched only when
596
+ * a project workspace is left unplaced by the open-PR graph, which is the
597
+ * situation this whole mechanism exists for.
598
+ */
599
+ async function listNonOpenPrs(ref: Pick<PrRef, "owner" | "repo">): Promise<PrListEntry[]> {
600
+ const key = repoSlug(ref).toLowerCase();
601
+ const hit = closedPrListCache.get(key);
602
+ if (hit !== undefined && Date.now() - hit.at < CLOSED_STACK_LIST_TTL_MS) return hit.entries;
603
+
604
+ const entries = await fetchPrList(ref, "closed", CLOSED_STACK_LIST_LIMIT);
605
+ if (entries.length >= CLOSED_STACK_LIST_LIMIT) {
606
+ // A repository's merged history is unbounded, so unlike the open list this
607
+ // cap will be hit by any busy repo. Say so: the symptom of truncation is
608
+ // "my merged stack branch was not recognised", and it is otherwise
609
+ // indistinguishable from the mechanism not working at all.
610
+ console.log(
611
+ `[send-to-paseo] ${repoSlug(ref)} has at least ${CLOSED_STACK_LIST_LIMIT} merged/closed PRs; ` +
612
+ `only the ${CLOSED_STACK_LIST_LIMIT} most recent were considered, so an older ` +
613
+ `merged stack branch may not be recognised`,
614
+ );
615
+ }
616
+ setBoundedCache(closedPrListCache, key, { at: Date.now(), entries }, {
617
+ maxEntries: MAX_REPOSITORY_CACHE_ENTRIES,
618
+ expired: (value) => Date.now() - value.at >= CLOSED_STACK_LIST_TTL_MS,
619
+ });
620
+ return entries;
621
+ }
622
+
623
+ /**
624
+ * The repository's default branch, according to GitHub.
625
+ *
626
+ * Only used as a fallback when the local clone has no `refs/remotes/origin/HEAD`
627
+ * (see `readTrunkBranch`), and cached for half an hour because a repository's
628
+ * default branch effectively never changes. Returns null rather than throwing:
629
+ * not knowing trunk costs precision in stack discovery, never the resolve.
630
+ */
631
+ export async function repoDefaultBranch(ref: Pick<PrRef, "owner" | "repo">): Promise<string | null> {
632
+ const key = repoSlug(ref).toLowerCase();
633
+ const hit = repoTrunkCache.get(key);
634
+ if (hit !== undefined && Date.now() - hit.at < REPO_TTL_MS) return hit.branch;
635
+ let branch: string | null = null;
636
+ try {
637
+ const bin = await ghBinary();
638
+ const { stdout } = await runProcess(
639
+ bin,
640
+ ["repo", "view", repoSlug(ref), "--json", "defaultBranchRef"],
641
+ { timeoutMs: REPO_VIEW_TIMEOUT_MS, env: ghEnv() },
642
+ );
643
+ const parsed = GhRepoSchema.safeParse(JSON.parse(stdout));
644
+ const name = parsed.success ? (parsed.data.defaultBranchRef?.name ?? "") : "";
645
+ branch = name === "" ? null : name;
646
+ } catch {
647
+ branch = null;
648
+ }
649
+ setBoundedCache(repoTrunkCache, key, { at: Date.now(), branch }, {
650
+ maxEntries: MAX_REPOSITORY_CACHE_ENTRIES,
651
+ expired: (value) => Date.now() - value.at >= REPO_TTL_MS,
652
+ });
653
+ return branch;
654
+ }
655
+
656
+ /**
657
+ * The stack containing `headBranch`, derived from GitHub itself.
658
+ *
659
+ * A Graphite stack is a real base->head chain on GitHub: PR #943's
660
+ * `baseRefName` is PR #942's `headRefName`. (The `graphite-base/942` ref shown
661
+ * in Graphite's own UI is display-only and never appears here.) So the stack is
662
+ * the connected component containing our PR in the graph whose edges are
663
+ * "A.base === B.head", and a breadth-first walk gives both downstack ancestors
664
+ * and upstack descendants at once, along with the hop distance.
665
+ *
666
+ * Trunk cannot create a false edge *among open PRs*: an edge exists only when
667
+ * one PR's base is another PR's head, and an open PR whose head is `main` is
668
+ * not a thing anyone opens. That stops being true the moment merged PRs join
669
+ * the graph — see `trunkLikeHeads` — which is why `includeNonOpen` also needs a
670
+ * trunk name.
671
+ *
672
+ * WHY NOT `gt`: the Graphite CLI answers "what is *my current* stack" from
673
+ * local, per-worktree metadata, relative to whatever branch happens to be
674
+ * checked out in the directory it runs in. This endpoint runs while the user is
675
+ * typing in a browser and must not depend on — or disturb — the state of any
676
+ * worktree, least of all the candidate workspaces themselves, each of which is
677
+ * on its own branch. It also needs no second credential: `gh` is already
678
+ * required here. See PLAN.md.
679
+ */
680
+ export interface StackGraph {
681
+ /**
682
+ * Stack members keyed by head branch. Excludes the PR's own head branch,
683
+ * which is the exact match rather than a sibling.
684
+ */
685
+ members: Map<string, StackMember>;
686
+ /**
687
+ * Every PR the walk *considered*, keyed by head branch, open entries winning
688
+ * a duplicate. Not the stack — this is how a branch proved to belong to the
689
+ * stack by some other means (local ancestry) gets a PR number and a state
690
+ * attached to it.
691
+ */
692
+ byHead: Map<string, PrListEntry>;
693
+ /** True when the merged/closed list was consulted. */
694
+ widened: boolean;
695
+ }
696
+
697
+ /**
698
+ * Head branches that are really trunk wearing a merged PR's clothes.
699
+ *
700
+ * MEASURED, not hypothetical: in `vercel/turborepo`, PR #13875 is MERGED with
701
+ * `headRefName: "main"` — a release back-merge. Feed that row to the walk and
702
+ * `main` becomes a graph node, at which point all 13 open PRs based on `main`
703
+ * are one connected component, i.e. one enormous false "stack". The same shape
704
+ * appears wherever a repository merges an integration branch back into trunk.
705
+ *
706
+ * Two guards, because the primary one can be unavailable:
707
+ * 1. the trunk branch's name, when the caller could determine it;
708
+ * 2. fan-out: a non-open head that `TRUNK_FANOUT` or more PRs are based on.
709
+ *
710
+ * Only non-open entries are filtered. Open entries keep the behaviour that the
711
+ * existing verification suite measured, and the failure mode of filtering is
712
+ * asymmetric anyway: dropping a real stack node costs a rank-2 candidate and
713
+ * falls back to "create a worktree", while keeping a false one *proposes the
714
+ * wrong workspace*.
715
+ */
716
+ function trunkLikeHeads(entries: readonly PrListEntry[], trunk: string | null): Set<string> {
717
+ const baseCounts = new Map<string, number>();
718
+ for (const entry of entries) {
719
+ baseCounts.set(entry.baseRefName, (baseCounts.get(entry.baseRefName) ?? 0) + 1);
720
+ }
721
+ const rejected = new Set<string>();
722
+ for (const entry of entries) {
723
+ if (entry.state === "open") continue;
724
+ if (trunk !== null && entry.headRefName === trunk) rejected.add(entry.headRefName);
725
+ if ((baseCounts.get(entry.headRefName) ?? 0) >= TRUNK_FANOUT) rejected.add(entry.headRefName);
726
+ }
727
+ return rejected;
728
+ }
729
+
730
+ export async function viewStackGraph(
731
+ ref: Pick<PrRef, "owner" | "repo">,
732
+ headBranch: string,
733
+ options: {
734
+ /**
735
+ * Also walk merged and closed PRs. Costs one extra `gh pr list`, so the
736
+ * caller only sets it once it knows the open-PR graph left a workspace
737
+ * unexplained.
738
+ */
739
+ includeNonOpen?: boolean;
740
+ /** Trunk's branch name, when known. See `trunkLikeHeads`. */
741
+ trunk?: string | null;
742
+ } = {},
743
+ ): Promise<StackGraph> {
744
+ const open = await listOpenPrs(ref);
745
+ const widened = options.includeNonOpen === true;
746
+ // Open first, so `byHead` prefers an open PR over a merged one for the same
747
+ // head branch. A branch that has both is a reopened-then-superseded head, and
748
+ // the open PR is the one the user is looking at.
749
+ const entries = widened ? [...open, ...(await listNonOpenPrs(ref))] : open;
750
+ const rejected = widened ? trunkLikeHeads(entries, options.trunk ?? null) : new Set<string>();
751
+
752
+ const byHead = new Map<string, PrListEntry>();
753
+ for (const entry of entries) {
754
+ // A branch with two open PRs is malformed; first wins, deterministically.
755
+ if (!byHead.has(entry.headRefName)) byHead.set(entry.headRefName, entry);
756
+ }
757
+ const children = new Map<string, PrListEntry[]>();
758
+ for (const entry of entries) {
759
+ const list = children.get(entry.baseRefName);
760
+ if (list === undefined) children.set(entry.baseRefName, [entry]);
761
+ else list.push(entry);
762
+ }
763
+
764
+ const start = byHead.get(headBranch);
765
+ const found = new Map<string, StackMember>();
766
+ if (start === undefined) return { members: found, byHead, widened };
767
+
768
+ const seen = new Set<string>([start.headRefName]);
769
+ let frontier: PrListEntry[] = [start];
770
+ let distance = 0;
771
+
772
+ while (frontier.length > 0) {
773
+ const next: PrListEntry[] = [];
774
+ for (const entry of frontier) {
775
+ if (distance > 0) {
776
+ found.set(entry.headRefName, {
777
+ number: entry.number,
778
+ branch: entry.headRefName,
779
+ distance,
780
+ state: entry.state,
781
+ });
782
+ }
783
+ // Downstack: the PR whose head is this PR's base.
784
+ const parent = byHead.get(entry.baseRefName);
785
+ if (
786
+ parent !== undefined &&
787
+ !seen.has(parent.headRefName) &&
788
+ !rejected.has(parent.headRefName)
789
+ ) {
790
+ seen.add(parent.headRefName);
791
+ next.push(parent);
792
+ }
793
+ // Upstack: every PR based on this PR's head.
794
+ for (const child of children.get(entry.headRefName) ?? []) {
795
+ if (seen.has(child.headRefName) || rejected.has(child.headRefName)) continue;
796
+ seen.add(child.headRefName);
797
+ next.push(child);
798
+ }
799
+ }
800
+ frontier = next;
801
+ distance += 1;
802
+ }
803
+
804
+ return { members: found, byHead, widened };
805
+ }
806
+
807
+ /**
808
+ * Head branches for the stack siblings, best-effort, with each sibling's state.
809
+ *
810
+ * A slow or failing sibling lookup must never block a send, so failures are
811
+ * dropped and the caller simply gets no rank-2 candidates for that PR.
812
+ */
813
+ export async function viewStackBranches(
814
+ ref: Pick<PrRef, "forge" | "owner" | "repo">,
815
+ numbers: readonly number[],
816
+ ): Promise<Map<string, { number: number; state: StackPrState }>> {
817
+ const byBranch = new Map<string, { number: number; state: StackPrState }>();
818
+ const unique = [...new Set(numbers)];
819
+ if (unique.length === 0) return byBranch;
820
+
821
+ const results = await Promise.allSettled(
822
+ unique.map(async (number) => {
823
+ const siblingRef: PrRef = { ...ref, number };
824
+ const key = cacheKey(siblingRef);
825
+ const hit = prCache.get(key);
826
+ if (hit !== undefined && Date.now() - hit.at < PR_TTL_MS) return hit.pr;
827
+ const pr = await viewPrRaw(siblingRef, STACK_TIMEOUT_MS);
828
+ setBoundedCache(prCache, key, { at: Date.now(), pr }, {
829
+ maxEntries: MAX_PR_CACHE_ENTRIES,
830
+ expired: (value) => Date.now() - value.at >= PR_TTL_MS,
831
+ });
832
+ return pr;
833
+ }),
834
+ );
835
+
836
+ let failures = 0;
837
+ for (const result of results) {
838
+ if (result.status !== "fulfilled") {
839
+ failures += 1;
840
+ continue;
841
+ }
842
+ // First writer wins, so the lowest sibling number labels a shared branch.
843
+ if (!byBranch.has(result.value.headBranch)) {
844
+ byBranch.set(result.value.headBranch, {
845
+ number: result.value.number,
846
+ state: normalizeStackPrState(result.value.state),
847
+ });
848
+ }
849
+ }
850
+ if (failures > 0) {
851
+ console.log(
852
+ `[send-to-paseo] ${failures} of ${unique.length} stack sibling lookups failed; continuing without them`,
853
+ );
854
+ }
855
+ return byBranch;
856
+ }
857
+
858
+ export function clearPrCache(): void {
859
+ prCache.clear();
860
+ prListCache.clear();
861
+ closedPrListCache.clear();
862
+ repoTrunkCache.clear();
863
+ outageLoggedAt.clear();
864
+ }