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
@@ -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,8 +47,10 @@ 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 {
53
+ type BranchFailure,
50
54
  RELEASE_WORDS,
51
55
  releaseWords,
52
56
  draftPullRequestBody,
@@ -55,15 +59,33 @@ import {
55
59
  guardComment,
56
60
  handoffComment,
57
61
  hasGuardWarning,
62
+ LEFT_TO_HUMAN,
63
+ mergeByHandComment,
58
64
  pullRequestBody,
59
65
  squashCommit,
66
+ type TranscriptsPlace,
60
67
  } from "./templates.js";
61
68
  import type { StartTimer } from "./timer.js";
62
- import { CODE_STAGE_JSON_SCHEMA, parseTitle, pullRequestTitle } from "./title.js";
69
+ import type { TranscriptHome } from "./transcript-home.js";
63
70
  import {
71
+ BRANCH_PROSE_FIELDS,
72
+ type BranchProse,
73
+ CODE_STAGE_JSON_SCHEMA,
74
+ parseBranchProse,
75
+ parseNoCommitReason,
76
+ parseTitle,
77
+ pullRequestTitle,
78
+ } from "./title.js";
79
+ import {
80
+ type AnsweredVerdict,
81
+ type Defect,
82
+ type GradedCriterion,
83
+ type Misnumbered,
64
84
  type Verdict,
65
85
  VERDICT_JSON_SCHEMA,
66
86
  countStatuses,
87
+ gradeVerdict,
88
+ isMisnumbered,
67
89
  parseVerdict,
68
90
  passes,
69
91
  unmetCriteria,
@@ -88,6 +110,13 @@ export type TicketOutcome =
88
110
  stage: FailurePoint;
89
111
  failure: string;
90
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 };
91
120
  notes: RoutedNote[];
92
121
  }
93
122
  | {
@@ -104,8 +133,13 @@ export type TicketOutcome =
104
133
  * told. Absent for an API failure, which says nothing of when it ends.
105
134
  */
106
135
  limitResetsAt?: string;
107
- /** The Check the Base branch fails, and where, for a Release over it. */
136
+ /** The Check the base branch fails, and where, for a Release over it. */
108
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;
109
143
  notes: RoutedNote[];
110
144
  }
