ticket-runner 0.6.4 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.ko.md +5 -5
  2. package/README.md +4 -4
  3. package/docs/templates/operator-skill.md +81 -16
  4. package/package.json +1 -1
  5. package/src/acceptance-criteria.ts +99 -2
  6. package/src/adapters/claude-agent-runner.ts +5 -5
  7. package/src/adapters/exec.ts +32 -4
  8. package/src/adapters/gh-tracker.ts +276 -60
  9. package/src/adapters/git-workspace.ts +27 -10
  10. package/src/adapters/liveness.ts +77 -0
  11. package/src/adapters/process-tree.ts +4 -7
  12. package/src/adapters/version.ts +5 -5
  13. package/src/branch.ts +1 -1
  14. package/src/cli.ts +2 -2
  15. package/src/config.ts +22 -4
  16. package/src/conventions.ts +22 -19
  17. package/src/credential.ts +14 -13
  18. package/src/criteria.ts +102 -52
  19. package/src/failing-base.ts +7 -7
  20. package/src/failure-message.ts +72 -0
  21. package/src/guards.ts +21 -6
  22. package/src/handoff.ts +2 -2
  23. package/src/init.ts +8 -8
  24. package/src/landing.ts +1 -1
  25. package/src/lifecycle.ts +2 -2
  26. package/src/lock.ts +10 -2
  27. package/src/note-schema.ts +14 -11
  28. package/src/notes.ts +19 -7
  29. package/src/operator-skill.ts +2 -2
  30. package/src/orchestrator.ts +758 -275
  31. package/src/outside-fault.ts +103 -0
  32. package/src/ports/agent-runner.ts +1 -1
  33. package/src/ports/tracker.ts +29 -15
  34. package/src/ports/workspace.ts +52 -24
  35. package/src/progress.ts +42 -7
  36. package/src/prompts.ts +242 -34
  37. package/src/readiness.ts +11 -11
  38. package/src/remove.ts +7 -7
  39. package/src/resume.ts +28 -20
  40. package/src/run-log.ts +5 -5
  41. package/src/run.ts +55 -13
  42. package/src/staleness.ts +14 -14
  43. package/src/start.ts +29 -16
  44. package/src/stranded.ts +19 -19
  45. package/src/templates.ts +398 -149
  46. package/src/title.ts +106 -8
  47. package/src/transcript-home.ts +49 -0
  48. package/src/verdict.ts +132 -27
  49. package/src/version-number.ts +13 -13
  50. package/src/version-pr.ts +12 -12
@@ -13,12 +13,14 @@ import type {
13
13
  PullRequestRef,
14
14
  SquashCommit,
15
15
  Tracker,
16
+ Visibility,
16
17
  } from "../ports/tracker.js";
17
18
  import { DEFAULT_CI_GRACE_MINUTES } from "../config.js";
18
19
  import { type HostKind, hostKind } from "../host.js";
19
20
  import { MAX_TAIL_LINES, logTail } from "../log-tail.js";
20
21
  import { highestVersion } from "../version-number.js";
21
- import { type Execution, type RunProcess, exec, throwOnFailure } from "./exec.js";
22
+ import { OutsideFault, firstLine, isGitHubFault } from "../outside-fault.js";
23
+ import { type Execution, type RunProcess, exec, shownCommand, throwOnFailure } from "./exec.js";
22
24
 
