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
@@ -1,19 +1,25 @@
1
1
  /**
2
2
  * `wachiman status`: what this laptop knows about its own local runs, and what they cost. It reads
3
3
  * the history files (`local --history`) and local git metadata only: no `claude`, no GitHub, no
4
- * network. Damaged history files are moved aside with a warning. Runs made by the GitHub Actions workflow are not in these files and are not counted.
4
+ * network. Damaged history files are moved aside with a warning. Runs made by the GitHub Actions workflow
5
+ * are not in these files and are not counted, unless the user connected a ledger and pulled it (ADR 0039):
6
+ * then the pulled day files are read directly (never the index, so `status` answers even when the index
7
+ * cannot be written) and one report covers both sources.
5
8
  */
6
9
  import { UsageError } from "../config";
7
10
  import { wachimanHome } from "../accounts/config";
8
11
  import { historySettings, historyRoot, listKeys, readRuns, repositoryKey } from "../history/store";
9
12
  import type { HistoryRun } from "../history/types";
13
+ import { readLedgerFromFiles } from "../ledger-read/rows";
14
+ import { buildReport, deriveCoverage, group as groupRows, limitUse, SOURCES, weekStart, type GroupBy, type LimitUse, type Report, type Source, type Split, type SpendRow } from "../spend/report";
10
15
 
11
16
  export const STATUS_FORMAT = "wachiman.status/1";
12
17
 
