ticket-runner 0.6.2 → 0.6.3

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/start.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { resolveBaseBranch } from "./base-branch.js";
2
2
  import type { Config } from "./config.js";
3
- import { hostKind } from "./host.js";
3
+ import { type Credential, credentialRefusal } from "./credential.js";
4
+ import { type HostKind, hostKind } from "./host.js";
4
5
  import { BaseBranchChecks } from "./failing-base.js";
5
6
  import { Landing } from "./landing.js";
6
7
  import { StandingNotes } from "./notes.js";
@@ -9,7 +10,7 @@ import type { Pipeline, TicketOutcome } from "./orchestrator.js";
9
10
  import type { AgentRunner } from "./ports/agent-runner.js";
10
11
  import type { Tracker } from "./ports/tracker.js";
11
12
  import type { Workspace } from "./ports/workspace.js";
12
- import { readinessRefusal } from "./readiness.js";
13
+ import { readinessRefusal, unpushedRefusal } from "./readiness.js";
13
14
  import { LOCAL_STATE_DIR, localStateTickets } from "./resume.js";
14
15
  import { writeRunVersion } from "./run-log.js";
15
16
  import { type RunStop, processRun } from "./run.js";
@@ -36,11 +37,15 @@ import { runSummary } from "./templates.js";
36
37
  * because how many Tickets a Host can carry at once is the Host's business, not
37
38
  * the Target's (ADR-0008). It may also be narrowed to the Tickets a human
38
39
  * named, ascending and each once; with none it drains the whole Frontier.
40
+ * It runs its Stages on the Host's API key only when it was started with
41
+ * `--api-key`, for the same reason: whose money a Run spends is the Host's
42
+ * business.
39
43
  */
40
44
  export interface Work {
41
45
  command: "run";
42
46
  lanes?: number;
43
47
  tickets?: number[];
48
+ apiKey?: true;
44
49
  }
45
50
 
