ticket-runner 0.6.5 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/templates.ts CHANGED
@@ -12,7 +12,6 @@ import {
12
12
  emptyBilling,
13
13
  } from "./credential.js";
14
14
  import type { GuardReason } from "./guards.js";
15
- import type { HostKind } from "./host.js";
16
15
  import { splitMessage } from "./failure-message.js";
17
16
  import type { FailurePoint } from "./lifecycle.js";
18
17
  import { logTail } from "./log-tail.js";
@@ -21,7 +20,8 @@ import type { ReleaseCause, TicketOutcome } from "./orchestrator.js";
21
20
  import type { IssueComment, SquashCommit } from "./ports/tracker.js";
22
21
  import type { KeptTranscripts } from "./ports/workspace.js";
23
22
  import type { RunStop } from "./run.js";
24
- import { type Criterion, type Verdict, countStatuses } from "./verdict.js";
23
+ import type { BranchProse } from "./title.js";
24
+ import type { Verdict } from "./verdict.js";
25
25
 
26
26
  /** How the pipeline finds its own hand-off comment again. */
27
27
  export const HANDOFF_MARKER = "<!-- ticket-runner:handoff -->";
@@ -108,60 +108,46 @@ export function hasGuardWarning(comments: IssueComment[], reason: GuardReason):
108
108
  return findMarkedComment(comments, guardMarker(reason)) !== undefined;
109
109
  }
110
110
 
