wachiman 1.14.0 → 1.16.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 (72) hide show
  1. package/README.md +2 -1
  2. package/package.json +4 -2
  3. package/src/accounts/commands.ts +3 -2
  4. package/src/accounts/confirm.ts +63 -4
  5. package/src/accounts/profile-list.ts +24 -0
  6. package/src/cli.ts +161 -142
  7. package/src/config.ts +19 -6
  8. package/src/connectors/local-git.ts +47 -0
  9. package/src/doctor/checks.ts +106 -1
  10. package/src/doctor/run.ts +9 -1
  11. package/src/engine.ts +294 -97
  12. package/src/help.ts +637 -0
  13. package/src/init/args.ts +5 -2
  14. package/src/init/github-login.ts +13 -0
  15. package/src/init/options.ts +31 -3
  16. package/src/init/prompt.ts +46 -15
  17. package/src/init/run.ts +238 -32
  18. package/src/init/settings.ts +127 -0
  19. package/src/init/write.ts +16 -102
  20. package/src/ledger-read/command.ts +106 -0
  21. package/src/ledger-read/credentials.ts +103 -0
  22. package/src/ledger-read/files.ts +141 -0
  23. package/src/ledger-read/pull.ts +69 -0
  24. package/src/ledger-read/rows.ts +60 -0
  25. package/src/ledger-read/types.ts +127 -0
  26. package/src/ledger.ts +34 -18
  27. package/src/local-ask.ts +5 -4
  28. package/src/local.ts +55 -10
  29. package/src/loop/command.ts +5 -5
  30. package/src/pr-template/adopt.ts +434 -0
  31. package/src/pr-template/catalog.ts +429 -0
  32. package/src/pr-template/check-run.ts +328 -0
  33. package/src/pr-template/check.ts +338 -0
  34. package/src/pr-template/describe.ts +368 -0
  35. package/src/pr-template/format.ts +399 -0
  36. package/src/pr-template/gh.ts +159 -0
  37. package/src/pr-template/install.ts +288 -0
  38. package/src/pr-template/legacy-guides.ts +50 -0
  39. package/src/pr-template/pr-risk.ts +426 -0
  40. package/src/pr-template/render.ts +302 -0
  41. package/src/pr-template/resolve.ts +65 -0
  42. package/src/pr-template/run.ts +88 -0
  43. package/src/pr-template/strip.ts +171 -0
  44. package/src/pr-template/write.ts +139 -0
  45. package/src/providers/claude-code.ts +7 -8
  46. package/src/providers/codex.ts +4 -4
  47. package/src/providers/spawn.ts +95 -0
  48. package/src/providers/types.ts +5 -2
  49. package/src/repo-settings.ts +159 -0
  50. package/src/setup/prompt.ts +49 -33
  51. package/src/setup/run.ts +58 -16
  52. package/src/sinks/common.ts +10 -3
  53. package/src/sinks/markdown.ts +3 -2
  54. package/src/sinks/terminal.ts +3 -2
  55. package/src/spend/report.ts +349 -0
  56. package/src/status/command.ts +150 -36
  57. package/src/store/command.ts +20 -3
  58. package/src/store/html.ts +205 -8
  59. package/src/store/index.ts +64 -5
  60. package/src/store/rows.ts +103 -0
  61. package/src/upgrade/command.ts +286 -0
  62. package/src/upgrade/pin.ts +112 -0
  63. package/src/wizard/interactive.ts +11 -0
  64. package/src/wizard/launcher.ts +340 -0
  65. package/src/wizard/load.ts +30 -0
  66. package/src/wizard/mascot.ts +228 -0
  67. package/src/wizard/prompt-fancy.ts +135 -0
  68. package/src/wizard/prompt.ts +108 -61
  69. package/src/wizard/style.ts +93 -13
  70. package/src/wizard/tone.ts +11 -0
  71. package/src/wizard/ui.ts +80 -0
  72. package/templates/pr/sections.json +163 -0
