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/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
 
@@ -185,7 +185,7 @@ This is not a sandbox. What is enforced, what the tests show and what is still u
185
185
  The current release is on [npm](https://www.npmjs.com/package/wachiman) and in
186
186
  [CHANGELOG.md](CHANGELOG.md). The command-line contract ([docs/cli.md](docs/cli.md)) and the
187
187
  provider adapter boundary are in place. The older `CLAUDE_REVIEW_*` variables,
188
- `.github/agent-review.md`, `.github/claude-review.md`, `/wachi` and the `@claude` mention are still
188
+ `.github/claude-review.md`, `/wachi` and the `@claude` mention are still
189
189
  read with a notice; see [docs/upgrading.md](docs/upgrading.md).
190
190
 
191
191
  - **Claude Code** (`claude -p`) is the provider the reusable workflow installs and runs, with
package/bin/wachiman.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // The npm `bin` for `wachiman` and `agent-review`: finds Bun on PATH and runs this package's
2
+ // The npm `bin` for `wachiman`: finds Bun on PATH and runs this package's
3
3
  // TypeScript engine with it. All logic is in ./launcher-args.js.
4
4
  import { dirname } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wachiman",
3
- "version": "1.13.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",
@@ -10,8 +10,7 @@
10
10
  "url": "git+https://github.com/niway-dev/wachiman.git"
11
11
  },
12
12
  "bin": {
13
- "wachiman": "bin/wachiman.js",
14
- "agent-review": "bin/wachiman.js"
13
+ "wachiman": "bin/wachiman.js"
15
14
  },
16
15
  "files": [
17
16
  "bin/wachiman.js",
@@ -26,7 +25,9 @@
26
25
  "!**/fixtures/"
27
26
  ],
28
27
  "dependencies": {
29
- "bun": "1.3.4"
28
+ "@clack/prompts": "1.9.0",
29
+ "bun": "1.3.4",
30
+ "chalk": "5.6.2"
30
31
  },
31
32
  "engines": {
32
33
  "bun": ">=1.3",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: wachiman-review
3
- description: Use when the developer asks to review, audit or "analyse" their own code with Wachiman (or agent-review) on their laptop — a branch, one commit, or a range from a commit — including on employer code that must not reach GitHub, when they ask Wachiman to explain or answer a question about such a change ("explain this change", "ask about this branch"), and when they judge a finding from such a review as right or wrong.
3
+ description: Use when the developer asks to review, audit or "analyse" their own code with Wachiman on their laptop — a branch, one commit, or a range from a commit — including on employer code that must not reach GitHub, when they ask Wachiman to explain or answer a question about such a change ("explain this change", "ask about this branch"), and when they judge a finding from such a review as right or wrong.
4
4
  ---
5
5
 
6
6
  # Review local code with Wachiman
@@ -119,7 +119,7 @@ wachiman history --repo-dir <clone> --verdict <id> correct|partial|wrong --reaso
119
119
 
120
120
  | Tempting | Instead |
121
121
  | --- | --- |
122
- | `wachiman review <pr>`, `AGENT_REVIEW_DRY_RUN`, `gh`, a GitHub token | `local`: the GitHub modes post to the PR and need the code on GitHub |
122
+ | `wachiman review <pr>`, `WACHIMAN_DRY_RUN`, `gh`, a GitHub token | `local`: the GitHub modes post to the PR and need the code on GitHub |
123
123
  | A verdict as a PR comment or `Verdict:` reply | `history --verdict`: it stays on the laptop |
124
124
  | Running with `ANTHROPIC_API_KEY` set | `env -u ANTHROPIC_API_KEY wachiman local ...`: `local` refuses a key; the subscription pays |
125
125
  | `--max-depth 1000` because "review everything" | A closer start commit, or the number the developer chose |
@@ -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);
@@ -27,7 +28,9 @@
27
28
  * wachiman skills install|uninstall copy the agent skills into place, or remove what was copied
