wachiman 1.13.0 → 1.15.0

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 (45) hide show
  1. package/README.md +2 -2
  2. package/bin/wachiman.js +1 -1
  3. package/package.json +5 -4
  4. package/skills/wachiman-review/SKILL.md +2 -2
  5. package/src/accounts/confirm.ts +62 -3
  6. package/src/cli.ts +136 -132
  7. package/src/config.ts +83 -35
  8. package/src/connectors/local-git.ts +1 -1
  9. package/src/cost.ts +28 -1
  10. package/src/engine.ts +396 -38
  11. package/src/help.ts +555 -0
  12. package/src/history/store.ts +5 -5
  13. package/src/init/options.ts +1 -1
  14. package/src/init/run.ts +43 -17
  15. package/src/ledger-read/command.ts +106 -0
  16. package/src/ledger-read/credentials.ts +103 -0
  17. package/src/ledger-read/files.ts +141 -0
  18. package/src/ledger-read/pull.ts +69 -0
  19. package/src/ledger-read/rows.ts +60 -0
  20. package/src/ledger-read/types.ts +127 -0
  21. package/src/ledger.ts +322 -0
  22. package/src/local.ts +4 -4
  23. package/src/providers/claude-code.ts +1 -1
  24. package/src/providers/codex.ts +5 -5
  25. package/src/providers/index.ts +1 -1
  26. package/src/providers/types.ts +3 -3
  27. package/src/setup/run.ts +27 -10
  28. package/src/sinks/common.ts +3 -3
  29. package/src/spend/report.ts +349 -0
  30. package/src/status/command.ts +151 -37
  31. package/src/store/command.ts +20 -3
  32. package/src/store/html.ts +205 -8
  33. package/src/store/index.ts +64 -5
  34. package/src/store/rows.ts +103 -0
  35. package/src/wizard/interactive.ts +11 -0
  36. package/src/wizard/launcher.ts +340 -0
  37. package/src/wizard/load.ts +30 -0
  38. package/src/wizard/mascot.ts +223 -0
  39. package/src/wizard/prompt-fancy.ts +127 -0
  40. package/src/wizard/prompt.ts +95 -61
  41. package/src/wizard/style.ts +93 -13
  42. package/src/wizard/tone.ts +11 -0
  43. package/src/wizard/ui.ts +78 -0
  44. package/templates/caller-workflow.yml +44 -47
  45. package/templates/wachiman-review-caller.yml +5 -0
package/src/setup/run.ts CHANGED
@@ -22,15 +22,15 @@ import {
22
22
  type InteractiveSpawn,
23
23
  } from "../accounts/commands";
24
24
  import { updateConfig, wachimanHome, type ProfileEntry, type ProjectBinding, type WachimanConfigV1 } from "../accounts/config";
25
- import { confirmProfile } from "../accounts/confirm";
25
+ import { confirmProfile, confirmProfileAsync, type AsyncSpawnFn } from "../accounts/confirm";
26
26
  import { managedDir } from "../accounts/profile-list";
27
27
  import { lookupProfileRef, profileLine } from "../accounts/resolve";
28
28
  import { UsageError } from "../config";
29
29
  import { repositoryKey } from "../history/store";
30
30
  import { claimManagedProfile, setupProfile } from "../profiles";
31
31
  import { isInteractive, type TerminalStreams } from "../wizard/interactive";
32
- import { createPrompter, type Prompter, type PromptIO } from "../wizard/prompt";
33
- import { wizardIo } from "../wizard/style";
32
+ import { loadTerminalUi } from "../wizard/load";
33
+ import type { Outcome, Prompter, PromptIO } from "../wizard/prompt";
34
34
  import { resolveSetupOptions, type RawSetupFlags } from "./options";
35
35
  import { promptForSetup, type PendingProfile } from "./prompt";
36
36
 
@@ -43,6 +43,8 @@ export interface SetupDeps extends AccountDeps {
43
43
  unboundHints?: readonly string[];
44
44
  streams?: TerminalStreams;
45
45
  promptIO?: PromptIO;
46
+ /** The asynchronous probe of the account, for a test; the default runs `claude` without blocking the terminal. */
47
+ spawnAsync?: AsyncSpawnFn;
46
48
  /** An open prompt session (shared with `init`); the caller closes it. */
47
49
  prompter?: Prompter;
48
50
  }
