wachiman 1.14.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.
package/README.md CHANGED
@@ -120,7 +120,7 @@ same material, in this repository:
120
120
 
121
121
  Design decisions are recorded as ADRs in [docs/adr/](docs/adr/), starting with
122
122
  [ADR 0001: distribution and trust](docs/adr/0001-distribution-and-trust.md) and
123
- [ADR 0002: TypeScript on Bun, no runtime dependencies besides Bun itself](docs/adr/0002-typescript-on-bun-zero-dependencies.md).
123
+ [ADR 0002: TypeScript on Bun, no libraries unless the owner asks for one](docs/adr/0002-typescript-on-bun-zero-dependencies.md).
124
124
 
125
125
  ## What a pull request review looks like
126
126
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wachiman",
3
- "version": "1.14.0",
3
+ "version": "1.15.0",
4
4
  "description": "Advisory pull request reviews by an agent CLI, run in your own GitHub Actions with your own key, or locally on your own Claude subscription",
5
5
  "private": false,
6
6
  "type": "module",
@@ -25,7 +25,9 @@
25
25
  "!**/fixtures/"
26
26
  ],
27
27
  "dependencies": {
28
- "bun": "1.3.4"
28
+ "@clack/prompts": "1.9.0",
29
+ "bun": "1.3.4",
30
+ "chalk": "5.6.2"
29
31
  },