23
25
  export interface GhTrackerOptions {
24
26
  run?: RunProcess;
@@ -38,6 +40,44 @@ export interface GhTrackerOptions {
38
40
  host?: HostKind;
39
41
  }
40
42
 
43
+ /**
44
+ * How long each try again of a `gh` call GitHub failed on its own side waits,
45
+ * in turn: doubling, and about a minute in all. A gateway down for seconds
46
+ * costs seconds, and one still down after the last is a fault of GitHub's,
47
+ * which the caller is told as an {@link OutsideFault}.
48
+ */
49
+ export const GITHUB_RETRY_DELAYS_MS: readonly number[] = [2_000, 4_000, 8_000, 16_000, 30_000];
50
+
51
+ /** What a call's stdout has to parse as: one JSON document, or one per line as `--jq` prints them. */
52
+ type Json = "document" | "lines";
53
+
54
+ /** How one `gh` call is run, and what of its failure the caller takes as an answer. */
55
+ interface GhOptions {
56
+ /** A failure comes back rather than throwing, once GitHub's own faults have had their tries. */
57
+ allowFailure?: boolean;
58
+ /** The one failure a caller takes as an answer: it comes back instead of throwing. */
59
+ tolerate?: RegExp;
60
+ /** What stdout must parse as. A response that does not is GitHub's fault, and tried again. */
61
+ json?: Json;
62
+ /**
63
+ * Tried once whatever fails: a write that creates something, which a second
64
+ * try after a failure that had in fact landed would create twice.
65
+ */
66
+ once?: boolean;
67
+ /**
68
+ * Whether what the call does has already happened, as a pull request a 502
69
+ * opened all the same has. Yes ends the tries, and the call answers with the
70
+ * failure it last met.
71
+ *
72
+ * Asked after each wait, before trying again, as a glance: once, and a
73
+ * failure to answer is a no. Asked again when GitHub refuses the call, since
74
+ * a refusal can be GitHub declining to do twice what an earlier try did while
75
+ * the glance between them failed. That ask is `patient`: tried again like any
76
+ * read, and a fault of GitHub's that outlasts the tries is thrown.
77
+ */
78
+ landed?: (patient: boolean) => Promise<boolean>;
79
+ }
80
+
41
81
  /**
42
82
  * One issue as the REST API reports it, in the fields the pipeline reads. The
43
83
  * issue list, the dependency list and a single issue all answer in this shape.
@@ -68,7 +108,7 @@ interface Blocker {
68
108
  open: boolean;
69
109
  }
70
110
 
71
- /** One entry of the REST release list, in the three fields a Version needs. */
111
+ /** One entry of the REST release list, in the three fields a version needs. */
72
112
  interface RawRelease {
73
113
  tag_name: string;
74
114
  draft: boolean;
@@ -82,6 +122,8 @@ interface RawPullRequest {
82
122
  /** The GraphQL id, which a workstation's draft and ready mutations take. */
83
123
  node_id: string;
84
124
  draft: boolean;
125
+ /** Whether it has merged, which a merge GitHub failed to answer may have. */
126
+ merged?: boolean;
85
127
  head: { sha: string };
86
128
  /**
87
129
  * Whether GitHub can merge the pull request into its base: `false` when the
@@ -234,14 +276,34 @@ export class GhTracker implements Tracker {
234
276
  }
235
277
 
236
278
  /**
237
- * The tag of the highest Version published on `repository` as a Release.
279
+ * Whether the Target is public, read through REST like {@link repository}.
280
+ * Every failure, and a visibility GitHub may add later, is no answer, which
281
+ * the caller counts as public.
282
+ */
283
+ async visibility(): Promise<Visibility | undefined> {
284
+ try {
285
+ const { exitCode, stdout } = await this.gh(
286
+ ["api", "repos/{owner}/{repo}", "--jq", ".visibility"],
287
+ { allowFailure: true },
288
+ );
289
+ if (exitCode !== 0) return undefined;
290
+ const said = stdout.trim();
291
+ if (said === "public") return "public";
292
+ return said === "private" || said === "internal" ? "private" : undefined;
293
+ } catch {
294
+ return undefined;
295
+ }
296
+ }
297
+
298
+ /**
299
+ * The tag of the highest version published on `repository` as a Release.
238
300
  *
239
301
  * Every failure is the same answer — no answer — because nothing the caller
240
302
  * does with it may stop a Run: a rate limit, a repository nobody can see, a
241
303
  * `gh` that is not installed. The list is asked for rather than GitHub's own
242
304
  * `latest`, which is the newest by date: a patch cut on an old branch after a
243
- * minor would otherwise be reported as the Version to upgrade to. A hundred
244
- * of them is every Version this tool is likely to have, and they arrive
305
+ * minor would otherwise be reported as the version to upgrade to. A hundred
306
+ * of them is every version this tool is likely to have, and they arrive
245
307
  * newest first, so the highest is among them wherever the count lands: one
246
308
  * page, never every page.
247
309
  */
@@ -249,7 +311,7 @@ export class GhTracker implements Tracker {
249
311
  try {
250
312
  const { exitCode, stdout } = await this.gh(
251
313
  ["api", "--method", "GET", `repos/${repository}/releases`, "-F", "per_page=100"],
252
- { allowFailure: true },
314
+ { allowFailure: true, json: "document" },
253
315
  );
254
316
  if (exitCode !== 0) return undefined;
255
317
  const releases = JSON.parse(stdout) as RawRelease[];
@@ -327,7 +389,9 @@ export class GhTracker implements Tracker {
327
389
  * its blockers, only a count of each.
328
390
  */
329
391
  async getIssue(number: number): Promise<Issue> {
330
- const { stdout } = await this.gh(["api", `repos/{owner}/{repo}/issues/${number}`]);
392
+ const { stdout } = await this.gh(["api", `repos/{owner}/{repo}/issues/${number}`], {
393
+ json: "document",
394
+ });
331
395
  const raw = JSON.parse(stdout) as RawIssue;
332
396
  const comments = await this.list<RawComment>(`repos/{owner}/{repo}/issues/${number}/comments`);
333
397
  const blockers = await this.blockers(number);
@@ -365,11 +429,18 @@ export class GhTracker implements Tracker {
365
429
  * issue, so a missing label is `init`'s to catch, not this call's.
366
430
  */
367
431
  async createIssue(issue: CreateIssue): Promise<IssueRef> {
368
- const { stdout } = await this.rest("POST", "repos/{owner}/{repo}/issues", [
369
- `title=${issue.title}`,
370
- `body=${issue.body}`,
371
- ...issue.labels.map((label) => `labels[]=${label}`),
372
- ]);
432
+ // Once: a 502 can follow an issue GitHub did open, and a second try would
433
+ // open a second.
434
+ const { stdout } = await this.rest(
435
+ "POST",
436
+ "repos/{owner}/{repo}/issues",
437
+ [
438
+ `title=${issue.title}`,
439
+ `body=${issue.body}`,
440
+ ...issue.labels.map((label) => `labels[]=${label}`),
441
+ ],
442
+ { once: true, json: "document" },
443
+ );
373
444
  const created = JSON.parse(stdout) as Partial<RawIssue>;
374
445
  if (typeof created.number !== "number" || typeof created.html_url !== "string") {
375
446
  throw new Error(`could not read an issue number from gh output: ${stdout}`);
@@ -411,7 +482,7 @@ export class GhTracker implements Tracker {
411
482
  * Assign `user`, and refuse an assignment GitHub did not make.
412
483
  *
413
484
  * REST answers a user it cannot assign with the issue as it was and a
414
- * success, where `gh issue edit --add-assignee` failed. A Claim nobody can
485
+ * success, where `gh issue edit --add-assignee` failed. A claim nobody can
415
486
  * see is worse than one that fails, so the answer is read back.
416
487
  */
417
488
  async assign(number: number, user: string): Promise<void> {
@@ -419,6 +490,7 @@ export class GhTracker implements Tracker {
419
490
  "POST",
420
491
  `repos/{owner}/{repo}/issues/${number}/assignees`,
421
492
  [`assignees[]=${user}`],
493
+ { json: "document" },
422
494
  );
423
495
  const assignees = (JSON.parse(stdout) as Partial<RawIssue>).assignees ?? [];
424
496
  if (!assignees.some((assignee) => assignee.login.toLowerCase() === user.toLowerCase())) {
@@ -450,11 +522,18 @@ export class GhTracker implements Tracker {
450
522
  await this.rest("DELETE", path, [], { tolerate: /Label does not exist/ });
451
523
  }
452
524
 
453
- /** REST answers with the new comment, whose id is what it is edited by later. */
525
+ /**
526
+ * REST answers with the new comment, whose id is what it is edited by later.
527
+ * Posted once, as an issue is opened once: a second try after a 502 that had
528
+ * posted it would post it twice, and notify twice.
529
+ */
454
530
  async comment(number: number, body: string): Promise<IssueComment> {
455
- const { stdout } = await this.rest("POST", `repos/{owner}/{repo}/issues/${number}/comments`, [
456
- `body=${body}`,
457
- ]);
531
+ const { stdout } = await this.rest(
532
+ "POST",
533
+ `repos/{owner}/{repo}/issues/${number}/comments`,
534
+ [`body=${body}`],
535
+ { once: true, json: "document" },
536
+ );
458
537
  return { ...withCommentId(JSON.parse(stdout) as RawComment), body };
459
538
  }
460
539
 
@@ -470,14 +549,29 @@ export class GhTracker implements Tracker {
470
549
  /**
471
550
  * Open a pull request through REST, and read its number back out of the
472
551
  * answer rather than off anything printed.
552
+ *
553
+ * Tried again after a fault of GitHub's like any write, but only once no
554
+ * pull request is open on the branch: one the failed try opened all the
555
+ * same is the answer. A try GitHub refuses, as it refuses a second pull
556
+ * request on one branch, is asked about the same way, so one opened while
557
+ * the lookup between tries failed is still the answer.
473
558
  */
474
559
  async createPullRequest(pr: CreatePullRequest): Promise<PullRequestRef> {
560
+ let opened: PullRequestRef | undefined;
475
561
  const { stdout } = await this.rest(
476
562
  "POST",
477
563
  "repos/{owner}/{repo}/pulls",
478
564
  [`base=${pr.base}`, `head=${pr.head}`, `title=${pr.title}`, `body=${pr.body}`],
479
- { typed: [`draft=${pr.draft}`] },
565
+ {
566
+ typed: [`draft=${pr.draft}`],
567
+ json: "document",
568
+ landed: async (patient) => {
569
+ opened = await this.openPullRequestOn(pr.head, patient);
570
+ return opened !== undefined;
571
+ },
572
+ },
480
573
  );
574
+ if (opened !== undefined) return opened;
481
575
  const created = JSON.parse(stdout) as Partial<RawPullRequest>;
482
576
  if (typeof created.number !== "number" || typeof created.html_url !== "string") {
483
577
  throw new Error(`could not read a pull request number from gh output: ${stdout}`);
@@ -493,6 +587,29 @@ export class GhTracker implements Tracker {
493
587
  return pulls.map((pull) => ({ number: pull.number, head: pull.head.ref }));
494
588
  }
495
589
 
590
+ /**
591
+ * The open pull request from `head`, or nothing where there is none.
592
+ *
593
+ * Between the tries of a create it is asked once, and GitHub not saying is
594
+ * nothing too: the next try then asks GitHub to open one, as it would have
595
+ * anyway. After a refusal it is asked `patient`ly, and a GitHub that still
596
+ * will not say is a fault of GitHub's, thrown as any read's is.
597
+ */
598
+ private async openPullRequestOn(head: string, patient: boolean): Promise<PullRequestRef | undefined> {
599
+ try {
600
+ const pulls = await this.list<{ number: number; html_url: string; head: { ref: string } }>(
601
+ "repos/{owner}/{repo}/pulls",
602
+ ["-f", "state=open"],
603
+ patient ? {} : { once: true },
604
+ );
605
+ const pull = pulls.find((candidate) => candidate.head.ref === head);
606
+ return pull === undefined ? undefined : { number: pull.number, url: pull.html_url };
607
+ } catch (error) {
608
+ if (patient) throw error;
609
+ return undefined;
610
+ }
611
+ }
612
+
496
613
  async convertPullRequestToDraft(number: number): Promise<void> {
497
614
  await this.setDraft(number, true);
498
615
  }
@@ -517,17 +634,17 @@ export class GhTracker implements Tracker {
517
634
  }
518
635
 
519
636
  /**
520
- * Poll the PR's CI until it settles or the timeout runs out. A PR with no
521
- * checks is reported as such, never as a pass.
637
+ * Poll the pull request's CI until it settles or the timeout runs out. A
638
+ * pull request with no checks is reported as such, never as a pass.
522
639
  *
523
640
  * The checks are the head commit's check runs and commit statuses, which is
524
641
  * everything `gh pr checks` read through GraphQL.
525
642
  *
526
- * Right after a PR opens, GitHub answers "no checks" for a while before the
527
- * workflow's check run exists, so "no checks" only counts once the grace
528
- * period has passed. A PR GitHub finds conflicting with its base is the
529
- * exception: GitHub runs no `pull_request` workflow for it, so no check is
530
- * coming and the wait ends as soon as the conflict is seen.
643
+ * Right after a pull request opens, GitHub answers "no checks" for a while
644
+ * before the workflow's check run exists, so "no checks" only counts once the
645
+ * grace period has passed. A pull request GitHub finds conflicting with its
646
+ * base is the exception: GitHub runs no `pull_request` workflow for it, so no
647
+ * check is coming and the wait ends as soon as the conflict is seen.
531
648
  */
532
649
  async waitForCi(number: number, timeoutMs: number): Promise<CiOutcome> {
533
650
  const startedAt = this.now();
@@ -573,9 +690,9 @@ export class GhTracker implements Tracker {
573
690
  * A check that is not an Actions job has no log to fetch and yields nothing.
574
691
  *
575
692
  * The cap counts the jobs a log could be fetched for, not the red checks: a
576
- * PR whose external checks went red alongside one Actions job still gets the
577
- * one log there is. What it keeps out of a prompt is a whole matrix failing
578
- * a leg at a time, each leg with the same log.
693
+ * pull request whose external checks went red alongside one Actions job
694
+ * still gets the one log there is. What it keeps out of a prompt is a whole
695
+ * matrix failing a leg at a time, each leg with the same log.
579
696
  */
580
697
  private async failedJobLogs(failed: CiCheck[]): Promise<string> {
581
698
  const jobs = failed.flatMap((check) => {
@@ -621,18 +738,36 @@ export class GhTracker implements Tracker {
621
738
  /**
622
739
  * Squash-merge through REST, with the subject and body the pipeline composed
623
740
  * as the commit's title and message.
741
+ *
742
+ * Tried again after a fault of GitHub's, but only while the pull request has
743
+ * not merged: a merge the failed try made is done. A try GitHub refuses, as
744
+ * it refuses to merge a pull request already merged, is asked about the same
745
+ * way, so a merge made while the lookup between tries failed is still done.
624
746
  */
625
747
  async squashMerge(number: number, commit: SquashCommit): Promise<void> {
626
- await this.rest("PUT", `repos/{owner}/{repo}/pulls/${number}/merge`, [
627
- "merge_method=squash",
628
- `commit_title=${commit.subject}`,
629
- `commit_message=${commit.body}`,
630
- ]);
748
+ await this.rest(
749
+ "PUT",
750
+ `repos/{owner}/{repo}/pulls/${number}/merge`,
751
+ ["merge_method=squash", `commit_title=${commit.subject}`, `commit_message=${commit.body}`],
752
+ {
753
+ landed: async (patient) => {
754
+ try {
755
+ return (await this.pullRequest(number, patient ? {} : { once: true })).merged === true;
756
+ } catch (error) {
757
+ if (patient) throw error;
758
+ return false;
759
+ }
760
+ },
761
+ },
762
+ );
631
763
  }
632
764
 
633
765
  /** One pull request, read through REST. */
634
- private async pullRequest(number: number): Promise<RawPullRequest> {
635
- const { stdout } = await this.gh(["api", `repos/{owner}/{repo}/pulls/${number}`]);
766
+ private async pullRequest(number: number, options: GhOptions = {}): Promise<RawPullRequest> {
767
+ const { stdout } = await this.gh(["api", `repos/{owner}/{repo}/pulls/${number}`], {
768
+ ...options,
769
+ json: "document",
770
+ });
636
771
  return JSON.parse(stdout) as RawPullRequest;
637
772
  }
638
773
 
@@ -677,10 +812,14 @@ export class GhTracker implements Tracker {
677
812
  * counts as its re-run, as `gh pr checks` counted it.
678
813
  */
679
814
  private async ciSnapshot(number: number): Promise<CiSnapshot> {
680
- const pr = await this.gh(["api", `repos/{owner}/{repo}/pulls/${number}`], {
681
- allowFailure: true,
682
- });
683
- if (pr.exitCode !== 0) return { checks: undefined, conflicting: false };
815
+ const args = ["api", `repos/{owner}/{repo}/pulls/${number}`];
816
+ const pr = await this.gh(args, { allowFailure: true, json: "document" });
817
+ if (pr.exitCode !== 0) {
818
+ // GitHub failing on its own side after every try is no reading at all,
819
+ // where any other refusal reads as no checks, as it always has.
820
+ if (isGitHubFault(pr.output)) throwOnFailure("gh", args, pr);
821
+ return { checks: undefined, conflicting: false };
822
+ }
684
823
  const { head, mergeable } = JSON.parse(pr.stdout) as RawPullRequest;
685
824
  // `null` is GitHub still working it out, which is no conflict yet.
686
825
  const conflicting = mergeable === false;
@@ -709,10 +848,12 @@ export class GhTracker implements Tracker {
709
848
  * joins arrays, not the objects around them.
710
849
  */
711
850
  private async wrappedList(path: string, key: string): Promise<unknown[] | undefined> {
712
- const result = await this.gh([...pagedGet(path), "--jq", `.${key}[]`], {
713
- allowFailure: true,
714
- });
715
- if (result.exitCode !== 0) return undefined;
851
+ const args = [...pagedGet(path), "--jq", `.${key}[]`];
852
+ const result = await this.gh(args, { allowFailure: true, json: "lines" });
853
+ if (result.exitCode !== 0) {
854
+ if (isGitHubFault(result.output)) throwOnFailure("gh", args, result);
855
+ return undefined;
856
+ }
716
857
  try {
717
858
  return result.stdout
718
859
  .split("\n")
@@ -755,39 +896,114 @@ export class GhTracker implements Tracker {
755
896
  method: "POST" | "PATCH" | "PUT" | "DELETE",
756
897
  path: string,
757
898
  fields: string[],
758
- options: { allowFailure?: boolean; typed?: string[]; tolerate?: RegExp } = {},
899
+ options: GhOptions & { typed?: string[] } = {},
759
900
  ): Promise<Execution> {
901
+ const { typed = [], ...rest } = options;
760
902
  const args = [
761
903
  "api",
762
904
  "--method",
763
905
  method,
764
906
  path,
765
907
  ...fields.flatMap((field) => ["-f", field]),
766
- ...(options.typed ?? []).flatMap((field) => ["-F", field]),
908
+ ...typed.flatMap((field) => ["-F", field]),
767
909
  ];
768
- const result = await this.gh(args, { allowFailure: true });
769
- if (options.allowFailure || options.tolerate?.test(result.output)) return result;
770
- return throwOnFailure("gh", args, result);
910
+ return await this.gh(args, rest);
771
911
  }
772
912
 
773
913
  /**
774
914
  * Every page of a REST list, as one array: `gh --paginate` joins the pages.
775
915
  * `--method GET` is spelled out because fields would otherwise make it a POST.
776
916
  */
777
- private async list<T>(path: string, fields: string[] = []): Promise<T[]> {
778
- const { stdout } = await this.gh([...pagedGet(path), ...fields]);
917
+ private async list<T>(path: string, fields: string[] = [], options: GhOptions = {}): Promise<T[]> {
918
+ const { stdout } = await this.gh([...pagedGet(path), ...fields], { ...options, json: "document" });
779
919
  return JSON.parse(stdout) as T[];
780
920
  }
781
921
 
782
- private async gh(
783
- args: string[],
784
- options: { allowFailure?: boolean } = {},
785
- ): Promise<Execution> {
786
- const result = await this.runProcess("gh", args, {
787
- ...(this.cwd === undefined ? {} : { cwd: this.cwd }),
788
- });
789
- return options.allowFailure ? result : throwOnFailure("gh", args, result);
922
+ /**
923
+ * One `gh` call, tried again while GitHub fails on its own side.
924
+ *
925
+ * A 5xx, or an answer that is not the complete JSON the caller reads, is
926
+ * GitHub's: the call waits and tries again, {@link GITHUB_RETRY_DELAYS_MS}
927
+ * apart, and one that still fails after the last is an {@link OutsideFault}
928
+ * — or, for a caller that takes failures as answers, the failure it met.
929
+ * Every other failure is the caller's at once, as it always was, unless the
930
+ * call can tell it has landed: a refusal that follows a try GitHub failed may
931
+ * be GitHub declining to do again what that try did after all.
932
+ */
933
+ private async gh(args: string[], options: GhOptions = {}): Promise<Execution> {
934
+ for (let tried = 0; ; tried++) {
935
+ const result = await this.runProcess("gh", args, {
936
+ ...(this.cwd === undefined ? {} : { cwd: this.cwd }),
937
+ });
938
+ const fault = githubFaultIn(result, options);
939
+ const delay = options.once === true ? undefined : GITHUB_RETRY_DELAYS_MS[tried];
940
+ if (fault === undefined || delay === undefined) {
941
+ if (tried > 0 && refused(result, fault, options) && (await options.landed?.(true))) {
942
+ return result;
943
+ }
944
+ return finalAnswer(args, result, fault, options);
945
+ }
946
+ await this.sleep(delay);
947
+ if (await options.landed?.(false)) return result;
948
+ }
949
+ }
950
+ }
951
+
952
+ /**
953
+ * The fault of GitHub's a call met, in the one line the Run's last line quotes,
954
+ * or nothing where it met none: a 5xx or an unreadable answer `gh` reported,
955
+ * or an answer that is not the JSON the caller asked for. A failure the caller
956
+ * tolerates is its answer, whatever it says.
957
+ */
958
+ function githubFaultIn(result: Execution, options: GhOptions): string | undefined {
959
+ if (result.exitCode !== 0) {
960
+ if (options.tolerate?.test(result.output)) return undefined;
961
+ return isGitHubFault(result.output) ? firstLine(result.output) : undefined;
962
+ }
963
+ return options.json === undefined ? undefined : incompleteJson(result.stdout, options.json);
964
+ }
965
+
966
+ /**
967
+ * Whether GitHub turned the call down, as a 4xx: a failure that is no fault of
968
+ * GitHub's and that the caller does not take as an answer.
969
+ */
970
+ function refused(result: Execution, fault: string | undefined, options: GhOptions): boolean {
971
+ if (result.exitCode === 0 || fault !== undefined || options.allowFailure) return false;
972
+ return options.tolerate?.test(result.output) !== true;
973
+ }
974
+
975
+ /** Why `stdout` is not the JSON a caller reads, or nothing when it is. */
976
+ function incompleteJson(stdout: string, json: Json): string | undefined {
977
+ try {
978
+ if (json === "document") JSON.parse(stdout);
979
+ else for (const line of stdout.split("\n")) if (line.trim() !== "") JSON.parse(line);
980
+ return undefined;
981
+ } catch (error) {
982
+ return (error as Error).message;
983
+ }
984
+ }
985
+
986
+ /** A call's last answer, as its caller takes it: the result, or the error it is. */
987
+ function finalAnswer(
988
+ args: string[],
989
+ result: Execution,
990
+ fault: string | undefined,
991
+ options: GhOptions,
992
+ ): Execution {
993
+ if (result.exitCode !== 0) {
994
+ if (options.allowFailure || options.tolerate?.test(result.output)) return result;
995
+ return throwOnFailure("gh", args, result);
996
+ }
997
+ if (fault !== undefined) {
998
+ const shown = shownCommand("gh", args);
999
+ throw new OutsideFault(
1000
+ "github",
1001
+ shown,
1002
+ fault,
1003
+ `\`${shown}\` answered with a response that is not complete JSON\n${fault}`,
1004
+ );
790
1005
  }
1006
+ return result;
791
1007
  }
792
1008
 
793
1009
  /**
@@ -845,8 +1061,8 @@ function subIssues(issue: RawIssue): number {
845
1061
  * `pending` means "ask again"; everything else is an answer. Checks GitHub
846
1062
  * would not report read as none, as a failing `gh pr checks` did, so the grace
847
1063
  * period still covers a wait that starts before the checks exist. No checks on
848
- * a PR GitHub finds conflicting is the conflict, since that is why there are
849
- * none; checks it does have are read as they are.
1064
+ * a pull request GitHub finds conflicting is the conflict, since that is why
1065
+ * there are none; checks it does have are read as they are.
850
1066
  */
851
1067
  function readCi({ checks, conflicting }: CiSnapshot): CiReading | "pending" {
852
1068
  if (checks === undefined || checks.length === 0) {
@@ -1,6 +1,6 @@
1
1
  import { existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
- import { basename, dirname, join, resolve } from "node:path";
3
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
4
  import { type Host, currentHost, sameHost } from "../host.js";
5
5
  import {
6
6
  LOCK_BRANCH,
@@ -36,7 +36,7 @@ import {
36
36
  stateFileName,
37
37
  stateFileTicket,
38
38
  } from "../resume.js";
39
- import { transcriptFiles } from "../run-log.js";
39
+ import { stageLogDir, transcriptFiles } from "../run-log.js";
40
40
  import { exec, execOrThrow, throwOnFailure } from "./exec.js";
41
41
 
42
42
  /**
@@ -106,9 +106,9 @@ interface TreeEntry {
106
106
  *
107
107
  * Commands that run in the main checkout go one at a time, because the Tickets
108
108
  * of a Run do not: adding and removing worktrees, deleting branches and moving
109
- * the Base branch all take git refs and index locks that git fails on rather
109
+ * the base branch all take git refs and index locks that git fails on rather
110
110
  * than waits for, and a read of a commit range taken while another Ticket is
111
- * moving the Base branch is a range nobody asked for. Commands inside a
111
+ * moving the base branch is a range nobody asked for. Commands inside a
112
112
  * worktree are left parallel — that is where a Run spends its time, and no two
113
113
  * Tickets share one.
114
114
  *
@@ -118,7 +118,7 @@ interface TreeEntry {
118
118
  * runs, which is what this gives; a pair that had to be indivisible would have
119
119
  * to say so, and none of them is.
120
120
  *
121
- * The State lives on the Target's remote, on {@link STATE_BRANCH}, so a Run on
121
+ * The state lives on the Target's remote, on {@link STATE_BRANCH}, so a Run on
122
122
  * any Host resumes a Ticket another left (ADR-0004). The branch is one snapshot
123
123
  * commit, rewritten whole and force-pushed with a lease on the tip it was built
124
124
  * from, and built from objects and a scratch index alone: the main checkout's
@@ -597,6 +597,13 @@ export class GitWorkspace implements Workspace {
597
597
  throwOnFailure("git", args, result);
598
598
  }
599
599
 
600
+ async unshallow(): Promise<boolean> {
601
+ const { stdout } = await this.git(["rev-parse", "--is-shallow-repository"]);
602
+ if (stdout.trim() !== "true") return false;
603
+ await this.git(["fetch", "--unshallow", this.remote]);
604
+ return true;
605
+ }
606
+
600
607
  async pullBase(base: string): Promise<void> {
601
608
  const { stdout } = await this.git(["rev-parse", "--abbrev-ref", "HEAD"]);
602
609
  if (stdout.trim() === base) {
@@ -641,21 +648,24 @@ export class GitWorkspace implements Workspace {
641
648
  });
642
649
  }
643
650
 
651
+ // These messages name the Ticket as `ticket <n>`, never `#<n>`: GitHub links
652
+ // a pushed commit that mentions `#<n>` to issue `<n>`, on whatever branch the
653
+ // commit is, so every write would leave a line on the Ticket's timeline.
644
654
  async writeState(state: TicketState): Promise<void> {
645
- await this.changeState(`Record #${state.ticket} at ${state.state}`, [
655
+ await this.changeState(`Record ticket ${state.ticket} at ${state.state}`, [
646
656
  { name: stateFileName(state.ticket), contents: stateFileContents(state) },
647
657
  ]);
648
658
  }
649
659
 
650
660
  async removeState(ticket: number): Promise<void> {
651
- await this.changeState(`Forget #${ticket}`, [
661
+ await this.changeState(`Forget ticket ${ticket}`, [
652
662
  { remove: stateFileName(ticket) },
653
663
  { remove: transcriptsDir(ticket) },
654
664
  ]);
655
665
  }
656
666
 
657
667
  /**
658
- * Each file goes up under `ticket-<n>/<runId>/`, beside the Ticket's State
668
+ * Each file goes up under `ticket-<n>/<runId>/`, beside the Ticket's state
659
669
  * file, as the Run's own directory lays it out; a Ticket handed off by more
660
670
  * than one Run keeps each Run's apart, and {@link removeState} takes them
661
671
  * all.
@@ -665,13 +675,20 @@ export class GitWorkspace implements Workspace {
665
675
  if (files.length === 0) return undefined;
666
676
 
667
677
  const directory = `${transcriptsDir(ticket)}/${runId}/`;
678
+ // `ticket <n>`, not `#<n>`, for the reason given above writeState.
668
679
  await this.changeState(
669
- `Keep #${ticket}'s transcripts from ${runId}`,
680
+ `Keep ticket ${ticket}'s transcripts from ${runId}`,
670
681
  files.map((file) => ({ name: `${directory}${file.name}`, from: file.path })),
671
682
  );
672
683
  return { branch: STATE_BRANCH, path: directory };
673
684
  }
674
685
 
686
+ async transcriptsOnHost(ticket: number, runId: string): Promise<string | undefined> {
687
+ if (transcriptFiles(this.repoRoot, runId, ticket).length === 0) return undefined;
688
+ const directory = relative(this.repoRoot, stageLogDir(this.repoRoot, runId, ticket));
689
+ return `${directory.split(sep).join("/")}/`;
690
+ }
691
+
675
692
  /**
676
693
  * Rewrite the state branch as one new snapshot commit, the same as the tip
677
694
  * but for `edits`, and push it over the tip it was built from. Edits that
@@ -952,7 +969,7 @@ function branchNames(refs: string[], prefix: string): string[] {
952
969
 
953
970
  /**
954
971
  * The directory of the state branch a handed-off Ticket's transcripts are kept
955
- * in, named like its State file without the extension, so the two sort together.
972
+ * in, named like its state file without the extension, so the two sort together.
956
973
  */
957
974
  function transcriptsDir(ticket: number): string {
958
975
  return `ticket-${ticket}`;