ticket-runner 0.6.3 → 0.6.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ticket-runner",
3
- "version": "0.6.3",
3
+ "version": "0.6.4",
4
4
  "description": "Drives the mattpocock-skills chain: humans plan, the pipeline executes.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -63,6 +63,11 @@ interface ResultEvent {
63
63
  subtype?: string;
64
64
  is_error?: boolean;
65
65
  num_turns?: number;
66
+ /**
67
+ * What the CLI priced the whole session at so far, in dollars. Unlike
68
+ * `num_turns`, it is the session's on every waking, not the waking's.
69
+ */
70
+ total_cost_usd?: unknown;
66
71
  result?: unknown;
67
72
  structured_output?: unknown;
68
73
  /**
@@ -93,8 +98,11 @@ interface InitEvent {
93
98
  */
94
99
  interface RateLimitEvent {
95
100
  type: "rate_limit_event";
96
- /** `resetsAt` is when the limit resets, in seconds since the epoch. */
97
- rate_limit_info?: { status?: string; resetsAt?: number };
101
+ /**
102
+ * `resetsAt` is when the limit resets, in seconds since the epoch, and
103
+ * `isUsingOverage` whether the request ran on the plan's extra usage.
104
+ */
105
+ rate_limit_info?: { status?: string; resetsAt?: number; isUsingOverage?: unknown };
98
106
  }
99
107
 
100
108
  /**
@@ -183,6 +191,7 @@ export class ClaudeAgentRunner implements AgentRunner {
183
191
  const turns = countTurns(results);
184
192
  const resetsAt = failure === "rate-limited" ? limitResetsAt(events) : undefined;
185
193
  const apiKeySource = keySource(events);
194
+ const cost = sessionCost(execution, events);
186
195
 
187
196
  return {
188
197
  ok: failure === undefined,
@@ -193,6 +202,8 @@ export class ClaudeAgentRunner implements AgentRunner {
193
202
  ...(turns === undefined ? {} : { turns }),
194
203
  ...(resetsAt === undefined ? {} : { limitResetsAt: resetsAt }),
195
204
  ...(apiKeySource === undefined ? {} : { apiKeySource }),
205
+ ...cost,
206
+ ...(events.some(usedExtraUsage) ? { extraUsage: true } : {}),
196
207
  // The clock is the runner's own. A session that woke for a background
197
208
  // agent reports one `duration_ms` per waking, and the time it spent
198
209
  // waiting for that agent belongs to none of them.
@@ -227,6 +238,39 @@ function countTurns(results: ResultEvent[]): number | undefined {
227
238
  return counted.reduce((sum, result) => sum + (result.num_turns ?? 0), 0);
228
239
  }
229
240
 
241
+ /**
242
+ * What the CLI priced the session at: the latest figure a `result` event gave.
243
+ * Every waking repeats the session's running total, so the last one is the
244
+ * whole session and summing them would count the early turns again.
245
+ *
246
+ * The figure is only part of the session's where the session did not end on
247
+ * the event that gave it: anything printed after it, a later `result` event
248
+ * without a figure included, or a kill at the wall-clock limit, which can land
249
+ * while a background agent runs and prints nothing.
250
+ */
251
+ function sessionCost(
252
+ execution: Execution,
253
+ events: unknown[],
254
+ ): { costUsd?: number; costIncomplete?: true } {
255
+ const priced = events.findLastIndex(
256
+ (event) => isResultEvent(event) && isAmount(event.total_cost_usd),
257
+ );
258
+ if (priced === -1) return {};
259
+ const costUsd = (events[priced] as ResultEvent).total_cost_usd as number;
260
+ const incomplete = execution.timedOut || priced < events.length - 1;
261
+ return incomplete ? { costUsd, costIncomplete: true } : { costUsd };
262
+ }
263
+
264
+ /** A figure a `result` event can be read for: a finite number. */
265
+ function isAmount(value: unknown): value is number {
266
+ return typeof value === "number" && Number.isFinite(value);
267
+ }
268
+
269
+ /** A `rate_limit_event` saying the request ran on the plan's extra usage. */
270
+ function usedExtraUsage(event: unknown): boolean {
271
+ return isRateLimitEvent(event) && event.rate_limit_info?.isUsingOverage === true;
272
+ }
273
+
230
274
  /** A session that could not even start still has to leave a trace behind. */
