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/init/run.ts CHANGED
@@ -11,9 +11,9 @@ import { UsageError } from "../config";
11
11
  import { spawnGit, type GitRunner } from "../evidence";
12
12
  import { repositoryKey } from "../history/store";
13
13
  import { isInteractive, type TerminalStreams } from "../wizard/interactive";
14
- import { createPrompter, type Prompter, type PromptIO } from "../wizard/prompt";
15
- import { wizardIo } from "../wizard/style";
16
- import { projectCommands } from "../wizard/command";
14
+ import { loadTerminalUi } from "../wizard/load";
15
+ import type { Outcome, Prompter, PromptIO } from "../wizard/prompt";
16
+ import { projectCommands, quoteArgument } from "../wizard/command";
17
17
  import { DEFAULT_WORKFLOW_REF, resolveInitOptions, type InitOptions, type RawInitFlags } from "./options";
18
18
  import { checkSupplied, promptForInit } from "./prompt";
19
19
  import { callerHeader, renderCallerWorkflow } from "./render";
@@ -44,38 +44,50 @@ export interface InitDeps {
44
44
  const TEMPLATE = join(import.meta.dir, "..", "..", "templates", "wachiman-review-caller.yml");
45
45
  const readDefaultTemplate = () => readFileSync(TEMPLATE, "utf8");
46
46
 
47
- const openSession = (deps: InitDeps, env: Record<string, string | undefined>) => {
48
- if (deps.prompter) return { prompter: deps.prompter, close: () => {} };
49
- const prompter = createPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr }, env);
50
- return { prompter, close: () => prompter.close() };
47
+ const openSession = async (deps: InitDeps, env: Record<string, string | undefined>, ui: Awaited<ReturnType<typeof loadTerminalUi>>) => {
48
+ if (deps.prompter) return { prompter: deps.prompter, close: (_outcome: Outcome) => {} };
49
+ const prompter = await ui.openPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr }, env);
50
+ return { prompter, close: (outcome: Outcome) => prompter.close(outcome) };
51
51
  };
52
52
 
53
+ /** How a finished run ends the session: 0 is done, 130 a cancel, anything else a stop. */
54
+ const outcomeOf = (code: number): Outcome => (code === 0 ? "done" : code === 130 ? "cancelled" : "failed");
55
+
53
56
  /** From the parsed flags: asks what is missing when a person can be asked, resolves, and runs. */
54
57
  export async function runInitCommand(flags: RawInitFlags, env: Record<string, string | undefined>, io: CommandIo, deps: InitDeps = {}): Promise<number> {
55
58
  // Fail before asking for an operator or account in an unusable target.
56
59
  const root = worktreeRoot(flags.repoDir ?? ".", deps.git);
57
60
  const interactive = deps.interactive ?? isInteractive(flags, env, deps.streams ?? { stdin: process.stdin, stdout: process.stdout });
58
- if (interactive) io = wizardIo(io, (deps.promptIO?.output ?? process.stderr) as { isTTY?: boolean }, env);
59
61
  const defaultWorkflowRef = "defaultWorkflowRef" in deps ? deps.defaultWorkflowRef : DEFAULT_WORKFLOW_REF;
60
- const session = interactive ? openSession(deps, env) : undefined;
62
+ // The terminal UI (chalk and Clack) is loaded only when questions are asked.
63
+ const ui = interactive ? await loadTerminalUi() : undefined;
64
+ const session = ui ? await openSession(deps, env, ui) : undefined;
65
+ if (ui) io = ui.wizardIo(io, (deps.promptIO?.output ?? process.stderr) as { isTTY?: boolean }, env, session?.prompter);
66
+ let outcome: Outcome = "failed";
61
67
  try {
62
68
  let answered = flags;
63
69
  if (session) {
64
70
  checkSupplied(flags);
71
+ // Only the command that opened the session plays the intro; a caller that passed its own prompter did already,
72
+ // and the launcher marks WACHIMAN_INTRO_DONE, which `prompter.intro` honors.
73
+ if (!deps.prompter) await session.prompter.intro(deps.version ?? "unknown", "Let's put a watch post on this repo.");
65
74
  session.prompter.step("Project", 1);
66
75
  session.prompter.say(root, "muted");
67
76
  const asked = await promptForInit(flags, { defaultWorkflowRef }, session.prompter);
68
77
  if (asked === null) {
69
78
  io.stderr("cancelled: nothing was written.");
79
+ outcome = "cancelled";
70
80
  return 130;
71
81
  }
72
82
  answered = asked;
73
83
  }
74
84
  const resolved = resolveInitOptions(answered, { interactive, defaultWorkflowRef });
75
85
  if (!resolved.ok) throw new UsageError(resolved.error);
76
- return await runInit(resolved.options, io, { ...deps, prompter: session?.prompter });
86
+ const code = await runInit(resolved.options, io, { ...deps, prompter: session?.prompter });
87
+ outcome = outcomeOf(code);
88
+ return code;
77
89
  } finally {
78
- session?.close();
90
+ session?.close(outcome);
79
91
  }
80
92
  }