28
29
  * wachiman --setup-profile [name] sign in an isolated Claude Code profile under the Wachiman home
29
30
  *
30
- * Exit codes: 0 posted or nothing to do; 1 engine error (nothing posted); 2 usage error;
31
+ * Exit codes: 0 posted or nothing to do; 1 engine error (nothing posted); 2 usage error; 3 the spend
32
+ * ledger stopped the run before any model call (a limit with `limit_mode: fail`, a repository it does
33
+ * not know, a job without an OIDC token, or an unreachable ledger with `ledger_unavailable: stop`);
31
34
  * 130 cancelled (`local`, `loop`, `setup`, `init`); `loop` also exits 10 and 11 (see its help).
32
35
  * The settings are documented in docs/cli.md.
33
36
  */
@@ -35,124 +38,32 @@ import { existsSync, readFileSync, statSync, writeSync } from "node:fs";
35
38
  import { join, resolve } from "node:path";
36
39
  import { writeStepSummary, type CallCost } from "./cost";
37
40
  import { loadConfig, UsageError } from "./config";
38
- import { historyUsage, parseHistoryArgs, runHistory } from "./history/command";
39
- import { parseStatusArgs, runStatus, statusUsage } from "./status/command";
40
- import { dashboardUsage, parseDashboardArgs, runDashboard } from "./store/command";
41
- import { comment, defaultGh, isThreadQuestion, review, threadReplies, type Deps, type GhFn, type ReviewLineComment } from "./engine";
42
- import { localUsage, parseLocalArgs, runLocal } from "./local";
43
- import { loopUsage, parseLoopArgs, runLoop } from "./loop/command";
44
- import { askUsage, parseAskArgs, runAsk } from "./local-ask";
45
- import { parseProfileArgs, parseProjectArgs, profileUsage, projectUsage, runProfile, runProject, setupUsage } from "./accounts/commands";
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";
46
+ import { LedgerStopped, SpendLimitReached, comment, defaultGh, isThreadQuestion, review, threadReplies, type Deps, type GhFn, type ReviewLineComment } from "./engine";
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";
46
51
  import { wachimanHome } from "./accounts/config";
47
- import { parseSkillsArgs, runSkills, skillsUsage } from "./skills/install";
48
- import { doctorUsage, parseDoctorArgs, runDoctor } from "./doctor/run";
49
- 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";
50
55
  import { DEFAULT_WORKFLOW_REF } from "./init/options";
51
- import { runInitCommand } from "./init/run";
52
56
  import { projectCommands } from "./wizard/command";
53
57
  import { DEFAULT_ISOLATED_NAME, setupProfile } from "./profiles";
54
58
  import { resetConfidence } from "./fidelity/sink";
55
59
  import { getProvider, PROVIDER_NAMES, UnknownProviderError } from "./providers";
56
60
  import { parseSetupFlags } from "./setup/args";
61
+ import { runInitCommand } from "./init/run";
57
62
  import { runSetupCommand } from "./setup/run";