231
275
  async function spawnFailure(error: unknown): Promise<Execution> {
232
276
  const message = `ticket-runner could not start the Stage: ${(error as Error).message}\n`;
package/src/config.ts CHANGED
@@ -53,7 +53,7 @@ const configSchema = z
53
53
  .optional(),
54
54
  permissionMode: z.enum(PERMISSION_MODES).optional(),
55
55
  ciTimeoutMinutes: z.number().positive().optional(),
56
- ciGraceMinutes: z.number().positive().optional(),
56
+ ciGraceMinutes: z.number().nonnegative().optional(),
57
57
  checkTimeoutMinutes: z.number().positive().optional(),
58
58
  labels: z
59
59
  .object({
@@ -112,7 +112,8 @@ export interface Config {
112
112
  /**
113
113
  * How long a pull request GitHub has registered no check run for still counts
114
114
  * as pending. A Target whose Actions queue slowly raises it; a Target with no
115
- * CI workflow pays it once per Landing, so it is not the CI timeout.
115
+ * CI sets it to zero, or else pays it once per Landing, so it is not the CI
116
+ * timeout.
116
117
  */
117
118
  ciGraceMinutes: number;
118
119
  /**
@@ -79,9 +79,9 @@ What \`ticket-runner\` requires of this repository, and nothing else. \`ticket-r
79
79
 
80
80
  ## Commits
81
81
 
82
- - Subject: \`<type>(<scope>): <summary> (#<n>)\`, where \`<n>\` is the Ticket number. Every commit carries the number, so no commit has to be traced back to the work it was part of.
83
- - The type and scope vocabulary is this repository's own. The pipeline reads the shape and the number, never the words.
84
- - A commit subject describes its own commit. The whole branch is summarised by the \`title\` the implement and fix Stages each answer beside their Notes: one line in the same shape without the \`(#<n>)\`. The latest one becomes the pull request title, and the pull request title becomes the subject of the squash commit that lands.
82
+ - Subject: \`<type>(<scope>): <summary>\`.
83
+ - The type and scope vocabulary is this repository's own. The pipeline reads the shape, never the words.
84
+ - A commit subject describes its own commit. The whole branch is summarised by the \`title\` the implement and fix Stages each answer beside their Notes: one line in the same shape. The latest one becomes the pull request title, and the pull request title becomes the subject of the squash commit that lands.
85
85
 
86
86
  ## Branches
87
87
 
package/src/credential.ts CHANGED
@@ -41,6 +41,90 @@ export interface StrayStage {
41
41
  stage: string;
42
42
  /** What the Stage's `system/init` event said it ran on. */
43
43
  apiKeySource: string;
44
+ /** What the CLI priced the Stage at, where it said. */
45
+ costUsd?: number;
46
+ /** Present, and true, where {@link costUsd} is only part of the Stage's. */
47
+ costIncomplete?: true;
48
+ }
49
+
50
+ /**
51
+ * What a Run's Stages were billed, gathered as each comes back and shared by
52
+ * every Ticket, for the Run summary and nothing else: the log and the Progress
53
+ * comment carry no amount.
54
+ */
55
+ export interface Billing {
56
+ /** Every Stage that ran on something other than the Run's credential, in order. */
57
+ strays: StrayStage[];
58
+ /**
59
+ * The Spend, in dollars: the CLI's figures for the Stages of an `--api-key`
60
+ * Run that ran on the Run's own key, added up, which is the amount that key's
61
+ * Console can be checked against. Always zero on a subscription Run, whose
62
+ * figure is an estimate at API prices and not money spent.
63
+ */
64
+ spendUsd: number;
65
+ /**
66
+ * Whether a Stage that ran on the Run's own key reported no figure, or only
67
+ * part of its session's — one the wall-clock limit stopped or that crashed —
68
+ * so the Spend is at least {@link spendUsd}.
69
+ */
70
+ spendUnreported: boolean;
71
+ /** Whether any Stage said it ran on the subscription's extra usage. */
72
+ extraUsage: boolean;
73
+ }
74
+
75
+ /** A Run's billing before any Stage has come back. */
76
+ export function emptyBilling(): Billing {
77
+ return { strays: [], spendUsd: 0, spendUnreported: false, extraUsage: false };
78
+ }
79
+
80
+ /** What a Stage said about what it was billed to, as far as {@link Billing} needs it. */
81
+ export interface StageBilling {
82
+ /** What the Stage's `system/init` event said it ran on, absent where it printed none. */
83
+ apiKeySource?: string;
84
+ /** What the CLI priced the Stage at, absent where no `result` event gave a figure. */
85
+ costUsd?: number;
86
+ /** Present, and true, where {@link costUsd} is only part of the Stage's. */
87
+ costIncomplete?: true;
88
+ /** Present, and true, where the Stage ran on the subscription's extra usage. */
89
+ extraUsage?: true;
90
+ }
91
+
92
+ /**
93
+ * Add one Stage of a Run on `credential` to the Run's billing, and return it as
94
+ * a stray where it ran on something else.
95
+ *
96
+ * A Stage that reported no `apiKeySource` printed no `system/init` event and so
97
+ * made no request: it is no stray, adds no Spend and leaves the Spend exact. A
98
+ * stray's figure stays on its own row and out of the Spend, which is the Run's
99
+ * own key's alone.
100
+ */
101
+ export function recordStage(
102
+ billing: Billing,
103
+ credential: Credential,
104
+ ticket: number,
105
+ stage: string,
106
+ { apiKeySource, costUsd, costIncomplete, extraUsage }: StageBilling,
107
+ ): StrayStage | undefined {
108
+ if (extraUsage === true) billing.extraUsage = true;
109
+ if (apiKeySource === undefined) return undefined;
110
+
111
+ if (apiKeySource !== expectedKeySource(credential)) {
112
+ const stray: StrayStage = {
113
+ ticket,
114
+ stage,
115
+ apiKeySource,
116
+ ...(costUsd === undefined ? {} : { costUsd }),
117
+ ...(costUsd !== undefined && costIncomplete === true ? { costIncomplete } : {}),
118
+ };
119
+ billing.strays.push(stray);
120
+ return stray;
121
+ }
122
+
123
+ if (credential === "api-key") {
124
+ if (costUsd === undefined || costIncomplete === true) billing.spendUnreported = true;
125
+ billing.spendUsd += costUsd ?? 0;
126
+ }
127
+ return undefined;
44
128
  }
45
129
 
46
130
  /**
@@ -1,10 +1,11 @@
1
1
  import { branchName, worktreePath } from "./branch.js";
2
2
  import type { Config } from "./config.js";
3
3
  import {
4
+ type Billing,
4
5
  CREDENTIAL_WORDS,
5
6
  type Credential,
6
- type StrayStage,
7
7
  expectedKeySource,
8
+ recordStage,
8
9
  } from "./credential.js";
9
10
  import { tickMetCriteria } from "./criteria.js";
10
11
  import type { BaseBranchChecks, FailingBase } from "./failing-base.js";
@@ -57,6 +58,7 @@ import {
57
58
  pullRequestBody,
58
59
  squashCommit,
59
60
  } from "./templates.js";
61
+ import type { StartTimer } from "./timer.js";
60
62
  import { CODE_STAGE_JSON_SCHEMA, parseTitle, pullRequestTitle } from "./title.js";
61
63
  import {
62
64
  type Verdict,
@@ -139,11 +141,11 @@ export interface Pipeline {
139
141
  */
140
142
  credential: Credential;
141
143
  /**
142
- * Every Stage of this Run that said it ran on something other than
143
- * {@link credential}, in the order they came back, shared by every Ticket so
144
- * the Run summary can name them all.
144
+ * What every Stage of this Run said it was billed, shared by every Ticket so
145
+ * the Run summary can name each Stage that ran on something other than
146
+ * {@link credential}, and say what the Run spent.
145
147
  */
146
- strayStages: StrayStage[];
148
+ billing: Billing;
147
149
  /**
148
150
  * The branch every Ticket of this Run branches from, rebases onto, merges
149
151
  * into and pulls, resolved once before the Run started
@@ -175,6 +177,12 @@ export interface Pipeline {
175
177
  * there is a Stage told to exercise it through its tests and fakes.
176
178
  */
177
179
  selfHosted: boolean;
180
+ /**
181
+ * How the Run waits between its looks at the Frontier while a Lane is free
182
+ * and another busy: the real clock, unless a test hands it one it moves
183
+ * itself. Never the interval, which is fixed.
184
+ */
185
+ startTimer?: StartTimer;
178
186
  log?: (line: string) => void;
179
187
  }
180
188
 
@@ -938,29 +946,29 @@ async function runStage(
938
946
  ? {}
939
947
  : { resultRequired: request.resultRequired }),
940
948
  });