81
93
 
@@ -107,8 +119,13 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
107
119
  throw new UsageError(`A workflow already exists at ${shown}. Re-run with --force to replace it (a .bak copy is kept).`);
108
120
  }
109
121
  if (prompter) {
110
- io.stderr(`--- ${shown} (${inspected.exists ? "would overwrite" : "new"})`);
111
- io.stderr(rendered.replace(/\n$/, ""));
122
+ const preview = rendered.replace(/\n$/, "");
123
+ // On a terminal the preview is a titled note in the session frame; otherwise it is the lines it always was.
124
+ if (prompter.fancy) prompter.note(preview, `${shown} (${inspected.exists ? "would overwrite" : "new"})`);
125
+ else {
126
+ io.stderr(`--- ${shown} (${inspected.exists ? "would overwrite" : "new"})`);
127
+ io.stderr(preview);
128
+ }
112
129
  const answer = await prompter.confirm("Write it?", true);
113
130
  if (answer === null) {
114
131
  io.stderr("cancelled: nothing was written.");
@@ -116,6 +133,8 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
116
133
  }
117
134
  if (!answer) {
118
135
  io.stderr("not written.");
136
+ // The closing line of a terminal session says what happened, not "All set".
137
+ if (prompter.fancy) prompter.close("done", "Nothing was written.");
119
138
  return 0;
120
139
  }
121
140
  } else {
@@ -125,10 +144,17 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
125
144
  written = shown;
126
145
  io.stderr(`wrote ${shown}${result.backup ? `; the earlier file is kept as ${join(dirname(github.path), basename(result.backup))}` : ""}.`);
127
146
  if (options.mode === "github") prompter?.step("Checks and next actions", 4, 4);
128
- io.stderr("Two things are left to do in GitHub:");
129
- io.stderr(" 1. Add the repository secret ANTHROPIC_API_KEY (a Console key; Actions runs are billed to it): Settings, Secrets and variables, Actions.");
130
- io.stderr(` 2. Open a pull request that adds ${shown}. init does not commit, push or open one.`);
131
- io.stderr("Local runs use your signed-in claude, never this key.");
147
+ if (prompter?.fancy) {
148
+ // The same two things, as the closing "Next steps" box with the commands to run.
149
+ prompter.nextAction("Add the repository secret ANTHROPIC_API_KEY (a Console key; Actions runs are billed to it): Settings, Secrets and variables, Actions.", ["gh secret set ANTHROPIC_API_KEY"]);
150
+ prompter.nextAction(`Open a pull request that adds ${shown}. init does not commit, push or open one.`, [`git add ${quoteArgument(shown, "posix")}`, 'git commit -m "Add the Wachiman review workflow"', "git push"]);
151
+ prompter.say("Local runs use your signed-in claude, never this key.", "muted");
152
+ } else {
153
+ io.stderr("Two things are left to do in GitHub:");
154
+ io.stderr(" 1. Add the repository secret ANTHROPIC_API_KEY (a Console key; Actions runs are billed to it): Settings, Secrets and variables, Actions.");
155
+ io.stderr(` 2. Open a pull request that adds ${shown}. init does not commit, push or open one.`);
156
+ io.stderr("Local runs use your signed-in claude, never this key.");
157
+ }
132
158
  }
133
159
 