111
145
  | {
@@ -125,16 +159,11 @@ export interface Pipeline {
125
159
  repoRoot: string;
126
160
  runId: string;
127
161
  /**
128
- * The Version this Run is, resolved once in the CLI and stamped on everything
162
+ * The version this Run is, resolved once in the CLI and stamped on everything
129
163
  * the Run writes (ADR-0007). A string, never a lookup: nothing here reads
130
164
  * `package.json` or runs git, so every stamp of one Run is the same string.
131
165
  */
132
166
  version: string;
133
- /**
134
- * The Host the Run is on, which decides whether a merged pull request's body
135
- * can point at the Run's directory: a cloud Host's is gone with its session.
136
- */
137
- host: HostKind;
138
167
  /**
139
168
  * What every Stage of this Run is billed to, chosen once when it started:
140
169
  * the subscription, or the Host's API key for a Run started with `--api-key`.
@@ -155,7 +184,7 @@ export interface Pipeline {
155
184
  /**
156
185
  * The Run's Landing, made once before the first Ticket and shared by every
157
186
  * Ticket it drives: only one of them is between its rebase and the pull of
158
- * the Base branch after its merge at a time (ADR-0005).
187
+ * the base branch after its merge at a time (ADR-0005).
159
188
  */
160
189
  landing: Landing;
161
190
  /**
@@ -165,9 +194,9 @@ export interface Pipeline {
165
194
  */
166
195
  standingNotes: StandingNotes;
167
196
  /**
168
- * The Checks the Run ran at merge-bases with the Base branch, made once and
197
+ * The Checks the Run ran at merge-bases with the base branch, made once and
169
198
  * shared by every Ticket: the Tickets that fail together over one broken
170
- * Base branch run the Check there once between them, and post one Note.
199
+ * base branch run the Check there once between them, and post one Note.
171
200
  */
172
201
  baseChecks: BaseBranchChecks;
173
202
  /**
@@ -177,6 +206,12 @@ export interface Pipeline {
177
206
  * there is a Stage told to exercise it through its tests and fakes.
178
207
  */
179
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;
180
215
  /**
181
216
  * How the Run waits between its looks at the Frontier while a Lane is free
182
217
  * and another busy: the real clock, unless a test hands it one it moves
@@ -190,6 +225,10 @@ export interface Pipeline {
190
225
  * A failure that ends the Ticket, unless the fix budget can still buy it a
191
226
  * second try. `kind` is set on exactly the failures a fix Stage is given:
192
227
  * everything else is a hand-off the moment it is thrown.
228
+ *
229
+ * `reason` is set on exactly one failure of each code Stage: the Stage
230
+ * finished and left no new commit, and it said why. The hand-off quotes it, and
231
+ * since it lives on this failure alone, no other hand-off of the Ticket can.
193
232
  */
194
233
  class TicketFailure extends Error {
195
234
  constructor(
@@ -197,19 +236,39 @@ class TicketFailure extends Error {
197
236
  readonly summary: string,
198
237
  readonly evidence: string = "",
199
238
  readonly kind?: FailureKind,
239
+ readonly reason?: string,
200
240
  ) {
201
241
  super(summary);
202
242
  }
203
243
  }
204
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
+
205
257
  /**
206
258
  * What stops a Ticket that says nothing about it: the rate limit, a transient
207
259
  * API failure — the API overloaded, broken or silent on its own side after the
208
260
  * CLI had already retried it — the API key of an `--api-key` Run out of credit
209
- * or past its workspace's spend limit, and a Base branch that fails the Check
210
- * 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}).
211
264
  */
212
- 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
+ }
213
272
 
214
273
  /** The Stage failures among them. */
215
274
  type StageReleaseCause = Extract<StageFailure, "rate-limited" | "api-error" | "out-of-budget">;
@@ -226,7 +285,7 @@ function releaseCause(result: StageResult): StageReleaseCause | undefined {
226
285
  * A Stage something other than the Ticket stopped, on its way to a Release.
227
286
  *
228
287
  * The Stage failures that say nothing about the Ticket are the ones that
229
- * neither end it nor spend its Fix budget: the Claim is released and a State
288
+ * neither end it nor spend its fix budget: the claim is released and a state
230
289
  * file is left for the next Run to resume from (ADR-0004). It is not a
231
290
  * {@link TicketFailure} because every path that handles one of those would
232
291
  * either hand the Ticket off or buy it a fix Stage, and this is neither.
@@ -238,13 +297,40 @@ class Releasing extends Error {
238
297
  readonly state: ReachedState,
239
298
  readonly reason: ReleaseCause,
240
299
  readonly limitResetsAt?: string,
241
- /** The Check the Base branch fails too, for a Release over it. */
242
- readonly failingBase?: FailingBase,
300
+ /** The Check the base branch fails too, for a Release over it. */
301
+ readonly failingBase?: InheritedFailure,
302
+ /** What GitHub or the remote failed, for a Release over a fault outside the Ticket. */
303
+ readonly fault?: OutsideFaultSeen,
243
304
  ) {
244
305
  super(`the ${point} Stage was stopped · ${RELEASE_WORDS[reason]}`);
245
306
  }
246
307
  }
247
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
+
327
+ /**
328
+ * A Check the base branch fails, and how the branch itself failed, which the
329
+ * Note about it quotes beside the merge-base's output: only the command is
330
+ * compared, so the two need not be the same failure.
331
+ */
332
+ type InheritedFailure = FailingBase & { onBranch: BranchFailure };
333
+
248
334
  /** An error the pipeline did not raise itself, blamed on the step it was on. */
249
335
  function asTicketFailure(error: unknown, point: FailurePoint): TicketFailure {
250
336
  return error instanceof TicketFailure
@@ -256,18 +342,18 @@ function asTicketFailure(error: unknown, point: FailurePoint): TicketFailure {
256
342
  * Take one Ticket from claimed to merged, hand it to a human, or pass it over.
257
343
  *
258
344
  * The happy path is: guards → claim → worktree and branch → implement Stage →
259
- * Checks → verify Stage → rebase → PR → CI → squash merge → cleanup. Work left
260
- * uncommitted, a failing Check, an unmet criterion, a red CI or a rebase
261
- * conflict the conflict Stage could not resolve spends the Ticket's fix budget
262
- * and starts again at the Checks; every other failure, and every second
263
- * failure, ends in a hand-off.
264
- * Nothing ends in a merge that has not been through a green pass of the whole
265
- * gauntlet.
345
+ * Checks → verify Stage → rebase → pull request → CI → squash merge → cleanup.
346
+ * Work left uncommitted, a failing Check, an unmet criterion, a red CI or a
347
+ * rebase conflict the conflict Stage could not resolve spends the Ticket's fix
348
+ * budget and starts again at the Checks; every other failure, and every second
349
+ * failure, ends in a hand-off. Nothing ends in a merge that has not been
350
+ * through a green pass of the whole gauntlet.
266
351
  *
267
352
  * A Stage the subscription rate limit or a transient API failure stopped ends
268
353
  * none of that: the Ticket is released, and a Run started once the limit has
269
354
  * reset, or the API recovered, resumes it from the state it had reached rather
270
- * 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
271
357
  * human who relabels the Ticket `ready-for-agent` hands it back and the next Run
272
358
  * carries on from what it reached rather than paying for the implement Stage a
273
359
  * second time.
@@ -277,9 +363,9 @@ function asTicketFailure(error: unknown, point: FailurePoint): TicketFailure {
277
363
  * untriaged from its Frontier, but the Ticket may have changed hands since the
278
364
  * listing, so the guards ask again.
279
365
  *
280
- * From the pull of the Base branch before the rebase to the pull after the
281
- * merge the Ticket holds the Run's Landing, so no other Ticket of the same Run moves the Base
282
- * branch underneath the branch CI is grading (ADR-0005).
366
+ * From the pull of the base branch before the rebase to the pull after the
367
+ * merge the Ticket holds the Run's Landing, so no other Ticket of the same Run
368
+ * moves the base branch underneath the branch CI is grading (ADR-0005).
283
369
  */
284
370
  export async function processTicket(
285
371
  pipeline: Pipeline,
@@ -318,7 +404,7 @@ async function takeTicket(
318
404
 
319
405
  // What an earlier Run left behind, read before the guards because it decides
320
406
  // one of them: a Ticket this pipeline still holds with state recorded for it is
321
- // stranded — the Claim on it is this pipeline's own, left by a Run that never
407
+ // stranded — the claim on it is this pipeline's own, left by a Run that never
322
408
  // came back — and the refusals must not read it as somebody else's.
323
409
  const recorded = await workspace.readState(ticket);
324
410
  const stranded = recorded !== undefined && holdsClaim(issue, user, config.labels.inProgress);
@@ -345,12 +431,12 @@ async function takeTicket(
345
431
  log,
346
432
  });
347
433
 
348
- // The State file, written as part of the Claim and kept current from here on,
434
+ // The state file, written as part of the claim and kept current from here on,
349
435
  // so a Run that is killed mid-Ticket — or a human handed the Ticket — still
350
436
  // leaves the next Run something to resume. A resumed Ticket carries on from
351
437
  // what it had already reached.
352
438
  //
353
- // First of the two, because a Claim no State file names is the one thing this
439
+ // First of the two, because a claim no state file names is the one thing this
354
440
  // has to rule out: a crash between the writes then leaves a Ticket nobody has
355
441
  // claimed with state beside it, which is a released Ticket and resumes itself.
356
442
  const record = await ResumeRecord.claim(pipeline, {
@@ -360,18 +446,16 @@ async function takeTicket(
360
446
  fixUsed: resume?.fixUsed ?? false,
361
447
  ...(resume?.pullRequest === undefined ? {} : { pullRequest: resume.pullRequest }),
362
448
  ...(resume?.title === undefined ? {} : { title: resume.title }),
449
+ ...(resume === undefined ? {} : recordedProse(resume)),
363
450
  ...(resume?.rebaseFirst === true ? { rebaseFirst: true } : {}),
364
451
  });
365
452
 
366
453
  // The claim is the first write on the board: it shows what the pipeline holds
367
454
  // before anything else can go wrong. A stranded Ticket is resumed in place,
368
- // wearing the Claim it never gave up — re-writing what is already there would
455
+ // wearing the claim it never gave up — re-writing what is already there would
369
456
  // only risk the Ticket on three tracker calls that change nothing.
370
- if (!stranded) {
371
- await tracker.assign(ticket, user);
372
- await tracker.addLabel(ticket, config.labels.inProgress);
373
- await tracker.removeLabel(ticket, config.labels.readyForAgent);
374
- }
457
+ //
458
+ if (!stranded) await writeClaim(pipeline, ticket, user);
375
459
  log(`#${ticket} ${howItWasTaken(resume, stranded)} · ${branch}`);
376
460
 
377
461
  // Whatever hand-off left this Ticket to a human is no longer the last word on
@@ -400,9 +484,15 @@ async function takeTicket(
400
484
  // The pass behind a fix Stage logs beside the first one rather than over it.
401
485
  let logDir = stageLogDir(repoRoot, runId, ticket);
402
486
  // The unmet criteria the fix Stage was sent in for, and their evidence, which
403
- // the verify behind it is held to. Only this Run's: the State file keeps no
404
- // Verdict, so a retry a later Run resumes is graded without them.
487
+ // the verify behind it is held to. Only this Run's: the state file keeps no
488
+ // verdict, so a retry a later Run resumes is graded without them.
405
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)]);
406
496
 
407
497
  // Declared out here because ticking the Acceptance Criteria it proved happens
408
498
  // after the merge, where a failure may no longer hand the Ticket off.
@@ -430,7 +520,7 @@ async function takeTicket(
430
520
  // Where the branch is decides what the human is asked to do about it:
431
521
  // a branch that is checked out cannot simply be deleted, so the human
432
522
  // is sent to the worktree holding it instead. Nothing the pipeline left
433
- // is here — a Ticket it handed off keeps its State file and resumes
523
+ // is here — a Ticket it handed off keeps its state file and resumes
434
524
  // without ever reaching this — so the branch is a human's either way.
435
525
  const checkedOutAt = (await workspace.hasWorktree({ path: worktree, branch }))
436
526
  ? worktree
@@ -442,7 +532,11 @@ async function takeTicket(
442
532
  checkedOutAt === undefined ? undefined : { path: checkedOutAt, pushable: false };
443
533
  throw new TicketFailure(
444
534
  "setup",
445
- describeBranchInTheWay(branch, checkedOutAt, config.labels.readyForAgent),
535
+ describeBranchInTheWay(
536
+ branch,
537
+ checkedOutAt === undefined ? undefined : inCheckout(repoRoot, checkedOutAt),
538
+ config.labels.readyForAgent,
539
+ ),
446
540
  );
447
541
  }
448
542
  await workspace.createWorktree({ path: worktree, branch }, baseBranch);
@@ -456,7 +550,7 @@ async function takeTicket(
456
550
  }
457
551
  if (resume === undefined || resume.state === "claimed") {
458
552
  point = "implement";
459
- await implement(pipeline, issue, worktree, branch, logDir, progress, notes, record);
553
+ await implement(pipeline, issue, worktree, branch, logDir, progress, { notes, written }, record);
460
554
  // The branch now carries work no later Run should pay for again.
461
555
  await record.advance({ state: "implemented" });
462
556
  }
@@ -464,8 +558,8 @@ async function takeTicket(
464
558
  let commits: string[];
465
559
  let coAuthors: string[];
466
560
  let title: string;
467
- // Owed once, by a Ticket released over a failing Base branch, and inside
468
- // the passes rather than before them: a conflict it meets spends the Fix
561
+ // Owed once, by a Ticket released over a failing base branch, and inside
562
+ // the passes rather than before them: a conflict it meets spends the fix
469
563
  // budget as one at the Landing does.
470
564
  let rebaseOwed = resume?.rebaseFirst === true;
471
565
 
@@ -485,14 +579,18 @@ async function takeTicket(
485
579
  await requireCommitted(pipeline, worktree, progress);
486
580
  await runChecks(pipeline, worktree, progress);
487
581
  point = "verify";
488
- 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
+ });
489
587
 
490
588
  point = "rebase";
491
- // The Landing, from here until the Base branch has been pulled: the
492
- // Ticket waits its turn, and the Base branch it rebases onto is then
589
+ // The Landing, from here until the base branch has been pulled: the
590
+ // Ticket waits its turn, and the base branch it rebases onto is then
493
591
  // the one its merge will land on.
494
592
  await landing.enter();
495
- // Up to the remote first: a Base branch the checkout holds behind it
593
+ // Up to the remote first: a base branch the checkout holds behind it
496
594
  // is a rebase that changes nothing and a pull request that conflicts,
497
595
  // which GitHub then runs no CI for. One that cannot be brought up is a
498
596
  // failure here, since rebasing onto it would be the same mistake.
@@ -512,7 +610,7 @@ async function takeTicket(
512
610
  progress,
513
611
  );
514
612
  // The resolution is code nothing has graded: the Checks passed on one
515
- // side of the conflict and CI on the other. The Verdict is not asked
613
+ // side of the conflict and CI on the other. The verdict is not asked
516
614
  // for again, because the conflict Stage is told to change no
517
615
  // behaviour the Acceptance Criteria are about.
518
616
  point = "checks";
@@ -529,7 +627,7 @@ async function takeTicket(
529
627
  title = pullRequestTitle(record.title, commits, issue.title);
530
628
  pullRequest = await publishPullRequest(
531
629
  pipeline,
532
- { issue, branch, worktree, verdict, title },
630
+ { issue, branch, worktree, title, body: record.prose.body },
533
631
  pullRequest,
534
632
  );
535
633
  await record.advance({ pullRequest });
@@ -537,9 +635,10 @@ async function takeTicket(
537
635
  await requireGreenCi(pipeline, worktree, pullRequest, progress, landing);
538
636
  break;
539
637
  } catch (error) {
540
- // A rate limit or an API failure is nobody's defect, so the fix budget
541
- // does not answer for it: the Ticket is released, whole, further up.
542
- 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;
543
642
  const failure = asTicketFailure(error, point);
544
643
  if (fixUsed || failure.kind === undefined) throw failure;
545
644
  fixUsed = true;
@@ -558,7 +657,7 @@ async function takeTicket(
558
657
  logDir,
559
658
  { kind: failure.kind, summary: failure.summary, evidence: failure.evidence },
560
659
  progress,
561
- notes,
660
+ { notes, written },
562
661
  record,
563
662
  );
564
663
  // Recorded once the Stage has come back, not when the budget was
@@ -569,30 +668,52 @@ async function takeTicket(
569
668
  }
570
669
 
571
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
+ }
572
678
  await tracker.squashMerge(
573
679
  pullRequest,
574
- 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
+ }),
575
689
  );
576
690
  await progress.record({ point: "merge", outcome: `✅ #${pullRequest}` });
691
+ await progress.settle();
577
692
  } catch (error) {
578
693
  // Out of the Landing before either ending is written: a hand-off's draft
579
694
  // pull request and a Release's labels are nothing for the next Ticket to
580
695
  // wait behind, and a Ticket that never reached the rebase gives up nothing.
581
696
  landing.leave();
582
- 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) {
583
702
  return release(pipeline, {
584
703
  issue,
585
704
  user,
586
705
  branch,
587
- stopped: error,
706
+ stopped,
588
707
  record,
589
708
  // A fix Stage stopped before it ran spends nothing: the budget is
590
709
  // still there for the Run that resumes the Ticket.
591
- fixUsed: fixUsed && error.point !== "fix",
710
+ fixUsed: fixUsed && stopped.point !== "fix",
711
+ progress,
592
712
  notes,
593
713
  });
594
714
  }
595
- return handOff(pipeline, {
715
+ const failure = asTicketFailure(error, point);
716
+ return await handOff(pipeline, {
596
717
  issue,
597
718
  user,
598
719
  branch,
@@ -601,22 +722,23 @@ async function takeTicket(
601
722
  // and whichever side a human keeps is one a later Run resumes from.
602
723
  keepsState: found?.refusal !== undefined || worktreeOnDisk?.pushable === true,
603
724
  pullRequest,
604
- failure: asTicketFailure(error, point),
725
+ failure,
605
726
  fixUsed,
606
727
  record,
728
+ progress,
607
729
  notes,
608
730
  });
609
731
  }
610
732
 
611
733
  // The Ticket is merged from here on, so nothing below may hand it off, and
612
734
  // it is still in the Landing: the pull below is the last of it.
613
- // The State file goes first: a merged Ticket must not look resumable to the
735
+ // The state file goes first: a merged Ticket must not look resumable to the
614
736
  // next Run, whatever else below fails — which is worth the Landing staying
615
737
  // shut for three writes nobody else is waiting on.
616
738
  try {
617
739
  await workspace.removeState(ticket);
618
740
  } catch (error) {
619
- log(`#${ticket} merged, but clearing its State file failed: ${(error as Error).message}`);
741
+ log(`#${ticket} merged, but clearing its state file failed: ${(error as Error).message}`);
620
742
  }
621
743
  try {
622
744
  await tickMetCriteria(tracker, ticket, verdict, log);
@@ -631,7 +753,7 @@ async function takeTicket(
631
753
  }
632
754
  try {
633
755
  await workspace.pullBase(baseBranch);
634
- // The pull ends the Landing: the next Ticket now rebases onto a Base branch
756
+ // The pull ends the Landing: the next Ticket now rebases onto a base branch
635
757
  // that already carries this one, and the cleanup below holds nobody up.
636
758
  landing.leave();
637
759
  await workspace.removeWorktree({ path: worktree, branch });
@@ -651,9 +773,10 @@ async function takeTicket(
651
773
  * Run log each carry. It names the branch twice on purpose: once as the thing
652
774
  * that is in the way, and once inside the command that clears it.
653
775
  *
654
- * `checkedOutAt` is the worktree the branch is in, when it is in one: a branch
655
- * git will not let go of is not one `git branch -D` can delete, so being told
656
- * 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.
657
780
  */
658
781
  function describeBranchInTheWay(
659
782
  branch: string,
@@ -681,7 +804,7 @@ interface Resumable {
681
804
  /**
682
805
  * Why it cannot, when it cannot: this Host's copy of the branch has parted
683
806
  * from the remote one, or the worktree could not be made ready at all.
684
- * Either is a hand-off at setup, and the State stays.
807
+ * Either is a hand-off at setup, and the state stays.
685
808
  */
686
809
  refusal?: string;
687
810
  /** The worktree the branch is checked out in, for a refusal to send a human to. */
@@ -692,7 +815,7 @@ interface Resumable {
692
815
  * The state an earlier Run left for this Ticket, if a Run can still resume it,
693
816
  * with the worktree it resumes in made ready.
694
817
  *
695
- * The State file only names where the work is; where the work actually is, is
818
+ * The state file only names where the work is; where the work actually is, is
696
819
  * the Workspace's answer, and the branch on the remote is what it answers from
697
820
  * (ADR-0004). Any Host's Run pushes it each time a Stage commits, so a Host
698
821
  * with no worktree of the Ticket makes one from it, and one that still has a
@@ -713,13 +836,16 @@ async function resumable(
713
836
  if (state === undefined) return undefined;
714
837
  const ref = { path: worktree, branch: state.branch };
715
838
  // Caught here, because nothing is claimed yet: the refusal is raised once the
716
- // Claim is made, as a hand-off a human can see on the board.
839
+ // claim is made, as a hand-off a human can see on the board.
717
840
  let found: WorktreeFromRemote;
718
841
  let checkedOut: boolean;
719
842
  try {
720
843
  found = await pipeline.workspace.worktreeFromRemote(ref);
721
844
  checkedOut = found === "parted" && (await pipeline.workspace.hasWorktree(ref));
722
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;
723
849
  return {
724
850
  state,
725
851
  refusal: `the worktree of ${state.branch} could not be made ready to resume in: ${(error as Error).message}`,
@@ -730,7 +856,11 @@ async function resumable(
730
856
  const checkedOutAt = checkedOut ? worktree : undefined;
731
857
  return {
732
858
  state,
733
- 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
+ ),
734
864
  ...(checkedOutAt === undefined ? {} : { checkedOutAt }),
735
865
  };
736
866
  }
@@ -738,7 +868,7 @@ async function resumable(
738
868
  pipeline.log?.(
739
869
  `#${ticket} was resumable, but ${state.branch} is neither in ${worktree} nor on the remote`,
740
870
  );
741
- // Logged and nothing more when it fails: the Claim writes this Ticket's State
871
+ // Logged and nothing more when it fails: the claim writes this Ticket's state
742
872
  // over it in a moment, from the top.
743
873
  try {
744
874
  await pipeline.workspace.removeState(ticket);
@@ -753,7 +883,8 @@ async function resumable(
753
883
  * one on the remote: which two copies, and the two ways to make them one.
754
884
  *
755
885
  * One line, as for {@link describeBranchInTheWay}. `checkedOutAt` is the
756
- * 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.
757
888
  */
758
889
  function describeParted(
759
890
  branch: string,
@@ -775,11 +906,21 @@ function describeParted(
775
906
  );
776
907
  }
777
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
+
778
919
  /**
779
920
  * How this Run came by the Ticket, for the one line it logs about it: resumed
780
921
  * from a recorded state, taken from the top, or claimed outright. A stranded
781
922
  * Ticket with nothing left to resume into is the middle one — it is started
782
- * again, but the Claim it is started under is the one it already had.
923
+ * again, but the claim it is started under is the one it already had.
783
924
  */
784
925
  function howItWasTaken(resume: TicketState | undefined, stranded: boolean): string {
785
926
  if (resume !== undefined) return `resumed from ${resume.state}`;
@@ -791,14 +932,17 @@ type Reached = Omit<TicketState, "runId" | "updatedAt">;
791
932
 
792
933
  /** What one write moves that on by. */
793
934
  type Advance = Partial<
794
- Pick<Reached, "state" | "fixUsed" | "pullRequest" | "title" | "rebaseFirst">
935
+ Pick<
936
+ Reached,
937
+ "state" | "fixUsed" | "pullRequest" | "title" | "body" | "problem" | "solution" | "rebaseFirst"
938
+ >
795
939
  >;
796
940
 
797
941
  /**
798
- * The State file a Ticket keeps, and the one place a Ticket writes it.
942
+ * The state file a Ticket keeps, and the one place a Ticket writes it.
799
943
  *
800
944
  * A Ticket is resumable for as long as its branch carries work worth resuming,
801
- * so the file is written as part of the Claim and rewritten whenever the Ticket
945
+ * so the file is written as part of the claim and rewritten whenever the Ticket
802
946
  * reaches something a later Run should not pay for again. The release is one
803
947
  * more such write rather than the only one, which is what makes a Run that was
804
948
  * killed recoverable too, and the hand-off is another.
@@ -820,12 +964,12 @@ class ResumeRecord {
820
964
  }
821
965
 
822
966
  /**
823
- * Record what the Claim is about to make true, and hand back the record that
967
+ * Record what the claim is about to make true, and hand back the record that
824
968
  * keeps it current.
825
969
  *
826
- * The one write that is allowed to fail the Ticket. It runs before the Claim,
970
+ * The one write that is allowed to fail the Ticket. It runs before the claim,
827
971
  * so a remote that will not take the file costs nothing at all: the Ticket ends
828
- * at setup with nothing claimed, where carrying on would put a Claim on the
972
+ * at setup with nothing claimed, where carrying on would put a claim on the
829
973
  * board that no later Run could ever resume — which is the state this record
830
974
  * exists to rule out.
831
975
  */
@@ -835,11 +979,21 @@ class ResumeRecord {
835
979
  return record;
836
980
  }
837
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
+
838
987
  /** The latest title a Stage answered for the branch, in this Run or an earlier one. */
839
988
  get title(): string | undefined {
840
989
  return this.reached.title;
841
990
  }
842
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
+
843
997
  /**
844
998
  * Move the record on, and put it where the next Run will look for it.
845
999
  *
@@ -860,12 +1014,12 @@ class ResumeRecord {
860
1014
  }
861
1015
 
862
1016
  /**
863
- * The Run, the Version and the time belong to the write, not to what the
1017
+ * The Run, the version and the time belong to the write, not to what the
864
1018
  * Ticket reached: they say which pipeline left the file, so a Run that cannot
865
1019
  * read one can still name what wrote it (ADR-0007).
866
1020
  */
867
1021
  private file(): TicketState {
868
- // Written only while it is owed, so a State file says nothing of a rebase
1022
+ // Written only while it is owed, so a state file says nothing of a rebase
869
1023
  // nobody has to do.
870
1024
  const { rebaseFirst, ...reached } = this.reached;
871
1025
  return {
@@ -895,7 +1049,7 @@ async function passOver(
895
1049
 
896
1050
  if (isGuardReason(reason)) {
897
1051
  if (!hasGuardWarning(issue.comments, reason)) {
898
- await tracker.comment(issue.number, guardComment(reason));
1052
+ await tracker.comment(issue.number, guardComment(reason, tickedBoxes(issue)));
899
1053
  }
900
1054
  // A Spec is not a Ticket and no edit will make it one; the other two are
901
1055
  // fixable in place, so their candidates keep the label and stay visible.
@@ -913,8 +1067,8 @@ async function passOver(
913
1067
  * config names. Everything a Stage differs in is the prompt, where it runs and
914
1068
  * where it logs; the limits come from one place so no Stage can quietly skip them.
915
1069
  *
916
- * The credential is the Run's too, and what the Stage says it actually ran on
917
- * is checked here for the same reason: a Stage billed somewhere the Run did not
1070
+ * What the Stages are billed to is the Run's too, and what the Stage says it
1071
+ * actually ran on is checked here for the same reason: a Stage billed somewhere the Run did not
918
1072
  * choose is named whichever Stage it was.
919
1073
  */
920
1074
  async function runStage(
@@ -952,8 +1106,8 @@ async function runStage(
952
1106
 
953
1107
  /**
954
1108
  * Add a Stage to what the Run was billed, and name it in the log now when its
955
- * `system/init` event reported another `apiKeySource` than the Run's credential
956
- * expects; the summary names it again at the end. A Stage that reported none,
1109
+ * `system/init` event reported another `apiKeySource` than the Run's
1110
+ * subscription or API key expects; the summary names it again at the end. A Stage that reported none,
957
1111
  * one that never started, is not named: there is nothing it said to set
958
1112
  * against the Run's choice. The log line carries no amount: the summary is the
959
1113
  * only place one is printed.
@@ -1042,7 +1196,12 @@ async function collectNotes(
1042
1196
  stage: NotingStage,
1043
1197
  result: StageResult,
1044
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[],
1045
1201
  ): Promise<void> {
1202
+ if (written !== undefined && stage !== "verify") {
1203
+ written.push(...parseNotes(result.result).map((note) => ({ stage, note })));
1204
+ }
1046
1205
  notes.push(
1047
1206
  ...(await routeNotes(
1048
1207
  {
@@ -1058,15 +1217,32 @@ async function collectNotes(
1058
1217
  }
1059
1218
 
1060
1219
  /**
1061
- * Record the title a code Stage answered for the whole branch, when it answered
1062
- * 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.
1063
1224
  *
1064
- * One that does not count costs the title alone, as a malformed Note costs that
1065
- * 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.
1066
1228
  */
1067
- async function recordTitle(result: StageResult, record: ResumeRecord): Promise<void> {
1229
+ async function recordAnswers(result: StageResult, record: ResumeRecord): Promise<void> {
1068
1230
  const title = parseTitle(result.result);
1069
- 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;
1070
1246
  }
1071
1247
 
1072
1248
  /** What the Run's standing Notes issue is found — and opened — with. */
@@ -1103,7 +1279,7 @@ async function commitCount(pipeline: Pipeline, branch: string): Promise<number>
1103
1279
  * Push the branch a Stage has just committed on, so the work outlives the Host
1104
1280
  * it was done on and a Run on any Host resumes from it (ADR-0004).
1105
1281
  *
1106
- * A push that does not land is logged and nothing more, as a State write that
1282
+ * A push that does not land is logged and nothing more, as a state write that
1107
1283
  * does not land is: the remote then holds an earlier tip of the same work, and
1108
1284
  * resuming from further back costs a Stage rather than being wrong. The push
1109
1285
  * the pull request needs is a different one, and fails the Ticket where it is.
@@ -1121,6 +1297,35 @@ async function pushCommitted(
1121
1297
  }
1122
1298
  }
1123
1299
 
1300
+ /**
1301
+ * The failure of a code Stage that finished with no new commit, carrying the
1302
+ * reason it gave, if any, for the hand-off to quote. Never one a fix Stage is
1303
+ * bought for: the implement Stage's has nothing to grade, and the fix Stage's
1304
+ * comes after the budget is spent.
1305
+ */
1306
+ function leftNoCommits(
1307
+ stage: "implement" | "fix",
1308
+ evidence: string,
1309
+ result: StageResult,
1310
+ ): TicketFailure {
1311
+ return new TicketFailure(
1312
+ stage,
1313
+ `the ${stage} Stage left no new commits on the branch`,
1314
+ evidence,
1315
+ undefined,
1316
+ parseNoCommitReason(result.result),
1317
+ );
1318
+ }
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
+
1124
1329
  async function implement(
1125
1330
  pipeline: Pipeline,
1126
1331
  issue: Issue,
@@ -1128,7 +1333,7 @@ async function implement(
1128
1333
  branch: string,
1129
1334
  logDir: string,
1130
1335
  progress: Progress,
1131
- notes: RoutedNote[],
1336
+ { notes, written }: CodeStageNotes,
1132
1337
  record: ResumeRecord,
1133
1338
  ): Promise<void> {
1134
1339
  const stage = pipeline.config.stages.implement;
@@ -1145,13 +1350,13 @@ async function implement(
1145
1350
  cwd: worktree,
1146
1351
  logDir,
1147
1352
  jsonSchema: CODE_STAGE_JSON_SCHEMA,
1148
- // The title and the Notes are side channels, not the Stage's product: a
1149
- // session that emitted neither has implemented the Ticket exactly as it
1150
- // always did.
1353
+ // The title, the Notes and the reason for no commit are side channels,
1354
+ // not the Stage's product: a session that emitted none of them has
1355
+ // implemented the Ticket exactly as it always did.
1151
1356
  resultRequired: false,
1152
1357
  });
1153
- await collectNotes(pipeline, issue.number, "implement", result, notes);
1154
- await recordTitle(result, record);
1358
+ await collectNotes(pipeline, issue.number, "implement", result, notes, written);
1359
+ await recordAnswers(result, record);
1155
1360
 
1156
1361
  // Pushed whatever became of the Stage, like its Notes: a session that
1157
1362
  // committed and then was stopped by the rate limit or an API failure still
@@ -1164,28 +1369,26 @@ async function implement(
1164
1369
  // failure, not something to verify. A resumed Ticket's branch is not clean —
1165
1370
  // it carries what the Stage a Release stopped had committed — so this
1166
1371
  // asks the same question there: is there anything at all to grade. Whether it
1167
- // is enough is the Verdict's business, not this guard's.
1372
+ // is enough is the verdict's business, not this guard's. The hand-off quotes
1373
+ // why, where the Stage said.
1168
1374
  if (commits === 0) {
1169
1375
  await progress.record(stageRow("implement", result, "❌ no commits"));
1170
- throw new TicketFailure(
1171
- "implement",
1172
- "the implement Stage left no new commits on the branch",
1173
- );
1376
+ throw leftNoCommits("implement", "", result);
1174
1377
  }
1175
1378
 
1176
1379
  await progress.record(stageRow("implement", result, "✅ committed"));
1177
1380
  }
1178
1381
 
1179
1382
  /**
1180
- * Bring a Ticket released over a failing Base branch up to the Base branch
1383
+ * Bring a Ticket released over a failing base branch up to the base branch
1181
1384
  * before its Checks grade it, so a fix a human has landed there meanwhile
1182
1385
  * reaches the branch. Without it the Ticket would meet the same failure with
1183
1386
  * its budget unspent, and spend it.
1184
1387
  *
1185
- * The pull and the rebase go through the Landing, which is where the Base
1388
+ * The pull and the rebase go through the Landing, which is where the base
1186
1389
  * branch is brought up to the remote's and rebased onto (ADR-0005), and out of
1187
1390
  * it again at once: nothing is merged behind them. A conflict goes to the
1188
- * Conflict Stage as one at the Landing does, outside it, since the rebase
1391
+ * conflict Stage as one at the Landing does, outside it, since the rebase
1189
1392
  * there runs again before the pull request anyway. Left unresolved, the
1190
1393
  * branch would keep the merge-base that fails and be released again by every
1191
1394
  * Run that took it up.
@@ -1255,9 +1458,9 @@ async function runChecks(
1255
1458
  if (!result.ok) {
1256
1459
  const durationMs = Date.now() - startedAt;
1257
1460
  // Asked before the row is written, because the row is what differs: a
1258
- // Check the Base branch fails too is nothing the Ticket did.
1461
+ // Check the base branch fails too is nothing the Ticket did.
1259
1462
  await releaseIfTheBaseFails(pipeline, {
1260
- point: "checks",
1463
+ onBranch: { point: "checks", command, output: result.output, timedOut: result.timedOut },
1261
1464
  worktree,
1262
1465
  commands: [command],
1263
1466
  progress,
@@ -1289,7 +1492,7 @@ async function runChecks(
1289
1492
  }
1290
1493
 
1291
1494
  /**
1292
- * The first of `commands` the Base branch fails, at the commit the branch at
1495
+ * The first of `commands` the base branch fails, at the commit the branch at
1293
1496
  * `worktree` inherited from it, or nothing when it passes them all.
1294
1497
  *
1295
1498
  * Nothing, too, when the merge-base could not be graded at all: the Ticket is
@@ -1315,6 +1518,9 @@ async function inheritedFailure(
1315
1518
  commands,
1316
1519
  );
1317
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;
1318
1524
  pipeline.log?.(
1319
1525
  `could not run the Checks at the merge-base with ${pipeline.baseBranch}: ${(error as Error).message}`,
1320
1526
  );
@@ -1323,7 +1529,7 @@ async function inheritedFailure(
1323
1529
  }
1324
1530
 
1325
1531
  /**
1326
- * Release the Ticket when the Base branch fails one of `commands` too, with the
1532
+ * Release the Ticket when the base branch fails one of `commands` too, with the
1327
1533
  * row that says so; return when it does not, for the caller to charge the
1328
1534
  * failure to the Ticket as it always did.
1329
1535
  *
@@ -1333,13 +1539,14 @@ async function inheritedFailure(
1333
1539
  async function releaseIfTheBaseFails(
1334
1540
  pipeline: Pipeline,
1335
1541
  {
1336
- point,
1542
+ onBranch,
1337
1543
  worktree,
1338
1544
  commands,
1339
1545
  progress,
1340
1546
  durationMs,
1341
1547
  }: {
1342
- point: "checks" | "ci";
1548
+ /** How the branch failed, which is also where: its Checks, or CI. */
1549
+ onBranch: BranchFailure;
1343
1550
  worktree: string;
1344
1551
  commands: readonly string[];
1345
1552
  progress: Progress;
@@ -1350,11 +1557,14 @@ async function releaseIfTheBaseFails(
1350
1557
  const inherited = await inheritedFailure(pipeline, worktree, commands);
1351
1558
  if (inherited === undefined) return;
1352
1559
  await progress.record({
1353
- point,
1354
- outcome: `⏸ \`${inherited.command}\` fails on the Base branch`,
1560
+ point: onBranch.point,
1561
+ outcome: `⏸ \`${inherited.command}\` fails on the base branch`,
1355
1562
  durationMs,
1356
1563
  });
1357
- throw new Releasing(point, "implemented", "failing-base", undefined, inherited);
1564
+ throw new Releasing(onBranch.point, "implemented", "failing-base", undefined, {
1565
+ ...inherited,
1566
+ onBranch,
1567
+ });
1358
1568
  }
1359
1569
 
1360
1570
  /**
@@ -1376,8 +1586,18 @@ async function verify(
1376
1586
  logDir: string,
1377
1587
  progress: Progress,
1378
1588
  notes: RoutedNote[],
1379
- /** The unmet criteria and evidence of the Verdict a fix Stage was sent in for. */
1380
- 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
+ },
1381
1601
  ): Promise<Verdict> {
1382
1602
  const stage = pipeline.config.stages.verify;
1383
1603
  const result = await runStage(pipeline, "verify", {
@@ -1389,6 +1609,7 @@ async function verify(
1389
1609
  pipeline.config.checks,
1390
1610
  await standingNotesNumber(pipeline),
1391
1611
  unmetBefore,
1612
+ { criteria, written },
1392
1613
  ),
1393
1614
  cwd: worktree,
1394
1615
  logDir,
@@ -1396,47 +1617,70 @@ async function verify(
1396
1617
  });
1397
1618
 
1398
1619
  // Before anything else is done with the Stage at all, as the code Stages do
1399
- // it: a session that ran out of turns, or came back with a Verdict nothing
1620
+ // it: a session that ran out of turns, or came back with a verdict nothing
1400
1621
  // can be made of, still noticed whatever it noticed. The scratch work it
1401
1622
  // noticed it in is about to be discarded, so its Notes are all that is left —
1402
1623
  // and a worktree that will not discard them is no reason to lose them too.
1403
1624
  await collectNotes(pipeline, issue.number, "verify", result, notes);
1404
1625
 
1405
- // verify is allowed to write throwaway tests; none of them reach the PR.
1626
+ // verify is allowed to write throwaway tests; none of them reach the pull
1627
+ // request.
1406
1628
  await pipeline.workspace.discardChanges(worktree);
1407
1629
 
1408
1630
  if (!result.ok) throw await stageDidNotFinish(pipeline, progress, "verify", result);
1409
1631
 
1410
- let verdict: Verdict;
1632
+ let answered: AnsweredVerdict;
1411
1633
  try {
1412
- verdict = parseVerdict(result.result);
1634
+ answered = parseVerdict(result.result);
1413
1635
  } catch (error) {
1414
- await progress.record(stageRow("verify", result, "❌ no Verdict"));
1636
+ await progress.record(stageRow("verify", result, "❌ no verdict"));
1415
1637
  throw new TicketFailure(
1416
1638
  "verify",
1417
- "the verify Stage did not return a usable Verdict",
1639
+ "the verify Stage did not return a usable verdict",
1418
1640
  (error as Error).message,
1419
1641
  );
1420
1642
  }
1421
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;
1422
1657
  const counts = countStatuses(verdict);
1423
1658
 
1424
1659
  // The agent's own `pass` is advisory; this is the decision that counts.
1425
1660
  if (!passes(verdict)) {
1426
1661
  const unmet = unmetCriteria(verdict);
1427
- if (unmet.length === 0) {
1662
+ const { defects } = verdict;
1663
+ if (unmet.length === 0 && defects.length === 0) {
1428
1664
  await progress.record(stageRow("verify", result, "❌ no evidence"));
1429
1665
  throw new TicketFailure(
1430
1666
  "verify",
1431
1667
  "every criterion came back unverifiable, so there is no evidence to merge on",
1432
- verdict.criteria.map((c) => `- ${c.text} — ${c.evidence}`).join("\n"),
1668
+ verdict.criteria.map(criterionLine).join("\n"),
1433
1669
  );
1434
1670
  }
1435
- 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}`));
1436
1680
  throw new TicketFailure(
1437
1681
  "verify",
1438
- `${unmet.length} of ${verdict.criteria.length} criteria unmet`,
1439
- unmet.map((c) => `- ${c.text} — ${c.evidence}`).join("\n"),
1682
+ summary,
1683
+ [...unmet.map(criterionLine), ...defects.map(defectLine)].join("\n"),
1440
1684
  "unmet-criteria",
1441
1685
  );
1442
1686
  }
@@ -1447,12 +1691,44 @@ async function verify(
1447
1691
  return verdict;
1448
1692
  }
1449
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
+
1450
1721
  /**
1451
1722
  * What the fix budget buys: a fresh session on the same branch in the same
1452
1723
  * worktree, handed the failure and its evidence and nothing else to do.
1453
1724
  *
1454
- * It drives no plugin skill. The implement skill would re-read the Ticket and
1455
- * 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.
1456
1732
  */
1457
1733
  async function fix(
1458
1734
  pipeline: Pipeline,
@@ -1462,7 +1738,7 @@ async function fix(
1462
1738
  logDir: string,
1463
1739
  failure: FixFailure,
1464
1740
  progress: Progress,
1465
- notes: RoutedNote[],
1741
+ { notes, written }: CodeStageNotes,
1466
1742
  record: ResumeRecord,
1467
1743
  ): Promise<void> {
1468
1744
  const stage = pipeline.config.stages.fix;
@@ -1483,14 +1759,15 @@ async function fix(
1483
1759
  pipeline.selfHosted,
1484
1760
  pipeline.config.checks,
1485
1761
  await standingNotesNumber(pipeline),
1762
+ record.prose,
1486
1763
  ),
1487
1764
  cwd: worktree,
1488
1765
  logDir,
1489
1766
  jsonSchema: CODE_STAGE_JSON_SCHEMA,
1490
1767
  resultRequired: false,
1491
1768
  });
1492
- await collectNotes(pipeline, issue.number, "fix", result, notes);
1493
- await recordTitle(result, record);
1769
+ await collectNotes(pipeline, issue.number, "fix", result, notes, written);
1770
+ await recordAnswers(result, record);
1494
1771
 
1495
1772
  // Pushed whatever became of the Stage, as the implement Stage's work is.
1496
1773
  const grew = (await commitCount(pipeline, branch)) > commitsBefore;
@@ -1498,7 +1775,7 @@ async function fix(
1498
1775
  if (!result.ok) throw await stageDidNotFinish(pipeline, progress, "fix", result);
1499
1776
 
1500
1777
  // A session that came back clean mended nothing, whatever it says. Believing
1501
- // it costs the Ticket a whole second pass of the Checks, the Verdict and CI
1778
+ // it costs the Ticket a whole second pass of the Checks, the verdict and CI
1502
1779
  // over a branch nobody touched, which can only fail the way it just did — and
1503
1780
  // a progress row claiming the Stage committed. The budget is already spent,
1504
1781
  // so this ends the Ticket rather than buying another try.
@@ -1507,16 +1784,14 @@ async function fix(
1507
1784
  // changed: a session that squashed the branch shorter, or amended in place,
1508
1785
  // is read here as having committed nothing.
1509
1786
  //
1510
- // The hand-off carries the evidence the Stage was sent in with. Committing
1787
+ // The hand-off carries the evidence the Stage was sent in with, and the
1788
+ // reason the Stage gave for committing nothing where it gave one. Committing
1511
1789
  // nothing is also how a fix Stage hands back an unmet criterion only a human
1512
- // can settle, and the human then reads the question where it was asked.
1790
+ // can settle, and that reason is the one place it says which, and why: the
1791
+ // evidence it was sent in with need not ask the question at all.
1513
1792
  if (!grew) {
1514
1793
  await progress.record(stageRow("fix", result, "❌ no commits"));
1515
- throw new TicketFailure(
1516
- "fix",
1517
- "the fix Stage left no new commits on the branch",
1518
- failure.evidence,
1519
- );
1794
+ throw leftNoCommits("fix", failure.evidence, result);
1520
1795
  }
1521
1796
 
1522
1797
  await progress.record(stageRow("fix", result, "✅ committed"));
@@ -1645,37 +1920,42 @@ interface PullRequestSubject {
1645
1920
  issue: Issue;
1646
1921
  branch: string;
1647
1922
  worktree: string;
1648
- verdict: Verdict;
1649
1923
  title: string;
1924
+ /** The latest body a Stage answered for the branch, when one has. */
1925
+ body: string | undefined;
1650
1926
  }
1651
1927
 
1652
1928
  /**
1653
1929
  * Push the branch, then open the pull request or bring the open one up to date.
1654
1930
  *
1655
1931
  * A second pass comes back to a pull request that already exists: the push is
1656
- * what GitHub re-runs its checks on, and the title and body are rewritten so
1657
- * the subject and the Verdict a human reads there are the ones that will reach
1658
- * 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.
1659
1935
  *
1660
1936
  * One that already exists is also taken out of draft, because a Ticket resumed
1661
1937
  * after a hand-off comes back to the pull request the hand-off drafted and a
1662
- * 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
1663
1944
  * often runs no workflows at all, so the wait for CI below would read it as
1664
1945
  * "no checks" and end the Ticket before the merge was ever asked for.
1665
1946
  */
1666
1947
  async function publishPullRequest(
1667
1948
  pipeline: Pipeline,
1668
- { issue, branch, worktree, verdict, title }: PullRequestSubject,
1949
+ { issue, branch, worktree, title, body: answered }: PullRequestSubject,
1669
1950
  existing: number | undefined,
1670
1951
  ): Promise<number> {
1671
1952
  await pipeline.workspace.push(worktree, branch);
1672
1953
  const body = pullRequestBody({
1673
1954
  ticket: issue.number,
1674
- verdict,
1675
- runId: pipeline.runId,
1676
- host: pipeline.host,
1955
+ ...(answered === undefined ? {} : { body: answered }),
1677
1956
  });
1678
1957
 
1958
+ existing ??= await openPullRequestOn(pipeline, branch);
1679
1959
  if (existing !== undefined) {
1680
1960
  // Retitled as well, so a title a fix Stage answered after the pull request
1681
1961
  // opened is the one it shows, as it is the subject that lands.
@@ -1695,6 +1975,12 @@ async function publishPullRequest(
1695
1975
  return pr.number;
1696
1976
  }
1697
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
+
1698
1984
  /**
1699
1985
  * A red, unfinished or conflicting pull request is a failure whatever the
1700
1986
  * gates say. Turning `gates.ci` off only tolerates a pull request that has no
@@ -1724,12 +2010,12 @@ async function requireGreenCi(
1724
2010
  // fix Stage, it leaves, and the Checks below take minutes nobody else
1725
2011
  // should wait behind.
1726
2012
  landing.leave();
1727
- // CI's own runs on the Base branch cannot say whether it fails there: a
2013
+ // CI's own runs on the base branch cannot say whether it fails there: a
1728
2014
  // workflow that runs only on pull requests leaves a squash commit with
1729
2015
  // none, and a failure the clock brings starts after its last green run.
1730
2016
  // So the merge-base is graded with the Checks, which CI runs too.
1731
2017
  await releaseIfTheBaseFails(pipeline, {
1732
- point: "ci",
2018
+ onBranch: { point: "ci", summary: outcome.summary, excerpt: outcome.excerpt },
1733
2019
  worktree,
1734
2020
  commands: pipeline.config.checks,
1735
2021
  progress,
@@ -1747,7 +2033,7 @@ async function requireGreenCi(
1747
2033
  `the pull request checks did not finish within ${pipeline.config.ciTimeoutMinutes} minutes`,
1748
2034
  );
1749
2035
  case "conflicting":
1750
- // The Landing keeps the Run's own Tickets from moving the Base branch
2036
+ // The Landing keeps the Run's own Tickets from moving the base branch
1751
2037
  // under a pull request, but not a human merging on GitHub meanwhile. A
1752
2038
  // fix Stage has nothing to act on, so no fix kind: a human takes it.
1753
2039
  await record("❌ conflicting");
@@ -1772,32 +2058,38 @@ interface Release {
1772
2058
  user: string;
1773
2059
  branch: string;
1774
2060
  stopped: Releasing;
1775
- /** The Ticket's State file, which the release brings up to date and leaves. */
2061
+ /** The Ticket's state file, which the release brings up to date and leaves. */
1776
2062
  record: ResumeRecord;
1777
- /** Whether the Fix budget was spent by a failure of the Ticket's own. */
2063
+ /** Whether the fix budget was spent by a failure of the Ticket's own. */
1778
2064
  fixUsed: boolean;
2065
+ /** The progress comment, written once more if its last write failed. */
2066
+ progress: Progress;
1779
2067
  notes: RoutedNote[];
1780
2068
  }
1781
2069
 
1782
2070
  /**
1783
- * Release the Ticket: undo the Claim and leave a State file behind.
2071
+ * Release the Ticket: undo the claim and leave a state file behind.
1784
2072
  *
1785
2073
  * The opposite of a hand-off, and deliberately quiet. Nothing about the Ticket
1786
2074
  * failed, nobody has to look at it, and the work already on its branch is worth
1787
2075
  * keeping — so the branch and the worktree stay, no comment is posted, no draft
1788
2076
  * pull request is opened, and the Ticket goes back on the Frontier for a Run
1789
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.
1790
2082
  */
1791
2083
  async function release(
1792
2084
  pipeline: Pipeline,
1793
- { issue, user, branch, stopped, record, fixUsed, notes }: Release,
2085
+ { issue, user, branch, stopped, record, fixUsed, progress, notes }: Release,
1794
2086
  ): Promise<TicketOutcome> {
1795
2087
  const { tracker, config } = pipeline;
1796
2088
  const ticket = issue.number;
1797
2089
 
1798
- // Brought up to date before the Claim comes off: a Ticket back on the Frontier
2090
+ // Brought up to date before the claim comes off: a Ticket back on the Frontier
1799
2091
  // whose state is out of date is one the next Run would redo Stages for. One
1800
- // released over a failing Base branch is rebased first when it comes back,
2092
+ // released over a failing base branch is rebased first when it comes back,
1801
2093
  // or it would meet the same failure.
1802
2094
  await record.advance({
1803
2095
  state: stopped.state,
@@ -1805,14 +2097,14 @@ async function release(
1805
2097
  ...(stopped.failingBase === undefined ? {} : { rebaseFirst: true }),
1806
2098
  });
1807
2099
  if (stopped.failingBase !== undefined) {
1808
- await noteFailingBase(pipeline, { issue, branch, stopped, failing: stopped.failingBase, notes });
2100
+ await noteFailingBase(pipeline, { issue, branch, failing: stopped.failingBase, notes });
1809
2101
  }
1810
2102
 
1811
- // The claim, undone in the order it was made, so the assignee — which is what
1812
- // another Run reads to tell a taken Ticket from a free one — comes off last.
1813
- await tracker.addLabel(ticket, config.labels.readyForAgent);
1814
- await tracker.removeLabel(ticket, config.labels.inProgress);
1815
- 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);
1816
2108
  pipeline.log?.(
1817
2109
  `#${ticket} released at ${stopped.point} · ${releaseWords(stopped.reason, pipeline.credential)} · ${branch}`,
1818
2110
  );
@@ -1830,14 +2122,96 @@ async function release(
1830
2122
  : {
1831
2123
  failingBase: { commit: stopped.failingBase.commit, command: stopped.failingBase.command },
1832
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 },
1833
2207
  notes,
1834
2208
  };
1835
2209
  }
1836
2210
 
1837
2211
  /**
1838
- * Tell triage the Base branch fails a Check, once this Run per merge-base
2212
+ * Tell triage the base branch fails a Check, once this Run per merge-base
1839
2213
  * commit however many Tickets it releases: the pipeline's own Note, on the
1840
- * standing Notes issue, since the defect is the Base branch's and no Ticket's.
2214
+ * standing Notes issue, since the defect is the base branch's and no Ticket's.
1841
2215
  *
1842
2216
  * Logged and nothing more when it cannot be posted, as a Stage's Note is: the
1843
2217
  * Release is what the Ticket is owed, and the next Ticket released over the
@@ -1848,14 +2222,12 @@ async function noteFailingBase(
1848
2222
  {
1849
2223
  issue,
1850
2224
  branch,
1851
- stopped,
1852
2225
  failing,
1853
2226
  notes,
1854
2227
  }: {
1855
2228
  issue: Issue;
1856
2229
  branch: string;
1857
- stopped: Releasing;
1858
- failing: FailingBase;
2230
+ failing: InheritedFailure;
1859
2231
  notes: RoutedNote[];
1860
2232
  },
1861
2233
  ): Promise<void> {
@@ -1869,7 +2241,6 @@ async function noteFailingBase(
1869
2241
  number,
1870
2242
  failingBaseNote({
1871
2243
  origin,
1872
- point: stopped.point === "ci" ? "ci" : "checks",
1873
2244
  baseBranch: pipeline.baseBranch,
1874
2245
  branch,
1875
2246
  ...failing,
@@ -1911,7 +2282,7 @@ interface HandOff {
1911
2282
  /** Where the work is, absent when the Ticket failed before it had a worktree. */
1912
2283
  worktree?: HandOffWorktree;
1913
2284
  /**
1914
- * Whether the State stays for a later Run to resume from: what the branch
2285
+ * Whether the state stays for a later Run to resume from: what the branch
1915
2286
  * carries is the pipeline's, whether or not this Run may push it.
1916
2287
  */
1917
2288
  keepsState: boolean;
@@ -1919,40 +2290,50 @@ interface HandOff {
1919
2290
  failure: TicketFailure;
1920
2291
  /** Whether the Ticket's fix budget had already been spent when this failure came. */
1921
2292
  fixUsed: boolean;
1922
- /** The Ticket's State file, which the hand-off either leaves current or removes. */
2293
+ /** The Ticket's state file, which the hand-off either leaves current or removes. */
1923
2294
  record: ResumeRecord;
2295
+ /** The progress comment, written once more if its last write failed. */
2296
+ progress: Progress;
1924
2297
  notes: RoutedNote[];
1925
2298
  }
1926
2299
 
1927
2300
  /**
1928
- * Hand the Ticket to a human: a draft PR to review, a comment naming where the
1929
- * work is, and the labels a human filters on. The branch, the worktree and the
1930
- * State file stay put, so a human who relabels the Ticket `ready-for-agent`
1931
- * hands it back and the next Run carries on from what it reached. The Stages'
1932
- * transcripts go up beside the State, since the Host they were written on may
1933
- * be gone by the time a human looks, and the comment says where they and the
1934
- * branch are. The draft PR's body says where they are too, once they are
1935
- * kept: a draft is opened first, because the State records it, and one that
1936
- * was already open is rewritten, since its body is an earlier Run's.
2301
+ * Hand the Ticket to a human: a draft pull request to review, a comment naming
2302
+ * where the work is, and the labels a human filters on. The branch, the
2303
+ * worktree and the state file stay put, so a human who relabels the Ticket
2304
+ * `ready-for-agent` hands it back and the next Run carries on from what it
2305
+ * reached. The Stages' transcripts go up beside the state, since the Host they
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.
1937
2312
  *
1938
2313
  * A Ticket handed over before its worktree was created has none: nothing was
1939
- * branched, so there is no directory to name and nothing to push a draft PR out
1940
- * of. Both are left out rather than written as a path that is not there and a
1941
- * push that fails.
2314
+ * branched, so there is no directory to name and nothing to push a draft pull
2315
+ * request out of. Both are left out rather than written as a path that is not
2316
+ * there and a push that fails.
1942
2317
  *
1943
2318
  * Where a human is sent and what the pipeline pushes are two different facts. A
1944
2319
  * Ticket refused at setup over a branch still checked out somewhere names that
1945
2320
  * worktree and stops there: the work in it is a human's, and pushing it or
1946
- * opening a PR that says `Closes #<n>` over it would claim it for this Run.
2321
+ * opening a pull request that says `Closes #<n>` over it would claim it for
2322
+ * this Run.
1947
2323
  *
1948
- * The same fact mostly decides the State file. A worktree this Run may push out
2324
+ * The same fact mostly decides the state file. A worktree this Run may push out
1949
2325
  * of is one a Stage of it worked in, and what it left is the pipeline's to
1950
2326
  * resume; a branch in the way at setup leaves nothing of the pipeline's behind,
1951
2327
  * and a file kept over it would let a later Run resume into a human's work and
1952
2328
  * run an implement Stage over it — which is what refusing at setup exists to
1953
- * prevent. The one worktree this Run may not push out of whose State stays is
2329
+ * prevent. The one worktree this Run may not push out of whose state stays is
1954
2330
  * one parted from the remote branch: both copies are the pipeline's, and
1955
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.
1956
2337
  */
1957
2338
  async function handOff(
1958
2339
  pipeline: Pipeline,
@@ -1966,22 +2347,29 @@ async function handOff(
1966
2347
  failure,
1967
2348
  fixUsed,
1968
2349
  record,
2350
+ progress,
1969
2351
  notes,
1970
2352
  }: HandOff,
1971
2353
  ): Promise<TicketOutcome> {
1972
2354
  const { tracker, workspace, config } = pipeline;
1973
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;
1974
2361
 
1975
2362
  // Nothing of this Run's is on the branch, so nothing may leave the Ticket
1976
2363
  // looking resumable: the next Run must not implement over what a human holds.
1977
- // Wrapped because the hand-off itself — the draft PR, the comment, the labels
1978
- // — is what a human is waiting for, and no file is worth losing it over.
2364
+ // Wrapped because the hand-off itself — the draft pull request, the comment,
2365
+ // the labels — is what a human is waiting for, and no file is worth losing it
2366
+ // over.
1979
2367
  if (!keepsState) {
1980
2368
  try {
1981
2369
  await workspace.removeState(ticket);
1982
2370
  } catch (error) {
1983
2371
  pipeline.log?.(
1984
- `#${ticket} handed off, but clearing its State file failed: ${(error as Error).message}`,
2372
+ `#${ticket} handed off, but clearing its state file failed: ${(error as Error).message}`,
1985
2373
  );
1986
2374
  }
1987
2375
  }
@@ -1995,82 +2383,117 @@ async function handOff(
1995
2383
  // Whether the draft's body is one this hand-off wrote, naming no transcripts.
1996
2384
  // One it only converted still says what its Run said, which is not this.
1997
2385
  let drafted = false;
1998
- if (pullRequest !== undefined) {
1999
- await tracker.convertPullRequestToDraft(pullRequest);
2000
- } else if (worktree?.pushable === true) {
2001
- // A draft PR is worth trying for, but never worth losing the relabel over.
2002
- try {
2003
- await workspace.push(worktree.path, branch);
2004
- const pr = await tracker.createPullRequest({
2005
- base: pipeline.baseBranch,
2006
- head: branch,
2007
- // A human can still merge the draft, and its squash commit takes this
2008
- // title, so it is the one a Stage answered for the branch where there is
2009
- // one. Without it, the Ticket title rather than a commit subject: the
2010
- // pipeline merges nothing here, so it derives nothing for a merge.
2011
- title: record.title ?? issue.title,
2012
- body: draftPullRequestBody(draftBody),
2013
- draft: true,
2014
- });
2015
- pullRequest = pr.number;
2016
- drafted = true;
2017
- } catch (error) {
2018
- pipeline.log?.(`#${ticket} could not open a draft PR: ${(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
+ }
2019
2417
  }
2020
- }
2021
2418
 
2022
- if (keepsState) {
2023
- // Written after the draft pull request, because that pull request is part of
2024
- // what a resuming Run must not open a second one beside.
2025
- //
2026
- // The Fix budget goes back unspent: the Ticket only comes back through a
2027
- // human's hands, and whatever they did to it is what the fresh budget is
2028
- // for. Nothing is lost by it — the hand-off comment says the budget was
2029
- // spent, and the Claim only marks that comment as history.
2030
- await record.advance({
2031
- fixUsed: false,
2032
- ...(pullRequest === undefined ? {} : { pullRequest }),
2033
- });
2034
- }
2035
- // Only beside a State that stays, because they go when it does, and after
2036
- // it, so the State they sit beside is the one a resuming Run reads.
2037
- const transcripts = keepsState ? await keepTranscripts(pipeline, ticket) : undefined;
2038
- // A draft this hand-off opened went up before anything was kept, and one it
2039
- // converted still carries an earlier body, so either learns where only now.
2040
- if (pullRequest !== undefined && !(drafted && transcripts === undefined)) {
2041
- try {
2042
- await tracker.updatePullRequestBody(
2043
- pullRequest,
2044
- draftPullRequestBody({
2045
- ...draftBody,
2046
- ...(transcripts === undefined ? {} : { transcripts }),
2047
- }),
2048
- );
2049
- } catch (error) {
2050
- pipeline.log?.(
2051
- `#${ticket} could not rewrite the body of PR #${pullRequest}: ${(error as Error).message}`,
2052
- );
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
+ });
2053
2431
  }
2054
- }
2055
- const onRemote = await branchOnRemote(pipeline, ticket, branch);
2056
-
2057
- await tracker.comment(
2058
- ticket,
2059
- handoffComment({
2060
- stage: failure.point,
2061
- 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,
2062
2489
  branch,
2063
- onRemote,
2064
- ...(worktree === undefined ? {} : { worktree: worktree.path }),
2065
- ...(transcripts === undefined ? {} : { transcripts }),
2066
- evidence: failure.evidence,
2067
- fixUsed,
2068
- ...(pullRequest === undefined ? {} : { pullRequest }),
2069
- }),
2070
- );
2071
- await tracker.removeLabel(ticket, config.labels.inProgress);
2072
- await tracker.addLabel(ticket, config.labels.readyForHuman);
2073
- await tracker.unassign(ticket, user);
2490
+ failure,
2491
+ pullRequest,
2492
+ notes,
2493
+ fault: error,
2494
+ resumable: keepsState && claimed,
2495
+ });
2496
+ }
2074
2497
  pipeline.log?.(`#${ticket} handed off at ${failure.point} · ${failure.summary}`);
2075
2498
 
2076
2499
  return {
@@ -2086,20 +2509,80 @@ async function handOff(
2086
2509
  }
2087
2510
 
2088
2511
  /**
2089
- * Keep the transcripts of the Stages this Run ran for a handed-off Ticket on
2090
- * the remote, where a human can still read them once this Host is gone, and
2091
- * say where.
2512
+ * The ending of a hand-off a fault outside the Ticket cut short.
2513
+ *
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).
2092
2568
  *
2093
- * Nothing when that fails, and the failure logged: the hand-off is what a
2094
- * human is waiting for, and the transcripts are still on this Host for as long
2095
- * as it lasts.
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.
2096
2572
  */
2097
2573
  async function keepTranscripts(
2098
2574
  pipeline: Pipeline,
2099
2575
  ticket: number,
2100
- ): Promise<KeptTranscripts | undefined> {
2576
+ ): Promise<TranscriptsPlace | undefined> {
2577
+ const { transcriptHome, workspace, runId } = pipeline;
2101
2578
  try {
2102
- 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 };
2103
2586
  } catch (error) {
2104
2587
  pipeline.log?.(
2105
2588
  `#${ticket} handed off, but keeping its transcripts failed: ${(error as Error).message}`,