46
51
  export interface StartOptions {
@@ -68,15 +73,21 @@ export interface StartOptions {
68
73
  error?: (line: string) => void;
69
74
  /** Where SIGTERM comes from. The process itself, unless a test is watching. */
70
75
  signals?: StopSource;
76
+ /**
77
+ * The Host's environment, which says what kind of Host this is and whether it
78
+ * exports a key. The process's own, unless a test says otherwise.
79
+ */
80
+ env?: Record<string, string | undefined>;
71
81
  }
72
82
 
73
83
  /**
74
84
  * Start a Run, and answer with the exit code it earned.
75
85
  *
76
- * Every refusal comes before the lock: a Target `init` has not set up, one
77
- * holding State files an earlier pipeline left in the checkout, and one with
78
- * nothing to gate a merge. None is a Run that went wrong, so none should leave
79
- * a lock behind for the next one to reclaim.
86
+ * Every refusal comes before the lock: an `--api-key` the Host cannot honour,
87
+ * a Target `init` has not set up, one whose remote lacks what `init` wrote,
88
+ * one holding State files an earlier pipeline left in the checkout, and one
89
+ * with nothing to gate a merge. None is a Run that went wrong, so none should
90
+ * leave a lock behind for the next one to reclaim.
80
91
  */
81
92
  export async function startRun(given: StartOptions): Promise<number> {
82
93
  // The count a Run was told is folded into the config once, here, so
@@ -87,6 +98,17 @@ export async function startRun(given: StartOptions): Promise<number> {
87
98
  const { repoRoot, config, tracker, workspace } = options;
88
99
  const log = options.log ?? ((line: string) => console.log(line));
89
100
  const error = options.error ?? ((line: string) => console.error(line));
101
+ const env = options.env ?? process.env;
102
+
103
+ // First, because it asks nothing of the Target: the Host either can or
104
+ // cannot run the Stages on the credential the Run was started with.
105
+ const credential: Credential = options.work.apiKey === true ? "api-key" : "subscription";
106
+ const host = hostKind(env);
107
+ const refusedCredential = credentialRefusal(credential, host, env);
108
+ if (refusedCredential !== undefined) {
109
+ error(refusedCredential);
110
+ return 2;
111
+ }
90
112
 
91
113
  const notReady = await readinessRefusal({ repoRoot, labels: config.labels, tracker });
92
114
  if (notReady !== undefined) {
@@ -94,6 +116,18 @@ export async function startRun(given: StartOptions): Promise<number> {
94
116
  return 2;
95
117
  }
96
118
 
119
+ // Once per Run, and here rather than with the rest of the Run's setup:
120
+ // readiness asks the remote's copy of this branch for what `init` wrote, and
121
+ // every branch, rebase, pull request and pull of the Run goes to the same one.
122
+ // After readiness's own questions, since the lookup may ask GitHub, which only
123
+ // a `gh` that runs can.
124
+ const baseBranch = await resolveBaseBranch(tracker, config);
125
+ const notPushed = await unpushedRefusal({ workspace, baseBranch });
126
+ if (notPushed !== undefined) {
127
+ error(notPushed);
128
+ return 2;
129
+ }
130
+
97
131
  const leftBehind = localStateTickets(repoRoot);
98
132
  if (leftBehind.length > 0) {
99
133
  error(localStateMessage(leftBehind));
@@ -140,7 +174,7 @@ export async function startRun(given: StartOptions): Promise<number> {
140
174
  const stopping = new StopSignal();
141
175
  const deafen = listenForStop(stopping, options.signals);
142
176
  try {
143
- return await execute(options, log, stopping);
177
+ return await execute(options, { credential, host, baseBranch }, log, stopping);
144
178
  } finally {
145
179
  // The lock goes first: SIGTERM between the two is a kill again, and a kill
146
180
  // that leaves the lock behind costs the next Run a stale holder to reclaim,
@@ -159,6 +193,11 @@ export async function startRun(given: StartOptions): Promise<number> {
159
193
 
160
194
  async function execute(
161
195
  options: StartOptions,
196
+ {
197
+ credential,
198
+ host,
199
+ baseBranch,
200
+ }: { credential: Credential; host: HostKind; baseBranch: string },
162
201
  log: (line: string) => void,
163
202
  stopping: StopSignal,
164
203
  ): Promise<number> {
@@ -183,11 +222,7 @@ async function execute(
183
222
  repository: options.repository,
184
223
  });
185
224
 
186
- // Once per Run, before any Ticket: every branch, rebase, pull request and
187
- // pull of this Run goes to the branch this answers.
188
- const baseBranch = await resolveBaseBranch(tracker, config);
189
-
190
- // Once per Run as well: only a Target that is the pipeline's own repository
225
+ // Once per Run: only a Target that is the pipeline's own repository
191
226
  // has a checkout that is the pipeline, and every Stage is told which it is in.
192
227
  const selfHosted = await isPipelineRepository(tracker, options.repository);
193
228
 
@@ -199,7 +234,9 @@ async function execute(
199
234
  repoRoot,
200
235
  runId,
201
236
  version,
202
- host: hostKind(process.env),
237
+ host,
238
+ credential,
239
+ strayStages: [],
203
240
  baseBranch,
204
241
  // Once per Run as well, and for the same reason: the Tickets of one Run
205
242
  // take turns between their rebase and their merge, and a Landing made per
@@ -223,7 +260,9 @@ async function execute(
223
260
  version,
224
261
  runId,
225
262
  durationMs: Date.now() - startedAt,
263
+ credential,
226
264
  outcomes,
265
+ strayStages: pipeline.strayStages,
227
266
  ...(newer === undefined ? {} : { newer }),
228
267
  stop,
229
268
  });
package/src/templates.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  import { UNCHECKED_BOX } from "./acceptance-criteria.js";
7
+ import { CREDENTIAL_WORDS, type Credential, type StrayStage } from "./credential.js";
7
8
  import type { GuardReason } from "./guards.js";
8
9
  import type { HostKind } from "./host.js";
9
10
  import type { FailurePoint } from "./lifecycle.js";
@@ -513,7 +514,14 @@ export interface RunSummary {
513
514
  version: string;
514
515
  runId: string;
515
516
  durationMs: number;
517
+ /** What the Run's Stages were billed to, which its header names. */
518
+ credential: Credential;
516
519
  outcomes: TicketOutcome[];
520
+ /**
521
+ * Every Stage that said it ran on something else, each named in a row after
522
+ * its own Ticket's.
523
+ */
524
+ strayStages?: readonly StrayStage[];
517
525
  /**
518
526
  * The line saying a newer Version is out, where one is. Above the header
519
527
  * rather than below it: the Run already said this hours ago, at the top of a
@@ -526,34 +534,54 @@ export interface RunSummary {
526
534
 
527
535
  /**
528
536
  * What a Release is put down to, in the words the Run summary and the log
529
- * share: the subscription rate limit, a transient API failure, or a Base
530
- * branch that fails the Check the Ticket's branch failed.
537
+ * share: the rate limit, a transient API failure, an API key out of credit or
538
+ * past its spend limit, or a Base branch that fails the Check the Ticket's
539
+ * branch failed.
531
540
  */
532
541
  export const RELEASE_WORDS: Record<ReleaseCause, string> = {
533
542
  "rate-limited": "rate limit",
534
543
  "api-error": "API failure",
544
+ "out-of-budget": "out of API budget",
535
545
  "failing-base": "failing Base branch",
536
546
  };
537
547
 
548
+ /**
549
+ * The same words, for a Run on `credential`. A rate limit on an `--api-key`
550
+ * Run is the API's, not the subscription's, and is named so: what the human
551
+ * looks at about it is the Console, not their plan.
552
+ */
553
+ export function releaseWords(cause: ReleaseCause, credential: Credential): string {
554
+ return cause === "rate-limited" && credential === "api-key"
555
+ ? "API rate limit"
556
+ : RELEASE_WORDS[cause];
557
+ }
558
+
538
559
  /** Every summary row is `<verb> #<n> <detail>`, so the numbers line up. */
539
560
  const VERB_WIDTH = 9;
540
561
 
541
562
  /**
542
563
  * What a Run prints when it ends. One line per Ticket, then why the Run
543
564
  * stopped — the Frontier is empty, everything left on it is blocked, the rate
544
- * limit, a transient API failure or a failing Base branch released a Ticket and
545
- * the Run went no further, or a human stopped it.
565
+ * limit, a transient API failure, the API key's budget or a failing Base branch
566
+ * released a Ticket and the Run went no further, or a human stopped it.
546
567
  */
547
568
  export function runSummary({
548
569
  version,
549
570
  runId,
550
571
  durationMs,
572
+ credential,
551
573
  outcomes,
574
+ strayStages = [],
552
575
  newer,
553
576
  stop,
554
577
  }: RunSummary): string {
555
578
  const rows = [
556
- ...outcomes.flatMap(ticketRows),
579
+ ...outcomes.flatMap((outcome) => [
580
+ ...ticketRows(outcome, credential),
581
+ ...strayStages
582
+ .filter((stray) => stray.ticket === outcome.ticket)
583
+ .map((stray) => row("billed", stray.ticket, `${stray.stage} · apiKeySource ${stray.apiKeySource}`)),
584
+ ]),
557
585
  // Only a Run that reached the end of the Frontier can name what was held
558
586
  // back all Run, so only that stop carries candidates to skip.
559
587
  ...(stop.reason === "frontier"
@@ -563,24 +591,28 @@ export function runSummary({
563
591
 
564
592
  return [
565
593
  ...(newer === undefined ? [] : [newer]),
566
- `ticket-runner ${version} run ${runId} · ${Math.round(durationMs / 60_000)}m`,
594
+ `ticket-runner ${version} run ${runId} · ${Math.round(durationMs / 60_000)}m · ${CREDENTIAL_WORDS[credential]}`,
567
595
  "",
568
596
  ...(rows.length === 0 ? [" nothing to do"] : rows),
569
597
  "",
570
- lastLine(stop),
598
+ lastLine(stop, credential),
571
599
  "",
572
600
  ].join("\n");
573
601
  }
574
602
 
575
603
  /** The one line that says why the Run stopped. */
576
- function lastLine(stop: RunStop): string {
604
+ function lastLine(stop: RunStop, credential: Credential): string {
577
605
  switch (stop.reason) {
578
- case "rate-limited":
606
+ case "rate-limited": {
607
+ const limited = credential === "api-key" ? "API rate limited" : "Rate limited";
579
608
  return stop.resetsAt === undefined
580
- ? "Rate limited."
581
- : `Rate limited · resets ${utcMinute(stop.resetsAt)}.`;
609
+ ? `${limited}.`
610
+ : `${limited} · resets ${utcMinute(stop.resetsAt)}.`;
611
+ }
582
612
  case "api-error":
583
613
  return "API failure.";
614
+ case "out-of-budget":
615
+ return "Out of API budget.";
584
616
  case "failing-base":
585
617
  return `Base branch \`${stop.baseBranch}\` fails \`${stop.command}\` at ${stop.commit.slice(0, 7)}.`;
586
618
  case "stopped":
@@ -618,9 +650,9 @@ function holding(busy: number[]): string {
618
650
  * The Notes follow their own Ticket rather than being gathered at the end, so a
619
651
  * Run that took six Tickets still says which one noticed what.
620
652
  */
621
- function ticketRows(outcome: TicketOutcome): string[] {
653
+ function ticketRows(outcome: TicketOutcome, credential: Credential): string[] {
622
654
  return [
623
- ticketRow(outcome),
655
+ ticketRow(outcome, credential),
624
656
  ...(outcome.outcome === "skipped" ? [] : outcome.notes.map(noteRow)),
625
657
  ];
626
658
  }
@@ -653,7 +685,7 @@ function noteRow({ origin, stage, issue, opened, summary }: RoutedNote): string
653
685
  }
654
686
 
655
687
  /** One Ticket's line in a summary: what happened to it, and where to look. */
656
- function ticketRow(outcome: TicketOutcome): string {
688
+ function ticketRow(outcome: TicketOutcome, credential: Credential): string {
657
689
  switch (outcome.outcome) {
658
690
  case "merged":
659
691
  return row("merged", outcome.ticket, `${outcome.title} (PR #${outcome.pullRequest})`);
@@ -669,7 +701,7 @@ function ticketRow(outcome: TicketOutcome): string {
669
701
  return row(
670
702
  "released",
671
703
  outcome.ticket,
672
- `${outcome.title} · ${RELEASE_WORDS[outcome.cause]} at ${outcome.stage}`,
704
+ `${outcome.title} · ${releaseWords(outcome.cause, credential)} at ${outcome.stage}`,
673
705
  );
674
706
  case "skipped":
675
707
  // The reason is the guard's own word for it, which is also the marker on