134
160
  if (options.mode === "github") {
@@ -0,0 +1,106 @@
1
+ /**
2
+ * `wachiman ledger connect <url> | disconnect | pull [--since <n>d]` (ADR 0039). `pull` is the only
3
+ * command here that makes a request, and only to the URL the user connected, with `GET /v1/entries`.
4
+ * The token is read from standard input without echo and never printed.
5
+ */
6
+ import { wachimanHome } from "../accounts/config";
7
+ import { UsageError } from "../config";
8
+ import { deleteCredentials, normaliseLedgerUrl, resolveCredentials, writeCredentials, credentialsPath } from "./credentials";
9
+ import { DEFAULT_PULL_DAYS, MAX_PULL_DAYS, pullLedger, realPullDeps, type PullDeps } from "./pull";
10
+
11
+ export const ledgerUsage = `wachiman ledger connect <url> ask for the read token (not echoed) and keep it, mode 0600
12
+ wachiman ledger disconnect delete the stored credentials
13
+ wachiman ledger pull [--since <n>d] download the last ${DEFAULT_PULL_DAYS} days (at most ${MAX_PULL_DAYS}) of the ledger's entries`;
14
+
15
+ export type LedgerArgs = { action: "connect"; url: string } | { action: "disconnect" } | { action: "pull"; sinceDays?: number };
16
+
17
+ export function parseLedgerArgs(argv: string[]): LedgerArgs | { help: true } {
18
+ const [action, ...rest] = argv;
19
+ if (action === undefined || action === "--help" || action === "-h") return { help: true };
20
+ if (rest.includes("--help") || rest.includes("-h")) return { help: true };
21
+ if (action === "connect") {
22
+ if (rest.length !== 1 || rest[0].startsWith("--")) throw new UsageError("ledger connect takes one argument: the ledger URL.");
23
+ return { action, url: rest[0] };
24
+ }
25
+ if (action === "disconnect") {
26
+ if (rest.length > 0) throw new UsageError("ledger disconnect takes no argument.");
27
+ return { action };
28
+ }
29
+ if (action === "pull") {
30
+ let sinceDays: number | undefined;
31
+ for (let i = 0; i < rest.length; i++) {
32
+ const arg = rest[i];
33
+ const eq = arg.indexOf("=");
34
+ const name = eq === -1 ? arg : arg.slice(0, eq);
35
+ if (name !== "--since") throw new UsageError(`ledger pull does not take "${arg}".`);
36
+ const v = eq === -1 ? rest[++i] : arg.slice(eq + 1);
37
+ if (v === undefined || !/^\d+d$/.test(v)) throw new UsageError(`--since takes a number of days such as 7d, got "${v ?? ""}".`);
38
+ sinceDays = Number.parseInt(v, 10);
39
+ if (sinceDays < 1 || sinceDays > MAX_PULL_DAYS) throw new UsageError(`--since takes 1 to ${MAX_PULL_DAYS} days.`);
40
+ }
41
+ return { action, ...(sinceDays !== undefined ? { sinceDays } : {}) };
42
+ }
43
+ throw new UsageError(`Unknown ledger action "${action}".`);
44
+ }
45
+
46
+ /** One line from standard input; on a terminal, typed without echo. */
47
+ export async function readSecretLine(stderr: (text: string) => void): Promise<string> {
48
+ const stdin = process.stdin;
49
+ stderr("Read token (input is hidden): ");
50
+ if (stdin.isTTY) {
51
+ return await new Promise<string>((resolve, reject) => {
52
+ let text = "";
53
+ stdin.setRawMode(true);
54
+ stdin.resume();
55
+ stdin.setEncoding("utf8");
56
+ const done = (fn: () => void) => {
57
+ stdin.setRawMode(false);
58
+ stdin.pause();
59
+ stdin.removeListener("data", onData);
60
+ stderr("\n");
61
+ fn();
62
+ };
63
+ const onData = (chunk: string) => {
64
+ for (const ch of chunk) {
65
+ if (ch === "\r" || ch === "\n") return done(() => resolve(text));
66
+ if (ch === "\u0003") return done(() => reject(new Error("cancelled")));
67
+ if (ch === "\u007f" || ch === "\b") text = text.slice(0, -1);
68
+ else text += ch;
69
+ }
70
+ };
71
+ stdin.on("data", onData);
72
+ });
73
+ }
74
+ const chunks: Buffer[] = [];
75
+ for await (const chunk of stdin) chunks.push(Buffer.from(chunk));
76
+ stderr("\n");
77
+ return Buffer.concat(chunks).toString("utf8").split(/\r?\n/)[0] ?? "";
78
+ }
79
+
80
+ export interface LedgerIo {
81
+ stdout: (text: string) => void;
82
+ stderr: (text: string) => void;
83
+ readToken?: () => Promise<string>;
84
+ pull?: PullDeps;
85
+ }
86
+
87
+ export async function runLedger(args: LedgerArgs, env: Record<string, string | undefined>, io: LedgerIo): Promise<number> {
88
+ const home = wachimanHome(env);
89
+ if (args.action === "connect") {
90
+ const url = normaliseLedgerUrl(args.url);
91
+ const token = (await (io.readToken ?? (() => readSecretLine(io.stderr)))()).trim();
92
+ if (token === "") throw new UsageError("No token was given.");
93
+ writeCredentials(home, { url, token });
94
+ io.stdout(`Connected to ${url}. Credentials kept in ${credentialsPath(home)} (mode 0600). Run \`wachiman ledger pull\` to download entries.\n`);
95
+ return 0;
96
+ }
97
+ if (args.action === "disconnect") {
98
+ io.stdout(deleteCredentials(home) ? "Disconnected: the stored credentials were deleted. Downloaded entries stay on disk.\n" : "No stored credentials to delete.\n");
99
+ if (resolveCredentials(home, env)) io.stderr("wachiman: WACHIMAN_LEDGER_URL and WACHIMAN_LEDGER_TOKEN are still set in the environment.\n");
100
+ return 0;
101
+ }
102
+ const result = await pullLedger(home, env, args.sinceDays, io.pull ?? realPullDeps);
103
+ io.stdout(`Pulled ${result.entries} entr${result.entries === 1 ? "y" : "ies"} for ${result.from} to ${result.to} from account ${result.account} (${result.daysWritten} day file${result.daysWritten === 1 ? "" : "s"} written).\n`);
104
+ if (result.daysRemoved > 0) io.stdout(`${result.daysRemoved} day file${result.daysRemoved === 1 ? "" : "s"} deleted: the ledger no longer returns entries for ${result.daysRemoved === 1 ? "that day" : "those days"} (days outside this pull are kept).\n`);
105
+ return 0;
106
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * The read credentials of the ledger: `<home>/ledger/credentials.json` (`{url, token}`, mode 0600),
3
+ * or `WACHIMAN_LEDGER_URL` / `WACHIMAN_LEDGER_TOKEN`, which override the file field by field. The
4
+ * token is written only here. It is never printed, logged or put in any other file (ADR 0039).
5
+ */
6
+ import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs";
7
+ import { dirname, join } from "node:path";
8
+ import { UsageError } from "../config";
9
+
10
+ export const ledgerDir = (home: string) => join(home, "ledger");
11
+ export const credentialsPath = (home: string) => join(ledgerDir(home), "credentials.json");
12
+
13
+ export interface LedgerCredentials {
14
+ url: string;
15
+ token: string;
16
+ }
17
+
18
+ /** The base URL of the ledger: https, or http only for a loopback address; no user info; no trailing slash. */
19
+ export function normaliseLedgerUrl(raw: string): string {
20
+ let u: URL;
21
+ try {
22
+ u = new URL(raw.trim());
23
+ } catch {
24
+ throw new UsageError(`"${raw}" is not a URL.`);
25
+ }
26
+ const loopback = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
27
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && loopback)) throw new UsageError("The ledger URL must be https (http is accepted only for localhost).");
28
+ if (u.username !== "" || u.password !== "") throw new UsageError("The ledger URL must not carry a user name or password.");
29
+ u.hash = "";
30
+ u.search = "";
31
+ return u.toString().replace(/\/+$/, "");
32
+ }
33
+
34
+ /** Writes `text` to `path` at 0600 through a temporary name beside it, in a 0700 directory. */
35
+ export function writePrivateFile(path: string, text: string) {
36
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
37
+ const tmp = `${path}.tmp-${process.pid}`;
38
+ const fd = openSync(tmp, "w", 0o600);
39
+ try {
40
+ try {
41
+ writeSync(fd, text);
42
+ fsyncSync(fd);
43
+ } finally {
44
+ closeSync(fd);
45
+ }
46
+ chmodSync(tmp, 0o600);
47
+ renameSync(tmp, path);
48
+ } catch (error) {
49
+ try {
50
+ unlinkSync(tmp);
51
+ } catch {
52
+ // Already gone.
53
+ }
54
+ throw error;
55
+ }
56
+ }
57
+
58
+ export function writeCredentials(home: string, credentials: LedgerCredentials) {
59
+ const url = normaliseLedgerUrl(credentials.url);
60
+ if (credentials.token.trim() === "") throw new UsageError("The read token is empty.");
61
+ writePrivateFile(credentialsPath(home), `${JSON.stringify({ url, token: credentials.token.trim() }, null, 2)}\n`);
62
+ }
63
+
64
+ /** True when a file was removed. */
65
+ export function deleteCredentials(home: string): boolean {
66
+ try {
67
+ unlinkSync(credentialsPath(home));
68
+ return true;
69
+ } catch (error) {
70
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
71
+ throw error;
72
+ }
73
+ }
74
+
75
+ function readFile(home: string): Partial<LedgerCredentials> {
76
+ let text: string;
77
+ try {
78
+ text = readFileSync(credentialsPath(home), "utf8");
79
+ } catch (error) {
80
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
81
+ throw error;
82
+ }
83
+ try {
84
+ const parsed = JSON.parse(text);
85
+ return {
86
+ ...(typeof parsed?.url === "string" ? { url: parsed.url } : {}),
87
+ ...(typeof parsed?.token === "string" ? { token: parsed.token } : {}),
88
+ };
89
+ } catch {
90
+ throw new UsageError(`${credentialsPath(home)} is not valid JSON; run \`wachiman ledger connect <url>\` again.`);
91
+ }
92
+ }
93
+
94
+ /** The credentials in force (environment over file), or undefined when the ledger is not connected. */
95
+ export function resolveCredentials(home: string, env: Record<string, string | undefined>): LedgerCredentials | undefined {
96
+ // A complete environment pair wins outright, so a damaged file cannot block it.
97
+ const complete = !!env.WACHIMAN_LEDGER_URL && !!env.WACHIMAN_LEDGER_TOKEN;
98
+ const file = complete ? {} : readFile(home);
99
+ const url = env.WACHIMAN_LEDGER_URL || file.url;
100
+ const token = env.WACHIMAN_LEDGER_TOKEN || file.token;
101
+ if (!url || !token) return undefined;
102
+ return { url: normaliseLedgerUrl(url), token };
103
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The ledger as files on the laptop (ADR 0039): `<home>/ledger/<account>/<day>.json` holds the entries
3
+ * of one UTC day, replaced as a whole by each pull, and `pull.json` beside them holds when the pull
4
+ * happened, the days it covered and the limits the ledger reported. These files are the record; the
5
+ * SQLite index is rebuilt from them. No token is ever written here.
6
+ */
7
+ import { existsSync, readdirSync, readFileSync, statSync, unlinkSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { ledgerDir, writePrivateFile } from "./credentials";
10
+ import { mergeRanges, type Range } from "../spend/report";
11
+ import { ACCOUNT_PATTERN, DAY_PATTERN, parseEntriesResponse, type EntriesResponse, type LedgerEntry, type LedgerLimits } from "./types";
12
+
13
+ export const PULL_FILE = "pull.json";
14
+ export const PULL_FORMAT = "wachiman.ledger-pull/1";
15
+ export const DAY_FORMAT = "wachiman.ledger-day/1";
16
+
17
+ export interface PullMeta {
18
+ account: string;
19
+ /** When the latest pull happened. */
20
+ pulledAt: string;
21
+ /** The days the pulls covered; ranges that overlap or touch are one. Day files outside the latest pull are kept. */
22
+ ranges: Range[];
23
+ limits: LedgerLimits;
24
+ }
25
+
26
+ const STALE_TMP_MS = 3_600_000;
27
+
28
+ /** Removes `*.tmp-<pid>` files a crashed write left in `dir`, when they are over an hour old. */
29
+ export function sweepStaleTemporaries(dir: string) {
30
+ if (!existsSync(dir)) return;
31
+ for (const name of readdirSync(dir)) {
32
+ if (!/\.tmp-\d+$/.test(name)) continue;
33
+ try {
34
+ if (Date.now() - statSync(join(dir, name)).mtimeMs > STALE_TMP_MS) unlinkSync(join(dir, name));
35
+ } catch {
36
+ // Gone already.
37
+ }
38
+ }
39
+ }
40
+
41
+ export const accountDir = (home: string, account: string) => join(ledgerDir(home), account);
42
+
43
+ /** Every `YYYY-MM-DD` from `from` to `to`, both included. */
44
+ export function daysBetween(from: string, to: string): string[] {
45
+ const days: string[] = [];
46
+ for (let t = Date.parse(`${from}T00:00:00Z`); t <= Date.parse(`${to}T00:00:00Z`); t += 86_400_000) days.push(new Date(t).toISOString().slice(0, 10));
47
+ return days;
48
+ }
49
+
50
+ /** Stores one pull: each day in the range is replaced by the entries received for it, or removed when none came. Days outside the range stay. */
51
+ export function storePull(home: string, response: EntriesResponse, from: string, to: string, pulledAt: string): { daysWritten: number; daysRemoved: number; entries: number } {
52
+ const dir = accountDir(home, response.account);
53
+ sweepStaleTemporaries(ledgerDir(home));
54
+ sweepStaleTemporaries(dir);
55
+ const byDay = new Map<string, LedgerEntry[]>();
56
+ for (const e of response.entries) {
57
+ if (e.day < from || e.day > to) continue;
58
+ byDay.set(e.day, [...(byDay.get(e.day) ?? []), e]);
59
+ }
60
+ let daysRemoved = 0;
61
+ for (const day of daysBetween(from, to)) {
62
+ const entries = byDay.get(day);
63
+ if (entries) writePrivateFile(join(dir, `${day}.json`), `${JSON.stringify({ format: DAY_FORMAT, account: response.account, day, entries }, null, 2)}\n`);
64
+ else if (existsSync(join(dir, `${day}.json`))) {
65
+ unlinkSync(join(dir, `${day}.json`));
66
+ daysRemoved++;
67
+ }
68
+ }
69
+ const earlier = readPullMeta(dir, response.account)?.ranges ?? [];
70
+ const meta = { format: PULL_FORMAT, account: response.account, pulledAt, ranges: mergeRanges([...earlier, { from, to }]), limits: response.limits };
71
+ writePrivateFile(join(dir, PULL_FILE), `${JSON.stringify(meta, null, 2)}\n`);
72
+ return { daysWritten: byDay.size, daysRemoved, entries: [...byDay.values()].reduce((n, e) => n + e.length, 0) };
73
+ }
74
+
75
+ /** `pull.json` of an account directory, or undefined when it is missing or damaged. Older files with `from`/`to` read as one range. */
76
+ export function readPullMeta(dir: string, account: string): PullMeta | undefined {
77
+ try {
78
+ const m = JSON.parse(readFileSync(join(dir, PULL_FILE), "utf8"));
79
+ if (!m || typeof m.pulledAt !== "string") return undefined;
80
+ const raw: unknown[] = Array.isArray(m.ranges) ? m.ranges : [{ from: m.from, to: m.to }];
81
+ const ranges = raw.filter((r): r is Range => !!r && typeof (r as Range).from === "string" && typeof (r as Range).to === "string" && DAY_PATTERN.test((r as Range).from) && DAY_PATTERN.test((r as Range).to));
82
+ if (ranges.length === 0) return undefined;
83
+ return {
84
+ account,
85
+ pulledAt: m.pulledAt,
86
+ ranges: mergeRanges(ranges),
87
+ limits: { dailyUsd: typeof m.limits?.dailyUsd === "number" ? m.limits.dailyUsd : null, weeklyUsd: typeof m.limits?.weeklyUsd === "number" ? m.limits.weeklyUsd : null },
88
+ };
89
+ } catch {
90
+ return undefined;
91
+ }
92
+ }
93
+
94
+ export interface LedgerAccountFiles {
95
+ account: string;
96
+ meta: PullMeta;
97
+ /** Day file paths, sorted. */
98
+ dayFiles: string[];
99
+ pullFile: string;
100
+ }
101
+
102
+ /**
103
+ * The account the laptop is connected to: the one pulled last, as a list of zero or one. Directories of
104
+ * accounts pulled earlier stay on disk (a disconnect keeps entries) and are ignored, so the figures and the
105
+ * limit never mix two accounts. A directory without a readable `pull.json` holds nothing the report can use.
106
+ */
107
+ export function listLedgerAccounts(home: string): LedgerAccountFiles[] {
108
+ const all = readAllLedgerAccounts(home);
109
+ if (all.length <= 1) return all;
110
+ const newest = [...all].sort((a, b) => b.meta.pulledAt.localeCompare(a.meta.pulledAt) || a.account.localeCompare(b.account))[0];
111
+ return [newest];
112
+ }
113
+
114
+ function readAllLedgerAccounts(home: string): LedgerAccountFiles[] {
115
+ const root = ledgerDir(home);
116
+ if (!existsSync(root)) return [];
117
+ const out: LedgerAccountFiles[] = [];
118
+ for (const account of readdirSync(root).sort()) {
119
+ if (!ACCOUNT_PATTERN.test(account)) continue;
120
+ const dir = join(root, account);
121
+ const pullFile = join(dir, PULL_FILE);
122
+ const meta = readPullMeta(dir, account);
123
+ if (!meta) continue;
124
+ const dayFiles = readdirSync(dir)
125
+ .filter((n) => /^\d{4}-\d{2}-\d{2}\.json$/.test(n))
126
+ .sort()
127
+ .map((n) => join(dir, n));
128
+ out.push({ account, meta, dayFiles, pullFile });
129
+ }
130
+ return out;
131
+ }
132
+
133
+ /** The entries of one day file, or undefined (with no throw) when it is not one. */
134
+ export function readDayFile(path: string): LedgerEntry[] | undefined {
135
+ try {
136
+ const d = JSON.parse(readFileSync(path, "utf8"));
137
+ return parseEntriesResponse({ account: "x", entries: d?.entries }).entries;
138
+ } catch {
139
+ return undefined;
140
+ }
141
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * `GET /v1/entries`: the only network request the laptop makes to the ledger, made only by
3
+ * `wachiman ledger pull` and by `--refresh`. The fetch function is injected so tests use no network.
4
+ * Errors never include the token.
5
+ */
6
+ import { UsageError } from "../config";
7
+ import { resolveCredentials } from "./credentials";
8
+ import { storePull } from "./files";
9
+ import { parseEntriesResponse } from "./types";
10
+
11
+ export const DEFAULT_PULL_DAYS = 35;
12
+ export const MAX_PULL_DAYS = 92;
13
+ const TIMEOUT_MS = 30_000;
14
+ const REDIRECT_MESSAGE = (url: string) => `the ledger URL ${url} redirected; the token is not sent to another address. Connect again with the final URL.`;
15
+
16
+ export interface PullDeps {
17
+ fetch: typeof fetch;
18
+ now: () => Date;
19
+ }
20
+ export const realPullDeps: PullDeps = { fetch: (input, init) => fetch(input, init), now: () => new Date() };
21
+
22
+ export interface PullResult {
23
+ account: string;
24
+ from: string;
25
+ to: string;
26
+ entries: number;
27
+ daysWritten: number;
28
+ /** Days inside the pulled range whose local file was deleted because the ledger returned no entries for them. */
29
+ daysRemoved: number;
30
+ url: string;
31
+ }
32
+
33
+ const dayOf = (d: Date) => d.toISOString().slice(0, 10);
34
+
35
+ export async function pullLedger(home: string, env: Record<string, string | undefined>, sinceDays: number | undefined, deps: PullDeps = realPullDeps): Promise<PullResult> {
36
+ const credentials = resolveCredentials(home, env);
37
+ if (!credentials) throw new UsageError("No ledger is connected: run `wachiman ledger connect <url>` first.");
38
+ const days = sinceDays ?? DEFAULT_PULL_DAYS;
39
+ if (!Number.isInteger(days) || days < 1 || days > MAX_PULL_DAYS) throw new UsageError(`--since takes 1 to ${MAX_PULL_DAYS} days, got ${days}.`);
40
+ const now = deps.now();
41
+ const to = dayOf(now);
42
+ const from = dayOf(new Date(now.getTime() - (days - 1) * 86_400_000));
43
+ const url = `${credentials.url}/v1/entries?from=${from}&to=${to}`;
44
+ let res: Response;
45
+ try {
46
+ res = await deps.fetch(url, { headers: { authorization: `Bearer ${credentials.token}`, accept: "application/json" }, signal: AbortSignal.timeout(TIMEOUT_MS), redirect: "error" });
47
+ } catch (error) {
48
+ if (error instanceof Error && /redirect/i.test(error.message)) throw new Error(REDIRECT_MESSAGE(credentials.url));
49
+ throw new Error(`could not reach the ledger at ${credentials.url}: ${error instanceof Error ? error.name : "network error"}`);
50
+ }
51
+ if (res.status >= 300 && res.status < 400) throw new Error(REDIRECT_MESSAGE(credentials.url));
52
+ if (res.status === 401) throw new Error("the ledger refused the read token (401); run `wachiman ledger connect <url>` with a valid one.");
53
+ if (!res.ok) throw new Error(`the ledger answered HTTP ${res.status}.`);
54
+ let body: unknown;
55
+ try {
56
+ body = await res.json();
57
+ } catch {
58
+ throw new Error("the ledger answer is not JSON.");
59
+ }
60
+ const response = (() => {
61
+ try {
62
+ return parseEntriesResponse(body);
63
+ } catch (error) {
64
+ throw new Error(`unexpected ledger answer: ${error instanceof Error ? error.message : "invalid"}.`);
65
+ }
66
+ })();
67
+ const stored = storePull(home, response, from, to, now.toISOString());
68
+ return { account: response.account, from, to, entries: stored.entries, daysWritten: stored.daysWritten, daysRemoved: stored.daysRemoved, url: credentials.url };
69
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Ledger entries as spend rows (ADR 0039), read straight from the pulled day files. `status` uses this,
3
+ * so it never depends on the index; the index holds the same entries for the dashboard.
4
+ */
5
+ import { mergeRanges, weekStart, type Limits, type Range, type SpendRow } from "../spend/report";
6
+ import { listLedgerAccounts, readDayFile } from "./files";
7
+ import type { LedgerEntry } from "./types";
8
+
9
+ /** A finished run keeps its calls and its dollars; a hold (`reserved`, `unsettled`) is not spend and has no calls. */
10
+ export function entryToRow(e: LedgerEntry): SpendRow {
11
+ const finished = e.state === "settled" || e.state === "unreserved";
12
+ return {
13
+ source: "actions",
14
+ state: e.state,
15
+ day: e.day,
16
+ week: e.week || weekStart(e.day),
17
+ repositoryKey: e.repository,
18
+ repository: e.repository,
19
+ pr: e.pr,
20
+ runId: e.run_id === null ? e.id : String(e.run_id),
21
+ profile: "",
22
+ costUsd: finished ? (e.settledUsd ?? 0) : 0,
23
+ reservedUsd: finished ? 0 : e.reservedUsd,
24
+ calls: finished ? e.calls.map((c) => ({ model: c.model, auth: c.auth, costUsd: c.cost_usd ?? 0, costKnown: c.costKnown })) : [],
25
+ };
26
+ }
27
+
28
+ export interface LedgerFromFiles {
29
+ rows: SpendRow[];
30
+ /** The days the pulls covered, merged over accounts. */
31
+ ranges: Range[];
32
+ limits: Limits | null;
33
+ pulledAt: string | null;
34
+ }
35
+
36
+ export function readLedgerFromFiles(home: string, warn: (line: string) => void): LedgerFromFiles {
37
+ const accounts = listLedgerAccounts(home);
38
+ const rows: SpendRow[] = [];
39
+ for (const a of accounts) {
40
+ const seen = new Set<string>();
41
+ for (const path of a.dayFiles) {
42
+ const entries = readDayFile(path);
43
+ if (!entries) {
44
+ warn(`status: ${path} is not a ledger day file; skipped`);
45
+ continue;
46
+ }
47
+ for (const e of entries) {
48
+ if (seen.has(e.id)) continue;
49
+ seen.add(e.id);
50
+ rows.push(entryToRow(e));
51
+ }
52
+ }
53
+ }
54
+ return {
55
+ rows,
56
+ ranges: mergeRanges(accounts.flatMap((a) => a.meta.ranges)),
57
+ limits: accounts.length ? accounts[0].meta.limits : null,
58
+ pulledAt: accounts.length ? accounts.map((a) => a.meta.pulledAt).sort().at(-1)! : null,
59
+ };
60
+ }