111
- /** The one warning a skipped candidate gets. Two sentences: the reason, the fix. */
112
- export function guardComment(reason: GuardReason): string {
113
- return [
114
- guardMarker(reason),
115
- `**Skipped by ticket-runner.** ${GUARD_SENTENCES[reason]}`,
116
- "",
117
- ].join("\n");
111
+ /**
112
+ * What the `no-criteria` guard says of a Ticket whose checkboxes are all
113
+ * ticked. Told only that it has no criteria, a human looking at a list of them
114
+ * reads the comment as wrong.
115
+ */
116
+ function allTickedSentences(ticked: number): string {
117
+ const boxes = ticked === 1 ? "its one checkbox is" : `all ${ticked} of its checkboxes are`;
118
+ return (
119
+ `No \`- [ ]\` acceptance criteria found: ${boxes} already ticked. ` +
120
+ "Untick each criterion not yet done, then re-run."
121
+ );
118
122
  }
119
123
 
120
- /** The verdict summary both the pull request body and the squash commit carry. */
121
- function verdictCounts(verdict: Verdict): string {
122
- const counts = countStatuses(verdict);
123
- return `${counts.met} met · ${counts.unmet} unmet · ${counts.unverifiable} unverifiable`;
124
+ /**
125
+ * The one warning a skipped candidate gets. Two sentences: the reason, the fix.
126
+ *
127
+ * `ticked` is how many ticked checkboxes the Ticket carries, which only the
128
+ * `no-criteria` warning reads.
129
+ */
130
+ export function guardComment(reason: GuardReason, ticked = 0): string {
131
+ const sentences =
132
+ reason === "no-criteria" && ticked > 0 ? allTickedSentences(ticked) : GUARD_SENTENCES[reason];
133
+ return [guardMarker(reason), `**Skipped by ticket-runner.** ${sentences}`, ""].join("\n");
124
134
  }
125
135
 
126
- const STATUS_ICON: Record<Criterion["status"], string> = {
127
- met: "✅",
128
- unmet: "❌",
129
- unverifiable: "❓",
130
- };
131
-
132
136
  export interface PullRequestBody {
133
137
  ticket: number;
134
- verdict: Verdict;
135
- runId: string;
136
- /** The Host the Run is on, which decides whether its run directory is worth naming. */
137
- host: HostKind;
138
+ /** The latest body a Stage answered for the branch, when one has. */
139
+ body?: string;
138
140
  }
139
141
 
140
- export function pullRequestBody({ ticket, verdict, runId, host }: PullRequestBody): string {
141
- const criteria = verdict.criteria.map((criterion) => {
142
- const line = `- ${STATUS_ICON[criterion.status]} ${criterion.text}`;
143
- return criterion.status === "met" ? line : `${line} — ${criterion.evidence}`;
144
- });
145
-
146
- // A merged Ticket keeps no transcripts on the remote, so the run directory is
147
- // the only place they are, and a cloud Host's goes with its session.
148
- const where =
149
- host === "workstation" ? `\`.ticket-runner/runs/${runId}/${ticket}/\`` : undefined;
150
-
151
- return [
152
- `Closes #${ticket}`,
153
- "",
154
- `**Verdict:** ${verdictCounts(verdict)}`,
155
- "",
156
- "<details><summary>Criteria</summary>",
157
- "",
158
- ...criteria,
159
- "",
160
- "</details>",
161
- "",
162
- runLine(runId, where),
163
- "",
164
- ].join("\n");
142
+ /**
143
+ * The body of a pipeline pull request: the one `Closes` the pipeline writes,
144
+ * and below it the body a Stage answered in the Target's shape or the `pr`
145
+ * skill's. The pipeline adds nothing of its own: the verify Stage's progress
146
+ * row carries the verdict, and the merge ticks the met criteria on the Ticket.
147
+ */
148
+ export function pullRequestBody({ ticket, body }: PullRequestBody): string {
149
+ const closes = `Closes #${ticket}`;
150
+ return body === undefined ? `${closes}\n` : `${closes}\n\n${body}\n`;
165
151
  }
166
152
 
167
153
  export interface DraftPullRequestBody {
@@ -173,8 +159,8 @@ export interface DraftPullRequestBody {
173
159
  */
174
160
  failure: string;
175
161
  runId: string;
176
- /** Where the hand-off kept the Stages' transcripts on the remote, when it kept any. */
177
- transcripts?: KeptTranscripts;
162
+ /** Where the hand-off kept the Stages' transcripts, when there are any. */
163
+ transcripts?: TranscriptsPlace;
178
164
  }
179
165
 
180
166
  /**
@@ -198,7 +184,7 @@ export function draftPullRequestBody({
198
184
  ...evidenceBlock(shown.evidence),
199
185
  `See the hand-off comment on #${ticket} for the branch, worktree and evidence.`,
200
186
  "",
201
- runLine(runId, transcripts === undefined ? undefined : keptPlace(transcripts)),
187
+ runLine(runId, transcripts),
202
188
  "",
203
189
  ].join("\n");
204
190
  }
@@ -229,27 +215,49 @@ function evidenceBlock(evidence: string): string[] {
229
215
  }
230
216
 
231
217
  /**
232
- * The line both pull request bodies end with: the Run, and where its
233
- * transcripts are when there is somewhere that outlives the Host to point at.
218
+ * Where a hand-off says the Stages' transcripts are: on the remote beside the
219
+ * Ticket's state, or kept off it on the Host, which a workstation outlives and
220
+ * a cloud Host's VM does not. A workstation's directory is named relative to
221
+ * the checkout, so a public comment does not publish the Host's home path.
234
222
  */
235
- function runLine(runId: string, where: string | undefined): string {
236
- const run = `Run \`${runId}\``;
237
- return where === undefined ? run : `${run} · transcripts in ${where}`;
238
- }
223
+ export type TranscriptsPlace =
224
+ | ({ on: "remote" } & KeptTranscripts)
225
+ | { on: "workstation"; path: string }
226
+ | { on: "cloud" };
239
227
 
240
- /** Where a hand-off kept the transcripts, as every shape that names it spells it. */
241
- function keptPlace(transcripts: KeptTranscripts): string {
242
- return `\`${transcripts.path}\` on the \`${transcripts.branch}\` branch`;
228
+ /**
229
+ * The line a draft pull request's body ends with: the Run, and where its
230
+ * transcripts are when there are any.
231
+ */
232
+ function runLine(runId: string, transcripts: TranscriptsPlace | undefined): string {
233
+ const run = `Run \`${runId}\``;
234
+ if (transcripts === undefined) return run;
235
+ // A directory is led into with `in`; the cloud Host's phrase names none.
236
+ const lead = transcripts.on === "cloud" ? "transcripts" : "transcripts in";
237
+ return `${run} · ${lead} ${placeOf(transcripts)}`;
238
+ }
239
+
240
+ /** Where the transcripts are, as every shape that names it spells it. */
241
+ function placeOf(transcripts: TranscriptsPlace): string {
242
+ switch (transcripts.on) {
243
+ case "remote":
244
+ return `\`${transcripts.path}\` on the \`${transcripts.branch}\` branch`;
245
+ case "workstation":
246
+ return `\`${transcripts.path}\` on the Host, kept off the remote`;
247
+ case "cloud":
248
+ return "kept off the remote, on the cloud Host, so they go with its VM";
249
+ }
243
250
  }
244
251
 
245
- export interface SquashCommitMessage {
252
+ export interface SquashCommitMessage extends Pick<BranchProse, "problem" | "solution"> {
246
253
  ticket: number;
247
254
  /** The pull request number, appended to the subject as GitHub would. */
248
255
  pullRequest: number;
249
256
  /** The pull request title, which is the subject that lands on the base branch. */
250
257
  title: string;
258
+ /** The verdict the merge is made on, whose unverifiable criteria the body names. */
251
259
  verdict: Verdict;
252
- /** The branch's commit subjects, oldest first. */
260
+ /** The branch's commit subjects, oldest first, which stand in for a solution no Stage answered. */
253
261
  commits: string[];
254
262
  /** Unique `Co-authored-by` values from the branch, carried as trailers. */
255
263
  coAuthors: string[];
@@ -258,34 +266,124 @@ export interface SquashCommitMessage {
258
266
  /**
259
267
  * The commit a merged Ticket leaves on the base branch.
260
268
  *
261
- * `git log` renders no HTML, so this is the one template with nothing folded
262
- * away: the verdict is counts only, and the per-criterion evidence stays in the
263
- * pull request body where a browser can collapse it.
269
+ * It opens with the problem and the solution a Stage answered, so `git log`
270
+ * says why without the Ticket. Where no Stage answered a solution, the
271
+ * branch's commit subjects say what changed in its place; nothing is made up
272
+ * for either.
273
+ *
274
+ * An unverifiable criterion's reason is kept nowhere on the Ticket, so it is
275
+ * carried here, one line per criterion. `git log` renders no HTML, so nothing
276
+ * is folded away.
264
277
  */
265
278
  export function squashCommit({
266
279
  ticket,
267
280
  pullRequest,
268
281
  title,
282
+ problem,
283
+ solution,
269
284
  verdict,
270
285
  commits,
271
286
  coAuthors,
272
287
  }: SquashCommitMessage): SquashCommit {
273
- // What GitHub's default message would have carried, now carried by hand.
274
- const trailers = coAuthors.map((author) => `Co-authored-by: ${author}`);
288
+ const paragraphs = [
289
+ [`Closes #${ticket}`],
290
+ ...(problem === undefined ? [] : [wrapLines(problem)]),
291
+ solution === undefined ? commits.map((subject) => `- ${subject}`) : wrapLines(solution),
292
+ unverifiedLines(verdict),
293
+ // What GitHub's default message would have carried, now carried by hand.
294
+ coAuthors.map((author) => `Co-authored-by: ${author}`),
295
+ ].filter((lines) => lines.length > 0);
275
296
  return {
276
297
  subject: `${title} (#${pullRequest})`,
277
- body: [
278
- `Closes #${ticket}`,
279
- "",
280
- `Verdict: ${verdictCounts(verdict)}`,
281
- "",
282
- ...commits.map((subject) => `- ${subject}`),
283
- "",
284
- ...(trailers.length === 0 ? [] : [...trailers, ""]),
285
- ].join("\n"),
298
+ body: `${paragraphs.map((lines) => lines.join("\n")).join("\n\n")}\n`,
286
299
  };
287
300
  }
288
301
 
302
+ /** The unverifiable criteria with their evidence on one line each, under a heading; nothing when there are none. */
303
+ function unverifiedLines(verdict: Verdict): string[] {
304
+ const unverifiable = unverifiableLines(verdict);
305
+ return unverifiable.length === 0 ? [] : ["Unverified:", ...unverifiable];
306
+ }
307
+
308
+ /**
309
+ * One `- <criterion> — <evidence>` line per unverifiable criterion, each joined
310
+ * into one line: what the squash commit carries, and what a hand-off on a
311
+ * Target that merges by hand says in its place.
312
+ */
313
+ function unverifiableLines(verdict: Verdict): string[] {
314
+ return verdict.criteria
315
+ .filter((criterion) => criterion.status === "unverifiable")
316
+ .map((criterion) => `- ${oneLine(criterion.text)} — ${oneLine(criterion.evidence)}`);
317
+ }
318
+
319
+ /** Text with its line breaks, and the space around them, joined into single spaces. */
320
+ function oneLine(text: string): string {
321
+ return text.trim().replace(/\s*\n\s*/g, " ");
322
+ }
323
+
324
+ /** How wide a commit body's line may run, as git's own convention has it. */
325
+ const COMMIT_BODY_COLUMNS = 72;
326
+
327
+ /**
328
+ * Prose for a commit body, each line wider than {@link COMMIT_BODY_COLUMNS}
329
+ * broken at its spaces. The lines the Stage wrote stay as they are, so a list
330
+ * stays a list, and a word wider than the limit is left whole.
331
+ */
332
+ export function wrapLines(text: string): string[] {
333
+ return text.split("\n").flatMap((line) => wrapLine(line.trimEnd()));
334
+ }
335
+
336
+ function wrapLine(line: string): string[] {
337
+ if (columns(line) <= COMMIT_BODY_COLUMNS) return [line];
338
+ // A line's indent belongs to its first word, so the break never lands in it.
339
+ const indent = /^\s*/.exec(line)?.[0] ?? "";
340
+ const words = line.slice(indent.length).split(/ +/);
341
+ const lines: string[] = [];
342
+ let current = indent + (words.shift() ?? "");
343
+ for (const word of words) {
344
+ const joined = `${current} ${word}`;
345
+ if (columns(joined) <= COMMIT_BODY_COLUMNS) {
346
+ current = joined;
347
+ } else {
348
+ lines.push(current);
349
+ current = word;
350
+ }
351
+ }
352
+ lines.push(current);
353
+ return lines;
354
+ }
355
+
356
+ /** How many columns a terminal gives `text`: two for a wide character such as Hangul, one for any other. */
357
+ export function columns(text: string): number {
358
+ let width = 0;
359
+ for (const character of text) width += isWide(character.codePointAt(0) ?? 0) ? 2 : 1;
360
+ return width;
361
+ }
362
+
363
+ /** East Asian Wide and Fullwidth code points, the ones a terminal draws two columns wide. */
364
+ const WIDE_RANGES: readonly (readonly [number, number])[] = [
365
+ [0x1100, 0x115f], // Hangul Jamo initial consonants
366
+ [0x2e80, 0x303e], // CJK radicals, Kangxi, CJK symbols and punctuation
367
+ [0x3041, 0x33ff], // Hiragana, Katakana, Bopomofo, Hangul compatibility Jamo, CJK compatibility
368
+ [0x3400, 0x4dbf], // CJK unified ideographs extension A
369
+ [0x4e00, 0x9fff], // CJK unified ideographs
370
+ [0xa000, 0xa4cf], // Yi
371
+ [0xa960, 0xa97f], // Hangul Jamo extended A
372
+ [0xac00, 0xd7a3], // Hangul syllables
373
+ [0xf900, 0xfaff], // CJK compatibility ideographs
374
+ [0xfe30, 0xfe4f], // CJK compatibility forms
375
+ [0xff00, 0xff60], // Fullwidth forms
376
+ [0xffe0, 0xffe6], // Fullwidth signs
377
+ [0x1f300, 0x1f64f], // Pictographs and emoticons
378
+ [0x1f680, 0x1f6ff], // Transport and map symbols
379
+ [0x1f900, 0x1f9ff], // Supplemental pictographs
380
+ [0x20000, 0x3fffd], // CJK unified ideographs extensions B onwards
381
+ ];
382
+
383
+ function isWide(codePoint: number): boolean {
384
+ return WIDE_RANGES.some(([low, high]) => codePoint >= low && codePoint <= high);
385
+ }
386
+
289
387
  export interface HandoffComment {
290
388
  stage: FailurePoint;
291
389
  /**
@@ -310,8 +408,8 @@ export interface HandoffComment {
310
408
  evidence: string;
311
409
  /** Whether the Ticket's fix budget had already been spent when this failure came. */
312
410
  fixUsed?: boolean;
313
- /** Where the Stages' transcripts were kept on the remote, when any were. */
314
- transcripts?: KeptTranscripts;
411
+ /** Where the Stages' transcripts are, when there are any. */
412
+ transcripts?: TranscriptsPlace;
315
413
  /**
316
414
  * Why the Stage this hand-off is for committed nothing, as it answered it in
317
415
  * `noCommitReason`. Set only for an implement or fix Stage that finished and
@@ -321,11 +419,10 @@ export interface HandoffComment {
321
419
  }
322
420
 
323
421
  export function handoffComment(handoff: HandoffComment): string {
324
- const location = [
325
- `Branch \`${handoff.branch}\`${handoff.onRemote === true ? " on the remote" : ""}`,
326
- ...(handoff.worktree === undefined ? [] : [`worktree \`${handoff.worktree}\``]),
327
- ...(handoff.pullRequest === undefined ? [] : [`PR #${handoff.pullRequest} (draft)`]),
328
- ].join(" · ");
422
+ const location = whereTheWorkIs(
423
+ handoff,
424
+ handoff.pullRequest === undefined ? undefined : `PR #${handoff.pullRequest} (draft)`,
425
+ );
329
426
 
330
427
  // The budget clause is the difference between one bad Stage and a Ticket the
331
428
  // pipeline already had a second go at, which is what a human needs to know.
@@ -340,13 +437,64 @@ export function handoffComment(handoff: HandoffComment): string {
340
437
  `- ${location}`,
341
438
  ...(handoff.transcripts === undefined
342
439
  ? []
343
- : [`- Transcripts: ${keptPlace(handoff.transcripts)}`]),
440
+ : [`- Transcripts: ${placeOf(handoff.transcripts)}`]),
344
441
  "",
345
442
  ...stageSaid(handoff.stage, handoff.reason),
346
443
  ...evidenceBlock(shown.evidence),
347
444
  ].join("\n");
348
445
  }
349
446
 
447
+ /** The branch, the worktree and the pull request, as one line of a hand-off comment says them. */
448
+ function whereTheWorkIs(
449
+ { branch, onRemote, worktree }: Pick<HandoffComment, "branch" | "onRemote" | "worktree">,
450
+ pullRequest: string | undefined,
451
+ ): string {
452
+ return [
453
+ `Branch \`${branch}\`${onRemote === true ? " on the remote" : ""}`,
454
+ ...(worktree === undefined ? [] : [`worktree \`${worktree}\``]),
455
+ ...(pullRequest === undefined ? [] : [pullRequest]),
456
+ ].join(" · ");
457
+ }
458
+
459
+ /** Why a Ticket handed off on a Target that merges by hand was handed off, in the words its row and log line give. */
460
+ export const LEFT_TO_HUMAN = "left to a human, as this Target merges by hand";
461
+
462
+ export interface MergeByHandComment extends Pick<HandoffComment, "branch" | "onRemote" | "worktree"> {
463
+ /** The pull request a human is to merge, published ready for review. */
464
+ pullRequest: number;
465
+ /** The verdict the Ticket passed on, whose unverifiable criteria the comment lists. */
466
+ verdict: Verdict;
467
+ }
468
+
469
+ /**
470
+ * The hand-off of a Ticket that passed every gate on a Target that merges by
471
+ * hand: nothing failed, so there is no failure line and no evidence block, and
472
+ * the pull request is no draft.
473
+ *
474
+ * The unverifiable criteria and their evidence are what the squash commit
475
+ * would have carried, had the pipeline merged. A human merging by hand gets
476
+ * GitHub's own message instead, so they are said here, where that human reads
477
+ * them. They are posted on the Ticket, whose comments are read for Acceptance
478
+ * Criteria, so a line that could read as a checkbox is defused.
479
+ */
480
+ export function mergeByHandComment(handoff: MergeByHandComment): string {
481
+ const unverifiable = unverifiableLines(handoff.verdict);
482
+ return [
483
+ HANDOFF_MARKER,
484
+ `**Handed off.** PR #${handoff.pullRequest} passed every gate and waits for a human to merge it: this Target merges by hand.`,
485
+ "",
486
+ `- ${whereTheWorkIs(handoff, `PR #${handoff.pullRequest}`)}`,
487
+ ...(unverifiable.length === 0
488
+ ? []
489
+ : [
490
+ "",
491
+ "**Unverifiable criteria:**",
492
+ "",
493
+ ...unverifiable.map(escapeCheckboxes),
494
+ ]),
495
+ ].join("\n");
496
+ }
497
+
350
498
  /**
351
499
  * The reason a Stage gave for committing nothing, as a paragraph of its own
352
500
  * between the hand-off's lines and its folded evidence, so a human reads it
@@ -625,16 +773,19 @@ export interface RunSummary {
625
773
  }
626
774
 
627
775
  /**
628
- * What a Release is put down to, in the words the Run summary and the log
629
- * share: the rate limit, a transient API failure, an API key out of credit or
630
- * past its spend limit, or a base branch that fails the Check the Ticket's
631
- * branch failed.
776
+ * What a Release is put down to, in the words the Run summary, the log and
777
+ * the progress comment share: the rate limit, a transient API failure, an API
778
+ * key out of credit or past its spend limit, a base branch that fails the
779
+ * Check the Ticket's branch failed, or GitHub or the git remote failing on its
780
+ * own side.
632
781
  */
633
782
  export const RELEASE_WORDS: Record<ReleaseCause, string> = {
634
783
  "rate-limited": "rate limit",
635
784
  "api-error": "API failure",
636
785
  "out-of-budget": "out of API budget",
637
786
  "failing-base": "failing base branch",
787
+ github: "GitHub failure",
788
+ remote: "remote unreachable",
638
789
  };
639
790
 
640
791
  /**
@@ -737,6 +888,11 @@ function lastLine(stop: RunStop, credential: Credential): string {
737
888
  return "Out of API budget.";
738
889
  case "failing-base":
739
890
  return `Base branch \`${stop.baseBranch}\` fails \`${stop.command}\` at ${stop.commit.slice(0, 7)}.`;
891
+ // What failed and what it said, because the human may have to act: an
892
+ // authentication failure mends only with a key or a login.
893
+ case "github":
894
+ case "remote":
895
+ return `${capitalised(RELEASE_WORDS[stop.reason])} · \`${stop.command}\` · ${stop.line}`;
740
896
  case "stopped":
741
897
  return `Stopped at ${clockTime(stop.at)} · ${holding(stop.busy)}.`;
742
898
  case "frontier":
@@ -744,6 +900,11 @@ function lastLine(stop: RunStop, credential: Credential): string {
744
900
  }
745
901
  }
746
902
 
903
+ /** `words` opening a line. */
904
+ function capitalised(words: string): string {
905
+ return `${words.charAt(0).toUpperCase()}${words.slice(1)}`;
906
+ }
907
+
747
908
  /**
748
909
  * The minute a Stop arrived, in UTC — the clock the run id on the first line of
749
910
  * the summary is already written in, so the two can be read against each other.
@@ -801,6 +962,9 @@ function noteRow({ origin, stage, issue, opened, summary }: RoutedNote): string
801
962
  );
802
963
  }
803
964
 
965
+ /** What a `handed` row says of a hand-off a fault outside the Ticket cut short. */
966
+ const CUT_SHORT = "hand-off cut short";
967
+
804
968
  /** One Ticket's line in a summary: what happened to it, and where to look. */
805
969
  function ticketRow(outcome: TicketOutcome, credential: Credential): string {
806
970
  switch (outcome.outcome) {
@@ -811,7 +975,11 @@ function ticketRow(outcome: TicketOutcome, credential: Credential): string {
811
975
  "handed",
812
976
  outcome.ticket,
813
977
  // The one line of an unexpected error; its output is the hand-off's.
814
- `${outcome.title} · ${outcome.stage} · ${splitMessage(outcome.failure).line}`,
978
+ `${outcome.title} · ${outcome.stage} · ${splitMessage(outcome.failure).line}` +
979
+ // A hand-off the fault cut short says so, since a human finishes it.
980
+ (outcome.fault === undefined
981
+ ? ""
982
+ : ` · ${CUT_SHORT} · ${releaseWords(outcome.fault.side, credential)}`),
815
983
  );
816
984
  case "released":
817
985
  // Nothing for a human to do, so the row says only what stopped the Stage
package/src/title.ts CHANGED
@@ -8,6 +8,10 @@
8
8
  * subject describes its own commit: a fix Stage that did most of a Ticket's
9
9
  * work could not retitle a branch whose first commit was already pushed without
10
10
  * rewriting it.
11
+ *
12
+ * The pull request body and the problem and solution the squash commit opens
13
+ * with are answered beside the title for the same reason, and recorded the
14
+ * same way ({@link BranchProse}).
11
15
  */
12
16
 
13
17
  import { CODE_STAGE_NOTES_LIST_SCHEMA } from "./note-schema.js";
@@ -33,16 +37,24 @@ const CONVENTIONAL_SUBJECT = /^[a-z]+(\([a-z0-9._-]+\))?: \S/;
33
37
  /** The `(#<n>)` a commit may carry, which the squash commit's `Closes #<n>` replaces. */
34
38
  const TICKET_REFERENCE = /\s*\(#\d+\)$/;
35
39
 
40
+ /**
41
+ * How the schema tells a Stage to keep an answer: an empty one is how a fix
42
+ * Stage leaves the body, problem or solution before it standing.
43
+ */
44
+ const KEEP_EARLIER = "An empty string keeps the one an earlier Stage answered.";
45
+
36
46
  /**
37
47
  * The `--json-schema` the implement and fix Stages are invoked with: the title
38
- * of the whole branch, the Notes channel beside it, and why the Stage ended
39
- * with no new commit when it did.
48
+ * of the whole branch, the pull request body, the problem and the solution the
49
+ * squash commit opens with, the Notes channel beside them, and why the Stage
50
+ * ended with no new commit when it did.
40
51
  *
41
- * All three are required, so a Stage always says something about each: an
42
- * empty Notes list when it found nothing, a title however little it did, and an
43
- * empty reason when it committed. The parsers forgive each one on its own
44
- * ({@link parseTitle}, `parseNotes` and {@link parseNoCommitReason}), so a bad
45
- * answer to one never costs the others.
52
+ * All are required, so a Stage always says something about each: an empty
53
+ * Notes list when it found nothing, a title however little it did, an empty
54
+ * string for a body, problem or solution it leaves as it was, and an empty
55
+ * reason when it committed. The parsers forgive each one on its own
56
+ * ({@link parseTitle}, {@link parseBranchProse}, `parseNotes` and
57
+ * {@link parseNoCommitReason}), so a bad answer to one never costs the others.
46
58
  *
47
59
  * The reason is asked for in its own field because, under `--json-schema`, the
48
60
  * answer is all of the session the pipeline reads: a last message in prose is
@@ -56,6 +68,18 @@ export const CODE_STAGE_JSON_SCHEMA = {
56
68
  type: "string",
57
69
  description: `Write ${BRANCH_TITLE}: \`${SUBJECT_SHAPE}\`, without the \`(#<n>)\`. It titles the pull request and the squash commit that lands.`,
58
70
  },
71
+ body: {
72
+ type: "string",
73
+ description: `The pull request body for the whole branch, without a title and without the \`Closes #<n>\` line the pipeline writes above it. ${KEEP_EARLIER}`,
74
+ },
75
+ problem: {
76
+ type: "string",
77
+ description: `The problem the branch solves, for the squash commit's body, in the shape your prompt gives. ${KEEP_EARLIER}`,
78
+ },
79
+ solution: {
80
+ type: "string",
81
+ description: `The solution, for the squash commit's body after the problem, in the shape your prompt gives. ${KEEP_EARLIER}`,
82
+ },
59
83
  notes: CODE_STAGE_NOTES_LIST_SCHEMA,
60
84
  noCommitReason: {
61
85
  type: "string",
@@ -63,7 +87,7 @@ export const CODE_STAGE_JSON_SCHEMA = {
63
87
  "When you end with no new commit on the branch, say why in a few sentences: ending so hands the Ticket to a human, and the hand-off comment quotes this. Otherwise an empty string.",
64
88
  },
65
89
  },
66
- required: ["title", "notes", "noCommitReason"],
90
+ required: ["title", "body", "problem", "solution", "notes", "noCommitReason"],
67
91
  additionalProperties: false,
68
92
  } as const;
69
93
 
@@ -93,6 +117,39 @@ export function parseTitle(result: unknown): string | undefined {
93
117
  return typeof raw === "string" ? asTitle(raw) : undefined;
94
118
  }
95
119
 
120
+ /**
121
+ * The prose a code Stage answers about the whole branch beside its title: the
122
+ * pull request body, and the problem and the solution the squash commit opens
123
+ * with. Each is absent where no Stage has answered one, and the latest one
124
+ * answered stands until a later Stage answers it again.
125
+ */
126
+ export interface BranchProse {
127
+ body?: string;
128
+ problem?: string;
129
+ solution?: string;
130
+ }
131
+
132
+ /** The fields of {@link BranchProse}, in the order the squash commit and the prompts give them. */
133
+ export const BRANCH_PROSE_FIELDS = ["body", "problem", "solution"] as const;
134
+
135
+ /**
136
+ * The body, the problem and the solution in a Stage's structured output, each
137
+ * one it answered with something in it.
138
+ *
139
+ * Forgiving, as the title is: output that is not an object and a missing,
140
+ * blank or non-string answer each cost that answer alone, and a blank one is
141
+ * also how a fix Stage leaves the earlier answer standing. The lines are kept as
142
+ * the Stage wrote them, so a list stays a list; only the ends are trimmed.
143
+ */
144
+ export function parseBranchProse(result: unknown): BranchProse {
145
+ const prose: BranchProse = {};
146
+ for (const field of BRANCH_PROSE_FIELDS) {
147
+ const answer = answeredText(result, field);
148
+ if (answer !== undefined) prose[field] = answer;
149
+ }
150
+ return prose;
151
+ }
152
+
96
153
  /**
97
154
  * Why a code Stage ended with no new commit, as it answered it, or nothing
98
155
  * when it gave no reason.
@@ -102,11 +159,16 @@ export function parseTitle(result: unknown): string | undefined {
102
159
  * The lines are kept as the Stage wrote them; only the ends are trimmed.
103
160
  */
104
161
  export function parseNoCommitReason(result: unknown): string | undefined {
162
+ return answeredText(result, "noCommitReason");
163
+ }
164
+
165
+ /** A string field of a Stage's output, trimmed, or nothing where it holds none. */
166
+ function answeredText(result: unknown, field: string): string | undefined {
105
167
  if (typeof result !== "object" || result === null) return undefined;
106
- const raw = (result as { noCommitReason?: unknown }).noCommitReason;
168
+ const raw = (result as Record<string, unknown>)[field];
107
169
  if (typeof raw !== "string") return undefined;
108
- const reason = raw.trim();
109
- return reason === "" ? undefined : reason;
170
+ const text = raw.trim();
171
+ return text === "" ? undefined : text;
110
172
  }
111
173
 
112
174
  /**
@@ -0,0 +1,49 @@
1
+ import type { Config } from "./config.js";
2
+ import type { HostKind } from "./host.js";
3
+ import type { Tracker } from "./ports/tracker.js";
4
+
5
+ /**
6
+ * Where a Run keeps a handed-off Ticket's transcripts: on the Target's remote,
7
+ * beside the Ticket's state (ADR-0004), or on the Host the Run executes on,
8
+ * which a workstation outlives and a cloud Host's VM does not.
9
+ */
10
+ export type TranscriptHome = "remote" | HostKind;
11
+
12
+ export interface ResolvedTranscriptHome {
13
+ home: TranscriptHome;
14
+ /** The one line the Run says when the Target's visibility could not be read. */
15
+ said?: string;
16
+ }
17
+
18
+ /**
19
+ * Where this Run keeps a handed-off Ticket's transcripts, decided once before
20
+ * the first Ticket.
21
+ *
22
+ * The config's `keepTranscripts` wins where it is set. Unset, the Target's
23
+ * visibility answers: a transcript holds whatever the Host could see, and on
24
+ * a public Target the state branch is public and a pushed commit stays
25
+ * reachable by its SHA, so it stays off the remote there (ADR-0004). A Target
26
+ * whose visibility cannot be read counts as public, and the Run says so.
27
+ */
28
+ export async function resolveTranscriptHome({
29
+ config,
30
+ tracker,
31
+ host,
32
+ }: {
33
+ config: Pick<Config, "keepTranscripts">;
34
+ tracker: Pick<Tracker, "visibility">;
35
+ host: HostKind;
36
+ }): Promise<ResolvedTranscriptHome> {
37
+ if (config.keepTranscripts !== undefined) {
38
+ return { home: config.keepTranscripts ? "remote" : host };
39
+ }
40
+ const visibility = await tracker.visibility();
41
+ if (visibility === "private") return { home: "remote" };
42
+ if (visibility === "public") return { home: host };
43
+ return {
44
+ home: host,
45
+ said:
46
+ "could not read whether the Target is public, so it counts as public: " +
47
+ "a handed-off Ticket's transcripts stay on this Host",
48
+ };
49
+ }