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
package/README.md CHANGED
@@ -110,6 +110,7 @@ same material, in this repository:
110
110
  | Run the engine from the command line | [docs/cli.md](docs/cli.md) |
111
111
  | Review a branch on my laptop, on my own Claude subscription | [docs/local-review.md](docs/local-review.md) |
112
112
  | See the spend, findings and loops of my local reviews on one page | [docs/local-dashboard.md](docs/local-dashboard.md) |
113
+ | Give every pull request the same description template, and check it | [docs/pr-template.md](docs/pr-template.md) |
113
114
  | See what a provider adapter runs and inherits | [docs/providers/claude-code.md](docs/providers/claude-code.md), [docs/providers/codex.md](docs/providers/codex.md) |
114
115
  | Move from a copied installation | [docs/setup-copy.md](docs/setup-copy.md) |
115
116
  | Understand how a review is built | [docs/architecture.md](docs/architecture.md) |
@@ -120,7 +121,7 @@ same material, in this repository:
120
121
 
121
122
  Design decisions are recorded as ADRs in [docs/adr/](docs/adr/), starting with
122
123
  [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).
124
+ [ADR 0002: TypeScript on Bun, no libraries unless the owner asks for one](docs/adr/0002-typescript-on-bun-zero-dependencies.md).
124
125
 
125
126
  ## What a pull request review looks like