941
- noteStrayCredential(pipeline, request.ticket, stage, result);
949
+ noteBilling(pipeline, request.ticket, stage, result);
942
950
  return result;
943
951
  }
944
952
 
945
953
  /**
946
- * Name a Stage whose `system/init` event reported another `apiKeySource` than
947
- * the Run's credential expects, in the log now and in the summary at the end.
948
- * A Stage that reported none, one that never started, is not named: there is
949
- * nothing it said to set against the Run's choice.
954
+ * 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,
957
+ * one that never started, is not named: there is nothing it said to set
958
+ * against the Run's choice. The log line carries no amount: the summary is the
959
+ * only place one is printed.
950
960
  */
951
- function noteStrayCredential(
961
+ function noteBilling(
952
962
  pipeline: Pipeline,
953
963
  ticket: number,
954
964
  stage: StageName,
955
965
  result: StageResult,
956
966
  ): void {
957
- const { apiKeySource } = result;
958
- const expected = expectedKeySource(pipeline.credential);
959
- if (apiKeySource === undefined || apiKeySource === expected) return;
960
- pipeline.strayStages.push({ ticket, stage, apiKeySource });
967
+ const stray = recordStage(pipeline.billing, pipeline.credential, ticket, stage, result);
968
+ if (stray === undefined) return;
961
969
  pipeline.log?.(
962
- `#${ticket} ${stage} ran on apiKeySource ${apiKeySource}, ` +
963
- `not the ${CREDENTIAL_WORDS[pipeline.credential]} (${expected})`,
970
+ `#${ticket} ${stage} ran on apiKeySource ${stray.apiKeySource}, ` +
971
+ `not the ${CREDENTIAL_WORDS[pipeline.credential]} (${expectedKeySource(pipeline.credential)})`,
964
972
  );
965
973
  }
966
974
 
@@ -1271,9 +1279,11 @@ async function runChecks(
1271
1279
  );
1272
1280
  }