@@ -59,7 +61,6 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
59
61
  }
60
62
 
61
63
  const repoDir = flags.repoDir ?? ".";
62
- io = wizardIo(io, (deps.promptIO?.output ?? process.stderr) as { isTTY?: boolean }, env);
63
64
  const home = wachimanHome(env);
64
65
  const userHome = deps.userHome ?? homedir();
65
66
  const now = deps.now ?? (() => new Date().toISOString());
@@ -73,8 +74,11 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
73
74
  if (!found.ok) throw new UsageError(found.problem);
74
75
  }
75
76
 
76
- const prompter = deps.prompter ?? createPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr }, env);
77
+ // The terminal UI (chalk and Clack) is loaded only when questions are asked.
78
+ const ui = await loadTerminalUi();
79
+ const prompter = deps.prompter ?? (await ui.openPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr }, env));
77
80
  const ownsPrompter = deps.prompter === undefined;
81
+ io = ui.wizardIo(io, (deps.promptIO?.output ?? process.stderr) as { isTTY?: boolean }, env, prompter);
78
82
  /** What already happened on disk or in Claude and cannot be rolled back; reported whenever the run ends early. */
79
83
  const effects: string[] = [];
80
84
  const reportEffects = () => {
@@ -108,7 +112,12 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
108
112
  }
109
113
  };
110
114
 
115
+ let outcome: Outcome = "failed";
116
+ let closing: string | undefined;
111
117
  try {
118
+ // Only the command that opened the session plays the intro; `init` already did when it hands over,
119
+ // and so did the launcher (it marks WACHIMAN_INTRO_DONE, which `prompter.intro` honors).
120
+ if (ownsPrompter) await prompter.intro(deps.doctor?.version ?? "unknown", "Let's choose which Claude account stands guard.");
112
121
  let answers;
113
122
  try {
114
123
  answers = await promptForSetup(flags, { repo, current, config, home, userHome, createManaged, fromInit: deps.fromInit, initMode: deps.initMode }, prompter);
@@ -121,12 +130,15 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
121
130
  io.stderr("cancelled: no configuration changes saved.");
122
131
  reportEffects();
123
132
  for (const hint of deps.unboundHints ?? []) io.stderr(`Next, on this machine: ${hint} (binds this repository to a Claude account)`);
133
+ outcome = "cancelled";
124
134
  return 130;
125
135
  }
126
136
  if (answers.kind === "declined") {
127
137
  io.stderr("nothing saved: the configuration is unchanged.");
128
138
  reportEffects();
129
139
  for (const hint of deps.unboundHints ?? []) io.stderr(`Next, on this machine: ${hint} (binds this repository to a Claude account)`);
140
+ outcome = "done";
141
+ closing = "Nothing was saved.";
130
142
  return 0;
131
143
  }
132
144
  const resolved = resolveSetupOptions(answers.flags, { interactive: true });
@@ -147,10 +159,12 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
147
159
  if (!found.ok) throw new UsageError(found.problem);
148
160
  const resolvedProfile = { profile: found.profile, rung: "binding" as const, overridden: [] };
149
161
  io.stderr(profileLine(resolvedProfile));
150
- const probe = () => confirmProfile(resolvedProfile, env, deps.spawn, deps.doctor?.confirmIo);
151
- // The probes block while claude runs; an Enter typed meanwhile must not reach "Sign in now?" through a live readline.
162
+ // The real probe is asynchronous, so the spinner turns while `claude` runs; a test's fake `spawn` is synchronous and is called as it always was.
163
+ const probe = () =>
164
+ deps.spawn ? confirmProfile(resolvedProfile, env, deps.spawn, deps.doctor?.confirmIo) : confirmProfileAsync(resolvedProfile, env, deps.spawnAsync, deps.doctor?.confirmIo);
165
+ // An Enter typed meanwhile must not reach "Sign in now?" through a live readline.
152
166
  prompter.suspend();
153
- let status = probe();
167
+ let status = await prompter.task("Checking your Claude account", probe, (s) => s.ok);
154
168
  const signedOut = !status.ok && status.stage === "auth" && status.auth !== undefined && status.auth.exitCode !== 0;
155
169
  // True once the user was told the account state in its own words, so the generic warning would repeat it.
156
170
  let explained = false;
@@ -159,6 +173,7 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
159
173
  const answer = await prompter.confirm("Sign in now?", true);
160
174
  if (answer === null) {
161
175
  io.stderr(`cancelled: the binding of ${repo.name} to ${name} was saved and stays; you are not signed in (run \`wachiman profile login ${name}\`).`);
176
+ outcome = "cancelled";
162
177
  return 130;
163
178
  }
164
179
  if (answer) {
@@ -166,9 +181,10 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
166
181
  const code = runProfile({ kind: "login", profile: name }, env, io, { ...deps, interactive: true, interactiveSpawn: deps.interactiveSpawn });
167
182
  if (code === 130) {
168
183
  io.stderr(`cancelled: the binding of ${repo.name} to ${name} was saved and stays.`);
184
+ outcome = "cancelled";
169
185
  return 130;
170
186
  }
171
- status = probe();
187
+ status = await prompter.task("Checking your Claude account", probe, (s) => s.ok);
172
188
  } else {
173
189
  io.stderr(`not signed in: run \`wachiman profile login ${name}\` before \`wachiman local\`.`);
174
190
  explained = true;
@@ -181,9 +197,10 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
181
197
  prompter.step("Checks and next actions", total, total);
182
198
  const code = closeSetup(repoDir, env, io, deps);
183
199
  if (flags.json) io.stdout(`${JSON.stringify(projectShow(repoDir, env, deps), null, 2)}\n`);
200
+ outcome = code === 0 ? "done" : code === 130 ? "cancelled" : "failed";
184
201
  return code;
185
202
  } finally {
186
- if (ownsPrompter) prompter.close();
203
+ if (ownsPrompter) prompter.close(outcome, closing);
187
204
  }
188
205
  }