13
18
  export const statusUsage = `wachiman status [--json] [--since <n>d] [--all-repos] [--repo <name|key>] [--model <text>]
14
- [--profile <name>] [--by day|repo|model|profile] [--repo-dir <dir>]`;
19
+ [--profile <name>] [--by day|week|repo|pr|model|profile|source] [--source laptop|actions|all]
20
+ [--refresh] [--repo-dir <dir>]`;
15
21
 
16
- export const GROUPS = ["day", "repo", "model", "profile"] as const;
22
+ export const GROUPS = ["day", "week", "repo", "pr", "model", "profile", "source"] as const;
17
23
  export type Group = (typeof GROUPS)[number];
18
24
 
19
25
  export interface StatusArgs {
@@ -24,11 +30,14 @@ export interface StatusArgs {
24
30
  model?: string;
25
31
  profile?: string;
26
32
  by: Group;
33
+ source: Source | "all";
34
+ /** Download the ledger first (the only request `status` can make). */
35
+ refresh: boolean;
27
36
  }
28
37
 
29
38
  /** The arguments after `status` (`--repo-dir` is already taken out). Both `--x v` and `--x=v`. */
30
39
  export function parseStatusArgs(argv: string[]): StatusArgs | { help: true } {
31
- const args: StatusArgs = { json: false, allRepos: false, by: "day" };
40
+ const args: StatusArgs = { json: false, allRepos: false, by: "day", source: "all", refresh: false };
32
41
  for (let i = 0; i < argv.length; i++) {
33
42
  const arg = argv[i];
34
43
  if (arg === "--help" || arg === "-h") return { help: true };
@@ -45,6 +54,12 @@ export function parseStatusArgs(argv: string[]): StatusArgs | { help: true } {
45
54
  };
46
55
  if (name === "--json") (flag(), (args.json = true));
47
56
  else if (name === "--all-repos") (flag(), (args.allRepos = true));
57
+ else if (name === "--refresh") (flag(), (args.refresh = true));
58
+ else if (name === "--source") {
59
+ const v = value();
60
+ if (v !== "all" && !(SOURCES as readonly string[]).includes(v)) throw new UsageError(`--source is one of laptop, actions, all; got "${v}".`);
61
+ args.source = v as Source | "all";
62
+ }
48
63
  else if (name === "--repo") args.repo = value();
49
64
  else if (name === "--model") args.model = value();
50
65
  else if (name === "--profile") args.profile = value();
@@ -97,29 +112,34 @@ export function flatten(run: HistoryRun): StatusRun {
97
112
  };
98
113
  }
99
114
 
100
- const keyOf: Record<Group, (r: StatusRun) => string> = {
101
- day: (r) => r.at.slice(0, 10),
102
- repo: (r) => r.repositoryKey,
103
- model: (r) => (r.effort ? `${r.model} (${r.effort})` : r.model),
104
- profile: (r) => r.profile || "(none)",
105
- };
106
-
107
115
  export interface StatusGroup {
108
116
  key: string;
109
117
  runs: number;
110
118
  costUsdEstimate: number;
111
119
  }
112
120
 
121
+ /** A laptop run in the row shape of the spend report. A local run is an API-equivalent estimate (ADR 0019). */
122
+ export function toRow(r: StatusRun): SpendRow {
123
+ const day = r.at.slice(0, 10);
124
+ return {
125
+ source: "laptop",
126
+ state: "settled",
127
+ day,
128
+ week: weekStart(day),
129
+ repositoryKey: r.repositoryKey,
130
+ repository: r.repository,
131
+ pr: null,
132
+ runId: `${r.repositoryKey}@${r.at}`,
133
+ profile: r.profile,
134
+ costUsd: r.costUsdEstimate,
135
+ reservedUsd: 0,
136
+ calls: [{ model: r.effort ? `${r.model} (${r.effort})` : r.model, auth: "subscription", costUsd: r.costUsdEstimate, costKnown: true }],
137
+ };
138
+ }
139
+
140
+ /** Groups laptop runs through the spend report; kept for the callers that group `StatusRun`s. */
113
141
  export function group(runs: StatusRun[], by: Group): StatusGroup[] {
114
- const map = new Map<string, StatusGroup>();
115
- for (const r of runs) {
116
- const key = keyOf[by](r);
117
- const g = map.get(key) ?? { key, runs: 0, costUsdEstimate: 0 };
118
- g.runs++;
119
- g.costUsdEstimate += r.costUsdEstimate;
120
- map.set(key, g);
121
- }
122
- return [...map.values()].sort((a, b) => (by === "day" ? b.key.localeCompare(a.key) : b.costUsdEstimate - a.costUsdEstimate));
142
+ return groupRows(runs.map(toRow), by as GroupBy).map((g) => ({ key: g.key, runs: g.split.total.runs, costUsdEstimate: g.split.total.usd }));
123
143
  }
124
144
 
125
145
  export function filterRuns(runs: StatusRun[], args: StatusArgs, now: Date): StatusRun[] {
@@ -133,10 +153,8 @@ export function filterRuns(runs: StatusRun[], args: StatusArgs, now: Date): Stat
133
153
  );
134
154
  }
135
155
 
136
- const usd = (n: number) => `$${n.toFixed(2)}`;
137
- const pad = (text: string, width: number) => text + " ".repeat(Math.max(0, width - text.length));
138
-
139
156
  export const LOCAL_ONLY = "Local runs only: those kept by `wachiman local --history`. Runs by the GitHub Actions workflow are not counted.";
157
+ export const WITH_LEDGER = "Laptop runs kept by `wachiman local --history` and GitHub Actions runs downloaded from the ledger. The ledger limit is best-effort and counts Actions runs only.";
140
158
 
141
159
  export interface StatusIo {
142
160
  stdout: (text: string) => void;
@@ -145,11 +163,69 @@ export interface StatusIo {
145
163
  version: string;
146
164
  }
147
165
 
166
+ /** `owner/name` of the clone's `origin`, lower case, when it has one. */
167
+ function remoteSlug(remote: string | undefined): string | undefined {
168
+ return remote?.match(/\/([^/]+\/[^/]+)$/)?.[1]?.toLowerCase();
169
+ }
170
+
171
+ /** Ledger rows kept by the same filters as the laptop runs; `slug` scopes them to one repository. */
172
+ function filterLedgerRows(rows: SpendRow[], args: StatusArgs, now: Date, slug: string | undefined, all: StatusRun[]): SpendRow[] {
173
+ const cutoff = args.sinceDays === undefined ? undefined : now.getTime() - args.sinceDays * 86_400_000;
174
+ const tail = (r: SpendRow) => r.repository.split("/").at(-1)?.toLowerCase();
175
+ const wanted = args.repo?.toLowerCase();
176
+ const repoMatches = (r: SpendRow) => {
177
+ if (args.repo !== undefined) return r.repository.toLowerCase() === args.repo.toLowerCase() || tail(r) === wanted || all.some((l) => l.repositoryKey === args.repo && l.repository.toLowerCase() === tail(r));
178
+ return args.allRepos || (slug !== undefined && r.repository.toLowerCase() === slug);
179
+ };
180
+ return rows.filter(
181
+ (r) =>
182
+ r.source === "actions" &&
183
+ (cutoff === undefined || Date.parse(`${r.day}T23:59:59Z`) >= cutoff) &&
184
+ repoMatches(r) &&
185
+ (args.model === undefined || r.calls.some((c) => c.model.includes(args.model!))) &&
186
+ args.profile === undefined,
187
+ );
188
+ }
189
+
190
+ const usd = (n: number) => `$${n.toFixed(2)}`;
191
+ const pad = (text: string, width: number) => text + " ".repeat(Math.max(0, width - text.length));
192
+
193
+ /** Estimated dollars, with unknown-credential dollars named beside them and never added in. */
194
+ function estimatedWithUnknown(s: Split): string {
195
+ const c = s.byCredential;
196
+ return c.unknown.usd > 0 ? `${usd(c.estimated.usd)} + ${usd(c.unknown.usd)} unknown` : usd(c.estimated.usd);
197
+ }
198
+
199
+ function creditLine(report: Report): string {
200
+ const c = report.totals.byCredential;
201
+ const parts = [`${usd(c.billed.usd)} billed (API key)`, `${usd(c.estimated.usd)} estimated (subscription, API-equivalent, not a bill)`];
202
+ if (c.unknown.usd > 0) parts.push(`${usd(c.unknown.usd)} of unknown credential`);
203
+ return parts.join(" + ");
204
+ }
205
+
206
+ /** The ledger limit is per account across every repository, so these figures never see `--repo`, `--model`, `--since` or `--profile`. */
207
+ function limitLines(use: { day: LimitUse | null; week: LimitUse | null }, now: Date): string[] {
208
+ const today = now.toISOString().slice(0, 10);
209
+ const one = (label: string, u: LimitUse | null) =>
210
+ u ? [`${label}: ${u.usedUsd === null ? "no data" : `${usd(u.usedUsd)} of ${usd(u.limitUsd)}`} counted against the ledger limit (Actions runs only, whole account, all repositories, best-effort)`] : [];
211
+ return [...one(`Today (${today} UTC)`, use.day), ...one(`This week (Monday ${weekStart(today)} UTC)`, use.week)];
212
+ }
213
+
214
+ function asideLine(report: Report): string[] {
215
+ const a = report.aside;
216
+ const parts: string[] = [];
217
+ if (a.unreserved.runs) parts.push(`${a.unreserved.runs} run${a.unreserved.runs === 1 ? "" : "s"} not reserved (${usd(a.unreserved.usd)} recorded after the fact)`);
218
+ if (a.unsettled.runs) parts.push(`${a.unsettled.runs} reservation${a.unsettled.runs === 1 ? "" : "s"} never settled (${usd(a.unsettled.reservedUsd)} held, not spent)`);
219
+ if (a.reserved.runs) parts.push(`${a.reserved.runs} run${a.reserved.runs === 1 ? "" : "s"} still reserved (${usd(a.reserved.reservedUsd)} held)`);
220
+ return parts.length ? [`Not counted as spend: ${parts.join("; ")}.`] : [];
221
+ }
222
+
148
223
  export function runStatus(args: StatusArgs, repoDir: string, env: Record<string, string | undefined>, io: StatusIo): number {
149
224
  const home = wachimanHome(env);
150
225
  const root = historyRoot(home);
151
226
  const now = io.now?.() ?? new Date();
152
- const keys = args.allRepos || args.repo !== undefined ? listKeys(root) : [repositoryKey(repoDir).key];
227
+ const repo = args.allRepos || args.repo !== undefined ? undefined : repositoryKey(repoDir);
228
+ const keys = args.allRepos || args.repo !== undefined ? listKeys(root) : [repo!.key];
153
229
  const all = keys.flatMap((key) => readRuns(root, key, io.stderr)).map(flatten);
154
230
  const retentionDays = historySettings(env, true).days;
155
231
  if (args.repo !== undefined && !all.some(r => r.repositoryKey === args.repo)) {
@@ -158,45 +234,83 @@ export function runStatus(args: StatusArgs, repoDir: string, env: Record<string,
158
234
  }
159
235
  const effectiveArgs = args.repo !== undefined && all.some(r => r.repositoryKey === args.repo) ? { ...args, repo: undefined } : args;
160
236
  const scoped = effectiveArgs !== args ? all.filter(r => r.repositoryKey === args.repo) : all;
161
- const runs = filterRuns(scoped, effectiveArgs, now).sort((a, b) => a.at.localeCompare(b.at));
162
- const groups = group(runs, args.by);
163
- const total = runs.reduce((sum, r) => sum + r.costUsdEstimate, 0);
237
+ const laptopRuns = filterRuns(scoped, effectiveArgs, now).sort((a, b) => a.at.localeCompare(b.at));
238
+
239
+ // The ledger is read only from files the user pulled; with none, everything below is the local-only status.
240
+ const ledger = readLedgerFromFiles(home, io.stderr);
241
+ const hasLedger = ledger.pulledAt !== null;
242
+ if (!hasLedger && args.source === "actions") throw new UsageError("--source actions needs a pulled ledger: run `wachiman ledger connect`, then `wachiman ledger pull`.");
243
+ const actionsRows = hasLedger ? filterLedgerRows(ledger.rows, args, now, remoteSlug(repo?.remote), all) : [];
244
+ const sources: Source[] = args.source === "all" ? [...SOURCES] : [args.source];
245
+ const useLaptop = sources.includes("laptop");
246
+ const rows = [...(useLaptop ? laptopRuns.map(toRow) : []), ...(sources.includes("actions") ? actionsRows : [])];
247
+ const report = buildReport({
248
+ rows,
249
+ sources: hasLedger ? sources : ["laptop"],
250
+ coverage: deriveCoverage(scoped.map(toRow), ledger.ranges, now),
251
+ limits: ledger.limits,
252
+ pulledAt: ledger.pulledAt,
253
+ now,
254
+ });
255
+ // The limit figures come from every ledger row of the account, whatever the filters say.
256
+ const limitReport = buildReport({ rows: ledger.rows, sources: ["actions"], coverage: { laptop: [], actions: ledger.ranges }, limits: ledger.limits, pulledAt: ledger.pulledAt, now });
257
+ const limits = limitUse(limitReport, now);
258
+ const groups = groupRows(rows, args.by as GroupBy);
259
+ const settled = rows.filter((r) => r.state === "settled");
260
+ const total = report.totals.total.usd;
164
261
  const filters = {
165
262
  scope: args.allRepos ? "all-repos" : args.repo !== undefined ? "repo" : "this-repo",
166
263
  ...(args.repo !== undefined ? { repo: args.repo } : {}),
167
264
  ...(args.sinceDays !== undefined ? { sinceDays: args.sinceDays } : {}),
168
265
  ...(args.model !== undefined ? { model: args.model } : {}),
169
266
  ...(args.profile !== undefined ? { profile: args.profile } : {}),
267
+ ...(hasLedger ? { source: args.source } : {}),
170
268
  };
269
+ const legacyGroups = groups.map((g) => ({ key: g.key, runs: g.split.total.runs, costUsdEstimate: g.split.total.usd }));
171
270
 
172
271
  if (args.json) {
173
272
  const doc = {
174
273
  format: STATUS_FORMAT,
175
274
  version: io.version,
176
275
  home,
177
- scope: LOCAL_ONLY,
276
+ scope: hasLedger ? WITH_LEDGER : LOCAL_ONLY,
178
277
  retentionDays,
179
278
  filters,
180
279
  by: args.by,
181
- totals: { runs: runs.length, costUsdEstimate: total },
182
- groups,
183
- runs,
280
+ totals: { runs: settled.length, costUsdEstimate: total },
281
+ groups: hasLedger ? groups.map((g, i) => ({ ...legacyGroups[i], label: g.label, split: g.split })) : legacyGroups,
282
+ runs: useLaptop ? laptopRuns : [],
283
+ ...(hasLedger ? { report, limitUse: limits } : {}),
184
284
  };
185
285
  io.stdout(`${JSON.stringify(doc, null, 2)}\n`);
186
286
  return 0;
187
287
  }
188
288
 
189
- const lines = [`Wachiman ${io.version} (home ${home})`, LOCAL_ONLY, ""];
190
- if (runs.length === 0) {
289
+ const lines = [`Wachiman ${io.version} (home ${home})`, hasLedger ? WITH_LEDGER : LOCAL_ONLY, ""];
290
+ if (settled.length === 0 && !hasLedger) {
191
291
  lines.push(all.length === 0 ? "No local runs kept yet: run `wachiman local --history` to start. Run `wachiman doctor` to check this machine." : `No run matches the filters (${all.length} kept before filtering).`);
192
292
  io.stdout(`${lines.join("\n")}\n`);
193
293
  return 0;
194
294
  }
295
+ if (settled.length === 0) {
296
+ lines.push(all.length === 0 && actionsRows.length === 0 ? "No run to show: no local run is kept and no ledger entry matches. Run `wachiman ledger pull` to refresh the ledger." : "No run matches the filters.");
297
+ lines.push(...asideLine(report), ...limitLines(limits, now));
298
+ io.stdout(`${lines.join("\n")}\n`);
299
+ return 0;
300
+ }
195
301
  const w = Math.max(args.by.length, ...groups.map((g) => g.key.length));
196
- lines.push(`${runs.length} run${runs.length === 1 ? "" : "s"}, ${usd(total)} estimated (API-equivalent, not a bill), ${runs[0].at.slice(0, 10)} → ${runs.at(-1)!.at.slice(0, 10)}`, "");
197
- lines.push(` ${pad(args.by, w)} runs cost`);
198
- for (const g of groups) lines.push(` ${pad(g.key, w)} ${pad(String(g.runs), 4)} ${usd(g.costUsdEstimate)}`);
199
- lines.push("", retentionDays === 0 ? "New `--history` runs keep all runs (AGENT_REVIEW_HISTORY_DAYS=0). `--json` lists every run with its attributes." : `A new \`--history\` run deletes runs older than ${retentionDays} days (AGENT_REVIEW_HISTORY_DAYS changes that). \`--json\` lists every run with its attributes.`);
302
+ const days = settled.map((r) => r.day).sort();
303
+ if (hasLedger) {
304
+ lines.push(`${settled.length} run${settled.length === 1 ? "" : "s"}, ${creditLine(report)}, ${days[0]} → ${days.at(-1)}`);
305
+ lines.push(...limitLines(limits, now), ...asideLine(report), "");
306
+ lines.push(` ${pad(args.by, w)} runs calls billed estimated`);
307
+ for (const g of groups) lines.push(` ${pad(g.key, w)} ${pad(String(g.split.total.runs), 4)} ${pad(String(g.split.total.calls), 5)} ${pad(usd(g.split.byCredential.billed.usd), 6)} ${estimatedWithUnknown(g.split)}`);
308
+ } else {
309
+ lines.push(`${settled.length} run${settled.length === 1 ? "" : "s"}, ${usd(total)} estimated (API-equivalent, not a bill), ${laptopRuns[0].at.slice(0, 10)} → ${laptopRuns.at(-1)!.at.slice(0, 10)}`, "");
310
+ lines.push(` ${pad(args.by, w)} runs cost`);
311
+ for (const g of legacyGroups) lines.push(` ${pad(g.key, w)} ${pad(String(g.runs), 4)} ${usd(g.costUsdEstimate)}`);
312
+ }
313
+ lines.push("", retentionDays === 0 ? "New `--history` runs keep all runs (WACHIMAN_HISTORY_DAYS=0). `--json` lists every run with its attributes." : `A new \`--history\` run deletes runs older than ${retentionDays} days (WACHIMAN_HISTORY_DAYS changes that). \`--json\` lists every run with its attributes.`);
200
314
  io.stdout(`${lines.join("\n")}\n`);