1273
1281
  }
1282
+ // No command is not a pass: only `gates.checks` off lets a Run start with
1283
+ // none, and the row says so as the ci row does for a pull request with none.
1274
1284
  await progress.record({
1275
1285
  point: "checks",
1276
- outcome: "✅ passed",
1286
+ outcome: pipeline.config.checks.length === 0 ? "⚠️ no checks" : "✅ passed",
1277
1287
  durationMs: Date.now() - startedAt,
1278
1288
  });
1279
1289
  }
@@ -96,6 +96,26 @@ export interface StageResult {
96
96
  * session printed no such event.
97
97
  */
98
98
  apiKeySource?: string;
99
+ /**
100
+ * What the CLI priced the session at, in dollars: the `total_cost_usd` of its
101
+ * last `result` event. A session that woke for background agents repeats the
102
+ * whole session's figure on every waking, so it is read once, never summed.
103
+ * Absent where no `result` event carried one: a session a Stop killed, the
104
+ * wall-clock limit stopped, or that crashed before it.
105
+ */
106
+ costUsd?: number;
107
+ /**
108
+ * Present, and true, when {@link costUsd} is only part of the session's:
109
+ * the session went on past the last `result` event that gave a figure, and
110
+ * was killed or crashed before it gave another, or the wall-clock limit
111
+ * stopped it while it waited for a background agent.
112
+ */
113
+ costIncomplete?: true;
114
+ /**
115
+ * Present, and true, when one of the session's `rate_limit_event`s said it
116
+ * was using the subscription's extra usage (`isUsingOverage`).
117
+ */
118
+ extraUsage?: true;
99
119
  }