30
32
  "engines": {
31
33
  "bun": ">=1.3",
@@ -12,7 +12,7 @@
12
12
  * an empty working directory, which is all the installed CLI lets it apply. There is no fallback
13
13
  * to an unrestricted helper.
14
14
  */
15
- import { spawnSync } from "node:child_process";
15
+ import { spawn as spawnChild, spawnSync } from "node:child_process";
16
16
  import { accessSync, constants, mkdtempSync, realpathSync, rmSync, statSync } from "node:fs";
17
17
  import { tmpdir } from "node:os";
18
18
  import { isAbsolute, join, resolve } from "node:path";
@@ -37,6 +37,47 @@ const defaultSpawn: SpawnFn = (binary, args, options) => {
37
37
  return { status: run.status, stdout: run.stdout ?? "", stderr: run.stderr ?? "", error: run.error };
38
38
  };
39
39
 
40
+ /** The same call without blocking the event loop, so a spinner keeps turning while `claude` runs. */
41
+ export type AsyncSpawnFn = (...args: Parameters<SpawnFn>) => Promise<SpawnResult>;
42
+
43
+ /** Like `spawnSync` with `timeout` and `maxBuffer`: a process that outlives the timeout is killed and reports ETIMEDOUT; output past the buffer reports ENOBUFS. */
44
+ export const defaultAsyncSpawn: AsyncSpawnFn = (binary, args, options) =>
45
+ new Promise((resolve) => {
46
+ let stdout = "";
47
+ let stderr = "";
48
+ let failure: Error | undefined;
49
+ let settled = false;
50
+ const finish = (status: number | null) => {
51
+ if (settled) return;
52
+ settled = true;
53
+ clearTimeout(timer);
54
+ resolve({ status, stdout, stderr, ...(failure ? { error: failure } : {}) });
55
+ };
56
+ const child = spawnChild(binary, args, { cwd: options.cwd, env: options.env, shell: false, stdio: ["ignore", "pipe", "pipe"] });
57
+ const fail = (code: string) => {
58
+ failure ??= Object.assign(new Error(`spawn ${binary} ${code}`), { code });
59
+ child.kill("SIGKILL");
60
+ };
61
+ const timer = setTimeout(() => fail("ETIMEDOUT"), options.timeout);
62
+ // Decode the stream, not each chunk, so a character split across two chunks stays whole, and count bytes like spawnSync.
63
+ child.stdout.setEncoding("utf8");
64
+ child.stderr.setEncoding("utf8");
65
+ let bytes = 0;
66
+ const collect = (which: "stdout" | "stderr") => (chunk: string) => {
67
+ if (which === "stdout") stdout += chunk;
68
+ else stderr += chunk;
69
+ bytes += Buffer.byteLength(chunk);
70
+ if (bytes > options.maxBuffer) fail("ENOBUFS");
71
+ };
72
+ child.stdout.on("data", collect("stdout"));
73
+ child.stderr.on("data", collect("stderr"));
74
+ child.on("error", (error) => {
75
+ failure ??= error;
76
+ finish(null);
77
+ });
78
+ child.on("close", (code) => finish(code));
79
+ });
80
+
40
81
  /** What the confirmation looks at on disk: the directory and the binary themselves, nothing inside. */
41
82
  export interface ConfirmIo {
42
83
  isDirectory: (path: string) => boolean;
@@ -111,8 +152,26 @@ function samePath(a: string, b: string, io: ConfirmIo) {
111
152
  * Runs `<binary> --version` and `<binary> auth status` (JSON, the documented default) with
112
153
  * `buildChildEnv(env, { auth: "subscription", configDir })`, from an empty temporary directory,
113
154
  * 15 s and 64 KiB each. Both `local` and `doctor` call it before any model call.
155
+ *
156
+ * The steps are one generator that yields each process it wants run and gets the result back, so
157
+ * the blocking `confirmProfile` and the non-blocking `confirmProfileAsync` share every check.
114
158
  */
115
159
  export function confirmProfile(p: ResolvedProfile, env: Env, spawn: SpawnFn = defaultSpawn, io: ConfirmIo = defaultIo): Confirmation {
160
+ const steps = confirmSteps(p, env, io);
161
+ let step = steps.next();
162
+ while (!step.done) step = steps.next(spawn(...step.value));
163
+ return step.value;
164
+ }
165
+
166
+ /** The same confirmation with `claude` run off the event loop; the default spawn is asynchronous. */
167
+ export async function confirmProfileAsync(p: ResolvedProfile, env: Env, spawn: AsyncSpawnFn = defaultAsyncSpawn, io: ConfirmIo = defaultIo): Promise<Confirmation> {
168
+ const steps = confirmSteps(p, env, io);
169
+ let step = steps.next();
170
+ while (!step.done) step = steps.next(await spawn(...step.value));
171
+ return step.value;
172
+ }
173
+
174
+ function* confirmSteps(p: ResolvedProfile, env: Env, io: ConfirmIo): Generator<Parameters<SpawnFn>, Confirmation, SpawnResult> {
116
175
  const { profile } = p;
117
176
  const label = profile.kind === "default" ? "default" : profile.name;
118
177
  const login =
@@ -162,7 +221,7 @@ export function confirmProfile(p: ResolvedProfile, env: Env, spawn: SpawnFn = de
162
221
  encoding: "utf8" as const,
163
222
  };
164
223
 
165
- const probe = spawn(binary, ["--version"], options);
224
+ const probe = yield [binary, ["--version"], options];
166
225
  if (probe.error || probe.status !== 0) {
167
226
  return {
168
227
  ok: false,
@@ -173,7 +232,7 @@ export function confirmProfile(p: ResolvedProfile, env: Env, spawn: SpawnFn = de
173
232
  }
174
233
  const version = probe.stdout.match(/\d+\.\d+\.\d+/)?.[0] ?? brief(probe.stdout);
175
234
 
176
- const run = spawn(binary, ["auth", "status"], options);
235
+ const run = yield [binary, ["auth", "status"], options];
177
236
  if (run.error) {
178
237
  return {
179
238
  ok: false,
package/src/cli.ts CHANGED
@@ -16,6 +16,7 @@
16
16
  * call, no GitHub request, grounded in the stored review (src/local-ask.ts)
17
17
  * wachiman history list and judge what `local --history` kept on this laptop
18
18
  * wachiman status what the local history kept and its estimated cost; files only
19
+ * wachiman ledger connect|disconnect|pull connect to the spend ledger and download its entries (src/ledger-read/)
19
20
  * wachiman dashboard spend, findings and loops across every repository in the history, as one
20
21
  * static HTML file or JSON, from a rebuildable index (src/store/)
21
22
  * wachiman setup [--profile <name>] bind this repository to an account profile (home config only);
@@ -37,126 +38,32 @@ import { existsSync, readFileSync, statSync, writeSync } from "node:fs";
37
38
  import { join, resolve } from "node:path";
38
39
  import { writeStepSummary, type CallCost } from "./cost";
39
40
  import { loadConfig, UsageError } from "./config";
40
- import { historyUsage, parseHistoryArgs, runHistory } from "./history/command";
41
- import { parseStatusArgs, runStatus, statusUsage } from "./status/command";
42
- import { dashboardUsage, parseDashboardArgs, runDashboard } from "./store/command";
41
+ import { parseHistoryArgs, runHistory } from "./history/command";
42
+ import { parseStatusArgs, runStatus } from "./status/command";
43
+ import { parseDashboardArgs, runDashboard } from "./store/command";
44
+ import { parseLedgerArgs, runLedger } from "./ledger-read/command";
45
+ import { pullLedger } from "./ledger-read/pull";
43
46
  import { LedgerStopped, SpendLimitReached, comment, defaultGh, isThreadQuestion, review, threadReplies, type Deps, type GhFn, type ReviewLineComment } from "./engine";
44
- import { localUsage, parseLocalArgs, runLocal } from "./local";
45
- import { loopUsage, parseLoopArgs, runLoop } from "./loop/command";
46
- import { askUsage, parseAskArgs, runAsk } from "./local-ask";
47
- import { parseProfileArgs, parseProjectArgs, profileUsage, projectUsage, runProfile, runProject, setupUsage } from "./accounts/commands";
47
+ import { parseLocalArgs, runLocal } from "./local";
48
+ import { parseLoopArgs, runLoop } from "./loop/command";
49
+ import { parseAskArgs, runAsk } from "./local-ask";
50
+ import { parseProfileArgs, parseProjectArgs, runProfile, runProject } from "./accounts/commands";
48
51
  import { wachimanHome } from "./accounts/config";
49
- import { parseSkillsArgs, runSkills, skillsUsage } from "./skills/install";
50
- import { doctorUsage, parseDoctorArgs, runDoctor } from "./doctor/run";
51
- import { initUsage, parseInitFlags } from "./init/args";
52
+ import { parseSkillsArgs, runSkills } from "./skills/install";
53
+ import { parseDoctorArgs, runDoctor } from "./doctor/run";
54
+ import { parseInitFlags } from "./init/args";
52
55
  import { DEFAULT_WORKFLOW_REF } from "./init/options";
53
- import { runInitCommand } from "./init/run";
54
56
  import { projectCommands } from "./wizard/command";
55
57
  import { DEFAULT_ISOLATED_NAME, setupProfile } from "./profiles";
56
58
  import { resetConfidence } from "./fidelity/sink";
57
59
  import { getProvider, PROVIDER_NAMES, UnknownProviderError } from "./providers";
58
60
  import { parseSetupFlags } from "./setup/args";
61
+ import { runInitCommand } from "./init/run";
59
62
  import { runSetupCommand } from "./setup/run";
60
-
61
- export const USAGE = `Usage:
62
- wachiman review <pr> [paths…] [--repo-dir <dir>] Review a pull request (or only the given paths)
63
- wachiman comment <pr> [--repo-dir <dir>] Handle the comment in $REQUEST (a review or an answer)
64
- wachiman threads <pr> [--repo-dir <dir>] Answer the pending Wachiman threads (an automatic run)
65
- wachiman reset-confidence <pr> [--commit <sha>] Write "cannot say" into the PR Confidence block (no model call;
66
- the first step of a review run, with WACHIMAN_CONFIDENCE=1)
67
- ${localUsage}
68
- Review the committed branch of a clone on your
69
- signed-in claude, and print it; nothing is posted.
70
- --commit: that one commit (<commit>^ → <commit>);
71
- --from: that commit forward (<commit>^ → HEAD)
72
- ${loopUsage}
73
- One round of a review loop on your signed-in claude:
74
- --base starts it (round 1 reviews the whole range),
75
- a call with a loop open continues it and reviews only
76
- the commits since the last round. Fix, or judge a
77
- finding wrong with a reason, between calls; the CLI
78
- never edits code. Three rounds by default
79
- ${askUsage}
80
- Answer a question about the change the scope flags
81
- select, or explain it when no question is given. One
82
- call on your signed-in claude; no GitHub request.
83
- Grounded in the stored review of this change when
84
- \`local --history\` kept one; never runs a review
85
- ${historyUsage}
86
- List, judge and forget the findings kept by
87
- \`local --history\`; reads files and local git
88
- metadata only: no claude, no GitHub
89
- ${statusUsage}
90
- What this laptop kept of its local runs and their
91
- estimated cost, filterable; uses local history. GitHub
92
- Actions runs are not counted
93
- ${dashboardUsage}
94
- Write one static HTML page (or print JSON) with the
95
- spend per day and repository, the findings by severity
96
- and verdict and the loop rounds of every repository in
97
- the local history. Built from an index under the
98
- Wachiman home that is rebuilt whenever it is missing or
99
- out of date. It writes only that index and, without
100
- --json, the page, and, like \`wachiman history\`, moves
101
- a damaged run file aside. No claude, no GitHub, no
102
- network, no server, no browser. --repo-dir is accepted
103
- and unused
104
- ${setupUsage}
105
- Bind this repository to an account profile; written
106
- in the Wachiman home, never in the repository. On a
107
- terminal without --profile it asks, and can register
108
- or create a profile; without a terminal --profile
109
- must name a profile that already exists
110
- ${initUsage}
111
- Write the GitHub Actions caller workflow
112
- (.github/workflows/wachiman-review.yml), or, with
113
- --mode local, write nothing and hand over to setup.
114
- --dry-run prints the file; --force keeps a .bak copy
115
- ${doctorUsage}
116
- Explain what a local run would use and what would
117
- fail; exit 1 when a required check fails
118
- ${profileUsage.split("\n").join("\n ")}
119
- Manage account profiles; a managed profile lives in
120
- ~/.wachiman/claude-<name>, an external one is your own
121
- Claude configuration directory, used in place
122
- ${projectUsage.split("\n").join("\n ")}
123
- ${skillsUsage.split("\n").join("\n ")}
124
- Copy the wachiman-review, wachiman-loop and wachiman-audit agent
125
- skills into ~/.agents/skills and each Claude Code
126
- config directory; uninstall removes only the copies
127
- it marked. Never touches ~/.wachiman
128
- wachiman --setup-profile [<name>] Sign in an isolated profile, ~/.wachiman/claude-<name>
129
- (an alias of \`wachiman profile create\`)
130
- wachiman --help | --version
131
-
132
- Options:
133
- --repo-dir <dir> The checked-out pull request head: every file the engine reads
134
- and the agent's working directory. Default: the current directory.
135
- For \`local\`: the clone whose branch is reviewed.
136
-
137
- Environment:
138
- GH_TOKEN, GITHUB_REPOSITORY required (not read by \`local\`, \`ask\` or \`--setup-profile\`)
139
- ANTHROPIC_API_KEY the claude-code provider needs this or CLAUDE_CODE_OAUTH_TOKEN
140
- (not in a dry run); \`local\` and \`ask\` refuse to start when it is set
141
- CLAUDE_CODE_OAUTH_TOKEN a Claude subscription token (\`claude setup-token\`); if set, it is
142
- used and ANTHROPIC_API_KEY never reaches the agent
143
- REQUEST the comment text, for \`comment\`
144
- WACHIMAN_COMMENT_AUTHOR the login of the comment's author, for \`comment\` and \`threads\`
145
- WACHIMAN_* optional settings; see docs/cli.md
146
-
147
- Exit codes: 0 posted or nothing to do, 1 engine error, 2 usage error, 3 the spend ledger stopped the run
148
- (a limit with \`limit_mode: fail\`, an unlinked repository, no OIDC token, or an unreachable ledger with
149
- \`ledger_unavailable: stop\`); with \`limit_mode: notice\` a limit exits 0.
150
- \`local\`: 0 a report was printed, 1 no call returned a review, 2 usage error, 130 interrupted.
151
- \`loop\`: 0 converged, 10 findings still open, 11 stopped without converging (round cap or review failed), 2 usage error, 130 interrupted. A stop is never an approval.
152
- \`ask\`: 0 an answer was printed (it may say what it could not answer), 1 no answer (the call failed or returned nothing usable), 2 usage error, 130 interrupted.
153
- \`history\`: 0 listed (or nothing to list), 2 usage error, including an unknown finding id.
154
- \`status\`: 0 printed (also with no run kept), 2 usage error.
155
- \`dashboard\`: 0 written or printed (also with no run kept), 2 usage error, 1 the index or the page could not be written.
156
- \`doctor\`: 0 every required check passed, 1 one failed. \`setup\`: 1 when its closing doctor summary failed.
157
- \`setup\`, \`init\`: 130 cancelled (Escape, Ctrl-C, Ctrl-D); nothing pending is saved.
158
- \`skills\`: 0 done (copies left in place are warned about), 1 a copy could not be written, 2 usage error or a refused target.
159
- Guide: docs/local-review.md`;
63
+ import { commandHelp, helpFor, isCommand, rootHelp } from "./help";
64
+ import { shouldLaunch } from "./wizard/interactive";
65
+ import { isMissingPackage } from "./wizard/load";
66
+ import { plain, type Paint } from "./wizard/tone";
160
67
 
161
68
  /** package.json sits one level above src/; in a copied layout it may belong to someone else. */
162
69
  export function readVersion(dir = import.meta.dir) {
@@ -259,21 +166,35 @@ function runAccountCommand(mode: "doctor" | "profile" | "project", args: string[
259
166
  if (mode === "profile") return runProfile(parseProfileArgs(args), env, io, deps);
260
167
  if (mode === "project") return runProject(parseProjectArgs(args, repoDir), env, io, deps);
261
168
  const parsed = parseDoctorArgs(args, repoDir);
262
- if ("help" in parsed) return (io.stdout(`${doctorUsage}\n`), 0);
169
+ if ("help" in parsed) return (io.stdout(commandHelp(["doctor"])!), 0);
263
170
  return runDoctor(parsed, env, io, deps.doctor);
264
171
  }
265
172
 
173
+ /** The colors for help: loaded only when stdout is a terminal, so a run with piped output never loads chalk. */
174
+ async function paintFor(output: { isTTY?: boolean }, env: Record<string, string | undefined>): Promise<Paint> {
175
+ if (output.isTTY !== true) return plain;
176
+ // A clone that never ran `bun install` has no chalk: its help is plain text. Any other failure is a bug and shows.
177
+ const style = await import("./wizard/style").catch(plainWhenMissing);
178
+ return style?.terminalStyle(output, env) ?? plain;
179
+ }
180
+
181
+ /** `undefined` for a package that is not installed, the error itself for anything else. */
182
+ function plainWhenMissing(error: unknown): undefined {
183
+ if (isMissingPackage(error)) return undefined;
184
+ throw error;
185
+ }
186
+
266
187
  /** `setup` and `init`: asked on a terminal, flags and exit code 2 otherwise. A cancellation is exit 130. */
267
188
  async function runWizard(mode: "setup" | "init", args: string[], repoDir: string, env: Record<string, string | undefined>): Promise<number> {
268
189
  const io = { stdout: (text: string) => writeAll(1, text), stderr: (line: string) => console.error(line) };
269
190
  const version = readVersion();
270
191
  if (mode === "setup") {
271
192
  const flags = parseSetupFlags(args, repoDir);
272
- if (flags.help) return (io.stdout(`${setupUsage}\n`), 0);
193
+ if (flags.help) return (io.stdout(commandHelp(["setup"])!), 0);
273
194
  return runSetupCommand(flags, env, io, { doctor: { version } });
274
195
  }
275
196
  const flags = parseInitFlags(args, repoDir);
276
- if (flags.help) return (io.stdout(`${initUsage}\n`), 0);
197
+ if (flags.help) return (io.stdout(commandHelp(["init"])!), 0);
277
198
  return runInitCommand(flags, env, io, {
278
199
  version,
279
200
  defaultWorkflowRef: DEFAULT_WORKFLOW_REF,
@@ -313,10 +234,67 @@ export function runResetConfidence(args: string[], env: Record<string, string |
313
234
  return 0;
314
235
  }
315
236
 
237
+ async function printRootHelp(env: Record<string, string | undefined>): Promise<number> {
238
+ writeAll(1, rootHelp(await paintFor(process.stdout, env)));
239
+ return 0;
240
+ }
241
+
242
+ /**
243
+ * Bare `wachiman`, with no arguments. On a terminal (stdin, stdout and stderr, no CI) it opens the
244
+ * interactive launcher; anywhere else it prints the root help, as it always did. This is the one
245
+ * place that decides what a bare invocation does. A command chosen in the launcher runs through
246
+ * `main` again, with WACHIMAN_INTRO_DONE set so it does not play the intro a second time.
247
+ */
248
+ async function runNoArgs(env: Record<string, string | undefined>): Promise<number> {
249
+ const streams = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr };
250
+ // The same test the launcher applies, so a bare `wachiman` outside a terminal never loads the terminal UI.
251
+ if (shouldLaunch(env, streams)) {
252
+ // Without the packages (a clone that never ran `bun install`) the launcher does not open: the help is printed.
253
+ const launcher = await import("./wizard/launcher").catch(plainWhenMissing);
254
+ const launched = await launcher?.maybeLaunch({ env, version: readVersion(), dispatch: (args) => main(args, { ...env, WACHIMAN_INTRO_DONE: "1" }) });
255
+ if (launched !== undefined) return launched;
256
+ }
257
+ return printRootHelp(env);
258
+ }
259
+
260
+ /** One short line and where to look; the command's own page is `wachiman <command> --help`. */
261
+ function usageError(message: string, command: string | undefined): number {
262
+ const hint = isCommand(command) ? `wachiman ${command} --help` : "wachiman --help";
263
+ console.error(`wachiman: ${message}\nRun '${hint}'.`);
264
+ return 2;
265
+ }
266
+
267
+ /** `--refresh`: download the ledger first. A failed download warns and leaves the files already on disk in use. */
268
+ async function refreshLedger(env: Record<string, string | undefined>) {
269
+ try {
270
+ const r = await pullLedger(wachimanHome(env), env, undefined);
271
+ console.error(`wachiman: ledger refreshed (${r.entries} entries, ${r.from} to ${r.to}).`);
272
+ } catch (error) {
273
+ if (error instanceof UsageError) throw error;
274
+ console.error(`wachiman: ledger refresh failed: ${error instanceof Error ? error.message : error}. Showing the entries already downloaded.`);
275
+ }
276
+ }
277
+
316
278
  export async function main(argv: string[], env: Record<string, string | undefined>): Promise<number> {
317
279
  const mode = argv[0];
318
- if (mode === "--help" || mode === "-h") {
319
- console.log(USAGE);
280
+ if (argv.length === 0) {
281
+ // A command picked in the launcher goes through `main` again and handles its own errors; this
282
+ // catches the launcher's (reading the repository, the config, the terminal) the same way.
283
+ try {
284
+ return await runNoArgs(env);
285
+ } catch (error) {
286
+ console.error(`wachiman: ${error instanceof Error ? error.message : error}`);
287
+ return 1;
288
+ }
289
+ }
290
+ if (mode === "--help" || mode === "-h") return await printRootHelp(env);
291
+ // Before extractRepoDir, the configuration, git, authentication and any model: help reads nothing. The
292
+ // `help` branches of the parsers below only serve direct callers of `parse*`; `helpFor` catches every
293
+ // `--help` and `-h` first.
294
+ const help = helpFor(argv, await paintFor(process.stdout, env));
295
+ if (help !== undefined) {
296
+ if ("error" in help) return usageError(help.error, "help");
297
+ writeAll(1, help.text);
320
298
  return 0;
321
299
  }
322
300
  if (mode === "--version" || mode === "-v") {
@@ -335,9 +313,15 @@ export async function main(argv: string[], env: Record<string, string | undefine
335
313
  if (mode === "skills") {
336
314
  // Before extractRepoDir: no repository is read, so `--repo-dir` is a usage error here.
337
315
  const parsed = parseSkillsArgs(argv.slice(1));
338
- if ("help" in parsed) return (writeAll(1, `${skillsUsage}\n`), 0);
316
+ if ("help" in parsed) return (writeAll(1, commandHelp(["skills"])!), 0);
339
317
  return runSkills(parsed, env, { stdout: (text) => writeAll(1, text), stderr: (line) => console.error(line) }, { version: readVersion() });
340
318
  }
319
+ if (mode === "ledger") {
320
+ // Before extractRepoDir: no repository is read. The only command that contacts the ledger (ADR 0039).
321
+ const parsed = parseLedgerArgs(argv.slice(1));
322
+ if ("help" in parsed) return (writeAll(1, commandHelp(["ledger"])!), 0);
323
+ return await runLedger(parsed, env, { stdout: (text) => writeAll(1, text), stderr: (text) => void process.stderr.write(text) });
324
+ }
341
325
  const { repoDir, rest: args } = extractRepoDir(argv);
342
326
  if (mode === "local") {
343
327
  // No GitHub: no token, no repository, no `gh` function anywhere on this path.
@@ -369,12 +353,14 @@ export async function main(argv: string[], env: Record<string, string | undefine
369
353
  if (mode === "setup" || mode === "init") return await runWizard(mode, args.slice(1), repoDir, env);
370
354
  if (mode === "status") {
371
355
  const parsed = parseStatusArgs(args.slice(1));
372
- if ("help" in parsed) return (writeAll(1, `${statusUsage}\n`), 0);
356
+ if ("help" in parsed) return (writeAll(1, commandHelp(["status"])!), 0);
357
+ if (parsed.refresh) await refreshLedger(env);
373
358
  return runStatus(parsed, repoDir, env, { stdout: (text) => writeAll(1, text), stderr: (line) => console.error(line), version: readVersion() });
374
359
  }
375
360
  if (mode === "dashboard") {
376
361
  const parsed = parseDashboardArgs(args.slice(1));
377
- if ("help" in parsed) return (writeAll(1, `${dashboardUsage}\n`), 0);
362
+ if ("help" in parsed) return (writeAll(1, commandHelp(["dashboard"])!), 0);
363
+ if (parsed.refresh) await refreshLedger(env);
378
364
  return runDashboard(parsed, env, { stdout: (text) => writeAll(1, text), stderr: (line) => console.error(line) });
379
365
  }
380
366
  if (mode === "history") {
@@ -383,7 +369,7 @@ export async function main(argv: string[], env: Record<string, string | undefine
383
369
  if (mode === "reset-confidence") return runResetConfidence(args.slice(1), env);
384
370
  const [, prArg, ...rest] = args;
385
371
  if (mode !== "review" && mode !== "comment" && mode !== "threads") {
386
- throw new UsageError(mode ? `Unknown command "${mode}".` : "No command given.");
372
+ throw new UsageError(`Unknown command "${mode}".`);
387
373
  }
388
374
  const pr = Number(prArg);
389
375
  if (!/^\d+$/.test(prArg ?? "") || pr <= 0) {
@@ -438,8 +424,7 @@ export async function main(argv: string[], env: Record<string, string | undefine
438
424
  return 0;
439
425
  } catch (error) {
440
426
  if (error instanceof UsageError || error instanceof UnknownProviderError) {
441
- console.error(`wachiman: ${error.message}\n\n${USAGE}`);
442
- return 2;
427
+ return usageError(error.message, mode);
443
428
  }
444
429
  if (error instanceof SpendLimitReached) {
445
430
  // The notice is already posted. `notice` mode keeps the job green.
package/src/engine.ts CHANGED
@@ -2544,6 +2544,9 @@ const short200 = (error: unknown) => (error instanceof Error ? error.message : S
2544
2544
  /** The dollars the calls since `grant` cost, for a run that ended before it could say what it spent. */
2545
2545
  export const spentSince = (deps: Deps, grant: SpendGrant) => (deps.costs ?? []).slice(grant.costsFrom).reduce((n, c) => n + c.costUsd, 0);
2546
2546
 
2547
+ /** Runs that already said the ledger is skipped, so the line appears once. */
2548
+ const skippedLedger = new WeakSet<Deps>();
2549
+
2547
2550
  /**
2548
2551
  * Asks the ledger how much this run may spend, before any model call. With no `ledger_url` there is
2549
2552
  * nothing to ask and the room is unlimited; `limit_bypass` skips the ledger the same way, and the
@@ -2552,11 +2555,22 @@ export const spentSince = (deps: Deps, grant: SpendGrant) => (deps.costs ?? []).
2552
2555
  * accept and a job without an OIDC token are configuration errors: `LedgerStopped`, whatever
2553
2556
  * `ledger_unavailable` says. A ledger that cannot be reached lets the run go on under its normal
2554
2557
  * budgets (`unreached`), or stops it with `LedgerStopped` when `ledger_unavailable` is `stop`.
2558
+ * Outside GitHub Actions (`GITHUB_ACTIONS` is not `true`) nothing is asked: the run goes on and a
2559
+ * line says so.
2555
2560
  */
2556
2561
  export function spendReserve(deps: Deps, repo: string, pr: number, headSha: string, wantedUsd: number, forced: boolean): SpendGrant {
2557
2562
  const { config } = deps;
2558
2563
  const open = { reservationId: null, roomUsd: Number.POSITIVE_INFINITY, costsFrom: deps.costs?.length ?? 0, trigger: config.trigger ?? "cli", pr };
2559
2564
  if (!config.ledgerUrl) return { kind: "none", ...open };
2565
+ // Laptop runs are not counted against the limit: `WACHIMAN_LEDGER_URL` there is the read side's
2566
+ // setting (`wachiman ledger`), not a request to reserve. Only a GitHub Actions job reserves.
2567
+ if ((deps.ledgerEnv ?? process.env).GITHUB_ACTIONS !== "true") {
2568
+ if (!skippedLedger.has(deps)) {
2569
+ skippedLedger.add(deps);
2570
+ deps.warn("The spend ledger is skipped: this is not a GitHub Actions run, and laptop runs are not counted against the limit.");
2571
+ }
2572
+ return { kind: "none", ...open };
2573
+ }
2560
2574
  if (config.limitBypass) {
2561
2575
  deps.log("ledger bypassed");
2562
2576
  ledgerNote(deps, "The spend limit was bypassed for this run (`limit_bypass`); nothing was reserved or recorded.");