189
206
 
@@ -128,9 +128,9 @@ export function costSentence(e: { costUsdEstimate: number; calls: number; turns:
128
128
 
129
129
  const STOP_REASONS: Record<Exclude<ReviewResult["execution"]["stop"], "complete">, string> = {
130
130
  quota: "the account's usage limit ended the run",
131
- budget: "the run's estimate guard (AGENT_REVIEW_BUDGET_USD) was spent",
132
- turns: "the calls hit the turn limit (AGENT_REVIEW_MAX_TURNS)",
133
- timeout: "the calls hit the time limit (AGENT_REVIEW_CALL_TIMEOUT_S)",
131
+ budget: "the run's estimate guard (WACHIMAN_BUDGET_USD) was spent",
132
+ turns: "the calls hit the turn limit (WACHIMAN_MAX_TURNS)",
133
+ timeout: "the calls hit the time limit (WACHIMAN_CALL_TIMEOUT_S)",
134
134
  error: "no call returned a review",
135
135
  };
136
136
 
@@ -0,0 +1,349 @@
1
+ /**
2
+ * One spend report for laptop runs and GitHub Actions runs (ADR 0039). Pure: rows in, report out. No
3
+ * file, no network, no Bun-only API, so a web page can reuse it. Dollars are never summed across the
4
+ * credential split without the split travelling with them: every figure is a `Split`.
5
+ *
6
+ * Spend is the dollars of finished runs (`settled`). Reservations that never settled and runs that
7
+ * were not reserved are reported as their own lines (`aside`), not as spend. A period outside what was
8
+ * downloaded is `known: false`, never zero.
9
+ */
10
+ export type Source = "laptop" | "actions";
11
+ export const SOURCES: readonly Source[] = ["laptop", "actions"];
12
+ export type RowState = "settled" | "reserved" | "unsettled" | "unreserved";
13
+ export type Credential = "billed" | "estimated" | "unknown";
14
+ export const CREDENTIALS: readonly Credential[] = ["billed", "estimated", "unknown"];
15
+
16
+ /** `api-key` is billed; a subscription token or login gives an API-price estimate, not a charge. */
17
+ export function credentialOf(auth: string): Credential {
18
+ if (auth === "api-key") return "billed";
19
+ if (auth === "oauth-token" || auth === "subscription") return "estimated";
20
+ return "unknown";
21
+ }
22
+
23
+ export interface SpendCall {
24
+ model: string;
25
+ auth: string;
26
+ costUsd: number;
27
+ costKnown: boolean;
28
+ }
29
+
30
+ export interface SpendRow {
31
+ source: Source;
32
+ state: RowState;
33
+ /** UTC `YYYY-MM-DD`. */
34
+ day: string;
35
+ /** The Monday of the row's week, UTC. */
36
+ week: string;
37
+ repositoryKey: string;
38
+ repository: string;
39
+ pr: number | null;
40
+ runId: string;
41
+ profile: string;
42
+ /** Dollars the run spent: for `settled` and `unreserved` rows; 0 for the others. */
43
+ costUsd: number;
44
+ /** Dollars held by a reservation (`reserved`, `unsettled`), else 0. */
45
+ reservedUsd: number;
46
+ calls: SpendCall[];
47
+ }
48
+
49
+ export interface Money {
50
+ runs: number;
51
+ calls: number;
52
+ usd: number;
53
+ }
54
+ export interface Split {
55
+ total: Money;
56
+ bySource: Record<Source, Money>;
57
+ byCredential: Record<Credential, Money>;
58
+ }
59
+ export interface Aside {
60
+ runs: number;
61
+ /** Dollars the run itself recorded (`unreserved`). */
62
+ usd: number;
63
+ /** Dollars held by reservations (`reserved`, `unsettled`). */
64
+ reservedUsd: number;
65
+ }
66
+ export interface AsideLines {
67
+ unreserved: Aside;
68
+ unsettled: Aside;
69
+ reserved: Aside;
70
+ }
71
+ export interface Range {
72
+ from: string;
73
+ to: string;
74
+ }
75
+ export interface Limits {
76
+ dailyUsd: number | null;
77
+ weeklyUsd: number | null;
78
+ }
79
+ export interface Bucket {
80
+ key: string;
81
+ /** Per source: whether the downloaded or kept data covers this period at all. */
82
+ known: Record<Source, boolean>;
83
+ /** The period is only partly inside the data of some source that covers it. */
84
+ partial: boolean;
85
+ spend: Split;
86
+ aside: AsideLines;
87
+ /** Actions only: settled + unreserved + reserved/unsettled holds, what the limit counts. Null without Actions data. */
88
+ countedAgainstLimitUsd: number | null;
89
+ }
90
+ export interface Group {
91
+ key: string;
92
+ label: string;
93
+ split: Split;
94
+ }
95
+ export type GroupBy = "day" | "week" | "repo" | "pr" | "model" | "profile" | "source";
96
+
97
+ export interface Report {
98
+ filters: { sources: Source[] };
99
+ coverage: Record<Source, Range | null>;
100
+ pulledAt: string | null;
101
+ limits: Limits | null;
102
+ totals: Split;
103
+ aside: AsideLines;
104
+ days: Bucket[];
105
+ weeks: Bucket[];
106
+ groups: { repository: Group[]; pr: Group[]; model: Group[] };
107
+ /** Calls whose dollar cost is unknown (counted as 0 in the figures). */
108
+ unknownCostCalls: number;
109
+ }
110
+
111
+ const zero = (): Money => ({ runs: 0, calls: 0, usd: 0 });
112
+ const emptySplit = (): Split => ({
113
+ total: zero(),
114
+ bySource: { laptop: zero(), actions: zero() },
115
+ byCredential: { billed: zero(), estimated: zero(), unknown: zero() },
116
+ });
117
+ const emptyAside = (): AsideLines => ({ unreserved: { runs: 0, usd: 0, reservedUsd: 0 }, unsettled: { runs: 0, usd: 0, reservedUsd: 0 }, reserved: { runs: 0, usd: 0, reservedUsd: 0 } });
118
+
119
+ /** Six decimals hide floating-point noise and lose no cent. */
120
+ export const roundUsd = (n: number) => Math.round(n * 1e6) / 1e6;
121
+
122
+ /** The spend of a row broken down by credential; dollars no call accounts for go to `unknown`. */
123
+ function creditBreakdown(row: SpendRow): { credential: Credential; calls: number; usd: number }[] {
124
+ const out = new Map<Credential, { credential: Credential; calls: number; usd: number }>();
125
+ const add = (credential: Credential, calls: number, usd: number) => {
126
+ const e = out.get(credential) ?? { credential, calls: 0, usd: 0 };
127
+ e.calls += calls;
128
+ e.usd += usd;
129
+ out.set(credential, e);
130
+ };
131
+ let itemised = 0;
132
+ for (const c of row.calls) {
133
+ add(credentialOf(c.auth), 1, c.costUsd);
134
+ itemised += c.costUsd;
135
+ }
136
+ const rest = row.costUsd - itemised;
137
+ if (rest > 1e-9) add("unknown", 0, rest);
138
+ return [...out.values()];
139
+ }
140
+
141
+ function addSpend(split: Split, row: SpendRow) {
142
+ const calls = row.calls.length;
143
+ for (const m of [split.total, split.bySource[row.source]]) {
144
+ m.runs++;
145
+ m.calls += calls;
146
+ m.usd += row.costUsd;
147
+ }
148
+ for (const b of creditBreakdown(row)) {
149
+ const m = split.byCredential[b.credential];
150
+ m.runs++;
151
+ m.calls += b.calls;
152
+ m.usd += b.usd;
153
+ }
154
+ }
155
+
156
+ function roundSplit(split: Split): Split {
157
+ for (const m of [split.total, ...Object.values(split.bySource), ...Object.values(split.byCredential)]) m.usd = roundUsd(m.usd);
158
+ return split;
159
+ }
160
+
161
+ function addAside(aside: AsideLines, row: SpendRow) {
162
+ if (row.state === "settled") return;
163
+ const line = aside[row.state];
164
+ line.runs++;
165
+ line.usd += row.state === "unreserved" ? row.costUsd : 0;
166
+ line.reservedUsd += row.reservedUsd;
167
+ }
168
+
169
+ const roundAside = (a: AsideLines): AsideLines => {
170
+ for (const l of Object.values(a)) {
171
+ l.usd = roundUsd(l.usd);
172
+ l.reservedUsd = roundUsd(l.reservedUsd);
173
+ }
174
+ return a;
175
+ };
176
+
177
+ /** What the ledger limit counts for one Actions row: spend, a reservation hold, or a late record. */
178
+ const counted = (row: SpendRow) => (row.source !== "actions" ? 0 : row.state === "settled" || row.state === "unreserved" ? row.costUsd : row.reservedUsd);
179
+
180
+ /** The Monday (UTC) of the week that contains `day`. */
181
+ export function weekStart(day: string): string {
182
+ const t = Date.parse(`${day}T00:00:00Z`);
183
+ const dow = (new Date(t).getUTCDay() + 6) % 7;
184
+ return new Date(t - dow * 86_400_000).toISOString().slice(0, 10);
185
+ }
186
+
187
+ const addDays = (day: string, n: number) => new Date(Date.parse(`${day}T00:00:00Z`) + n * 86_400_000).toISOString().slice(0, 10);
188
+
189
+ function modelOf(call: SpendCall) {
190
+ return call.model === "" ? "(unknown model)" : call.model;
191
+ }
192
+
193
+ /** Groups rows. `model` groups by call: a run with two models appears in both, with only that model's calls and dollars. */
194
+ export function group(rows: SpendRow[], by: GroupBy): Group[] {
195
+ const map = new Map<string, Group>();
196
+ const get = (key: string, label: string) => {
197
+ let g = map.get(key);
198
+ if (!g) map.set(key, (g = { key, label, split: emptySplit() }));
199
+ return g;
200
+ };
201
+ for (const row of rows) {
202
+ if (row.state !== "settled") continue;
203
+ if (by === "model") {
204
+ const byModel = new Map<string, SpendRow>();
205
+ const itemised = row.calls.reduce((n, c) => n + c.costUsd, 0);
206
+ for (const c of row.calls) {
207
+ const key = modelOf(c);
208
+ const part = byModel.get(key) ?? { ...row, calls: [], costUsd: 0 };
209
+ part.calls = [...part.calls, c];
210
+ part.costUsd += c.costUsd;
211
+ byModel.set(key, part);
212
+ }
213
+ if (row.costUsd - itemised > 1e-9) byModel.set("(not itemised)", { ...row, calls: [], costUsd: row.costUsd - itemised });
214
+ if (byModel.size === 0) byModel.set("(no calls recorded)", row);
215
+ for (const [key, part] of byModel) addSpend(get(key, key).split, part);
216
+ continue;
217
+ }
218
+ const [key, label] =
219
+ by === "day"
220
+ ? [row.day, row.day]
221
+ : by === "week"
222
+ ? [row.week, row.week]
223
+ : by === "repo"
224
+ ? [row.repositoryKey, row.repository]
225
+ : by === "pr"
226
+ ? row.pr !== null
227
+ ? [`${row.repositoryKey}#${row.pr}`, `${row.repository} #${row.pr}`]
228
+ : row.source === "laptop"
229
+ ? [`${row.repositoryKey}#local`, `${row.repository} (local branch)`]
230
+ : [`${row.repositoryKey}#none`, `${row.repository} (no pull request)`]
231
+ : by === "profile"
232
+ ? [row.profile || "(none)", row.profile || "(none)"]
233
+ : [row.source, row.source === "actions" ? "GitHub Actions" : "Laptop"];
234
+ addSpend(get(key, label).split, row);
235
+ }
236
+ const groups = [...map.values()];
237
+ for (const g of groups) roundSplit(g.split);
238
+ return groups.sort((a, b) => (by === "day" || by === "week" ? b.key.localeCompare(a.key) : b.split.total.usd - a.split.total.usd || a.key.localeCompare(b.key)));
239
+ }
240
+
241
+ export interface ReportInput {
242
+ rows: SpendRow[];
243
+ /** Which sources the caller asked for; the others are `known: false`. */
244
+ sources?: Source[];
245
+ /** The days each source's data covers, as separate ranges: the pulls for Actions, first kept run to today for the laptop. Empty: no data. */
246
+ coverage: Record<Source, Range[]>;
247
+ limits?: Limits | null;
248
+ pulledAt?: string | null;
249
+ now: Date;
250
+ }
251
+
252
+ /** The laptop covers from its first kept run to today, whatever the filters; Actions covers what the last pull asked for. */
253
+ export function deriveCoverage(allRows: SpendRow[], actions: Range[], now: Date): Record<Source, Range[]> {
254
+ const days = allRows.filter((r) => r.source === "laptop").map((r) => r.day).sort();
255
+ return { laptop: days.length ? [{ from: days[0], to: now.toISOString().slice(0, 10) }] : [], actions: mergeRanges(actions) };
256
+ }
257
+
258
+ /** Sorted ranges where those that overlap or touch (the next starts the day after the previous ends) become one. */
259
+ export function mergeRanges(ranges: Range[]): Range[] {
260
+ const out: Range[] = [];
261
+ for (const r of [...ranges].sort((a, b) => a.from.localeCompare(b.from))) {
262
+ const last = out.at(-1);
263
+ if (last && r.from <= addDays(last.to, 1)) last.to = r.to > last.to ? r.to : last.to;
264
+ else out.push({ ...r });
265
+ }
266
+ return out;
267
+ }
268
+
269
+ const hull = (ranges: Range[]): Range | null => (ranges.length ? { from: ranges[0].from, to: ranges.at(-1)!.to } : null);
270
+
271
+ const MAX_BUCKETS = 120;
272
+
273
+ function buckets(input: ReportInput, kind: "day" | "week", sources: Source[]): Bucket[] {
274
+ const today = input.now.toISOString().slice(0, 10);
275
+ const ranges = sources.flatMap((s) => input.coverage[s]);
276
+ if (ranges.length === 0) return [];
277
+ const first = ranges.map((r) => r.from).sort()[0];
278
+ const last = [today, ...ranges.map((r) => r.to)].sort().at(-1)!;
279
+ const step = kind === "day" ? 1 : 7;
280
+ // The newest periods are kept: with a long history it is the old ones that fall off the chart.
281
+ const lastKey = kind === "day" ? last : weekStart(last);
282
+ const oldest = addDays(lastKey, -(MAX_BUCKETS - 1) * step);
283
+ const firstKey = kind === "day" ? first : weekStart(first);
284
+ const keys: string[] = [];
285
+ for (let k = firstKey > oldest ? firstKey : oldest; k <= lastKey; k = addDays(k, step)) keys.push(k);
286
+ const rows = input.rows.filter((r) => sources.includes(r.source));
287
+ return keys.map((key): Bucket => {
288
+ const end = kind === "day" ? key : addDays(key, 6);
289
+ const known = { laptop: false, actions: false } as Record<Source, boolean>;
290
+ let partial = false;
291
+ const wanted = end > today ? today : end;
292
+ for (const s of sources) {
293
+ const ranges = input.coverage[s];
294
+ if (!ranges.some((r) => r.to >= key && r.from <= end)) continue;
295
+ known[s] = true;
296
+ if (!ranges.some((r) => r.from <= key && r.to >= wanted)) partial = true;
297
+ }
298
+ const spend = emptySplit();
299
+ const aside = emptyAside();
300
+ let limitUse = 0;
301
+ for (const row of rows) {
302
+ if ((kind === "day" ? row.day : row.week) !== key) continue;
303
+ if (row.state === "settled") addSpend(spend, row);
304
+ addAside(aside, row);
305
+ limitUse += counted(row);
306
+ }
307
+ return { key, known, partial, spend: roundSplit(spend), aside: roundAside(aside), countedAgainstLimitUsd: known.actions ? roundUsd(limitUse) : null };
308
+ });
309
+ }
310
+
311
+ export interface LimitUse {
312
+ key: string;
313
+ /** Dollars the ledger counts in this period; null when the downloaded days do not cover it. */
314
+ usedUsd: number | null;
315
+ limitUsd: number;
316
+ }
317
+
318
+ /** Today's and this week's figure against the ledger limits. Give it a report built from every Actions row of the account, unfiltered. */
319
+ export function limitUse(report: Report, now: Date): { day: LimitUse | null; week: LimitUse | null } {
320
+ const today = now.toISOString().slice(0, 10);
321
+ const one = (buckets: Bucket[], key: string, limit: number | null): LimitUse | null =>
322
+ report.limits === null || limit === null ? null : { key, usedUsd: buckets.find((b) => b.key === key)?.countedAgainstLimitUsd ?? null, limitUsd: limit };
323
+ return { day: one(report.days, today, report.limits?.dailyUsd ?? null), week: one(report.weeks, weekStart(today), report.limits?.weeklyUsd ?? null) };
324
+ }
325
+
326
+ export function buildReport(input: ReportInput): Report {
327
+ const sources = input.sources ?? [...SOURCES];
328
+ const rows = input.rows.filter((r) => sources.includes(r.source));
329
+ const totals = emptySplit();
330
+ const aside = emptyAside();
331
+ let unknownCostCalls = 0;
332
+ for (const row of rows) {
333
+ if (row.state === "settled") addSpend(totals, row);
334
+ addAside(aside, row);
335
+ unknownCostCalls += row.calls.filter((c) => !c.costKnown).length;
336
+ }
337
+ return {
338
+ filters: { sources },
339
+ coverage: { laptop: sources.includes("laptop") ? hull(input.coverage.laptop) : null, actions: sources.includes("actions") ? hull(input.coverage.actions) : null },
340
+ pulledAt: input.pulledAt ?? null,
341
+ limits: input.limits ?? null,
342
+ totals: roundSplit(totals),
343
+ aside: roundAside(aside),
344
+ days: buckets(input, "day", sources),
345
+ weeks: buckets(input, "week", sources),
346
+ groups: { repository: group(rows, "repo"), pr: group(rows, "pr"), model: group(rows, "model") },
347
+ unknownCostCalls,
348
+ };
349
+ }