100
120
 
101
121
  /**
package/src/prompts.ts CHANGED
@@ -86,8 +86,13 @@ const titleGuidance = (base: string) =>
86
86
  /**
87
87
  * Guidance appended to every implement Stage, working around known defects of
88
88
  * the `implement` skill in an unattended session.
89
+ *
90
+ * The Ticket's URL is handed to the review explicitly: the review looks for its
91
+ * spec in the commit messages first, the skill does not always pass it on, and
92
+ * commit subjects need not carry the Ticket number.
89
93
  */
90
94
  const implementGuidance = (
95
+ issueUrl: string,
91
96
  base: string,
92
97
  checks: readonly string[],
93
98
  ) => `This session is unattended. Follow this guidance as well as the skill's own:
@@ -95,6 +100,7 @@ const implementGuidance = (
95
100
  - Make an initial commit before running \`/mattpocock-skills:code-review\`, so the reviewed diff is not empty.
96
101
  ${titleGuidance(base)}
97
102
  - The review the skill asks for is \`/mattpocock-skills:code-review\`. Invoke it by that full name: the short name also matches the CLI's own built-in review skill, which runs neither the Standards review nor the Spec review.
103
+ - Pass the review this Ticket's URL, \`${issueUrl}\`, as the spec. It otherwise looks for the spec in the commit messages, which need not name the Ticket, and reviews with no spec without saying so.
98
104
  - Spawn its review sub-agents with \`run_in_background: false\` set explicitly, several in one message so they still run in parallel. Omitting \`run_in_background\` still runs them in the background, and you would then reach your answer before the review has come back.
99
105
  - Do not answer the schema until the review has returned and the fixes you take from it are committed. An answer you have already given does not stop you committing: the pipeline waits for this session to exit before it reads the branch.
100
106
  - A later answer replaces an earlier one, so if you answer again, repeat every Note you still stand by.${codeChecksLine(checks, true)}
@@ -284,7 +290,7 @@ export function implementPrompt(
284
290
  ): string {
285
291
  return sections([
286
292
  `/mattpocock-skills:implement ${issueUrl}`,
287
- implementGuidance(base, checks),
293
+ implementGuidance(issueUrl, base, checks),
288
294
  stageBoundary(selfHosted),
289
295
  notesGuidance(standingNotes),
290
296
  extraPrompt,
package/src/run.ts CHANGED
@@ -6,6 +6,14 @@ import { type Pipeline, type TicketOutcome, processTicket } from "./orchestrator
6
6
  import { StopSignal, stopLine } from "./stop.js";
7
7
  import { holdsClaim, strandedTickets } from "./stranded.js";
8
8
  import { releaseWords } from "./templates.js";
9
+ import { startTimer } from "./timer.js";
10
+
11
+ /**
12
+ * How long a free Lane waits, after the Run last listed the Frontier, before it
13
+ * looks at the Frontier again while another Lane is busy. Fixed: nothing in the
14
+ * Target's config or on the command line sets it, and nothing turns it off.
15
+ */
16
+ export const POLL_MS = 5 * 60_000;
9
17
 
10
18
  /**
11
19
  * What a Run has to show for itself: every Ticket it took, in the order they
@@ -73,6 +81,15 @@ export type RunStop =
73
81
  * working is still an open blocker. Those edges are the whole of what keeps two
74
82
  * Tickets apart: no heuristic here decides which are safe together.
75
83
  *
84
+ * A Ticket can also join the Frontier with no Lane ending — a human labels it
85
+ * `ready-for-agent`, or closes its last blocker outside the Run — so while one
86
+ * Lane is free and another busy, the Run looks at the Frontier again
87
+ * {@link POLL_MS} after it last listed it, whatever listed it, and takes what
88
+ * a refill would. A Run with nothing busy has nothing to wait for and ends, as
89
+ * before: it never waits for new Tickets. A look that cannot list is logged
90
+ * and tried again next time, since nothing about the Run depended on it; a
91
+ * refill that cannot list still ends the Run's claiming.
92
+ *
76
93
  * A Ticket that fails is handed off and the Lane moves on: one bad Ticket must
77
94
  * not cost the rest of the night.
78
95
  *
@@ -122,7 +139,7 @@ export async function processRun(
122
139
  // that several Lanes came back during sees every one of them free.
123
140
  const busy = new Map<number, Promise<void>>();
124
141
  // What the last Frontier this Run computed held back, which is what a Run
125
- // that drained the Frontier reports. Replaced at every refill: a candidate a
142
+ // that drained the Frontier reports. Replaced at every listing: a candidate a
126
143
  // Lane unblocked on the way is not one the Run was still held up by.
127
144
  let blocked: number[] = [];
128
145
  // Why this Run stopped, which is also what it reports. Set by whichever of
@@ -137,6 +154,12 @@ export async function processRun(
137
154
  // went down, so the error waits for them and is thrown where a Run with one
138
155
  // Lane threw it: out of the Run, with nothing else left running.
139
156
  let listing: unknown;
157
+ // How many Lanes have ended, and how many had when the last pass listed the
158
+ // Frontier, which tells a refill a Lane's ending brought from a look the
159
+ // clock brought: a listing that fails is the Run's to throw only in the
160
+ // first. -1 until the first pass, which is a refill too.
161
+ let ended = 0;
162
+ let endedAtLastPass = -1;
140
163
 
141
164
  // Registered before the sweep, because a Stop that arrives during it is a Run
142
165
  // that claims nothing at all: the Lanes are empty, so there is nothing to
@@ -181,6 +204,7 @@ export async function processRun(
181
204
  ticket.number,
182
205
  take(pipeline, ticket).then((outcome) => {
183
206
  busy.delete(ticket.number);
207
+ ended += 1;
184
208
  outcomes.push(outcome);
185
209
  if (outcome.outcome !== "released") return;
186
210
  if (runStop === undefined) {
@@ -228,18 +252,50 @@ export async function processRun(
228
252
  }
229
253
  }
230
254
 
255
+ /**
256
+ * Whether a free Lane should look at the Frontier again before a busy one
257
+ * ends. Only after a pass that listed it, which every pass that leaves a Lane
258
+ * free while the Run is still taking Tickets did: so the wait counts from
259
+ * that listing.
260
+ */
261
+ function polling(): boolean {
262
+ return runStop === undefined && listing === undefined && busy.size > 0 && laneFree();
263
+ }
264
+
265
+ /** Wait for a Lane to end, or for the time to look at the Frontier again. */
266
+ async function nextPass(): Promise<void> {
267
+ const ending = Promise.race(busy.values());
268
+ if (!polling()) return await ending;
269
+ const poll = (pipeline.startTimer ?? startTimer)(POLL_MS);
270
+ try {
271
+ await Promise.race([ending, poll.elapsed]);
272
+ } finally {
273
+ poll.cancel();
274
+ }
275
+ }
276
+
231
277
  for (;;) {
232
278
  if (runStop === undefined && listing === undefined) {
279
+ const endedBefore = ended;
280
+ const looking = endedBefore === endedAtLastPass;
233
281
  try {
234
282
  await fillLanes();
283
+ endedAtLastPass = ended;
235
284
  } catch (error) {
236
- listing = error;
285
+ if (!looking) {
286
+ listing = error;
287
+ } else {
288
+ pipeline.log?.(pollFailure(error));
289
+ // A Lane that ended while the look was listing is still owed its
290
+ // refill, which runs now, and only that one's failure is the Run's.
291
+ if (ended !== endedBefore) continue;
292
+ }
237
293
  }
238
294
  }
239
295
  // Never while a Lane is busy, whatever the Frontier had to offer: that Lane
240
296
  // may be about to close the blocker the rest of the Frontier is waiting on.
241
297
  if (busy.size === 0) break;
242
- await Promise.race(busy.values());
298
+ await nextPass();
243
299
  }
244
300
 
245
301
  if (listing !== undefined) throw listing;
@@ -255,6 +311,12 @@ export async function processRun(
255
311
  return { outcomes, stop };
256
312
  }
257
313
 
314
+ /** The one line a look at the Frontier that could not list it earns. */
315
+ function pollFailure(error: unknown): string {
316
+ const minutes = POLL_MS / 60_000;
317
+ return `listing the Frontier failed, trying again in ${minutes} minutes · ${(error as Error).message}`;
318
+ }
319
+
258
320
  /**
259
321
  * The stop a Release puts on the Run: what released it, when a limit resets,
260
322
  * and which Check the Base branch fails.
package/src/start.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { resolveBaseBranch } from "./base-branch.js";
2
2
  import type { Config } from "./config.js";
3
- import { type Credential, credentialRefusal } from "./credential.js";
3
+ import { type Credential, credentialRefusal, emptyBilling } from "./credential.js";
4
4
  import { type HostKind, hostKind } from "./host.js";
5
5
  import { BaseBranchChecks } from "./failing-base.js";
6
6
  import { Landing } from "./landing.js";
@@ -236,7 +236,7 @@ async function execute(
236
236
  version,
237
237
  host,
238
238
  credential,
239
- strayStages: [],
239
+ billing: emptyBilling(),
240
240
  baseBranch,
241
241
  // Once per Run as well, and for the same reason: the Tickets of one Run
242
242
  // take turns between their rebase and their merge, and a Landing made per
@@ -262,7 +262,7 @@ async function execute(
262
262
  durationMs: Date.now() - startedAt,
263
263
  credential,
264
264
  outcomes,
265
- strayStages: pipeline.strayStages,
265
+ billing: pipeline.billing,
266
266
  ...(newer === undefined ? {} : { newer }),
267
267
  stop,
268
268
  });
package/src/templates.ts CHANGED
@@ -4,7 +4,13 @@
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
+ import {
8
+ type Billing,
9
+ CREDENTIAL_WORDS,
10
+ type Credential,
11
+ type StrayStage,
12
+ emptyBilling,
13
+ } from "./credential.js";
8
14
  import type { GuardReason } from "./guards.js";
9
15
  import type { HostKind } from "./host.js";
10
16
  import type { FailurePoint } from "./lifecycle.js";
@@ -518,10 +524,11 @@ export interface RunSummary {
518
524
  credential: Credential;
519
525
  outcomes: TicketOutcome[];
520
526
  /**
521
- * Every Stage that said it ran on something else, each named in a row after
522
- * its own Ticket's.
527
+ * What the Run's Stages said they were billed: the Spend or extra usage its
528
+ * header gives, and every Stage that said it ran on something else, each
529
+ * named in a row after its own Ticket's.
523
530
  */
524
- strayStages?: readonly StrayStage[];
531
+ billing?: Billing;
525
532
  /**
526
533
  * The line saying a newer Version is out, where one is. Above the header
527
534
  * rather than below it: the Run already said this hours ago, at the top of a
@@ -571,16 +578,14 @@ export function runSummary({
571
578
  durationMs,
572
579
  credential,
573
580
  outcomes,
574
- strayStages = [],
581
+ billing = emptyBilling(),
575
582
  newer,
576
583
  stop,
577
584
  }: RunSummary): string {
578
585
  const rows = [
579
586
  ...outcomes.flatMap((outcome) => [
580
587
  ...ticketRows(outcome, credential),
581
- ...strayStages
582
- .filter((stray) => stray.ticket === outcome.ticket)
583
- .map((stray) => row("billed", stray.ticket, `${stray.stage} · apiKeySource ${stray.apiKeySource}`)),
588
+ ...billing.strays.filter((stray) => stray.ticket === outcome.ticket).map(billedRow),
584
589
  ]),
585
590
  // Only a Run that reached the end of the Frontier can name what was held
586
591
  // back all Run, so only that stop carries candidates to skip.
@@ -591,7 +596,7 @@ export function runSummary({
591
596
 
592
597
  return [
593
598
  ...(newer === undefined ? [] : [newer]),
594
- `ticket-runner ${version} run ${runId} · ${Math.round(durationMs / 60_000)}m · ${CREDENTIAL_WORDS[credential]}`,
599
+ `ticket-runner ${version} run ${runId} · ${Math.round(durationMs / 60_000)}m · ${billedTo(credential, billing)}`,
595
600
  "",
596
601
  ...(rows.length === 0 ? [" nothing to do"] : rows),
597
602
  "",
@@ -600,6 +605,38 @@ export function runSummary({
600
605
  ].join("\n");
601
606
  }
602
607
 
608
+ /**
609
+ * What the header says the Run's Stages were billed to. An `--api-key` Run
610
+ * adds its Spend, ending `+` where a Stage on the key reported no figure, so it
611
+ * is at least that much. A subscription Run adds no amount, since its figure
612
+ * is an estimate at API prices and not money spent, only whether a Stage ran
613
+ * on the plan's extra usage.
614
+ */
615
+ function billedTo(credential: Credential, billing: Billing): string {
616
+ const words = CREDENTIAL_WORDS[credential];
617
+ if (credential === "api-key") {
618
+ return `${words} · ${dollars(billing.spendUsd)}${billing.spendUnreported ? "+" : ""}`;
619
+ }
620
+ return billing.extraUsage ? `${words} · extra usage` : words;
621
+ }
622
+
623
+ /**
624
+ * A Stage billed somewhere the Run did not choose, with its own figure where it
625
+ * gave one, ending `+` where that is only part of its session's.
626
+ */
627
+ function billedRow(stray: StrayStage): string {
628
+ const cost =
629
+ stray.costUsd === undefined
630
+ ? ""
631
+ : ` · ${dollars(stray.costUsd)}${stray.costIncomplete === true ? "+" : ""}`;
632
+ return row("billed", stray.ticket, `${stray.stage} · apiKeySource ${stray.apiKeySource}${cost}`);
633
+ }
634
+
635
+ /** An amount of dollars as the Run summary prints one: `$12.34`. */
636
+ function dollars(usd: number): string {
637
+ return `$${usd.toFixed(2)}`;
638
+ }
639
+
603
640
  /** The one line that says why the Run stopped. */
604
641
  function lastLine(stop: RunStop, credential: Credential): string {
605
642
  switch (stop.reason) {
package/src/timer.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * A wait the caller can call off before it elapses.
3
+ *
4
+ * Called off rather than left to run out, because a pending timer keeps Node's
5
+ * process alive: a Run that ended while one was still counting down would
6
+ * hold the terminal until it did.
7
+ */
8
+ export interface Timer {
9
+ /** Resolves once the wait has elapsed, and never if it was called off first. */
10
+ elapsed: Promise<void>;
11
+ /** Call the wait off. Calling it off again, or after it elapsed, does nothing. */
12
+ cancel(): void;
13
+ }
14
+
15
+ /** Start a wait of `ms` milliseconds. */
16
+ export type StartTimer = (ms: number) => Timer;
17
+
18
+ /** A wait on the real clock. */
19
+ export const startTimer: StartTimer = (ms) => {
20
+ let handle: ReturnType<typeof setTimeout> | undefined;
21
+ const elapsed = new Promise<void>((resolve) => {
22
+ handle = setTimeout(resolve, ms);
23
+ });
24
+ return { elapsed, cancel: () => clearTimeout(handle) };
25
+ };
package/src/title.ts CHANGED
@@ -22,7 +22,7 @@ export const BRANCH_TITLE =
22
22
  /** Any `<type>(<scope>): <summary>`; the repo's own types and scopes are CONTRIBUTING.md's business. */
23
23
  const CONVENTIONAL_SUBJECT = /^[a-z]+(\([a-z0-9._-]+\))?: \S/;
24
24
 
25
- /** The `(#<n>)` a branch commit carries, which the squash commit's `Closes #<n>` replaces. */
25
+ /** The `(#<n>)` a commit may carry, which the squash commit's `Closes #<n>` replaces. */
26
26
  const TICKET_REFERENCE = /\s*\(#\d+\)$/;
27
27
 
28
28
  /**