@@ -0,0 +1,127 @@
1
+ /**
2
+ * The repository settings file `.wachiman.yml`, written by `init` (ADR 0048). `init` records one
3
+ * key, `kind`, and a new file carries `model` and `effort` commented out (ADR 0049); the engine reads
4
+ * the file through `parseRepoSettings` in `src/repo-settings.ts`. It never chooses an account, a
5
+ * profile or a binary. Writing is plain string handling on purpose: init only ever creates the file
6
+ * or replaces the one top-level `kind:` line, and keeps every other line as it was.
7
+ *
8
+ * It lives at the repository root so it is visible in every mode, including local mode where there
9
+ * is no workflow and no `.github/` folder. It is never inside `.github/workflows/`: GitHub parses
10
+ * every YAML file there as a workflow.
11
+ */
12
+ import { randomBytes } from "node:crypto";
13
+ import { linkSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
14
+ import { basename, dirname, join } from "node:path";
15
+ import { UsageError } from "../config";
16
+ import { parseRepoSettings, SETTINGS_PATH } from "../repo-settings";
17
+ import type { ProjectKind } from "./options";
18
+ import { inspectTarget, type TargetState } from "./write";
19
+
20
+ export { SETTINGS_PATH };
21
+
22
+ const KIND_LINE = /^kind:[^\r\n]*/m;
23
+
24
+ /** The content of a new settings file. */
25
+ export const settingsContent = (kind: ProjectKind) =>
26
+ [
27
+ "# Wachiman settings for this repository, written by `wachiman init`. Commit it like any file.",
28
+ '# kind: the shape of the repository, "monorepo" or "single". Metadata only for now.',
29
+ `kind: ${kind}`,
30
+ "",
31
+ "# Optional. Wachiman's defaults are what its benchmarks measure; change them knowing that.",
32
+ "# model: claude-sonnet-5-5",
33
+ "# effort: high",
34
+ "",
35
+ ].join("\n");
36
+
37
+ /** The value of the top-level `kind:` line (quotes and a trailing comment removed), or undefined when there is none. */
38
+ export function readKind(content: string): string | undefined {
39
+ const line = KIND_LINE.exec(content);
40
+ if (!line) return undefined;
41
+ let value = line[0].slice("kind:".length).trim();
42
+ const quoted = /^(["'])(.*?)\1/.exec(value);
43
+ value = quoted ? quoted[2] : value.replace(/(^|\s+)#.*$/, "").trim();
44
+ return value === "" ? undefined : value;
45
+ }
46
+
47
+ /** Any top-level line that names the key, however it is written (`kind:`, `"kind":`, `'kind' :`). */
48
+ const ANY_KIND_KEY = /^(?:kind|"kind"|'kind')[ \t]*:/gm;
49
+
50
+ /**
51
+ * The file with only its top-level `kind:` line replaced (or `kind: X` appended when there is none).
52
+ * Plain string handling can miss a differently written key (a quoted key, a flow mapping) and leave
53
+ * a duplicate or invalid result, so the result is checked before it is returned: it must parse with
54
+ * the engine's own parser, name `kind` exactly once and say `kind: X`. Otherwise this refuses, and
55
+ * the person edits the file by hand.
56
+ */
57
+ export function withKind(content: string, kind: ProjectKind): string {
58
+ let next: string;
59
+ if (KIND_LINE.test(content)) next = content.replace(KIND_LINE, `kind: ${kind}`);
60
+ else {
61
+ const separator = content === "" || content.endsWith("\n") ? "" : "\n";
62
+ next = `${content}${separator}kind: ${kind}\n`;
63
+ }
64
+ const byHand = `Edit ${SETTINGS_PATH} by hand to say \`kind: ${kind}\`; init will not rewrite it.`;
65
+ let parsed: ReturnType<typeof parseRepoSettings>;
66
+ try {
67
+ parsed = parseRepoSettings(next);
68
+ } catch (error) {
69
+ throw new UsageError(`${SETTINGS_PATH} cannot be updated safely (${error instanceof Error ? error.message : error}) ${byHand}`);
70
+ }
71
+ if ((next.match(ANY_KIND_KEY) ?? []).length !== 1 || parsed.kind !== kind) {
72
+ throw new UsageError(`${SETTINGS_PATH} has a \`kind\` key that init cannot rewrite as a plain top-level line (a quoted key, a flow mapping or a duplicate). ${byHand}`);
73
+ }
74
+ return next;
75
+ }
76
+
77
+ export type SettingsPlan =
78
+ | { action: "create"; kind: ProjectKind; content: string; inspected: TargetState }
79
+ | { action: "same"; kind: ProjectKind }
80
+ | { action: "change"; kind: ProjectKind; from: string | undefined; content: string; inspected: TargetState };
81
+
82
+ /** Looks at the file without writing: what writing `kind` would do. Refuses a link or a non-file like the workflow does. */
83
+ export function planSettings(repoDir: string, kind: ProjectKind): SettingsPlan {
84
+ const inspected = inspectTarget(repoDir, SETTINGS_PATH);
85
+ if (!inspected.exists) return { action: "create", kind, content: settingsContent(kind), inspected };
86
+ const current = readFileSync(inspected.target, "utf8");
87
+ const from = readKind(current);
88
+ if (from === kind) return { action: "same", kind };
89
+ return { action: "change", kind, from, content: withKind(current, kind), inspected };
90
+ }
91
+
92
+ /** Writes a planned create or change: an exclusive temporary file, then a link (new) or a rename (only if the file is unchanged since the plan). */
93
+ export function writeSettings(repoDir: string, plan: Exclude<SettingsPlan, { action: "same" }>, hooks?: { beforeCommit?: () => void }): string {
94
+ const { inspected } = plan;
95
+ const dir = dirname(inspected.target);
96
+ const again = inspectTarget(repoDir, SETTINGS_PATH);
97
+ if (again.exists !== inspected.exists || again.identity !== inspected.identity) {
98
+ throw new UsageError(`${inspected.target} changed while init was running; nothing was written. Run it again.`);
99
+ }
100
+ const tmp = join(dir, `.${basename(inspected.target)}.${process.pid}-${randomBytes(4).toString("hex")}.tmp`);
101
+ writeFileSync(tmp, plan.content, { flag: "wx", mode: 0o644 });
102
+ try {
103
+ hooks?.beforeCommit?.();
104
+ if (inspected.exists) {
105
+ // Checked again right before the rename: an edit made since the plan is never overwritten.
106
+ if (inspectTarget(repoDir, SETTINGS_PATH).identity !== inspected.identity) {
107
+ throw new UsageError(`${inspected.target} changed while init was running; it was not replaced. Run it again.`);
108
+ }
109
+ renameSync(tmp, inspected.target);
110
+ }
111
+ else {
112
+ try {
113
+ linkSync(tmp, inspected.target);
114
+ } catch (error) {
115
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") throw new UsageError(`${inspected.target} appeared while init was running; nothing was written.`);
116
+ throw error;
117
+ }
118
+ }
119
+ } finally {
120
+ try {
121
+ unlinkSync(tmp);
122
+ } catch {
123
+ // Renamed into place, or already gone.
124
+ }
125
+ }
126
+ return inspected.target;
127
+ }
package/src/init/write.ts CHANGED
@@ -1,61 +1,16 @@
1
1
  /**
2
- * Writing the workflow file safely (contract section 5.5): no symbolic link may stand in for
3
- * `.github`, `workflows` or the target, an existing file is copied to a backup that never
4
- * overwrites another backup, and the new content goes in through an exclusive temporary file and a
5
- * rename after the target is found unchanged since it was inspected.
2
+ * Writing the workflow file safely (contract section 5.5). The mechanism is shared with
3
+ * `wachiman pr-template` and lives in `../pr-template/write.ts`; this file keeps the names and the
4
+ * behaviour `init` relies on: a backup of an existing file on every write, and messages that say
5
+ * `init`.
6
6
  */
7
- import { randomBytes } from "node:crypto";
8
- import { constants, copyFileSync, linkSync, lstatSync, mkdirSync, realpathSync, renameSync, unlinkSync, writeFileSync, type Stats } from "node:fs";
9
- import { basename, dirname, join, sep } from "node:path";
10
- import { UsageError } from "../config";
7
+ import { backupStamp, inspectManagedTarget, writeManagedFile, type TargetState, type WriteHooks } from "../pr-template/write";
11
8
 
12
- export interface TargetState {
13
- /** The real path the file is written to: the real repository root plus the relative path. */
14
- target: string;
15
- exists: boolean;
16
- identity?: string;
17
- }
18
-
19
- const identityOf = (s: Stats) => `${s.dev}:${s.ino}:${s.size}:${s.mtimeMs}`;
20
-
21
- const lstatOrNull = (path: string) => {
22
- try {
23
- return lstatSync(path);
24
- } catch (error) {
25
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
26
- throw error;
27
- }
28
- };
9
+ export { backupStamp };
10
+ export type { TargetState, WriteHooks };
29
11
 
30
12
  /** Looks at the target and its ancestors without following a link; refuses anything that is not a plain directory chain and a plain file. */
31
- export function inspectTarget(repoDir: string, relativePath: string): TargetState {
32
- const root = realpathSync(repoDir);
33
- let current = root;
34
- const parts = relativePath.split("/");
35
- for (const part of parts.slice(0, -1)) {
36
- current = join(current, part);
37
- const stat = lstatOrNull(current);
38
- if (stat === null) break;
39
- if (stat.isSymbolicLink()) throw new UsageError(`${current} is a symbolic link; init does not write through links. Replace it with a real directory.`);
40
- if (!stat.isDirectory()) throw new UsageError(`${current} is not a directory; init cannot write ${relativePath}.`);
41
- const real = realpathSync(current);
42
- if (real !== root && !real.startsWith(root + sep)) throw new UsageError(`${current} resolves outside the repository (${real}); init refuses it.`);
43
- }
44
- const target = join(root, relativePath);
45
- const stat = lstatOrNull(target);
46
- if (stat === null) return { target, exists: false };
47
- if (stat.isSymbolicLink()) throw new UsageError(`${target} is a symbolic link; init does not write through links.`);
48
- if (!stat.isFile()) throw new UsageError(`${target} exists and is not a regular file.`);
49
- return { target, exists: true, identity: identityOf(stat) };
50
- }
51
-
52
- /** `YYYYMMDD-HHMMSS` in UTC, from an ISO timestamp. */
53
- export const backupStamp = (iso: string) => iso.replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
54
-
55
- export interface WriteHooks {
56
- /** Runs after the temporary file is complete and before it replaces the target; a test changes the target here. */
57
- beforeCommit?: () => void;
58
- }
13
+ export const inspectTarget = (repoDir: string, relativePath: string): TargetState => inspectManagedTarget(repoDir, relativePath, "init");
59
14
 
60
15
  /**
61
16
  * Writes `content` to the inspected target. An existing file is copied to `<target>.bak-<stamp>`
@@ -63,52 +18,11 @@ export interface WriteHooks {
63
18
  * inspected. A new file is linked into place, which fails if one appeared meanwhile. Returns the
64
19
  * backup path when one was made.
65
20
  */
66
- export function writeWorkflow(p: { repoDir: string; relativePath: string; content: string; inspected: TargetState; now: string; hooks?: WriteHooks }): { target: string; backup?: string } {
67
- const { inspected } = p;
68
- const dir = dirname(inspected.target);
69
- mkdirSync(dir, { recursive: true });
70
- // The directories exist now: look again, so a link planted between the first look and the mkdir is still refused.
71
- const again = inspectTarget(p.repoDir, p.relativePath);
72
- if (again.exists !== inspected.exists || again.identity !== inspected.identity) {
73
- throw new UsageError(`${inspected.target} changed while init was running; nothing was written. Run it again.`);
74
- }
75
- let backup: string | undefined;
76
- if (inspected.exists) {
77
- const stamp = backupStamp(p.now);
78
- for (let n = 1; backup === undefined; n++) {
79
- const candidate = `${inspected.target}.bak-${stamp}${n === 1 ? "" : `-${n}`}`;
80
- try {
81
- copyFileSync(inspected.target, candidate, constants.COPYFILE_EXCL);
82
- backup = candidate;
83
- } catch (error) {
84
- if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
85
- }
86
- }
87
- }
88
- const tmp = join(dir, `.${basename(inspected.target)}.${process.pid}-${randomBytes(4).toString("hex")}.tmp`);
89
- writeFileSync(tmp, p.content, { flag: "wx", mode: 0o644 });
90
- try {
91
- p.hooks?.beforeCommit?.();
92
- if (inspected.exists) {
93
- const now = lstatOrNull(inspected.target);
94
- if (now === null || now.isSymbolicLink() || identityOf(now) !== inspected.identity) {
95
- throw new UsageError(`${inspected.target} changed while init was running; it was not replaced.${backup ? ` A copy of the earlier file is at ${backup}.` : ""}`);
96
- }
97
- renameSync(tmp, inspected.target);
98
- } else {
99
- try {
100
- linkSync(tmp, inspected.target);
101
- } catch (error) {
102
- if ((error as NodeJS.ErrnoException).code === "EEXIST") throw new UsageError(`${inspected.target} appeared while init was running; nothing was written.`);
103
- throw error;
104
- }
105
- }
106
- } finally {
107
- try {
108
- unlinkSync(tmp);
109
- } catch {
110
- // Renamed into place, or already gone.
111
- }
112
- }
113
- return { target: inspected.target, ...(backup ? { backup } : {}) };
114
- }
21
+ export const writeWorkflow = (p: { repoDir: string; relativePath: string; content: string; inspected: TargetState; now: string; hooks?: WriteHooks }): { target: string; backup?: string } =>
22
+ writeManagedFile({ ...p, label: "init", backup: true });
23
+
24
+ /** The generated first line carries a version and a date; a re-run on another day still writes the same workflow. */
25
+ const withoutHeader = (text: string) => text.replace(/^# Generated by wachiman init [^\n]*\n/, "");
26
+
27
+ /** True when `existing` is what `rendered` would write, apart from the generated header line. */
28
+ export const sameWorkflow = (existing: string, rendered: string) => withoutHeader(existing) === withoutHeader(rendered);
@@ -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
+ }