201
315
  return 0;
202
316
  }
@@ -4,24 +4,30 @@
4
4
  * only the index and, without `--json`, the page; like `wachiman history`, it moves a damaged run
5
5
  * file aside. No `claude`, no GitHub, no network, no server, and it never opens a browser.
6
6
  */
7
- import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from "node:fs";
7
+ import { existsSync, chmodSync, closeSync, fsyncSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from "node:fs";
8
8
  import { dirname, join, resolve } from "node:path";
9
9
  import { wachimanHome } from "../accounts/config";
10
10
  import { UsageError } from "../config";
11
11
  import { readFigures, type Figures } from "./figures";
12
12
  import { renderHtml, type DashboardDocument } from "./html";
13
+ import { credentialsPath } from "../ledger-read/credentials";
14
+ import { listLedgerAccounts } from "../ledger-read/files";
15
+ import { buildReport, deriveCoverage } from "../spend/report";
16
+ import { readSpendRows } from "./rows";
13
17
  import { refreshIndex } from "./index";
14
18
 
15
19
  export const DASHBOARD_FORMAT = "wachiman.dashboard/1";
16
20
  export const DASHBOARD_FILE = "dashboard.html";
17
21
 
18
- export const dashboardUsage = `wachiman dashboard [--json] [--out <file>] [--repo-dir <dir>]`;
22
+ export const dashboardUsage = `wachiman dashboard [--json] [--out <file>] [--refresh] [--repo-dir <dir>]`;
19
23
 
20
24
  export const LOCAL_ONLY = "Local runs only: those kept by `wachiman local --history` and `wachiman loop`. Runs by the GitHub Actions workflow are not counted.";
21
25
 
22
26
  export interface DashboardArgs {
23
27
  json: boolean;
24
28
  out?: string;
29
+ /** Download the ledger first (the only request `dashboard` can make). */
30
+ refresh?: boolean;
25
31
  }
26
32
 
27
33
  /** The arguments after `dashboard` (`--repo-dir` is already taken out). Both `--x v` and `--x=v`. */
@@ -36,6 +42,9 @@ export function parseDashboardArgs(argv: string[]): DashboardArgs | { help: true
36
42
  if (name === "--json") {
37
43
  if (eq !== -1) throw new UsageError("--json takes no value.");
38
44
  args.json = true;
45
+ } else if (name === "--refresh") {
46
+ if (eq !== -1) throw new UsageError("--refresh takes no value.");
47
+ args.refresh = true;
39
48
  } else if (name === "--out") {
40
49
  const v = eq === -1 ? argv[++i] : arg.slice(eq + 1);
41
50
  if (v === undefined || v === "" || (eq === -1 && v.startsWith("--"))) throw new UsageError("--out needs a file name.");
@@ -92,12 +101,20 @@ export interface DashboardIo {
92
101
 
93
102
  export function runDashboard(args: DashboardArgs, env: Record<string, string | undefined>, io: DashboardIo): number {
94
103
  const home = wachimanHome(env);
104
+ const now = io.now?.() ?? new Date();
95
105
  const doc: DashboardDocument = {
96
106
  format: DASHBOARD_FORMAT,
97
- generatedAt: (io.now?.() ?? new Date()).toISOString(),
107
+ generatedAt: now.toISOString(),
98
108
  scope: LOCAL_ONLY,
99
109
  ...loadFigures(home, io.stderr),
100
110
  };
111
+ // A ledger is "connected" when a credentials file exists or a pull left files (nothing is parsed or resolved here: only `--refresh` makes a request, and the CLI does that first); otherwise the page is as before (ADR 0039).
112
+ if (existsSync(credentialsPath(home)) || listLedgerAccounts(home).length > 0) {
113
+ const spend = readSpendRows(refreshIndex(home, io.stderr).path);
114
+ const report = buildReport({ rows: spend.rows, coverage: deriveCoverage(spend.rows, spend.actions, now), limits: spend.limits, pulledAt: spend.pulledAt, now });
115
+ doc.usage = { report, pulled: spend.pulledAt !== null };
116
+ doc.scope = "Laptop runs kept by `wachiman local --history` and `wachiman loop`, and GitHub Actions runs downloaded from the ledger.";
117
+ }
101
118
  if (args.json) {
102
119
  io.stdout(`${JSON.stringify(doc, null, 2)}\n`);
103
120
  return 0;
package/src/store/html.ts CHANGED
@@ -5,11 +5,20 @@
5
5
  */
6
6
  import { GRADES } from "../fidelity/types";
7
7
  import { SEVERITY_ORDER, type Figures } from "./figures";
8
+ import type { Aside, Bucket, Group, Limits, Money, Report, Source, Split } from "../spend/report";
9
+
10
+ /** The laptop-plus-ledger section (ADR 0039): present only when a ledger is connected or was pulled. */
11
+ export interface UsageSection {
12
+ report: Report;
13
+ /** False when credentials exist but nothing was pulled yet. */
14
+ pulled: boolean;
15
+ }
8
16
 
9
17
  export interface DashboardDocument extends Figures {
10
18
  format: string;
11
19
  generatedAt: string;
12
20
  scope: string;
21
+ usage?: UsageSection;
13
22
  }
14
23
 
15
24
  /** Text for an element or a quoted attribute. */
@@ -22,7 +31,14 @@ export function esc(text: unknown): string {
22
31
  .replace(/'/g, "&#39;");
23
32
  }
24
33
 
34
+ /** Escaped text where `backtick spans` become <code>; the escape runs first, so a span cannot open a tag. */
35
+ export function withCode(text: string): string {
36
+ return esc(text).replace(/`([^`]+)`/g, "<code>$1</code>");
37
+ }
38
+
25
39
  const usd = (n: number) => `$${n.toFixed(2)}`;
40
+ /** Estimated dollars, with unknown-credential dollars named beside them and never added in. */
41
+ const estimated = (s: Split) => (s.byCredential.unknown.usd > 0 ? `${usd(s.byCredential.estimated.usd)} + ${usd(s.byCredential.unknown.usd)} unknown` : usd(s.byCredential.estimated.usd));
26
42
  const SEVERITY_WORD: Record<string, string> = { blocker: "Blocker", fix: "Fix", consider: "Consider", info: "Info" };
27
43
 
28
44
  /** A bar as wide as `value` is of `max`, drawn as inline SVG; `max` 0 gives an empty bar. */
@@ -38,7 +54,176 @@ function table(head: string[], rows: string[][], numeric: number[] = []): string
38
54
  .join("")}</tbody></table>`;
39
55
  }
40
56
 
41
- const empty = (text: string) => `<p class="muted">${esc(text)}</p>`;
57
+ const empty = (text: string) => `<p class="muted">${withCode(text)}</p>`;
58
+
59
+
60
+ const NO_DATA = "no data";
61
+ const SOURCE_WORD: Record<Source, string> = { actions: "GitHub Actions", laptop: "laptop" };
62
+
63
+ /** A figure of one source, or "no data" when the downloaded or kept data does not cover the period. */
64
+ const sourceCell = (split: Split, source: Source, known: boolean) => (known ? usd(split.bySource[source].usd) : NO_DATA);
65
+
66
+ function bucketLabel(b: Bucket, kind: "day" | "week") {
67
+ return kind === "week" ? `Week of ${b.key}${b.partial ? " (partial)" : ""}` : b.key;
68
+ }
69
+
70
+ /** Consecutive periods with no data in any source are one row, so a long gap does not read as zeros. */
71
+ function bucketTable(buckets: Bucket[], kind: "day" | "week"): string {
72
+ const rows: string[][] = [];
73
+ let gap: Bucket[] = [];
74
+ const flush = () => {
75
+ if (gap.length === 0) return;
76
+ const range = gap.length === 1 ? gap[0].key : `${gap[0].key} to ${gap.at(-1)!.key}`;
77
+ rows.push([esc(kind === "week" ? `Weeks of ${range}` : range), esc(NO_DATA), "", "", "", "", ""]);
78
+ gap = [];
79
+ };
80
+ for (const b of [...buckets].reverse()) {
81
+ if (!b.known.laptop && !b.known.actions) {
82
+ gap.push(b);
83
+ continue;
84
+ }
85
+ flush();
86
+ rows.push([
87
+ esc(bucketLabel(b, kind)),
88
+ String(b.spend.total.runs),
89
+ String(b.spend.total.calls),
90
+ usd(b.spend.total.usd),
91
+ sourceCell(b.spend, "actions", b.known.actions),
92
+ sourceCell(b.spend, "laptop", b.known.laptop),
93
+ `${usd(b.spend.byCredential.billed.usd)} / ${estimated(b.spend)}`,
94
+ ]);
95
+ }
96
+ flush();
97
+ return table([kind === "day" ? "Day (UTC)" : "Week (Monday, UTC)", "Runs", "Calls", "Total", "GitHub Actions", "Laptop", "Billed / estimated"], rows, [1, 2, 3, 4, 5, 6]);
98
+ }
99
+
100
+ /**
101
+ * Inline-SVG bars, one kind per chart so a line is never drawn over bars that do not mean the same thing:
102
+ * "counted" is what the ledger counts against its limit (GitHub Actions only) with the limit line;
103
+ * "source" is settled dollars by source (GitHub Actions below, laptop above) and has no limit line.
104
+ */
105
+ function chart(buckets: Bucket[], kind: "counted" | "source", limit: number | null, what: string, limitWord: string, tickEvery: number): string {
106
+ const W = 640;
107
+ const H = 170;
108
+ const left = 46;
109
+ const top = 18;
110
+ const bottom = 22;
111
+ const plotW = W - left - 8;
112
+ const plotH = H - top - bottom;
113
+ if (buckets.length === 0) return "";
114
+ const counted = (b: Bucket) => b.countedAgainstLimitUsd;
115
+ const totals = buckets.map((b) => (kind === "counted" ? (counted(b) ?? 0) : b.spend.total.usd));
116
+ const max = Math.max(kind === "counted" ? (limit ?? 0) : 0, ...totals, 0.01);
117
+ const y = (v: number) => top + plotH - (v / max) * plotH;
118
+ const slot = plotW / buckets.length;
119
+ const barW = Math.max(1, slot * 0.7);
120
+ const parts = buckets.map((b, i) => {
121
+ const x = left + i * slot + (slot - barW) / 2;
122
+ const noData = kind === "counted" ? counted(b) === null : !b.known.laptop && !b.known.actions;
123
+ if (noData) {
124
+ return `<rect class="nodata" x="${x.toFixed(1)}" y="${(top + plotH - 2).toFixed(1)}" width="${barW.toFixed(1)}" height="2"><title>${esc(b.key)}: ${NO_DATA}</title></rect>`;
125
+ }
126
+ if (kind === "counted") {
127
+ const v = counted(b) ?? 0;
128
+ return `<g><title>${esc(`${b.key}: ${usd(v)} counted against the limit`)}</title><rect class="fill" x="${x.toFixed(1)}" y="${y(v).toFixed(1)}" width="${barW.toFixed(1)}" height="${(top + plotH - y(v)).toFixed(1)}"/></g>`;
129
+ }
130
+ const a = b.known.actions ? b.spend.bySource.actions.usd : 0;
131
+ const l = b.known.laptop ? b.spend.bySource.laptop.usd : 0;
132
+ const label = `${b.key}: ${usd(b.spend.total.usd)} (GitHub Actions ${b.known.actions ? usd(a) : NO_DATA}, laptop ${b.known.laptop ? usd(l) : NO_DATA})`;
133
+ return `<g><title>${esc(label)}</title><rect class="fill" x="${x.toFixed(1)}" y="${y(a).toFixed(1)}" width="${barW.toFixed(1)}" height="${(top + plotH - y(a)).toFixed(1)}"/><rect class="fill2" x="${x.toFixed(1)}" y="${y(a + l).toFixed(1)}" width="${barW.toFixed(1)}" height="${(y(a) - y(a + l)).toFixed(1)}"/></g>`;
134
+ });
135
+ // A label under every `tickEvery`-th bucket, counted back from the newest so that the last one is always named.
136
+ const ticks = buckets
137
+ .map((b, i) => ((buckets.length - 1 - i) % tickEvery === 0 ? `<text class="axis" x="${(left + i * slot + slot / 2).toFixed(1)}" y="${H - 6}" text-anchor="middle">${esc(b.key.slice(5))}</text>` : ""))
138
+ .join("");
139
+ const limitLine =
140
+ kind !== "counted" || limit === null
141
+ ? ""
142
+ : `<line class="limit" x1="${left}" x2="${W - 8}" y1="${y(limit).toFixed(1)}" y2="${y(limit).toFixed(1)}"/><text class="axis" x="${W - 10}" y="${(y(limit) - 3).toFixed(1)}" text-anchor="end">${esc(limitWord)} ${esc(usd(limit))}</text>`;
143
+ return `<svg class="chart" viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(what)}"><title>${esc(what)}</title><line class="axisline" x1="${left}" x2="${W - 8}" y1="${top + plotH}" y2="${top + plotH}"/><text class="axis" x="${left - 4}" y="${top + plotH}" text-anchor="end">$0</text><text class="axis" x="${left - 4}" y="${top + 8}" text-anchor="end">${esc(usd(max))}</text>${ticks}${parts.join("")}${limitLine}</svg>`;
144
+ }
145
+
146
+ const cell = (m: Money, known: boolean) => (known ? usd(m.usd) : NO_DATA);
147
+
148
+ function groupTable(head: string, groups: Group[], coverage: Report["coverage"], empty_: string): string {
149
+ if (groups.length === 0) return empty(empty_);
150
+ const hasLaptop = coverage.laptop !== null;
151
+ const hasActions = coverage.actions !== null;
152
+ return table(
153
+ [head, "Runs", "Calls", "Total", "GitHub Actions", "Laptop", "Billed", "Estimated"],
154
+ groups.map((g) => [
155
+ esc(g.label),
156
+ String(g.split.total.runs),
157
+ String(g.split.total.calls),
158
+ usd(g.split.total.usd),
159
+ cell(g.split.bySource.actions, hasActions),
160
+ cell(g.split.bySource.laptop, hasLaptop),
161
+ usd(g.split.byCredential.billed.usd),
162
+ estimated(g.split),
163
+ ]),
164
+ [1, 2, 3, 4, 5, 6, 7],
165
+ );
166
+ }
167
+
168
+ function asideTable(aside: Report["aside"]): string {
169
+ const row = (label: string, a: Aside, money: string) => [esc(label), String(a.runs), esc(money)];
170
+ return table(
171
+ ["Not counted as spend", "Runs", "Dollars"],
172
+ [
173
+ row("Runs that were not reserved (the ledger was unreachable; recorded afterwards)", aside.unreserved, `${usd(aside.unreserved.usd)} recorded`),
174
+ row("Reservations that never settled (the run was killed; the hold is not spend)", aside.unsettled, `${usd(aside.unsettled.reservedUsd)} held`),
175
+ row("Runs still reserved (under six hours old)", aside.reserved, `${usd(aside.reserved.reservedUsd)} held`),
176
+ ],
177
+ [1],
178
+ );
179
+ }
180
+
181
+ function renderUsage(u: UsageSection): string {
182
+ const r = u.report;
183
+ const t = r.totals;
184
+ const limits: Limits | null = r.limits;
185
+ const lastPull = r.pulledAt ? `The ledger was last pulled ${esc(r.pulledAt)}; GitHub Actions figures cover ${esc(r.coverage.actions?.from ?? "")} to ${esc(r.coverage.actions?.to ?? "")}.` : "The ledger has not been pulled yet: run <code>wachiman ledger pull</code>. GitHub Actions figures show no data until then.";
186
+ const limitText = limits && (limits.dailyUsd !== null || limits.weeklyUsd !== null)
187
+ ? `Ledger limits: ${limits.dailyUsd !== null ? `daily ${usd(limits.dailyUsd)}` : "no daily limit"}, ${limits.weeklyUsd !== null ? `weekly ${usd(limits.weeklyUsd)}` : "no weekly limit"}. The limit is best-effort and counts GitHub Actions runs only, never laptop runs.`
188
+ : "The ledger limit, when one is set, is best-effort and counts GitHub Actions runs only, never laptop runs.";
189
+ const legend = `<p class="legend"><span class="sw"></span>${esc(SOURCE_WORD.actions)}<span class="sw sw2"></span>${esc(SOURCE_WORD.laptop)}</p>`;
190
+ const tile = (value: string, label: string) => `<div class="tile"><b>${value}</b>${esc(label)}</div>`;
191
+ return `<h2>Spend, laptop and GitHub Actions</h2>
192
+ <p class="muted">${lastPull}</p>
193
+ <p class="muted">${esc(limitText)} Weeks start on Monday, UTC. Dollars are shown as billed (API key) and estimated (subscription, API-equivalent, not a bill); the two are never merged into one figure without both being shown.</p>
194
+ <div class="tiles">
195
+ ${tile(String(t.total.runs), "finished runs")}
196
+ ${tile(usd(t.byCredential.billed.usd), "billed (API key)")}
197
+ ${tile(usd(t.byCredential.estimated.usd), "estimated (subscription)")}
198
+ ${t.byCredential.unknown.usd > 0 ? tile(usd(t.byCredential.unknown.usd), "unknown credential") : ""}
199
+ ${tile(r.coverage.actions ? usd(t.bySource.actions.usd) : NO_DATA, SOURCE_WORD.actions)}
200
+ ${tile(r.coverage.laptop ? usd(t.bySource.laptop.usd) : NO_DATA, SOURCE_WORD.laptop)}
201
+ </div>
202
+ <h2>Counted against the limit, per day (GitHub Actions runs)</h2>
203
+ <p class="muted">Each bar is what the ledger counts against its limit on one UTC day: settled runs, runs recorded without a reservation, and dollars still held by reservations. GitHub Actions only, for the whole account. A grey dash means no data for that day. ${limits?.dailyUsd != null ? "The dashed line is the daily limit." : "No daily limit is set."}</p>
204
+ ${chart(r.days, "counted", limits?.dailyUsd ?? null, "Dollars counted against the ledger limit per UTC day, GitHub Actions runs", "daily limit", 7)}
205
+ <h2>Spend per day, by source</h2>
206
+ <p class="muted">Each bar is the dollars of finished runs on one UTC day: GitHub Actions in the lower colour, this laptop in the upper colour. A grey dash means no data for that day. There is no limit line here because the limit does not count laptop runs.</p>
207
+ ${chart(r.days, "source", null, "Dollars of finished runs per UTC day, by source", "", 7)}${legend}
208
+ ${bucketTable(r.days, "day")}
209
+ <h2>Counted against the limit, per week (GitHub Actions runs)</h2>
210
+ <p class="muted">The same counting per week, which starts on Monday, UTC. ${limits?.weeklyUsd != null ? "The dashed line is the weekly limit." : "No weekly limit is set."}</p>
211
+ ${chart(r.weeks, "counted", limits?.weeklyUsd ?? null, "Dollars counted against the ledger limit per week starting Monday UTC, GitHub Actions runs", "weekly limit", 4)}
212
+ <h2>Spend per week, by source</h2>
213
+ <p class="muted">Each bar is the dollars of finished runs in one week that starts on Monday, UTC, with no limit line.</p>
214
+ ${chart(r.weeks, "source", null, "Dollars of finished runs per week starting Monday UTC, by source", "", 4)}${legend}
215
+ ${bucketTable(r.weeks, "week")}
216
+ <h2>Per repository</h2>
217
+ ${groupTable("Repository", r.groups.repository, r.coverage, "No finished run yet.")}
218
+ <h2>Per pull request</h2>
219
+ ${groupTable("Pull request", r.groups.pr, r.coverage, "No finished run yet.")}
220
+ <h2>Per model</h2>
221
+ <p class="muted">A run that used several models counts once in each, with only that model's calls and dollars.</p>
222
+ ${groupTable("Model", r.groups.model, r.coverage, "No finished run yet.")}
223
+ <h2>Not counted as spend</h2>
224
+ ${asideTable(r.aside)}
225
+ ${r.unknownCostCalls > 0 ? `<p class="muted">${r.unknownCostCalls} call${r.unknownCostCalls === 1 ? "" : "s"} died without a result: their dollars are unknown and counted as $0.00 above.</p>` : ""}`;
226
+ }
42
227
 
43
228
  export function renderHtml(doc: DashboardDocument): string {
44
229
  const { totals, spend, findings, loops, prConfidence } = doc;
@@ -87,8 +272,8 @@ export function renderHtml(doc: DashboardDocument): string {
87
272
  <meta name="viewport" content="width=device-width, initial-scale=1">
88
273
  <title>Wachiman dashboard</title>
89
274
  <style>
90
- :root { color-scheme: light dark; --bg: #fbfbf9; --fg: #1d1d1b; --muted: #6b6b66; --line: #dcdcd6; --fill: #2f6f9f; --track: #ecece6; }
91
- @media (prefers-color-scheme: dark) { :root { --bg: #161615; --fg: #ecece8; --muted: #9a9a94; --line: #34342f; --fill: #6fa8d6; --track: #262623; } }
275
+ :root { color-scheme: light dark; --bg: #fbfbf9; --fg: #1d1d1b; --muted: #6b6b66; --line: #dcdcd6; --fill: #2f6f9f; --fill2: #d98c2b; --track: #ecece6; }
276
+ @media (prefers-color-scheme: dark) { :root { --bg: #161615; --fg: #ecece8; --muted: #9a9a94; --line: #34342f; --fill: #6fa8d6; --fill2: #e0a458; --track: #262623; } }
92
277
  body { margin: 0; background: var(--bg); color: var(--fg); font: 15px/1.5 system-ui, sans-serif; }
93
278
  main { max-width: 56rem; margin: 0 auto; padding: 2rem 1.25rem 4rem; }
94
279
  h1 { font-size: 1.5rem; margin: 0 0 .25rem; }
@@ -104,24 +289,36 @@ th { font-weight: 500; color: var(--muted); font-size: .85rem; }
104
289
  .bar { width: 100%; min-width: 6rem; height: .5rem; display: block; }
105
290
  .track { fill: var(--track); }
106
291
  .fill { fill: var(--fill); }
292
+ .fill2 { fill: var(--fill2); }
293
+ .nodata { fill: var(--muted); opacity: .5; }
294
+ .chart { width: 100%; height: auto; display: block; margin: .5rem 0; }
295
+ .legend { font-size: .85rem; color: var(--muted); margin: 0 0 .5rem; }
296
+ .sw { display: inline-block; width: .8em; height: .8em; margin: 0 .35em 0 .9em; background: var(--fill); }
297
+ .sw:first-child { margin-left: 0; }
298
+ .sw2 { background: var(--fill2); }
299
+ .axis { fill: var(--muted); font-size: 9px; }
300
+ .axisline { stroke: var(--line); stroke-width: 1; }
301
+ .limit { stroke: #c0392b; stroke-width: 1.5; stroke-dasharray: 5 3; }
302
+ code { font: .9em ui-monospace, monospace; }
107
303
  </style>
108
304
  </head>
109
305
  <body>
110
306
  <main>
111
307
  <h1>Wachiman dashboard</h1>
112
- <p class="muted">${esc(doc.scope)}</p>
113
- <p class="muted">Generated ${esc(doc.generatedAt)} from the local history. Spend is an API-equivalent estimate, not a bill. Nothing on this page was sent anywhere.</p>
308
+ <p class="muted">${withCode(doc.scope)}</p>
309
+ <p class="muted">Generated ${esc(doc.generatedAt)} from ${doc.usage ? "the local history and the ledger entries downloaded earlier" : "the local history. Spend is an API-equivalent estimate, not a bill"}. Nothing on this page was sent anywhere.</p>
114
310
  <div class="tiles">
115
- <div class="tile"><b>${totals.runs}</b>runs</div>
116
- <div class="tile"><b>${usd(totals.costUsdEstimate)}</b>estimated spend</div>
311
+ ${doc.usage ? "" : `<div class="tile"><b>${totals.runs}</b>runs</div>
312
+ <div class="tile"><b>${usd(totals.costUsdEstimate)}</b>estimated spend</div>`}
117
313
  <div class="tile"><b>${totals.repositories}</b>repositories</div>
118
314
  <div class="tile"><b>${findings.total}</b>findings</div>
119
315
  <div class="tile"><b>${loops.totals.rounds}</b>loop rounds</div>
120
316
  </div>
121
- <h2>Spend per day</h2>
317
+ ${doc.usage ? renderUsage(doc.usage) : `<h2>Spend per day</h2>
122
318
  ${spendDay}
123
319
  <h2>Spend per repository</h2>
124
320
  ${spendRepo}
321
+ <p class="muted">To include GitHub Actions runs here, connect a ledger: <code>wachiman ledger connect &lt;url&gt;</code>.</p>`}
125
322
  <h2>Findings by severity</h2>
126
323
  ${bySeverity}
127
324
  <h2>Findings by your verdict</h2>