ticket-runner 0.6.5 → 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.
@@ -1,3 +1,5 @@
1
+ import { relative } from "node:path";
2
+ import { type ListedCriterion, listCriteria } from "./acceptance-criteria.js";
1
3
  import { branchName, worktreePath } from "./branch.js";
2
4
  import type { Config } from "./config.js";
3
5
  import {
@@ -9,9 +11,8 @@ import {
9
11
  } from "./credential.js";
10
12
  import { tickMetCriteria } from "./criteria.js";
11
13
  import type { BaseBranchChecks, FailingBase } from "./failing-base.js";
12
- import { type SkipReason, isGuardReason, skipReason } from "./guards.js";
14
+ import { type SkipReason, isGuardReason, skipReason, tickedBoxes } from "./guards.js";
13
15
  import { markHandoffsTaken } from "./handoff.js";
14
- import type { HostKind } from "./host.js";
15
16
  import type { Landing, LandingTurn } from "./landing.js";
16
17
  import type { FailureKind, FailurePoint } from "./lifecycle.js";
17
18
  import {
@@ -19,6 +20,8 @@ import {
19
20
  type RoutedNote,
20
21
  type StandingNotes,
21
22
  type StandingNotesLookup,
23
+ type WrittenNote,
24
+ parseNotes,
22
25
  routeNotes,
23
26
  } from "./notes.js";
24
27
  import type {
@@ -29,7 +32,6 @@ import type {
29
32
  } from "./ports/agent-runner.js";
30
33
  import type { Issue, Tracker } from "./ports/tracker.js";
31
34
  import type {
32
- KeptTranscripts,
33
35
  ReachedState,
34
36
  RebaseOutcome,
35
37
  TicketState,
@@ -45,6 +47,7 @@ import {
45
47
  verifyPrompt,
46
48
  } from "./prompts.js";
47
49
  import { retryLogDir, stageLogDir } from "./run-log.js";
50
+ import { type FaultSide, OutsideFault } from "./outside-fault.js";
48
51
  import { holdsClaim } from "./stranded.js";
49
52
  import {
50
53
  type BranchFailure,
@@ -56,20 +59,33 @@ import {
56
59
  guardComment,
57
60
  handoffComment,
58
61
  hasGuardWarning,
62
+ LEFT_TO_HUMAN,
63
+ mergeByHandComment,
59
64
  pullRequestBody,
60
65
  squashCommit,
66
+ type TranscriptsPlace,
61
67
  } from "./templates.js";
62
68
  import type { StartTimer } from "./timer.js";
69
+ import type { TranscriptHome } from "./transcript-home.js";
63
70
  import {
71
+ BRANCH_PROSE_FIELDS,
72
+ type BranchProse,
64
73
  CODE_STAGE_JSON_SCHEMA,
74
+ parseBranchProse,
65
75
  parseNoCommitReason,
66
76
  parseTitle,
67
77
  pullRequestTitle,
68
78
  } from "./title.js";
69
79
  import {
80
+ type AnsweredVerdict,
81
+ type Defect,
82
+ type GradedCriterion,
83
+ type Misnumbered,
70
84
  type Verdict,
71
85
  VERDICT_JSON_SCHEMA,
72
86
  countStatuses,
87
+ gradeVerdict,
88
+ isMisnumbered,
73
89
  parseVerdict,
74
90
  passes,
75
91
  unmetCriteria,
@@ -94,6 +110,13 @@ export type TicketOutcome =
94
110
  stage: FailurePoint;
95
111
  failure: string;
96
112
  pullRequest?: number;
113
+ /**
114
+ * The fault outside the Ticket that cut the hand-off short, where one
115
+ * did and left the Ticket no longer claimed: whose side it was on, the
116
+ * command, and the first line it printed. The Run claims no more after
117
+ * it, as after a Release over the same fault.
118
+ */
119
+ fault?: OutsideFaultSeen & { side: FaultSide };
97
120
  notes: RoutedNote[];
98
121
  }
99
122
  | {
@@ -112,6 +135,11 @@ export type TicketOutcome =
112
135
  limitResetsAt?: string;
113
136
  /** The Check the base branch fails, and where, for a Release over it. */
114
137
  failingBase?: { commit: string; command: string };
138
+ /**
139
+ * The command GitHub or the remote failed, and the first line it
140
+ * printed, for a Release over a fault outside the Ticket.
141
+ */
142
+ fault?: OutsideFaultSeen;
115
143
  notes: RoutedNote[];
116
144
  }
117
145
  | {
@@ -136,11 +164,6 @@ export interface Pipeline {
136
164
  * `package.json` or runs git, so every stamp of one Run is the same string.
137
165
  */
138
166
  version: string;
139
- /**
140
- * The Host the Run is on, which decides whether a merged pull request's body
141
- * can point at the Run's directory: a cloud Host's is gone with its session.
142
- */
143
- host: HostKind;
144
167
  /**
145
168
  * What every Stage of this Run is billed to, chosen once when it started:
146
169
  * the subscription, or the Host's API key for a Run started with `--api-key`.
@@ -183,6 +206,12 @@ export interface Pipeline {
183
206
  * there is a Stage told to exercise it through its tests and fakes.
184
207
  */
185
208
  selfHosted: boolean;
209
+ /**
210
+ * Where a handed-off Ticket's transcripts are kept, decided once before the
211
+ * Run started ({@link import("./transcript-home.js").resolveTranscriptHome}):
212
+ * on the Target's remote, or kept off it on this Host.
213
+ */
214
+ transcriptHome: TranscriptHome;
186
215
  /**
187
216
  * How the Run waits between its looks at the Frontier while a Lane is free
188
217
  * and another busy: the real clock, unless a test hands it one it moves
@@ -213,14 +242,33 @@ class TicketFailure extends Error {
213
242
  }
214
243
  }
215
244
 
245
+ /**
246
+ * A Ticket that passed every gate on a Target that merges by hand (`merge`
247
+ * off). Nothing failed: it ends in a hand-off only because a human merges here,
248
+ * so the hand-off leaves its pull request as published and keeps no
249
+ * transcripts, and its comment lists what the squash commit would have carried.
250
+ */
251
+ class LeftToHuman extends TicketFailure {
252
+ constructor(readonly verdict: Verdict) {
253
+ super("merge", LEFT_TO_HUMAN);
254
+ }
255
+ }
256
+
216
257
  /**
217
258
  * What stops a Ticket that says nothing about it: the rate limit, a transient
218
259
  * API failure — the API overloaded, broken or silent on its own side after the
219
260
  * CLI had already retried it — the API key of an `--api-key` Run out of credit
220
- * or past its workspace's spend limit, and a base branch that fails the Check
221
- * the Ticket's branch failed.
261
+ * or past its workspace's spend limit, a base branch that fails the Check the
262
+ * Ticket's branch failed, and GitHub or the git remote failing on its own side
263
+ * ({@link OutsideFault}).
222
264
  */
223
- export type ReleaseCause = StageReleaseCause | "failing-base";
265
+ export type ReleaseCause = StageReleaseCause | "failing-base" | FaultSide;
266
+
267
+ /** A fault outside the Ticket as a Release reports it: the command, and the first line it printed. */
268
+ export interface OutsideFaultSeen {
269
+ command: string;
270
+ line: string;
271
+ }
224
272
 
225
273
  /** The Stage failures among them. */
226
274
  type StageReleaseCause = Extract<StageFailure, "rate-limited" | "api-error" | "out-of-budget">;
@@ -251,11 +299,31 @@ class Releasing extends Error {
251
299
  readonly limitResetsAt?: string,
252
300
  /** The Check the base branch fails too, for a Release over it. */
253
301
  readonly failingBase?: InheritedFailure,
302
+ /** What GitHub or the remote failed, for a Release over a fault outside the Ticket. */
303
+ readonly fault?: OutsideFaultSeen,
254
304
  ) {
255
305
  super(`the ${point} Stage was stopped · ${RELEASE_WORDS[reason]}`);
256
306
  }
257
307
  }
258
308
 
309
+ /**
310
+ * The Release a fault outside the Ticket earns at `point`, with the row that
311
+ * says so: the Ticket is left at the state it had reached, as over a failing
312
+ * base branch, and nothing it did is charged for it.
313
+ */
314
+ async function faultRelease(
315
+ fault: OutsideFault,
316
+ point: FailurePoint,
317
+ record: ResumeRecord,
318
+ progress: Progress,
319
+ ): Promise<Releasing> {
320
+ await progress.record({ point, outcome: `⏸ ${RELEASE_WORDS[fault.side]}` });
321
+ return new Releasing(point, record.state, fault.side, undefined, undefined, {
322
+ command: fault.command,
323
+ line: fault.line,
324
+ });
325
+ }
326
+
259
327
  /**
260
328
  * A Check the base branch fails, and how the branch itself failed, which the
261
329
  * Note about it quotes beside the merge-base's output: only the command is
@@ -284,7 +352,8 @@ function asTicketFailure(error: unknown, point: FailurePoint): TicketFailure {
284
352
  * A Stage the subscription rate limit or a transient API failure stopped ends
285
353
  * none of that: the Ticket is released, and a Run started once the limit has
286
354
  * reset, or the API recovered, resumes it from the state it had reached rather
287
- * than from the top. A hand-off keeps that state too, so a
355
+ * than from the top. So is a Ticket GitHub or the git remote failed on its own
356
+ * side, wherever it was ({@link OutsideFault}). A hand-off keeps that state too, so a
288
357
  * human who relabels the Ticket `ready-for-agent` hands it back and the next Run
289
358
  * carries on from what it reached rather than paying for the implement Stage a
290
359
  * second time.
@@ -377,6 +446,7 @@ async function takeTicket(
377
446
  fixUsed: resume?.fixUsed ?? false,
378
447
  ...(resume?.pullRequest === undefined ? {} : { pullRequest: resume.pullRequest }),
379
448
  ...(resume?.title === undefined ? {} : { title: resume.title }),
449
+ ...(resume === undefined ? {} : recordedProse(resume)),
380
450
  ...(resume?.rebaseFirst === true ? { rebaseFirst: true } : {}),
381
451
  });
382
452
 
@@ -384,11 +454,8 @@ async function takeTicket(
384
454
  // before anything else can go wrong. A stranded Ticket is resumed in place,
385
455
  // wearing the claim it never gave up — re-writing what is already there would
386
456
  // only risk the Ticket on three tracker calls that change nothing.
387
- if (!stranded) {
388
- await tracker.assign(ticket, user);
389
- await tracker.addLabel(ticket, config.labels.inProgress);
390
- await tracker.removeLabel(ticket, config.labels.readyForAgent);
391
- }
457
+ //
458
+ if (!stranded) await writeClaim(pipeline, ticket, user);
392
459
  log(`#${ticket} ${howItWasTaken(resume, stranded)} · ${branch}`);
393
460
 
394
461
  // Whatever hand-off left this Ticket to a human is no longer the last word on
@@ -420,6 +487,12 @@ async function takeTicket(
420
487
  // the verify behind it is held to. Only this Run's: the state file keeps no
421
488
  // verdict, so a retry a later Run resumes is graded without them.
422
489
  let unmetBefore: string | undefined;
490
+ // The Notes this Ticket's code Stages write in this Run, which every verify
491
+ // behind them grades for a defect of the branch.
492
+ const written: WrittenNote[] = [];
493
+ // The criteria verify grades, numbered once from the Ticket as it was
494
+ // claimed, so a verify behind a fix answers the same numbers as the first.
495
+ const criteria = listCriteria([issue.body, ...issue.comments.map((comment) => comment.body)]);
423
496
 
424
497
  // Declared out here because ticking the Acceptance Criteria it proved happens
425
498
  // after the merge, where a failure may no longer hand the Ticket off.
@@ -459,7 +532,11 @@ async function takeTicket(
459
532
  checkedOutAt === undefined ? undefined : { path: checkedOutAt, pushable: false };
460
533
  throw new TicketFailure(
461
534
  "setup",
462
- describeBranchInTheWay(branch, checkedOutAt, config.labels.readyForAgent),
535
+ describeBranchInTheWay(
536
+ branch,
537
+ checkedOutAt === undefined ? undefined : inCheckout(repoRoot, checkedOutAt),
538
+ config.labels.readyForAgent,
539
+ ),
463
540
  );
464
541
  }
465
542
  await workspace.createWorktree({ path: worktree, branch }, baseBranch);
@@ -473,7 +550,7 @@ async function takeTicket(
473
550
  }
474
551
  if (resume === undefined || resume.state === "claimed") {
475
552
  point = "implement";
476
- await implement(pipeline, issue, worktree, branch, logDir, progress, notes, record);
553
+ await implement(pipeline, issue, worktree, branch, logDir, progress, { notes, written }, record);
477
554
  // The branch now carries work no later Run should pay for again.
478
555
  await record.advance({ state: "implemented" });
479
556
  }
@@ -502,7 +579,11 @@ async function takeTicket(
502
579
  await requireCommitted(pipeline, worktree, progress);
503
580
  await runChecks(pipeline, worktree, progress);
504
581
  point = "verify";
505
- verdict = await verify(pipeline, issue, worktree, logDir, progress, notes, unmetBefore);
582
+ verdict = await verify(pipeline, issue, worktree, logDir, progress, notes, {
583
+ criteria,
584
+ written,
585
+ unmetBefore,
586
+ });
506
587
 
507
588
  point = "rebase";
508
589
  // The Landing, from here until the base branch has been pulled: the
@@ -546,7 +627,7 @@ async function takeTicket(
546
627
  title = pullRequestTitle(record.title, commits, issue.title);
547
628
  pullRequest = await publishPullRequest(
548
629
  pipeline,
549
- { issue, branch, worktree, verdict, title },
630
+ { issue, branch, worktree, title, body: record.prose.body },
550
631
  pullRequest,
551
632
  );
552
633
  await record.advance({ pullRequest });
@@ -554,9 +635,10 @@ async function takeTicket(
554
635
  await requireGreenCi(pipeline, worktree, pullRequest, progress, landing);
555
636
  break;
556
637
  } catch (error) {
557
- // A rate limit or an API failure is nobody's defect, so the fix budget
558
- // does not answer for it: the Ticket is released, whole, further up.
559
- if (error instanceof Releasing) throw error;
638
+ // A rate limit, an API failure or a fault of GitHub's or the remote's
639
+ // is nobody's defect, so the fix budget does not answer for it: the
640
+ // Ticket is released, whole, further up.
641
+ if (error instanceof Releasing || error instanceof OutsideFault) throw error;
560
642
  const failure = asTicketFailure(error, point);
561
643
  if (fixUsed || failure.kind === undefined) throw failure;
562
644
  fixUsed = true;
@@ -575,7 +657,7 @@ async function takeTicket(
575
657
  logDir,
576
658
  { kind: failure.kind, summary: failure.summary, evidence: failure.evidence },
577
659
  progress,
578
- notes,
660
+ { notes, written },
579
661
  record,
580
662
  );
581
663
  // Recorded once the Stage has come back, not when the budget was
@@ -586,30 +668,52 @@ async function takeTicket(
586
668
  }
587
669
 
588
670
  point = "merge";
671
+ if (!config.merge) {
672
+ // A Target that merges by hand. The Ticket leaves the Landing below
673
+ // without the pull, since nothing was merged: the next Ticket rebases
674
+ // onto a base branch without this one, as a human may merge in any order.
675
+ await progress.record({ point: "merge", outcome: "👤 left to a human" });
676
+ throw new LeftToHuman(verdict);
677
+ }
589
678
  await tracker.squashMerge(
590
679
  pullRequest,
591
- squashCommit({ ticket, pullRequest, title, verdict, commits, coAuthors }),
680
+ squashCommit({
681
+ ticket,
682
+ pullRequest,
683
+ title,
684
+ ...record.prose,
685
+ verdict,
686
+ commits,
687
+ coAuthors,
688
+ }),
592
689
  );
593
690
  await progress.record({ point: "merge", outcome: `✅ #${pullRequest}` });
691
+ await progress.settle();
594
692
  } catch (error) {
595
693
  // Out of the Landing before either ending is written: a hand-off's draft
596
694
  // pull request and a Release's labels are nothing for the next Ticket to
597
695
  // wait behind, and a Ticket that never reached the rebase gives up nothing.
598
696
  landing.leave();
599
- if (error instanceof Releasing) {
697
+ const stopped =
698
+ error instanceof OutsideFault
699
+ ? await faultRelease(error, point, record, progress)
700
+ : error;
701
+ if (stopped instanceof Releasing) {
600
702
  return release(pipeline, {
601
703
  issue,
602
704
  user,
603
705
  branch,
604
- stopped: error,
706
+ stopped,
605
707
  record,
606
708
  // A fix Stage stopped before it ran spends nothing: the budget is
607
709
  // still there for the Run that resumes the Ticket.
608
- fixUsed: fixUsed && error.point !== "fix",
710
+ fixUsed: fixUsed && stopped.point !== "fix",
711
+ progress,
609
712
  notes,
610
713
  });
611
714
  }
612
- return handOff(pipeline, {
715
+ const failure = asTicketFailure(error, point);
716
+ return await handOff(pipeline, {
613
717
  issue,
614
718
  user,
615
719
  branch,
@@ -618,9 +722,10 @@ async function takeTicket(
618
722
  // and whichever side a human keeps is one a later Run resumes from.
619
723
  keepsState: found?.refusal !== undefined || worktreeOnDisk?.pushable === true,
620
724
  pullRequest,
621
- failure: asTicketFailure(error, point),
725
+ failure,
622
726
  fixUsed,
623
727
  record,
728
+ progress,
624
729
  notes,
625
730
  });
626
731
  }
@@ -668,9 +773,10 @@ async function takeTicket(
668
773
  * Run log each carry. It names the branch twice on purpose: once as the thing
669
774
  * that is in the way, and once inside the command that clears it.
670
775
  *
671
- * `checkedOutAt` is the worktree the branch is in, when it is in one: a branch
672
- * git will not let go of is not one `git branch -D` can delete, so being told
673
- * to run that would send the human round a second failure.
776
+ * `checkedOutAt` is the worktree the branch is in, when it is in one, relative
777
+ * to the Target's checkout ({@link inCheckout}): a branch git will not let go
778
+ * of is not one `git branch -D` can delete, so being told to run that would
779
+ * send the human round a second failure.
674
780
  */
675
781
  function describeBranchInTheWay(
676
782
  branch: string,
@@ -737,6 +843,9 @@ async function resumable(
737
843
  found = await pipeline.workspace.worktreeFromRemote(ref);
738
844
  checkedOut = found === "parted" && (await pipeline.workspace.hasWorktree(ref));
739
845
  } catch (error) {
846
+ // Nothing is claimed yet, so a remote that cannot be reached leaves the
847
+ // Ticket as it was for the next Run, rather than handing it off.
848
+ if (error instanceof OutsideFault) throw error;
740
849
  return {
741
850
  state,
742
851
  refusal: `the worktree of ${state.branch} could not be made ready to resume in: ${(error as Error).message}`,
@@ -747,7 +856,11 @@ async function resumable(
747
856
  const checkedOutAt = checkedOut ? worktree : undefined;
748
857
  return {
749
858
  state,
750
- refusal: describeParted(state.branch, checkedOutAt, pipeline.config.labels.readyForAgent),
859
+ refusal: describeParted(
860
+ state.branch,
861
+ checkedOutAt === undefined ? undefined : inCheckout(pipeline.repoRoot, checkedOutAt),
862
+ pipeline.config.labels.readyForAgent,
863
+ ),
751
864
  ...(checkedOutAt === undefined ? {} : { checkedOutAt }),
752
865
  };
753
866
  }
@@ -770,7 +883,8 @@ async function resumable(
770
883
  * one on the remote: which two copies, and the two ways to make them one.
771
884
  *
772
885
  * One line, as for {@link describeBranchInTheWay}. `checkedOutAt` is the
773
- * worktree the branch is in, when it is in one.
886
+ * worktree the branch is in, when it is in one, relative to the Target's
887
+ * checkout.
774
888
  */
775
889
  function describeParted(
776
890
  branch: string,
@@ -792,6 +906,16 @@ function describeParted(
792
906
  );
793
907
  }
794
908
 
909
+ /**
910
+ * A worktree as a hand-off names it: relative to the Target's checkout, such
911
+ * as `.worktrees/ticket-<n>`, on every Target whatever its visibility. A
912
+ * comment on a public Target would otherwise publish the Host's home path, and
913
+ * the commands a refusal gives work from the checkout's root as they stand.
914
+ */
915
+ function inCheckout(repoRoot: string, path: string): string {
916
+ return relative(repoRoot, path);
917
+ }
918
+
795
919
  /**
796
920
  * How this Run came by the Ticket, for the one line it logs about it: resumed
797
921
  * from a recorded state, taken from the top, or claimed outright. A stranded
@@ -808,7 +932,10 @@ type Reached = Omit<TicketState, "runId" | "updatedAt">;
808
932
 
809
933
  /** What one write moves that on by. */
810
934
  type Advance = Partial<
811
- Pick<Reached, "state" | "fixUsed" | "pullRequest" | "title" | "rebaseFirst">
935
+ Pick<
936
+ Reached,
937
+ "state" | "fixUsed" | "pullRequest" | "title" | "body" | "problem" | "solution" | "rebaseFirst"
938
+ >
812
939
  >;
813
940
 
814
941
  /**
@@ -852,11 +979,21 @@ class ResumeRecord {
852
979
  return record;
853
980
  }
854
981
 
982
+ /** The state the Ticket has reached, which is where a later Run picks it up. */
983
+ get state(): ReachedState {
984
+ return this.reached.state;
985
+ }
986
+
855
987
  /** The latest title a Stage answered for the branch, in this Run or an earlier one. */
856
988
  get title(): string | undefined {
857
989
  return this.reached.title;
858
990
  }
859
991
 
992
+ /** The latest body, problem and solution a Stage answered for the branch, in this Run or an earlier one. */
993
+ get prose(): BranchProse {
994
+ return recordedProse(this.reached);
995
+ }
996
+
860
997
  /**
861
998
  * Move the record on, and put it where the next Run will look for it.
862
999
  *
@@ -912,7 +1049,7 @@ async function passOver(
912
1049
 
913
1050
  if (isGuardReason(reason)) {
914
1051
  if (!hasGuardWarning(issue.comments, reason)) {
915
- await tracker.comment(issue.number, guardComment(reason));
1052
+ await tracker.comment(issue.number, guardComment(reason, tickedBoxes(issue)));
916
1053
  }
917
1054
  // A Spec is not a Ticket and no edit will make it one; the other two are
918
1055
  // fixable in place, so their candidates keep the label and stay visible.
@@ -1059,7 +1196,12 @@ async function collectNotes(
1059
1196
  stage: NotingStage,
1060
1197
  result: StageResult,
1061
1198
  notes: RoutedNote[],
1199
+ /** Where a code Stage's Notes are kept for the verify Stage behind it, whether they reach GitHub or not. */
1200
+ written?: WrittenNote[],
1062
1201
  ): Promise<void> {
1202
+ if (written !== undefined && stage !== "verify") {
1203
+ written.push(...parseNotes(result.result).map((note) => ({ stage, note })));
1204
+ }
1063
1205
  notes.push(
1064
1206
  ...(await routeNotes(
1065
1207
  {
@@ -1075,15 +1217,32 @@ async function collectNotes(
1075
1217
  }
1076
1218
 
1077
1219
  /**
1078
- * Record the title a code Stage answered for the whole branch, when it answered
1079
- * one that counts, so it names the pull request and outlives this Run.
1220
+ * Record the title, the body, the problem and the solution a code Stage
1221
+ * answered for the whole branch, each one it answered with something that
1222
+ * counts, so they write the pull request and the squash commit and outlive
1223
+ * this Run.
1080
1224
  *
1081
- * One that does not count costs the title alone, as a malformed Note costs that
1082
- * Note: the one before it, or the first commit subject, is used instead.
1225
+ * One that does not count, or one answered blank, costs that answer alone, as
1226
+ * a malformed Note costs that Note: the one an earlier Stage answered stands,
1227
+ * and for the title, the first commit subject after it.
1083
1228
  */
1084
- async function recordTitle(result: StageResult, record: ResumeRecord): Promise<void> {
1229
+ async function recordAnswers(result: StageResult, record: ResumeRecord): Promise<void> {
1085
1230
  const title = parseTitle(result.result);
1086
- if (title !== undefined) await record.advance({ title });
1231
+ const answered: Advance = {
1232
+ ...(title === undefined ? {} : { title }),
1233
+ ...parseBranchProse(result.result),
1234
+ };
1235
+ if (Object.keys(answered).length > 0) await record.advance(answered);
1236
+ }
1237
+
1238
+ /** The body, the problem and the solution a state names, without the keys it holds none for. */
1239
+ function recordedProse(state: BranchProse): BranchProse {
1240
+ const prose: BranchProse = {};
1241
+ for (const field of BRANCH_PROSE_FIELDS) {
1242
+ const answer = state[field];
1243
+ if (answer !== undefined) prose[field] = answer;
1244
+ }
1245
+ return prose;
1087
1246
  }
1088
1247
 
1089
1248
  /** What the Run's standing Notes issue is found — and opened — with. */
@@ -1158,6 +1317,15 @@ function leftNoCommits(
1158
1317
  );
1159
1318
  }
1160
1319
 
1320
+ /**
1321
+ * Where a code Stage's Notes go: the Run's list of those that reached GitHub,
1322
+ * and the Ticket's own list of what its code Stages wrote, for verify.
1323
+ */
1324
+ interface CodeStageNotes {
1325
+ notes: RoutedNote[];
1326
+ written: WrittenNote[];
1327
+ }
1328
+
1161
1329
  async function implement(
1162
1330
  pipeline: Pipeline,
1163
1331
  issue: Issue,
@@ -1165,7 +1333,7 @@ async function implement(
1165
1333
  branch: string,
1166
1334
  logDir: string,
1167
1335
  progress: Progress,
1168
- notes: RoutedNote[],
1336
+ { notes, written }: CodeStageNotes,
1169
1337
  record: ResumeRecord,
1170
1338
  ): Promise<void> {
1171
1339
  const stage = pipeline.config.stages.implement;
@@ -1187,8 +1355,8 @@ async function implement(
1187
1355
  // implemented the Ticket exactly as it always did.
1188
1356
  resultRequired: false,
1189
1357
  });
1190
- await collectNotes(pipeline, issue.number, "implement", result, notes);
1191
- await recordTitle(result, record);
1358
+ await collectNotes(pipeline, issue.number, "implement", result, notes, written);
1359
+ await recordAnswers(result, record);
1192
1360
 
1193
1361
  // Pushed whatever became of the Stage, like its Notes: a session that
1194
1362
  // committed and then was stopped by the rate limit or an API failure still
@@ -1350,6 +1518,9 @@ async function inheritedFailure(
1350
1518
  commands,
1351
1519
  );
1352
1520
  } catch (error) {
1521
+ // A remote that cannot be reached is a fault of its own, which releases
1522
+ // the Ticket rather than charging it for a failure nobody could grade.
1523
+ if (error instanceof OutsideFault) throw error;
1353
1524
  pipeline.log?.(
1354
1525
  `could not run the Checks at the merge-base with ${pipeline.baseBranch}: ${(error as Error).message}`,
1355
1526
  );
@@ -1415,8 +1586,18 @@ async function verify(
1415
1586
  logDir: string,
1416
1587
  progress: Progress,
1417
1588
  notes: RoutedNote[],
1418
- /** The unmet criteria and evidence of the verdict a fix Stage was sent in for. */
1419
- unmetBefore: string | undefined,
1589
+ {
1590
+ criteria,
1591
+ written,
1592
+ unmetBefore,
1593
+ }: {
1594
+ /** The Ticket's criteria, numbered, which the verdict answers by number. */
1595
+ criteria: readonly ListedCriterion[];
1596
+ /** The Notes this Ticket's code Stages wrote in this Run. */
1597
+ written: readonly WrittenNote[];
1598
+ /** The unmet criteria, defects and evidence of the verdict a fix Stage was sent in for. */
1599
+ unmetBefore: string | undefined;
1600
+ },
1420
1601
  ): Promise<Verdict> {
1421
1602
  const stage = pipeline.config.stages.verify;
1422
1603
  const result = await runStage(pipeline, "verify", {
@@ -1428,6 +1609,7 @@ async function verify(
1428
1609
  pipeline.config.checks,
1429
1610
  await standingNotesNumber(pipeline),
1430
1611
  unmetBefore,
1612
+ { criteria, written },
1431
1613
  ),
1432
1614
  cwd: worktree,
1433
1615
  logDir,
@@ -1447,9 +1629,9 @@ async function verify(
1447
1629
 
1448
1630
  if (!result.ok) throw await stageDidNotFinish(pipeline, progress, "verify", result);
1449
1631
 
1450
- let verdict: Verdict;
1632
+ let answered: AnsweredVerdict;
1451
1633
  try {
1452
- verdict = parseVerdict(result.result);
1634
+ answered = parseVerdict(result.result);
1453
1635
  } catch (error) {
1454
1636
  await progress.record(stageRow("verify", result, "❌ no verdict"));
1455
1637
  throw new TicketFailure(
@@ -1459,24 +1641,46 @@ async function verify(
1459
1641
  );
1460
1642
  }
1461
1643
 
1644
+ // A verdict that left a listed criterion out, or graded one nobody listed,
1645
+ // has not graded this Ticket, whatever it says of the rest: it is no
1646
+ // evidence to merge on, and no fix Stage can mend a session's arithmetic.
1647
+ const graded = gradeVerdict(answered, criteria);
1648
+ if (isMisnumbered(graded)) {
1649
+ await progress.record(stageRow("verify", result, "❌ misnumbered"));
1650
+ throw new TicketFailure(
1651
+ "verify",
1652
+ "the verdict's numbers are not the criteria it was given, so it graded nothing to merge on",
1653
+ misnumberedEvidence(graded, criteria.length),
1654
+ );
1655
+ }
1656
+ const verdict = graded;
1462
1657
  const counts = countStatuses(verdict);
1463
1658
 
1464
1659
  // The agent's own `pass` is advisory; this is the decision that counts.
1465
1660
  if (!passes(verdict)) {
1466
1661
  const unmet = unmetCriteria(verdict);
1467
- if (unmet.length === 0) {
1662
+ const { defects } = verdict;
1663
+ if (unmet.length === 0 && defects.length === 0) {
1468
1664
  await progress.record(stageRow("verify", result, "❌ no evidence"));
1469
1665
  throw new TicketFailure(
1470
1666
  "verify",
1471
1667
  "every criterion came back unverifiable, so there is no evidence to merge on",
1472
- verdict.criteria.map((c) => `- ${c.text} — ${c.evidence}`).join("\n"),
1668
+ verdict.criteria.map(criterionLine).join("\n"),
1473
1669
  );
1474
1670
  }
1475
- await progress.record(stageRow("verify", result, `❌ ${unmet.length} unmet`));
1671
+ const cell = [
1672
+ ...(unmet.length === 0 ? [] : [`${unmet.length} unmet`]),
1673
+ ...(defects.length === 0 ? [] : [defectCount(defects.length)]),
1674
+ ].join(" · ");
1675
+ const summary = [
1676
+ ...(unmet.length === 0 ? [] : [`${unmet.length} of ${verdict.criteria.length} criteria unmet`]),
1677
+ ...(defects.length === 0 ? [] : [`the branch made ${defectCount(defects.length)}`]),
1678
+ ].join(", and ");
1679
+ await progress.record(stageRow("verify", result, `❌ ${cell}`));
1476
1680
  throw new TicketFailure(
1477
1681
  "verify",
1478
- `${unmet.length} of ${verdict.criteria.length} criteria unmet`,
1479
- unmet.map((c) => `- ${c.text} — ${c.evidence}`).join("\n"),
1682
+ summary,
1683
+ [...unmet.map(criterionLine), ...defects.map(defectLine)].join("\n"),
1480
1684
  "unmet-criteria",
1481
1685
  );
1482
1686
  }
@@ -1487,12 +1691,44 @@ async function verify(
1487
1691
  return verdict;
1488
1692
  }
1489
1693
 
1694
+ /**
1695
+ * A criterion as a hand-off, a fix Stage and the verify behind it read it: its
1696
+ * number, its checkbox line as the Ticket writes it, and the verdict's evidence.
1697
+ */
1698
+ function criterionLine(criterion: GradedCriterion): string {
1699
+ return `- ${criterion.number}. ${criterion.text} — ${criterion.evidence}`;
1700
+ }
1701
+
1702
+ /** A defect of the branch, beside the criteria in the same evidence. */
1703
+ function defectLine(defect: Defect): string {
1704
+ return `- Defect: ${defect.summary} — ${defect.evidence}`;
1705
+ }
1706
+
1707
+ function defectCount(count: number): string {
1708
+ return `${count} ${count === 1 ? "defect" : "defects"}`;
1709
+ }
1710
+
1711
+ /** Which numbers a verdict answered wrong, against the list it was given. */
1712
+ function misnumberedEvidence({ missing, unlisted, repeated }: Misnumbered, listed: number): string {
1713
+ return [
1714
+ `The verify Stage was given criteria 1 to ${listed}.`,
1715
+ ...(missing.length === 0 ? [] : [`Not answered: ${missing.join(", ")}`]),
1716
+ ...(unlisted.length === 0 ? [] : [`Answered but not listed: ${unlisted.join(", ")}`]),
1717
+ ...(repeated.length === 0 ? [] : [`Answered more than once: ${repeated.join(", ")}`]),
1718
+ ].join("\n");
1719
+ }
1720
+
1490
1721
  /**
1491
1722
  * What the fix budget buys: a fresh session on the same branch in the same
1492
1723
  * worktree, handed the failure and its evidence and nothing else to do.
1493
1724
  *
1494
- * It drives no plugin skill. The implement skill would re-read the Ticket and
1495
- * start over, where what is wanted here is one concrete defect mended.
1725
+ * It drives no plugin skill but the `pr` skill, for a body its fix changes.
1726
+ * The implement skill would re-read the Ticket and start over, where what is
1727
+ * wanted here is one concrete defect mended.
1728
+ *
1729
+ * It is handed the body, the problem and the solution answered so far, so a
1730
+ * fix that changes what one says revises it for the whole branch rather than
1731
+ * describing only itself, and one that does not leaves it standing.
1496
1732
  */
1497
1733
  async function fix(
1498
1734
  pipeline: Pipeline,
@@ -1502,7 +1738,7 @@ async function fix(
1502
1738
  logDir: string,
1503
1739
  failure: FixFailure,
1504
1740
  progress: Progress,
1505
- notes: RoutedNote[],
1741
+ { notes, written }: CodeStageNotes,
1506
1742
  record: ResumeRecord,
1507
1743
  ): Promise<void> {
1508
1744
  const stage = pipeline.config.stages.fix;
@@ -1523,14 +1759,15 @@ async function fix(
1523
1759
  pipeline.selfHosted,
1524
1760
  pipeline.config.checks,
1525
1761
  await standingNotesNumber(pipeline),
1762
+ record.prose,
1526
1763
  ),
1527
1764
  cwd: worktree,
1528
1765
  logDir,
1529
1766
  jsonSchema: CODE_STAGE_JSON_SCHEMA,
1530
1767
  resultRequired: false,
1531
1768
  });
1532
- await collectNotes(pipeline, issue.number, "fix", result, notes);
1533
- await recordTitle(result, record);
1769
+ await collectNotes(pipeline, issue.number, "fix", result, notes, written);
1770
+ await recordAnswers(result, record);
1534
1771
 
1535
1772
  // Pushed whatever became of the Stage, as the implement Stage's work is.
1536
1773
  const grew = (await commitCount(pipeline, branch)) > commitsBefore;
@@ -1683,37 +1920,42 @@ interface PullRequestSubject {
1683
1920
  issue: Issue;
1684
1921
  branch: string;
1685
1922
  worktree: string;
1686
- verdict: Verdict;
1687
1923
  title: string;
1924
+ /** The latest body a Stage answered for the branch, when one has. */
1925
+ body: string | undefined;
1688
1926
  }
1689
1927
 
1690
1928
  /**
1691
1929
  * Push the branch, then open the pull request or bring the open one up to date.
1692
1930
  *
1693
1931
  * A second pass comes back to a pull request that already exists: the push is
1694
- * what GitHub re-runs its checks on, and the title and body are rewritten so
1695
- * the subject and the verdict a human reads there are the ones that will reach
1696
- * the base branch.
1932
+ * what GitHub re-runs its checks on, and the title and body are rewritten
1933
+ * from the latest a Stage answered, so a fix Stage's revision is the one a
1934
+ * human reads there.
1697
1935
  *
1698
1936
  * One that already exists is also taken out of draft, because a Ticket resumed
1699
1937
  * after a hand-off comes back to the pull request the hand-off drafted and a
1700
- * draft cannot be merged. Here rather than at the merge: a draft pull request
1938
+ * draft cannot be merged.
1939
+ *
1940
+ * One the Ticket has not recorded may still be open on its branch: an attempt
1941
+ * GitHub failed to answer may have opened it all the same, in this Run or the
1942
+ * one released over the failure. It is the Ticket's, and used as one it had
1943
+ * recorded, rather than refused a second beside it. Here rather than at the merge: a draft pull request
1701
1944
  * often runs no workflows at all, so the wait for CI below would read it as
1702
1945
  * "no checks" and end the Ticket before the merge was ever asked for.
1703
1946
  */
1704
1947
  async function publishPullRequest(
1705
1948
  pipeline: Pipeline,
1706
- { issue, branch, worktree, verdict, title }: PullRequestSubject,
1949
+ { issue, branch, worktree, title, body: answered }: PullRequestSubject,
1707
1950
  existing: number | undefined,
1708
1951
  ): Promise<number> {
1709
1952
  await pipeline.workspace.push(worktree, branch);
1710
1953
  const body = pullRequestBody({
1711
1954
  ticket: issue.number,
1712
- verdict,
1713
- runId: pipeline.runId,
1714
- host: pipeline.host,
1955
+ ...(answered === undefined ? {} : { body: answered }),
1715
1956
  });
1716
1957
 
1958
+ existing ??= await openPullRequestOn(pipeline, branch);
1717
1959
  if (existing !== undefined) {
1718
1960
  // Retitled as well, so a title a fix Stage answered after the pull request
1719
1961
  // opened is the one it shows, as it is the subject that lands.
@@ -1733,6 +1975,12 @@ async function publishPullRequest(
1733
1975
  return pr.number;
1734
1976
  }
1735
1977
 
1978
+ /** The open pull request from `branch`, if there is one. */
1979
+ async function openPullRequestOn(pipeline: Pipeline, branch: string): Promise<number | undefined> {
1980
+ const open = await pipeline.tracker.openPullRequests();
1981
+ return open.find((pull) => pull.head === branch)?.number;
1982
+ }
1983
+
1736
1984
  /**
1737
1985
  * A red, unfinished or conflicting pull request is a failure whatever the
1738
1986
  * gates say. Turning `gates.ci` off only tolerates a pull request that has no
@@ -1814,6 +2062,8 @@ interface Release {
1814
2062
  record: ResumeRecord;
1815
2063
  /** Whether the fix budget was spent by a failure of the Ticket's own. */
1816
2064
  fixUsed: boolean;
2065
+ /** The progress comment, written once more if its last write failed. */
2066
+ progress: Progress;
1817
2067
  notes: RoutedNote[];
1818
2068
  }
1819
2069
 
@@ -1825,10 +2075,14 @@ interface Release {
1825
2075
  * keeping — so the branch and the worktree stay, no comment is posted, no draft
1826
2076
  * pull request is opened, and the Ticket goes back on the Frontier for a Run
1827
2077
  * started after the limit has reset.
2078
+ *
2079
+ * Never thrown out of: a Release is what stops the Run claiming, and a claim
2080
+ * GitHub would not take off — over the very fault that released the Ticket,
2081
+ * say — leaves the Ticket claimed, which a later Run resumes as stranded.
1828
2082
  */
1829
2083
  async function release(
1830
2084
  pipeline: Pipeline,
1831
- { issue, user, branch, stopped, record, fixUsed, notes }: Release,
2085
+ { issue, user, branch, stopped, record, fixUsed, progress, notes }: Release,
1832
2086
  ): Promise<TicketOutcome> {
1833
2087
  const { tracker, config } = pipeline;
1834
2088
  const ticket = issue.number;
@@ -1846,11 +2100,11 @@ async function release(
1846
2100
  await noteFailingBase(pipeline, { issue, branch, failing: stopped.failingBase, notes });
1847
2101
  }
1848
2102
 
1849
- // The claim, undone in the order it was made, so the assignee — which is what
1850
- // another Run reads to tell a taken Ticket from a free one — comes off last.
1851
- await tracker.addLabel(ticket, config.labels.readyForAgent);
1852
- await tracker.removeLabel(ticket, config.labels.inProgress);
1853
- await tracker.unassign(ticket, user);
2103
+ await progress.settle();
2104
+
2105
+ // The assignee — which is what another Run reads to tell a taken Ticket from
2106
+ // a free one — comes off last.
2107
+ await undoClaim(pipeline, ticket, user);
1854
2108
  pipeline.log?.(
1855
2109
  `#${ticket} released at ${stopped.point} · ${releaseWords(stopped.reason, pipeline.credential)} · ${branch}`,
1856
2110
  );
@@ -1868,6 +2122,88 @@ async function release(
1868
2122
  : {
1869
2123
  failingBase: { commit: stopped.failingBase.commit, command: stopped.failingBase.command },
1870
2124
  }),
2125
+ ...(stopped.fault === undefined ? {} : { fault: stopped.fault }),
2126
+ notes,
2127
+ };
2128
+ }
2129
+
2130
+ /**
2131
+ * Claim a Ticket on the board.
2132
+ *
2133
+ * In an order that leaves the Ticket free or stranded wherever a write fails,
2134
+ * as one GitHub keeps failing does: `in-progress` with no assignee is still on
2135
+ * the Frontier, and an assignee wearing `in-progress` is the claim. An
2136
+ * assignee alone would be neither, and no Run would take it up again.
2137
+ */
2138
+ async function writeClaim(pipeline: Pipeline, ticket: number, user: string): Promise<void> {
2139
+ const { tracker, config } = pipeline;
2140
+ await tracker.addLabel(ticket, config.labels.inProgress);
2141
+ await tracker.assign(ticket, user);
2142
+ await tracker.removeLabel(ticket, config.labels.readyForAgent);
2143
+ }
2144
+
2145
+ /**
2146
+ * Take the claim off a released Ticket, or leave it on whole.
2147
+ *
2148
+ * In an order that leaves the Ticket claimed or free wherever a write fails:
2149
+ * the assignee comes off before `in-progress`, since a Ticket left assigned
2150
+ * without it would be neither free for the Frontier nor stranded for the
2151
+ * sweep, and no Run would take it up again. One that stays claimed is resumed
2152
+ * by the next Run as a Stranded Ticket, and one left wearing only
2153
+ * `ready-for-agent` and `in-progress` is taken from the Frontier and resumed
2154
+ * from its state, as any released Ticket is.
2155
+ *
2156
+ * A write that fails stops the rest, and the claim is written back whole, in
2157
+ * the claim's own order, so the Ticket stays claimed as the Release asks
2158
+ * wherever GitHub lets it. Logged and nothing more, since the Release stands
2159
+ * either way.
2160
+ */
2161
+ async function undoClaim(pipeline: Pipeline, ticket: number, user: string): Promise<void> {
2162
+ const { tracker, config } = pipeline;
2163
+ let touched = false;
2164
+ try {
2165
+ await tracker.addLabel(ticket, config.labels.readyForAgent);
2166
+ touched = true;
2167
+ await tracker.unassign(ticket, user);
2168
+ await tracker.removeLabel(ticket, config.labels.inProgress);
2169
+ } catch (error) {
2170
+ pipeline.log?.(
2171
+ `#${ticket} stays claimed for the next Run to resume, as the claim could not come off: ${(error as Error).message}`,
2172
+ );
2173
+ if (!touched) return;
2174
+ try {
2175
+ await writeClaim(pipeline, ticket, user);
2176
+ } catch (again) {
2177
+ pipeline.log?.(
2178
+ `#${ticket} could not be claimed whole again, and is resumed from where the claim stopped: ${(again as Error).message}`,
2179
+ );
2180
+ }
2181
+ }
2182
+ }
2183
+
2184
+ /**
2185
+ * The outcome of a Ticket a fault outside it stopped where nothing more could
2186
+ * be written about it: before the claim or in it, or in a hand-off that kept
2187
+ * the state file and the claim. Free, or still claimed, which a later Run
2188
+ * resumes it from as a Stranded Ticket. The Run reports it released all the
2189
+ * same, since what the Run does next is what a Release asks of it: claim
2190
+ * nothing more.
2191
+ */
2192
+ export function faultOutcome(
2193
+ issue: { number: number; title: string },
2194
+ branch: string,
2195
+ stage: FailurePoint,
2196
+ fault: OutsideFault,
2197
+ notes: RoutedNote[],
2198
+ ): TicketOutcome {
2199
+ return {
2200
+ outcome: "released",
2201
+ ticket: issue.number,
2202
+ title: issue.title,
2203
+ branch,
2204
+ stage,
2205
+ cause: fault.side,
2206
+ fault: { command: fault.command, line: fault.line },
1871
2207
  notes,
1872
2208
  };
1873
2209
  }
@@ -1956,6 +2292,8 @@ interface HandOff {
1956
2292
  fixUsed: boolean;
1957
2293
  /** The Ticket's state file, which the hand-off either leaves current or removes. */
1958
2294
  record: ResumeRecord;
2295
+ /** The progress comment, written once more if its last write failed. */
2296
+ progress: Progress;
1959
2297
  notes: RoutedNote[];
1960
2298
  }
1961
2299
 
@@ -1965,11 +2303,12 @@ interface HandOff {
1965
2303
  * worktree and the state file stay put, so a human who relabels the Ticket
1966
2304
  * `ready-for-agent` hands it back and the next Run carries on from what it
1967
2305
  * reached. The Stages' transcripts go up beside the state, since the Host they
1968
- * were written on may be gone by the time a human looks, and the comment says
1969
- * where they and the branch are. The draft pull request's body says where they
1970
- * are too, once they are kept: a draft is opened first, because the state
1971
- * records it, and one that was already open is rewritten, since its body is an
1972
- * earlier Run's.
2306
+ * were written on may be gone by the time a human looks, unless the Run keeps
2307
+ * them off the remote, where they stay on this Host; the comment says where
2308
+ * they and the branch are. The draft pull request's body says where they are
2309
+ * too, once they are kept: a draft is opened first, because the state records
2310
+ * it, and one that was already open is rewritten, since its body is an earlier
2311
+ * Run's.
1973
2312
  *
1974
2313
  * A Ticket handed over before its worktree was created has none: nothing was
1975
2314
  * branched, so there is no directory to name and nothing to push a draft pull
@@ -1990,6 +2329,11 @@ interface HandOff {
1990
2329
  * prevent. The one worktree this Run may not push out of whose state stays is
1991
2330
  * one parted from the remote branch: both copies are the pipeline's, and
1992
2331
  * pushing either over the other is the choice the human is handed.
2332
+ *
2333
+ * A fault outside the Ticket that meets one of the hand-off's writes cuts it
2334
+ * short where it stands, and the Run claims no more, as over any fault of the
2335
+ * kind ({@link cutShort}). Never thrown out of: the Ticket's ending is what
2336
+ * the summary reports, whichever it turns out to be.
1993
2337
  */
1994
2338
  async function handOff(
1995
2339
  pipeline: Pipeline,
@@ -2003,11 +2347,17 @@ async function handOff(
2003
2347
  failure,
2004
2348
  fixUsed,
2005
2349
  record,
2350
+ progress,
2006
2351
  notes,
2007
2352
  }: HandOff,
2008
2353
  ): Promise<TicketOutcome> {
2009
2354
  const { tracker, workspace, config } = pipeline;
2010
2355
  const ticket = issue.number;
2356
+ await progress.settle();
2357
+ // A green Ticket on a Target that merges by hand: its pull request is the
2358
+ // one a human reviews and merges, so it stays as published, and nothing
2359
+ // failed, so no transcripts are kept.
2360
+ const byHand = failure instanceof LeftToHuman ? failure : undefined;
2011
2361
 
2012
2362
  // Nothing of this Run's is on the branch, so nothing may leave the Ticket
2013
2363
  // looking resumable: the next Run must not implement over what a human holds.
@@ -2033,84 +2383,117 @@ async function handOff(
2033
2383
  // Whether the draft's body is one this hand-off wrote, naming no transcripts.
2034
2384
  // One it only converted still says what its Run said, which is not this.
2035
2385
  let drafted = false;
2036
- if (pullRequest !== undefined) {
2037
- await tracker.convertPullRequestToDraft(pullRequest);
2038
- } else if (worktree?.pushable === true) {
2039
- // A draft pull request is worth trying for, but never worth losing the
2040
- // relabel over.
2041
- try {
2042
- await workspace.push(worktree.path, branch);
2043
- const pr = await tracker.createPullRequest({
2044
- base: pipeline.baseBranch,
2045
- head: branch,
2046
- // A human can still merge the draft, and its squash commit takes this
2047
- // title, so it is the one a Stage answered for the branch where there is
2048
- // one. Without it, the Ticket title rather than a commit subject: the
2049
- // pipeline merges nothing here, so it derives nothing for a merge.
2050
- title: record.title ?? issue.title,
2051
- body: draftPullRequestBody(draftBody),
2052
- draft: true,
2053
- });
2054
- pullRequest = pr.number;
2055
- drafted = true;
2056
- } catch (error) {
2057
- pipeline.log?.(`#${ticket} could not open a draft pull request: ${(error as Error).message}`);
2386
+ // Whether the Ticket still wears its claim, `in-progress` and its assignee,
2387
+ // which is what decides how a fault met below is reported.
2388
+ let claimed = true;
2389
+ try {
2390
+ if (byHand !== undefined) {
2391
+ // Nothing to do: ready for review, its title and body as the pr step wrote them.
2392
+ } else if (pullRequest !== undefined) {
2393
+ await tracker.convertPullRequestToDraft(pullRequest);
2394
+ } else if (worktree?.pushable === true) {
2395
+ // A draft pull request is worth trying for, but never worth losing the
2396
+ // relabel over, unless GitHub or the remote is failing on its own side:
2397
+ // then the relabel would meet the same fault, so the hand-off stops here.
2398
+ try {
2399
+ await workspace.push(worktree.path, branch);
2400
+ const pr = await tracker.createPullRequest({
2401
+ base: pipeline.baseBranch,
2402
+ head: branch,
2403
+ // A human can still merge the draft, and its squash commit takes this
2404
+ // title, so it is the one a Stage answered for the branch where there is
2405
+ // one. Without it, the Ticket title rather than a commit subject: the
2406
+ // pipeline merges nothing here, so it derives nothing for a merge.
2407
+ title: record.title ?? issue.title,
2408
+ body: draftPullRequestBody(draftBody),
2409
+ draft: true,
2410
+ });
2411
+ pullRequest = pr.number;
2412
+ drafted = true;
2413
+ } catch (error) {
2414
+ if (error instanceof OutsideFault) throw error;
2415
+ pipeline.log?.(`#${ticket} could not open a draft pull request: ${(error as Error).message}`);
2416
+ }
2058
2417
  }
2059
- }
2060
2418
 
2061
- if (keepsState) {
2062
- // Written after the draft pull request, because that pull request is part of
2063
- // what a resuming Run must not open a second one beside.
2064
- //
2065
- // The fix budget goes back unspent: the Ticket only comes back through a
2066
- // human's hands, and whatever they did to it is what the fresh budget is
2067
- // for. Nothing is lost by it — the hand-off comment says the budget was
2068
- // spent, and the claim only marks that comment as history.
2069
- await record.advance({
2070
- fixUsed: false,
2071
- ...(pullRequest === undefined ? {} : { pullRequest }),
2072
- });
2073
- }
2074
- // Only beside a state that stays, because they go when it does, and after
2075
- // it, so the state they sit beside is the one a resuming Run reads.
2076
- const transcripts = keepsState ? await keepTranscripts(pipeline, ticket) : undefined;
2077
- // A draft this hand-off opened went up before anything was kept, and one it
2078
- // converted still carries an earlier body, so either learns where only now.
2079
- if (pullRequest !== undefined && !(drafted && transcripts === undefined)) {
2080
- try {
2081
- await tracker.updatePullRequestBody(
2082
- pullRequest,
2083
- draftPullRequestBody({
2084
- ...draftBody,
2085
- ...(transcripts === undefined ? {} : { transcripts }),
2086
- }),
2087
- );
2088
- } catch (error) {
2089
- pipeline.log?.(
2090
- `#${ticket} could not rewrite the body of PR #${pullRequest}: ${(error as Error).message}`,
2091
- );
2419
+ if (keepsState) {
2420
+ // Written after the draft pull request, because that pull request is part of
2421
+ // what a resuming Run must not open a second one beside.
2422
+ //
2423
+ // The fix budget goes back unspent: the Ticket only comes back through a
2424
+ // human's hands, and whatever they did to it is what the fresh budget is
2425
+ // for. Nothing is lost by it — the hand-off comment says the budget was
2426
+ // spent, and the claim only marks that comment as history.
2427
+ await record.advance({
2428
+ fixUsed: false,
2429
+ ...(pullRequest === undefined ? {} : { pullRequest }),
2430
+ });
2092
2431
  }
2093
- }
2094
- const onRemote = await branchOnRemote(pipeline, ticket, branch);
2095
-
2096
- await tracker.comment(
2097
- ticket,
2098
- handoffComment({
2099
- stage: failure.point,
2100
- failure: failure.summary,
2432
+ // Only beside a state that stays, because on the remote they go when it
2433
+ // does, and after it, so the state they sit beside is the one a resuming Run
2434
+ // reads. A hand-off that leaves no state ran no Stage, so it has none anyway.
2435
+ const transcripts =
2436
+ keepsState && byHand === undefined ? await keepTranscripts(pipeline, ticket) : undefined;
2437
+ // A draft this hand-off opened went up before anything was kept, and one it
2438
+ // converted still carries an earlier body, so either learns where only now.
2439
+ if (byHand === undefined && pullRequest !== undefined && !(drafted && transcripts === undefined)) {
2440
+ try {
2441
+ await tracker.updatePullRequestBody(
2442
+ pullRequest,
2443
+ draftPullRequestBody({
2444
+ ...draftBody,
2445
+ ...(transcripts === undefined ? {} : { transcripts }),
2446
+ }),
2447
+ );
2448
+ } catch (error) {
2449
+ pipeline.log?.(
2450
+ `#${ticket} could not rewrite the body of PR #${pullRequest}: ${(error as Error).message}`,
2451
+ );
2452
+ }
2453
+ }
2454
+ const onRemote = await branchOnRemote(pipeline, ticket, branch);
2455
+ const shownWorktree =
2456
+ worktree === undefined ? undefined : inCheckout(pipeline.repoRoot, worktree.path);
2457
+
2458
+ await tracker.comment(
2459
+ ticket,
2460
+ byHand !== undefined && pullRequest !== undefined
2461
+ ? mergeByHandComment({
2462
+ branch,
2463
+ onRemote,
2464
+ ...(shownWorktree === undefined ? {} : { worktree: shownWorktree }),
2465
+ pullRequest,
2466
+ verdict: byHand.verdict,
2467
+ })
2468
+ : handoffComment({
2469
+ stage: failure.point,
2470
+ failure: failure.summary,
2471
+ branch,
2472
+ onRemote,
2473
+ ...(shownWorktree === undefined ? {} : { worktree: shownWorktree }),
2474
+ ...(transcripts === undefined ? {} : { transcripts }),
2475
+ evidence: failure.evidence,
2476
+ ...(failure.reason === undefined ? {} : { reason: failure.reason }),
2477
+ fixUsed,
2478
+ ...(pullRequest === undefined ? {} : { pullRequest }),
2479
+ }),
2480
+ );
2481
+ await tracker.removeLabel(ticket, config.labels.inProgress);
2482
+ claimed = false;
2483
+ await tracker.addLabel(ticket, config.labels.readyForHuman);
2484
+ await tracker.unassign(ticket, user);
2485
+ } catch (error) {
2486
+ if (!(error instanceof OutsideFault)) throw error;
2487
+ return cutShort(pipeline, {
2488
+ issue,
2101
2489
  branch,
2102
- onRemote,
2103
- ...(worktree === undefined ? {} : { worktree: worktree.path }),
2104
- ...(transcripts === undefined ? {} : { transcripts }),
2105
- evidence: failure.evidence,
2106
- ...(failure.reason === undefined ? {} : { reason: failure.reason }),
2107
- fixUsed,
2108
- ...(pullRequest === undefined ? {} : { pullRequest }),
2109
- }),
2110
- );
2111
- await tracker.removeLabel(ticket, config.labels.inProgress);
2112
- await tracker.addLabel(ticket, config.labels.readyForHuman);
2113
- await tracker.unassign(ticket, user);
2490
+ failure,
2491
+ pullRequest,
2492
+ notes,
2493
+ fault: error,
2494
+ resumable: keepsState && claimed,
2495
+ });
2496
+ }
2114
2497
  pipeline.log?.(`#${ticket} handed off at ${failure.point} · ${failure.summary}`);
2115
2498
 
2116
2499
  return {
@@ -2126,20 +2509,80 @@ async function handOff(
2126
2509
  }
2127
2510
 
2128
2511
  /**
2129
- * Keep the transcripts of the Stages this Run ran for a handed-off Ticket on
2130
- * the remote, where a human can still read them once this Host is gone, and
2131
- * say where.
2512
+ * The ending of a hand-off a fault outside the Ticket cut short.
2132
2513
  *
2133
- * Nothing when that fails, and the failure logged: the hand-off is what a
2134
- * human is waiting for, and the transcripts are still on this Host for as long
2135
- * as it lasts.
2514
+ * Reported released only where the next Run picks the Ticket up by itself: the
2515
+ * hand-off kept the state file and the Ticket still wears its claim, so it is
2516
+ * resumed as a Stranded Ticket. Anywhere else nothing sweeps it: one whose
2517
+ * state file went before the writes, or one left assigned once `in-progress`
2518
+ * came off, waits for a human, so it is reported handed off, with the fault
2519
+ * beside the failure it was being handed off for. Either way the Run claims
2520
+ * no more, as over any fault of the kind.
2521
+ */
2522
+ function cutShort(
2523
+ pipeline: Pipeline,
2524
+ {
2525
+ issue,
2526
+ branch,
2527
+ failure,
2528
+ pullRequest,
2529
+ notes,
2530
+ fault,
2531
+ resumable,
2532
+ }: {
2533
+ issue: Issue;
2534
+ branch: string;
2535
+ failure: TicketFailure;
2536
+ pullRequest: number | undefined;
2537
+ notes: RoutedNote[];
2538
+ fault: OutsideFault;
2539
+ resumable: boolean;
2540
+ },
2541
+ ): TicketOutcome {
2542
+ const ticket = issue.number;
2543
+ if (resumable) {
2544
+ pipeline.log?.(`#${ticket} could not be handed off at ${failure.point} · ${fault.message}`);
2545
+ return faultOutcome(issue, branch, failure.point, fault, notes);
2546
+ }
2547
+ pipeline.log?.(
2548
+ `#${ticket} handed off at ${failure.point}, but the hand-off was cut short · ${fault.message}`,
2549
+ );
2550
+ return {
2551
+ outcome: "handed-off",
2552
+ ticket,
2553
+ title: issue.title,
2554
+ branch,
2555
+ stage: failure.point,
2556
+ failure: failure.summary,
2557
+ ...(pullRequest === undefined ? {} : { pullRequest }),
2558
+ fault: { side: fault.side, command: fault.command, line: fault.line },
2559
+ notes,
2560
+ };
2561
+ }
2562
+
2563
+ /**
2564
+ * Keep the transcripts of the Stages this Run ran for a handed-off Ticket where
2565
+ * the Run keeps them, and say where: on the remote, where a human can still
2566
+ * read them once this Host is gone, or off it, on this Host, for a Run whose
2567
+ * Target would publish them (ADR-0004).
2568
+ *
2569
+ * Nothing when the Run wrote none for the Ticket, and nothing when keeping
2570
+ * them fails, the failure logged: the hand-off is what a human is waiting for,
2571
+ * and the transcripts are still on this Host for as long as it lasts.
2136
2572
  */
2137
2573
  async function keepTranscripts(
2138
2574
  pipeline: Pipeline,
2139
2575
  ticket: number,
2140
- ): Promise<KeptTranscripts | undefined> {
2576
+ ): Promise<TranscriptsPlace | undefined> {
2577
+ const { transcriptHome, workspace, runId } = pipeline;
2141
2578
  try {
2142
- return await pipeline.workspace.keepTranscripts(ticket, pipeline.runId);
2579
+ if (transcriptHome === "remote") {
2580
+ const kept = await workspace.keepTranscripts(ticket, runId);
2581
+ return kept === undefined ? undefined : { on: "remote", ...kept };
2582
+ }
2583
+ const path = await workspace.transcriptsOnHost(ticket, runId);
2584
+ if (path === undefined) return undefined;
2585
+ return transcriptHome === "cloud" ? { on: "cloud" } : { on: "workstation", path };
2143
2586
  } catch (error) {
2144
2587
  pipeline.log?.(
2145
2588
  `#${ticket} handed off, but keeping its transcripts failed: ${(error as Error).message}`,