58
-
59
- export const USAGE = `Usage:
60
- wachiman review <pr> [paths…] [--repo-dir <dir>] Review a pull request (or only the given paths)
61
- wachiman comment <pr> [--repo-dir <dir>] Handle the comment in $REQUEST (a review or an answer)
62
- wachiman threads <pr> [--repo-dir <dir>] Answer the pending Wachiman threads (an automatic run)
63
- wachiman reset-confidence <pr> [--commit <sha>] Write "cannot say" into the PR Confidence block (no model call;
64
- the first step of a review run, with AGENT_REVIEW_CONFIDENCE=1)
65
- ${localUsage}
66
- Review the committed branch of a clone on your
67
- signed-in claude, and print it; nothing is posted.
68
- --commit: that one commit (<commit>^ → <commit>);
69
- --from: that commit forward (<commit>^ → HEAD)
70
- ${loopUsage}
71
- One round of a review loop on your signed-in claude:
72
- --base starts it (round 1 reviews the whole range),
73
- a call with a loop open continues it and reviews only
74
- the commits since the last round. Fix, or judge a
75
- finding wrong with a reason, between calls; the CLI
76
- never edits code. Three rounds by default
77
- ${askUsage}
78
- Answer a question about the change the scope flags
79
- select, or explain it when no question is given. One
80
- call on your signed-in claude; no GitHub request.
81
- Grounded in the stored review of this change when
82
- \`local --history\` kept one; never runs a review
83
- ${historyUsage}
84
- List, judge and forget the findings kept by
85
- \`local --history\`; reads files and local git
86
- metadata only: no claude, no GitHub
87
- ${statusUsage}
88
- What this laptop kept of its local runs and their
89
- estimated cost, filterable; uses local history. GitHub
90
- Actions runs are not counted
91
- ${dashboardUsage}
92
- Write one static HTML page (or print JSON) with the
93
- spend per day and repository, the findings by severity
94
- and verdict and the loop rounds of every repository in
95
- the local history. Built from an index under the
96
- Wachiman home that is rebuilt whenever it is missing or
97
- out of date. It writes only that index and, without
98
- --json, the page, and, like \`wachiman history\`, moves
99
- a damaged run file aside. No claude, no GitHub, no
100
- network, no server, no browser. --repo-dir is accepted
101
- and unused
102
- ${setupUsage}
103
- Bind this repository to an account profile; written
104
- in the Wachiman home, never in the repository. On a
105
- terminal without --profile it asks, and can register
106
- or create a profile; without a terminal --profile
107
- must name a profile that already exists
108
- ${initUsage}
109
- Write the GitHub Actions caller workflow
110
- (.github/workflows/wachiman-review.yml), or, with
111
- --mode local, write nothing and hand over to setup.
112
- --dry-run prints the file; --force keeps a .bak copy
113
- ${doctorUsage}
114
- Explain what a local run would use and what would
115
- fail; exit 1 when a required check fails
116
- ${profileUsage.split("\n").join("\n ")}
117
- Manage account profiles; a managed profile lives in
118
- ~/.wachiman/claude-<name>, an external one is your own
119
- Claude configuration directory, used in place
120
- ${projectUsage.split("\n").join("\n ")}
121
- ${skillsUsage.split("\n").join("\n ")}
122
- Copy the wachiman-review, wachiman-loop and wachiman-audit agent
123
- skills into ~/.agents/skills and each Claude Code
124
- config directory; uninstall removes only the copies
125
- it marked. Never touches ~/.wachiman
126
- wachiman --setup-profile [<name>] Sign in an isolated profile, ~/.wachiman/claude-<name>
127
- (an alias of \`wachiman profile create\`)
128
- wachiman --help | --version
129
-
130
- Options:
131
- --repo-dir <dir> The checked-out pull request head: every file the engine reads
132
- and the agent's working directory. Default: the current directory.
133
- For \`local\`: the clone whose branch is reviewed.
134
-
135
- Environment:
136
- GH_TOKEN, GITHUB_REPOSITORY required (not read by \`local\`, \`ask\` or \`--setup-profile\`)
137
- ANTHROPIC_API_KEY the claude-code provider needs this or CLAUDE_CODE_OAUTH_TOKEN
138
- (not in a dry run); \`local\` and \`ask\` refuse to start when it is set
139
- CLAUDE_CODE_OAUTH_TOKEN a Claude subscription token (\`claude setup-token\`); if set, it is
140
- used and ANTHROPIC_API_KEY never reaches the agent
141
- REQUEST the comment text, for \`comment\`
142
- AGENT_REVIEW_COMMENT_AUTHOR the login of the comment's author, for \`comment\` and \`threads\`
143
- AGENT_REVIEW_* optional settings; see docs/cli.md
144
-
145
- Exit codes: 0 posted or nothing to do, 1 engine error, 2 usage error.
146
- \`local\`: 0 a report was printed, 1 no call returned a review, 2 usage error, 130 interrupted.
147
- \`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.
148
- \`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.
149
- \`history\`: 0 listed (or nothing to list), 2 usage error, including an unknown finding id.
150
- \`status\`: 0 printed (also with no run kept), 2 usage error.
151
- \`dashboard\`: 0 written or printed (also with no run kept), 2 usage error, 1 the index or the page could not be written.
152
- \`doctor\`: 0 every required check passed, 1 one failed. \`setup\`: 1 when its closing doctor summary failed.
153
- \`setup\`, \`init\`: 130 cancelled (Escape, Ctrl-C, Ctrl-D); nothing pending is saved.
154
- \`skills\`: 0 done (copies left in place are warned about), 1 a copy could not be written, 2 usage error or a refused target.
155
- 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";
156
67
 
157
68
  /** package.json sits one level above src/; in a copied layout it may belong to someone else. */
158
69
  export function readVersion(dir = import.meta.dir) {
@@ -160,7 +71,7 @@ export function readVersion(dir = import.meta.dir) {
160
71
  const path = join(dir, "..", "package.json");
161
72
  if (!existsSync(path)) return "unknown";
162
73
  const pkg = JSON.parse(readFileSync(path, "utf8"));
163
- return pkg.name === "wachiman" || pkg.name === "agent-review" ? String(pkg.version) : "unknown";
74
+ return pkg.name === "wachiman" ? String(pkg.version) : "unknown";
164
75
  } catch {
165
76
  return "unknown";
166
77
  }
@@ -225,7 +136,7 @@ export function routeMode(mode: string, commentLine: ReviewLineComment | undefin
225
136
  * comment's text is `REQUEST`.
226
137
  */
227
138
  export function readCommentLine(env: Record<string, string | undefined>): ReviewLineComment | undefined {
228
- const id = env.AGENT_REVIEW_COMMENT_ID ?? "";
139
+ const id = env.WACHIMAN_COMMENT_ID ?? "";
229
140
  if (id === "") return undefined;
230
141
  const number = (name: string) => {
231
142
  const raw = env[name] ?? "";
@@ -233,12 +144,12 @@ export function readCommentLine(env: Record<string, string | undefined>): Review
233
144
  if (!/^\d+$/.test(raw)) throw new UsageError(`${name} must be a comment id or a line number, got "${raw}".`);
234
145
  return Number(raw);
235
146
  };
236
- if (!/^\d+$/.test(id)) throw new UsageError(`AGENT_REVIEW_COMMENT_ID must be a comment id, got "${id}".`);
147
+ if (!/^\d+$/.test(id)) throw new UsageError(`WACHIMAN_COMMENT_ID must be a comment id, got "${id}".`);
237
148
  return {
238
149
  id: Number(id),
239
- replyTo: number("AGENT_REVIEW_COMMENT_IN_REPLY_TO"),
240
- path: env.AGENT_REVIEW_COMMENT_PATH || null,
241
- line: number("AGENT_REVIEW_COMMENT_LINE"),
150
+ replyTo: number("WACHIMAN_COMMENT_IN_REPLY_TO"),
151
+ path: env.WACHIMAN_COMMENT_PATH || null,
152
+ line: number("WACHIMAN_COMMENT_LINE"),
242
153
  };
243
154
  }
244
155
 
@@ -255,21 +166,35 @@ function runAccountCommand(mode: "doctor" | "profile" | "project", args: string[
255
166
  if (mode === "profile") return runProfile(parseProfileArgs(args), env, io, deps);
256
167
  if (mode === "project") return runProject(parseProjectArgs(args, repoDir), env, io, deps);
257
168
  const parsed = parseDoctorArgs(args, repoDir);
258
- if ("help" in parsed) return (io.stdout(`${doctorUsage}\n`), 0);
169
+ if ("help" in parsed) return (io.stdout(commandHelp(["doctor"])!), 0);
259
170
  return runDoctor(parsed, env, io, deps.doctor);
260
171
  }
261
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
+
262
187
  /** `setup` and `init`: asked on a terminal, flags and exit code 2 otherwise. A cancellation is exit 130. */
263
188
  async function runWizard(mode: "setup" | "init", args: string[], repoDir: string, env: Record<string, string | undefined>): Promise<number> {
264
189
  const io = { stdout: (text: string) => writeAll(1, text), stderr: (line: string) => console.error(line) };
265
190
  const version = readVersion();
266
191
  if (mode === "setup") {
267
192
  const flags = parseSetupFlags(args, repoDir);
268
- if (flags.help) return (io.stdout(`${setupUsage}\n`), 0);
193
+ if (flags.help) return (io.stdout(commandHelp(["setup"])!), 0);
269
194
  return runSetupCommand(flags, env, io, { doctor: { version } });
270
195
  }
271
196
  const flags = parseInitFlags(args, repoDir);
272
- if (flags.help) return (io.stdout(`${initUsage}\n`), 0);
197
+ if (flags.help) return (io.stdout(commandHelp(["init"])!), 0);
273
198
  return runInitCommand(flags, env, io, {
274
199
  version,
275
200
  defaultWorkflowRef: DEFAULT_WORKFLOW_REF,
@@ -284,7 +209,7 @@ async function runWizard(mode: "setup" | "init", args: string[], repoDir: string
284
209
  * before the push wait, so a run cancelled during it leaves no letter from an older commit. No
285
210
  * model, no provider. A failure inside the reset itself (reading or writing the description) is a
286
211
  * warning and the exit code stays 0. A usage or configuration error is not: a bad pull request
287
- * number or flag, an invalid `AGENT_REVIEW_*` value, or a missing `GH_TOKEN` or
212
+ * number or flag, an invalid `WACHIMAN_*` value, or a missing `GH_TOKEN` or
288
213
  * `GITHUB_REPOSITORY` exits non-zero. The workflow steps run it with `continue-on-error`.
289
214
  */
290
215
  export function runResetConfidence(args: string[], env: Record<string, string | undefined>, gh: GhFn = defaultGh): number {
@@ -309,10 +234,67 @@ export function runResetConfidence(args: string[], env: Record<string, string |
309
234
  return 0;
310
235
  }
311
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
+
312
278
  export async function main(argv: string[], env: Record<string, string | undefined>): Promise<number> {
313
279
  const mode = argv[0];
314
- if (mode === "--help" || mode === "-h") {
315
- 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);
316
298
  return 0;
317
299
  }
318
300
  if (mode === "--version" || mode === "-v") {
@@ -331,9 +313,15 @@ export async function main(argv: string[], env: Record<string, string | undefine
331
313
  if (mode === "skills") {
332
314
  // Before extractRepoDir: no repository is read, so `--repo-dir` is a usage error here.
333
315
  const parsed = parseSkillsArgs(argv.slice(1));
334
- if ("help" in parsed) return (writeAll(1, `${skillsUsage}\n`), 0);
316
+ if ("help" in parsed) return (writeAll(1, commandHelp(["skills"])!), 0);
335
317
  return runSkills(parsed, env, { stdout: (text) => writeAll(1, text), stderr: (line) => console.error(line) }, { version: readVersion() });
336
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
+ }
337
325
  const { repoDir, rest: args } = extractRepoDir(argv);
338
326
  if (mode === "local") {
339
327
  // No GitHub: no token, no repository, no `gh` function anywhere on this path.
@@ -365,12 +353,14 @@ export async function main(argv: string[], env: Record<string, string | undefine
365
353
  if (mode === "setup" || mode === "init") return await runWizard(mode, args.slice(1), repoDir, env);
366
354
  if (mode === "status") {
367
355
  const parsed = parseStatusArgs(args.slice(1));
368
- 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);
369
358
  return runStatus(parsed, repoDir, env, { stdout: (text) => writeAll(1, text), stderr: (line) => console.error(line), version: readVersion() });
370
359
  }
371
360
  if (mode === "dashboard") {
372
361
  const parsed = parseDashboardArgs(args.slice(1));
373
- 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);
374
364
  return runDashboard(parsed, env, { stdout: (text) => writeAll(1, text), stderr: (line) => console.error(line) });
375
365
  }
376
366
  if (mode === "history") {
@@ -379,7 +369,7 @@ export async function main(argv: string[], env: Record<string, string | undefine
379
369
  if (mode === "reset-confidence") return runResetConfidence(args.slice(1), env);
380
370
  const [, prArg, ...rest] = args;
381
371
  if (mode !== "review" && mode !== "comment" && mode !== "threads") {
382
- throw new UsageError(mode ? `Unknown command "${mode}".` : "No command given.");
372
+ throw new UsageError(`Unknown command "${mode}".`);
383
373
  }
384
374
  const pr = Number(prArg);
385
375
  if (!/^\d+$/.test(prArg ?? "") || pr <= 0) {
@@ -402,8 +392,10 @@ export async function main(argv: string[], env: Record<string, string | undefine
402
392
  const repo = required(env, "GITHUB_REPOSITORY");
403
393
  const request = effective === "comment" ? required(env, "REQUEST") : "";
404
394
  const costs: CallCost[] = [];
395
+ const ledgerNotes: string[] = [];
405
396
  const deps: Deps = {
406
397
  costs,
398
+ ledgerNotes,
407
399
  gh: defaultGh,
408
400
  provider,
409
401
  ...(verifier ? { verifier } : {}),
@@ -423,17 +415,29 @@ export async function main(argv: string[], env: Record<string, string | undefine
423
415
  }
424
416
  try {
425
417
  if (effective === "review") review(deps, repo, pr, rest);
426
- else if (effective === "threads") threadReplies(deps, repo, pr, env.AGENT_REVIEW_COMMENT_AUTHOR || undefined);
427
- else comment(deps, repo, pr, request, env.AGENT_REVIEW_COMMENT_AUTHOR || undefined, commentLine);
418
+ else if (effective === "threads") threadReplies(deps, repo, pr, env.WACHIMAN_COMMENT_AUTHOR || undefined);
419
+ else comment(deps, repo, pr, request, env.WACHIMAN_COMMENT_AUTHOR || undefined, commentLine);
428
420
  } finally {
429
421
  // Also after a failed run: the calls it made were paid for.
430
- writeStepSummary(costs, env);
422
+ writeStepSummary(costs, env, undefined, ledgerNotes);
431
423
  }
432
424
  return 0;
433
425
  } catch (error) {
434
426
  if (error instanceof UsageError || error instanceof UnknownProviderError) {
435
- console.error(`wachiman: ${error.message}\n\n${USAGE}`);
436
- return 2;
427
+ return usageError(error.message, mode);
428
+ }
429
+ if (error instanceof SpendLimitReached) {
430
+ // The notice is already posted. `notice` mode keeps the job green.
431
+ if (error.mode === "notice") {
432
+ console.log(`wachiman: spend limit reached: ${error.message}`);
433
+ return 0;
434
+ }
435
+ console.error(`wachiman: spend limit reached: ${error.message}`);
436
+ return 3;
437
+ }
438
+ if (error instanceof LedgerStopped) {
439
+ console.error(`wachiman: ledger: ${error.message}`);
440
+ return 3;
437
441
  }
438
442
  console.error(`wachiman: ${error instanceof Error ? error.message : error}`);
439
443
  return 1;