126
127
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wachiman",
3
- "version": "1.14.0",
3
+ "version": "1.16.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",
@@ -379,7 +379,7 @@ function removeProfile(cmd: Extract<ProfileCommand, { kind: "remove" }>, env: Re
379
379
  function loginProfile(cmd: Extract<ProfileCommand, { kind: "login" }>, env: Record<string, string | undefined>, io: CommandIo, deps: AccountDeps) {
380
380
  const home = wachimanHome(env);
381
381
  if (parseProfileRef(cmd.profile).kind === "default") {
382
- throw new UsageError("`default` is your own claude: sign in with your own claude (run it and use /login).");
382
+ throw new UsageError("`default` is your own claude: sign in with `claude auth login`.");
383
383
  }
384
384
  if (!(deps.interactive ?? isInteractive(env, { stdin: process.stdin.isTTY === true, stdout: process.stdout.isTTY === true }))) {
385
385
  throw new UsageError("profile login needs a terminal: run it yourself in a terminal, not from an agent or a pipe.");
@@ -609,12 +609,13 @@ export function parseSetupArgs(argv: string[], repoDir: string): SetupOptions |
609
609
  * The end of `setup`: the compact doctor summary and the suggested `wachiman local` line, on stderr.
610
610
  * Returns the exit code the summary decides (1 when a required check failed; the binding stays written).
611
611
  */
612
- export function closeSetup(repoDir: string, env: Record<string, string | undefined>, io: CommandIo, deps: AccountDeps = {}): number {
612
+ export function closeSetup(repoDir: string, env: Record<string, string | undefined>, io: CommandIo, deps: AccountDeps = {}, result?: { failedRequired?: number }): number {
613
613
  const report = buildDoctorReport(
614
614
  { repoDir, allProfiles: false, json: false, redactPaths: false },
615
615
  env,
616
616
  { spawn: deps.spawn, git: deps.git, userHome: deps.userHome, ...deps.doctor },
617
617
  );
618
+ if (result) result.failedRequired = report.failedRequired;
618
619
  const width = Math.max(...report.checks.map((r) => r.id.length));
619
620
  io.stderr(`doctor: ${report.checks.length} checks, ${report.failedRequired} required failed`);
620
621
  for (const row of report.checks) if (row.status === "fail" || row.status === "warn") for (const line of renderRow(row, width)) io.stderr(line);
@@ -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,12 +152,30 @@ 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 =
119
- profile.kind === "default" ? "sign in with your own `claude` (run it and use /login)" : `wachiman profile login ${profile.name}`;
178
+ profile.kind === "default" ? "sign in with your own claude: `claude auth login`" : `wachiman profile login ${profile.name}`;
120
179
  const configDir = profile.kind === "default" ? undefined : profile.configDir;
121
180
 
122
181
  if (configDir !== undefined && !io.isDirectory(configDir)) {
@@ -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,
@@ -42,6 +42,30 @@ export interface ProfileList {
42
42
  profiles: ProfileListEntry[];
43
43
  }
44
44
 
45
+ export interface DetectedClaudeDir {
46
+ /** The profile name proposed for it: the suffix of `~/.claude-<suffix>`. */
47
+ name: string;
48
+ configDir: string;
49
+ }
50
+
51
+ /**
52
+ * The `~/.claude-<name>` directories in the person's home that no profile registers: the
53
+ * configuration directories people keep for a second account, usually reached through a shell alias
54
+ * or function that sets CLAUDE_CONFIG_DIR, which Wachiman cannot see. Looks at the listing only.
55
+ */
56
+ export function detectClaudeDirs(userHome: string, config: WachimanConfigV1 | undefined): DetectedClaudeDir[] {
57
+ const registered = new Set(Object.values(config?.profiles ?? {}).map((p) => p.configDir));
58
+ try {
59
+ return readdirSync(userHome, { withFileTypes: true })
60
+ .filter((d) => d.isDirectory() && d.name.startsWith(".claude-"))
61
+ .map((d) => ({ name: d.name.slice(".claude-".length).toLowerCase(), configDir: join(userHome, d.name) }))
62
+ .filter((d) => /^[a-z0-9][a-z0-9-]{0,31}$/.test(d.name) && !registered.has(d.configDir))
63
+ .sort((a, b) => a.name.localeCompare(b.name));
64
+ } catch {
65
+ return [];
66
+ }
67
+ }
68
+
45
69
  /** Registered profiles plus the `claude-*` directories under the home that no entry names. Looks at the home's listing only. */
46
70
  export function buildProfileList(home: string, config: WachimanConfigV1 | undefined): ProfileList {
47
71
  const profiles: ProfileListEntry[] = Object.entries(config?.profiles ?? {}).map(([name, entry]) => ({
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);
@@ -24,7 +25,10 @@
24
25
  * wachiman doctor explain what a local run would use and what would fail
25
26
  * wachiman profile … list, create, add, login, remove and default account profiles
26
27
  * wachiman project show|unbind inspect or remove this repository's binding
28
+ * wachiman upgrade [--check] update the CLI, then the workflow pin in this repository (src/upgrade/)
27
29
  * wachiman skills install|uninstall copy the agent skills into place, or remove what was copied
30
+ * wachiman pr-template show|install|status|check|format|risk|strip the PR description template: install it,
31
+ * report its state, check and reorder a description, and compute the risk floor
28
32
  * wachiman --setup-profile [name] sign in an isolated Claude Code profile under the Wachiman home
29
33
  *
30
34
  * Exit codes: 0 posted or nothing to do; 1 engine error (nothing posted); 2 usage error; 3 the spend
@@ -37,126 +41,35 @@ import { existsSync, readFileSync, statSync, writeSync } from "node:fs";
37
41
  import { join, resolve } from "node:path";
38
42
  import { writeStepSummary, type CallCost } from "./cost";
39
43
  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";
43
- 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";
44
+ import { parseHistoryArgs, runHistory } from "./history/command";
45
+ import { parseStatusArgs, runStatus } from "./status/command";
46
+ import { parseDashboardArgs, runDashboard } from "./store/command";
47
+ import { parseLedgerArgs, runLedger } from "./ledger-read/command";
48
+ import { pullLedger } from "./ledger-read/pull";
49
+ import { LedgerStopped, SpendLimitReached, comment, defaultGh, isThreadQuestion, review, threadReplies, withBaseSettings, type Deps, type GhFn, type ReviewLineComment } from "./engine";
50
+ import { parseLocalArgs, runLocal } from "./local";
51
+ import { parseLoopArgs, runLoop } from "./loop/command";
52
+ import { parseAskArgs, runAsk } from "./local-ask";
53
+ import { parseProfileArgs, parseProjectArgs, runProfile, runProject } from "./accounts/commands";
48
54
  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";
55
+ import { parseSkillsArgs, runSkills } from "./skills/install";
56
+ import { runPrTemplate } from "./pr-template/run";
57
+ import { parseUpgradeArgs, runUpgrade } from "./upgrade/command";
58
+ import { parseDoctorArgs, runDoctor } from "./doctor/run";
59
+ import { parseInitFlags } from "./init/args";
60
+ import { ghLogin } from "./init/github-login";
52
61
  import { DEFAULT_WORKFLOW_REF } from "./init/options";
53
- import { runInitCommand } from "./init/run";
54
62
  import { projectCommands } from "./wizard/command";
55
63
  import { DEFAULT_ISOLATED_NAME, setupProfile } from "./profiles";
56
64
  import { resetConfidence } from "./fidelity/sink";
57
65
  import { getProvider, PROVIDER_NAMES, UnknownProviderError } from "./providers";
58
66
  import { parseSetupFlags } from "./setup/args";
67
+ import { runInitCommand } from "./init/run";
59
68
  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`;
69
+ import { commandHelp, helpFor, isCommand, rootHelp } from "./help";
70
+ import { shouldLaunch } from "./wizard/interactive";
71
+ import { isMissingPackage } from "./wizard/load";
72
+ import { plain, type Paint } from "./wizard/tone";
160
73
 
161
74
  /** package.json sits one level above src/; in a copied layout it may belong to someone else. */
162
75
  export function readVersion(dir = import.meta.dir) {
@@ -259,26 +172,41 @@ function runAccountCommand(mode: "doctor" | "profile" | "project", args: string[
259
172
  if (mode === "profile") return runProfile(parseProfileArgs(args), env, io, deps);
260
173
  if (mode === "project") return runProject(parseProjectArgs(args, repoDir), env, io, deps);
261
174
  const parsed = parseDoctorArgs(args, repoDir);
262
- if ("help" in parsed) return (io.stdout(`${doctorUsage}\n`), 0);
175
+ if ("help" in parsed) return (io.stdout(commandHelp(["doctor"])!), 0);
263
176
  return runDoctor(parsed, env, io, deps.doctor);
264
177
  }
265
178
 
179
+ /** The colors for help: loaded only when stdout is a terminal, so a run with piped output never loads chalk. */
180
+ async function paintFor(output: { isTTY?: boolean }, env: Record<string, string | undefined>): Promise<Paint> {
181
+ if (output.isTTY !== true) return plain;
182
+ // A clone that never ran `bun install` has no chalk: its help is plain text. Any other failure is a bug and shows.
183
+ const style = await import("./wizard/style").catch(plainWhenMissing);
184
+ return style?.terminalStyle(output, env) ?? plain;
185
+ }
186
+
187
+ /** `undefined` for a package that is not installed, the error itself for anything else. */
188
+ function plainWhenMissing(error: unknown): undefined {
189
+ if (isMissingPackage(error)) return undefined;
190
+ throw error;
191
+ }
192
+
266
193
  /** `setup` and `init`: asked on a terminal, flags and exit code 2 otherwise. A cancellation is exit 130. */
267
194
  async function runWizard(mode: "setup" | "init", args: string[], repoDir: string, env: Record<string, string | undefined>): Promise<number> {
268
195
  const io = { stdout: (text: string) => writeAll(1, text), stderr: (line: string) => console.error(line) };
269
196
  const version = readVersion();
270
197
  if (mode === "setup") {
271
198
  const flags = parseSetupFlags(args, repoDir);
272
- if (flags.help) return (io.stdout(`${setupUsage}\n`), 0);
199
+ if (flags.help) return (io.stdout(commandHelp(["setup"])!), 0);
273
200
  return runSetupCommand(flags, env, io, { doctor: { version } });
274
201
  }
275
202
  const flags = parseInitFlags(args, repoDir);
276
- if (flags.help) return (io.stdout(`${initUsage}\n`), 0);
203
+ if (flags.help) return (io.stdout(commandHelp(["init"])!), 0);
277
204
  return runInitCommand(flags, env, io, {
278
205
  version,
279
206
  defaultWorkflowRef: DEFAULT_WORKFLOW_REF,
280
- // Choosing local/both already requests setup; keep its final write confirmation.
281
- bindNow: (prompter, mode) => runSetupCommand({ repoDir }, env, io, { doctor: { version }, interactive: true, prompter, fromInit: true, initMode: mode, unboundHints: projectCommands("setup", repoDir, process.cwd()) }),
207
+ githubLogin: ghLogin,
208
+ // Choosing local/both already requests setup, which saves the binding without asking again.
209
+ bindNow: (prompter, mode, closing) => runSetupCommand({ repoDir }, env, io, { doctor: { version }, interactive: true, prompter, fromInit: true, initMode: mode, unboundHints: projectCommands("setup", repoDir, process.cwd()), closing }),
282
210
  });
283
211
  }
284
212
 
@@ -313,10 +241,67 @@ export function runResetConfidence(args: string[], env: Record<string, string |
313
241
  return 0;
314
242
  }
315
243
 
244
+ async function printRootHelp(env: Record<string, string | undefined>): Promise<number> {
245
+ writeAll(1, rootHelp(await paintFor(process.stdout, env)));
246
+ return 0;
247
+ }
248
+
249
+ /**
250
+ * Bare `wachiman`, with no arguments. On a terminal (stdin, stdout and stderr, no CI) it opens the
251
+ * interactive launcher; anywhere else it prints the root help, as it always did. This is the one
252
+ * place that decides what a bare invocation does. A command chosen in the launcher runs through
253
+ * `main` again, with WACHIMAN_INTRO_DONE set so it does not play the intro a second time.
254
+ */
255
+ async function runNoArgs(env: Record<string, string | undefined>): Promise<number> {
256
+ const streams = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr };
257
+ // The same test the launcher applies, so a bare `wachiman` outside a terminal never loads the terminal UI.
258
+ if (shouldLaunch(env, streams)) {
259
+ // Without the packages (a clone that never ran `bun install`) the launcher does not open: the help is printed.
260
+ const launcher = await import("./wizard/launcher").catch(plainWhenMissing);
261
+ const launched = await launcher?.maybeLaunch({ env, version: readVersion(), dispatch: (args) => main(args, { ...env, WACHIMAN_INTRO_DONE: "1" }) });
262
+ if (launched !== undefined) return launched;
263
+ }
264
+ return printRootHelp(env);
265
+ }
266
+
267
+ /** One short line and where to look; the command's own page is `wachiman <command> --help`. */
268
+ function usageError(message: string, command: string | undefined): number {
269
+ const hint = isCommand(command) ? `wachiman ${command} --help` : "wachiman --help";
270
+ console.error(`wachiman: ${message}\nRun '${hint}'.`);
271
+ return 2;
272
+ }
273
+
274
+ /** `--refresh`: download the ledger first. A failed download warns and leaves the files already on disk in use. */
275
+ async function refreshLedger(env: Record<string, string | undefined>) {
276
+ try {
277
+ const r = await pullLedger(wachimanHome(env), env, undefined);
278
+ console.error(`wachiman: ledger refreshed (${r.entries} entries, ${r.from} to ${r.to}).`);
279
+ } catch (error) {
280
+ if (error instanceof UsageError) throw error;
281
+ console.error(`wachiman: ledger refresh failed: ${error instanceof Error ? error.message : error}. Showing the entries already downloaded.`);
282
+ }
283
+ }
284
+
316
285
  export async function main(argv: string[], env: Record<string, string | undefined>): Promise<number> {
317
286
  const mode = argv[0];
318
- if (mode === "--help" || mode === "-h") {
319
- console.log(USAGE);
287
+ if (argv.length === 0) {
288
+ // A command picked in the launcher goes through `main` again and handles its own errors; this
289
+ // catches the launcher's (reading the repository, the config, the terminal) the same way.
290
+ try {
291
+ return await runNoArgs(env);
292
+ } catch (error) {
293
+ console.error(`wachiman: ${error instanceof Error ? error.message : error}`);
294
+ return 1;
295
+ }
296
+ }
297
+ if (mode === "--help" || mode === "-h") return await printRootHelp(env);
298
+ // Before extractRepoDir, the configuration, git, authentication and any model: help reads nothing. The
299
+ // `help` branches of the parsers below only serve direct callers of `parse*`; `helpFor` catches every
300
+ // `--help` and `-h` first.
301
+ const help = helpFor(argv, await paintFor(process.stdout, env));
302
+ if (help !== undefined) {
303
+ if ("error" in help) return usageError(help.error, "help");
304
+ writeAll(1, help.text);
320
305
  return 0;
321
306
  }
322
307
  if (mode === "--version" || mode === "-v") {
@@ -335,13 +320,19 @@ export async function main(argv: string[], env: Record<string, string | undefine
335
320
  if (mode === "skills") {
336
321
  // Before extractRepoDir: no repository is read, so `--repo-dir` is a usage error here.
337
322
  const parsed = parseSkillsArgs(argv.slice(1));
338
- if ("help" in parsed) return (writeAll(1, `${skillsUsage}\n`), 0);
323
+ if ("help" in parsed) return (writeAll(1, commandHelp(["skills"])!), 0);
339
324
  return runSkills(parsed, env, { stdout: (text) => writeAll(1, text), stderr: (line) => console.error(line) }, { version: readVersion() });
340
325
  }
326
+ if (mode === "ledger") {
327
+ // Before extractRepoDir: no repository is read. The only command that contacts the ledger (ADR 0039).
328
+ const parsed = parseLedgerArgs(argv.slice(1));
329
+ if ("help" in parsed) return (writeAll(1, commandHelp(["ledger"])!), 0);
330
+ return await runLedger(parsed, env, { stdout: (text) => writeAll(1, text), stderr: (text) => void process.stderr.write(text) });
331
+ }
341
332
  const { repoDir, rest: args } = extractRepoDir(argv);
342
333
  if (mode === "local") {
343
334
  // No GitHub: no token, no repository, no `gh` function anywhere on this path.
344
- return runLocal(parseLocalArgs(args.slice(1)), repoDir, env, {
335
+ return await runLocal(parseLocalArgs(args.slice(1)), repoDir, env, {
345
336
  stdout: (text) => writeAll(1, text),
346
337
  stderr: (line) => console.error(line),
347
338
  engineVersion: readVersion(),
@@ -349,7 +340,7 @@ export async function main(argv: string[], env: Record<string, string | undefine
349
340
  }
350
341
  if (mode === "loop") {
351
342
  // Like `local`: no GitHub token, no `gh` function anywhere on this path.
352
- return runLoop(parseLoopArgs(args.slice(1)), repoDir, env, {
343
+ return await runLoop(parseLoopArgs(args.slice(1)), repoDir, env, {
353
344
  stdout: (text) => writeAll(1, text),
354
345
  stderr: (line) => console.error(line),
355
346
  engineVersion: readVersion(),
@@ -357,24 +348,35 @@ export async function main(argv: string[], env: Record<string, string | undefine
357
348
  }
358
349
  if (mode === "ask") {
359
350
  // Like `local`: no GitHub token, no `gh` function anywhere on this path.
360
- return runAsk(parseAskArgs(args.slice(1)), repoDir, env, {
351
+ return await runAsk(parseAskArgs(args.slice(1)), repoDir, env, {
361
352
  stdout: (text) => writeAll(1, text),
362
353
  stderr: (line) => console.error(line),
363
354
  engineVersion: readVersion(),
364
355
  });
365
356
  }
357
+ if (mode === "pr-template") {
358
+ // No model, no provider; `check --pr` and `risk` shell out to gh and git in the repository directory.
359
+ return runPrTemplate(args.slice(1), repoDir, { stdout: (text) => writeAll(1, text), stderr: (line) => console.error(line) });
360
+ }
366
361
  if (mode === "doctor" || mode === "profile" || mode === "project") {
367
362
  return runAccountCommand(mode, args.slice(1), repoDir, env);
368
363
  }
364
+ if (mode === "upgrade") {
365
+ const parsed = parseUpgradeArgs(args.slice(1), repoDir);
366
+ if ("help" in parsed) return (writeAll(1, commandHelp(["upgrade"])!), 0);
367
+ return runUpgrade(parsed, { stdout: (text) => writeAll(1, text), stderr: (line) => console.error(line) }, { version: readVersion() });
368
+ }
369
369
  if (mode === "setup" || mode === "init") return await runWizard(mode, args.slice(1), repoDir, env);
370
370
  if (mode === "status") {
371
371
  const parsed = parseStatusArgs(args.slice(1));
372
- if ("help" in parsed) return (writeAll(1, `${statusUsage}\n`), 0);
372
+ if ("help" in parsed) return (writeAll(1, commandHelp(["status"])!), 0);
373
+ if (parsed.refresh) await refreshLedger(env);
373
374
  return runStatus(parsed, repoDir, env, { stdout: (text) => writeAll(1, text), stderr: (line) => console.error(line), version: readVersion() });
374
375
  }
375
376
  if (mode === "dashboard") {
376
377
  const parsed = parseDashboardArgs(args.slice(1));
377
- if ("help" in parsed) return (writeAll(1, `${dashboardUsage}\n`), 0);
378
+ if ("help" in parsed) return (writeAll(1, commandHelp(["dashboard"])!), 0);
379
+ if (parsed.refresh) await refreshLedger(env);
378
380
  return runDashboard(parsed, env, { stdout: (text) => writeAll(1, text), stderr: (line) => console.error(line) });
379
381
  }
380
382
  if (mode === "history") {
@@ -383,7 +385,7 @@ export async function main(argv: string[], env: Record<string, string | undefine
383
385
  if (mode === "reset-confidence") return runResetConfidence(args.slice(1), env);
384
386
  const [, prArg, ...rest] = args;
385
387
  if (mode !== "review" && mode !== "comment" && mode !== "threads") {
386
- throw new UsageError(mode ? `Unknown command "${mode}".` : "No command given.");
388
+ throw new UsageError(`Unknown command "${mode}".`);
387
389
  }
388
390
  const pr = Number(prArg);
389
391
  if (!/^\d+$/.test(prArg ?? "") || pr <= 0) {
@@ -398,13 +400,39 @@ export async function main(argv: string[], env: Record<string, string | undefine
398
400
  // decision 4); the rest of the thread-only run is unchanged. Its trigger is the question's, not
399
401
  // an automatic run's, so it does not spend from the automatic ceiling.
400
402
  const effective = routeMode(mode, commentLine, env.REQUEST ?? "", loaded.mention);
401
- const config = effective === "comment" ? { ...loaded, trigger: "comment" } : effective === "threads" ? { ...loaded, trigger: "thread" } : loaded;
402
- const provider = getProvider(config.provider, config);
403
+ const routed = effective === "comment" ? { ...loaded, trigger: "comment" } : effective === "threads" ? { ...loaded, trigger: "thread" } : loaded;
404
+ const mainProvider = (c: typeof routed) => getProvider(c.provider, c);
403
405
  // The verifier is its own adapter on its own model, always at effort high (ADR 0027).
404
- const verifier = config.verify && mode !== "threads" ? getProvider(config.provider, { ...config, model: config.verifierModel, effort: "high" }) : undefined;
406
+ const verifier = routed.verify && mode !== "threads" ? getProvider(routed.provider, { ...routed, model: routed.verifierModel, effort: "high" }) : undefined;
407
+ let provider = mainProvider(routed);
405
408
  required(env, "GH_TOKEN");
406
409
  const repo = required(env, "GITHUB_REPOSITORY");
407
410
  const request = effective === "comment" ? required(env, "REQUEST") : "";
411
+ // Before any call is paid for: a missing binary or settings file would fail every batch.
412
+ try {
413
+ provider.preflight();
414
+ verifier?.preflight();
415
+ } catch (error) {
416
+ console.error(`wachiman: ${error instanceof Error ? error.message : error}`);
417
+ return 1;
418
+ }
419
+ // Where no workflow input or WACHIMAN_* set them, the model and the effort come from the base
420
+ // commit's `.wachiman.yml` (never the head's, ADR 0049), so the estimate, the size gate and every
421
+ // call agree. The adapters are rebuilt only when the file changed one of them.
422
+ let config = withBaseSettings(routed, defaultGh, repo, pr, (line) => console.log(line), (line) => console.error(line));
423
+ if (config.model !== routed.model || config.effort !== routed.effort) {
424
+ // Settings never change the verifier (own model, effort high), so only the main provider is rebuilt.
425
+ const before = provider;
426
+ provider = mainProvider(config);
427
+ try {
428
+ provider.preflight();
429
+ } catch (error) {
430
+ // A value the base file set that this provider cannot use must not block the pull request that fixes it.
431
+ console.error(`wachiman: ignored model/effort from .wachiman.yml at the base commit: ${error instanceof Error ? error.message : error}; using the workflow's values.`);
432
+ provider = before;
433
+ config = routed;
434
+ }
435
+ }
408
436
  const costs: CallCost[] = [];
409
437
  const ledgerNotes: string[] = [];
410
438
  const deps: Deps = {
@@ -419,18 +447,10 @@ export async function main(argv: string[], env: Record<string, string | undefine
419
447
  log: (line) => console.log(line),
420
448
  warn: (line) => console.error(line),
421
449
  };
422
- // Before any call is paid for: a missing binary or settings file would fail every batch.
423
- try {
424
- provider.preflight();
425
- verifier?.preflight();
426
- } catch (error) {
427
- console.error(`wachiman: ${error instanceof Error ? error.message : error}`);
428
- return 1;
429
- }
430
450
  try {
431
- if (effective === "review") review(deps, repo, pr, rest);
432
- else if (effective === "threads") threadReplies(deps, repo, pr, env.WACHIMAN_COMMENT_AUTHOR || undefined);
433
- else comment(deps, repo, pr, request, env.WACHIMAN_COMMENT_AUTHOR || undefined, commentLine);
451
+ if (effective === "review") await review(deps, repo, pr, rest);
452
+ else if (effective === "threads") await threadReplies(deps, repo, pr, env.WACHIMAN_COMMENT_AUTHOR || undefined);
453
+ else await comment(deps, repo, pr, request, env.WACHIMAN_COMMENT_AUTHOR || undefined, commentLine);
434
454
  } finally {
435
455
  // Also after a failed run: the calls it made were paid for.
436
456
  writeStepSummary(costs, env, undefined, ledgerNotes);
@@ -438,8 +458,7 @@ export async function main(argv: string[], env: Record<string, string | undefine
438
458
  return 0;
439
459
  } catch (error) {
440
460
  if (error instanceof UsageError || error instanceof UnknownProviderError) {
441
- console.error(`wachiman: ${error.message}\n\n${USAGE}`);
442
- return 2;
461
+ return usageError(error.message, mode);
443
462
  }
444
463
  if (error instanceof SpendLimitReached) {
445
464
  // The notice is already posted. `notice` mode keeps the job green.