wachiman 1.15.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 (54) hide show
  1. package/README.md +1 -0
  2. package/package.json +1 -1
  3. package/src/accounts/commands.ts +3 -2
  4. package/src/accounts/confirm.ts +1 -1
  5. package/src/accounts/profile-list.ts +24 -0
  6. package/src/cli.ts +54 -20
  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 +280 -97
  12. package/src/help.ts +85 -3
  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 +204 -24
  18. package/src/init/settings.ts +127 -0
  19. package/src/init/write.ts +16 -102
  20. package/src/local-ask.ts +5 -4
  21. package/src/local.ts +55 -10
  22. package/src/loop/command.ts +5 -5
  23. package/src/pr-template/adopt.ts +434 -0
  24. package/src/pr-template/catalog.ts +429 -0
  25. package/src/pr-template/check-run.ts +328 -0
  26. package/src/pr-template/check.ts +338 -0
  27. package/src/pr-template/describe.ts +368 -0
  28. package/src/pr-template/format.ts +399 -0
  29. package/src/pr-template/gh.ts +159 -0
  30. package/src/pr-template/install.ts +288 -0
  31. package/src/pr-template/legacy-guides.ts +50 -0
  32. package/src/pr-template/pr-risk.ts +426 -0
  33. package/src/pr-template/render.ts +302 -0
  34. package/src/pr-template/resolve.ts +65 -0
  35. package/src/pr-template/run.ts +88 -0
  36. package/src/pr-template/strip.ts +171 -0
  37. package/src/pr-template/write.ts +139 -0
  38. package/src/providers/claude-code.ts +7 -8
  39. package/src/providers/codex.ts +4 -4
  40. package/src/providers/spawn.ts +95 -0
  41. package/src/providers/types.ts +5 -2
  42. package/src/repo-settings.ts +159 -0
  43. package/src/setup/prompt.ts +49 -33
  44. package/src/setup/run.ts +31 -6
  45. package/src/sinks/common.ts +10 -3
  46. package/src/sinks/markdown.ts +3 -2
  47. package/src/sinks/terminal.ts +3 -2
  48. package/src/upgrade/command.ts +286 -0
  49. package/src/upgrade/pin.ts +112 -0
  50. package/src/wizard/mascot.ts +56 -51
  51. package/src/wizard/prompt-fancy.ts +10 -2
  52. package/src/wizard/prompt.ts +17 -4
  53. package/src/wizard/ui.ts +2 -0
  54. 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) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wachiman",
3
- "version": "1.15.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",
@@ -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);
@@ -175,7 +175,7 @@ function* confirmSteps(p: ResolvedProfile, env: Env, io: ConfirmIo): Generator<P
175
175
  const { profile } = p;
176
176
  const label = profile.kind === "default" ? "default" : profile.name;
177
177
  const login =
178
- 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}`;
179
179
  const configDir = profile.kind === "default" ? undefined : profile.configDir;
180
180
 
181
181
  if (configDir !== undefined && !io.isDirectory(configDir)) {
@@ -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
@@ -25,7 +25,10 @@
25
25
  * wachiman doctor explain what a local run would use and what would fail
26
26
  * wachiman profile … list, create, add, login, remove and default account profiles
27
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/)
28
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
29
32
  * wachiman --setup-profile [name] sign in an isolated Claude Code profile under the Wachiman home
30
33
  *
31
34
  * Exit codes: 0 posted or nothing to do; 1 engine error (nothing posted); 2 usage error; 3 the spend
@@ -43,15 +46,18 @@ import { parseStatusArgs, runStatus } from "./status/command";
43
46
  import { parseDashboardArgs, runDashboard } from "./store/command";
44
47
  import { parseLedgerArgs, runLedger } from "./ledger-read/command";
45
48
  import { pullLedger } from "./ledger-read/pull";
46
- import { LedgerStopped, SpendLimitReached, comment, defaultGh, isThreadQuestion, review, threadReplies, type Deps, type GhFn, type ReviewLineComment } from "./engine";
49
+ import { LedgerStopped, SpendLimitReached, comment, defaultGh, isThreadQuestion, review, threadReplies, withBaseSettings, type Deps, type GhFn, type ReviewLineComment } from "./engine";
47
50
  import { parseLocalArgs, runLocal } from "./local";
48
51
  import { parseLoopArgs, runLoop } from "./loop/command";
49
52
  import { parseAskArgs, runAsk } from "./local-ask";
50
53
  import { parseProfileArgs, parseProjectArgs, runProfile, runProject } from "./accounts/commands";
51
54
  import { wachimanHome } from "./accounts/config";
52
55
  import { parseSkillsArgs, runSkills } from "./skills/install";
56
+ import { runPrTemplate } from "./pr-template/run";
57
+ import { parseUpgradeArgs, runUpgrade } from "./upgrade/command";
53
58
  import { parseDoctorArgs, runDoctor } from "./doctor/run";
54
59
  import { parseInitFlags } from "./init/args";
60
+ import { ghLogin } from "./init/github-login";
55
61
  import { DEFAULT_WORKFLOW_REF } from "./init/options";
56
62
  import { projectCommands } from "./wizard/command";
57
63
  import { DEFAULT_ISOLATED_NAME, setupProfile } from "./profiles";
@@ -198,8 +204,9 @@ async function runWizard(mode: "setup" | "init", args: string[], repoDir: string
198
204
  return runInitCommand(flags, env, io, {
199
205
  version,
200
206
  defaultWorkflowRef: DEFAULT_WORKFLOW_REF,
201
- // Choosing local/both already requests setup; keep its final write confirmation.
202
- 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 }),
203
210
  });
204
211
  }
205
212
 
@@ -325,7 +332,7 @@ export async function main(argv: string[], env: Record<string, string | undefine
325
332
  const { repoDir, rest: args } = extractRepoDir(argv);
326
333
  if (mode === "local") {
327
334
  // No GitHub: no token, no repository, no `gh` function anywhere on this path.
328
- return runLocal(parseLocalArgs(args.slice(1)), repoDir, env, {
335
+ return await runLocal(parseLocalArgs(args.slice(1)), repoDir, env, {
329
336
  stdout: (text) => writeAll(1, text),
330
337
  stderr: (line) => console.error(line),
331
338
  engineVersion: readVersion(),
@@ -333,7 +340,7 @@ export async function main(argv: string[], env: Record<string, string | undefine
333
340
  }
334
341
  if (mode === "loop") {
335
342
  // Like `local`: no GitHub token, no `gh` function anywhere on this path.
336
- return runLoop(parseLoopArgs(args.slice(1)), repoDir, env, {
343
+ return await runLoop(parseLoopArgs(args.slice(1)), repoDir, env, {
337
344
  stdout: (text) => writeAll(1, text),
338
345
  stderr: (line) => console.error(line),
339
346
  engineVersion: readVersion(),
@@ -341,15 +348,24 @@ export async function main(argv: string[], env: Record<string, string | undefine
341
348
  }
342
349
  if (mode === "ask") {
343
350
  // Like `local`: no GitHub token, no `gh` function anywhere on this path.
344
- return runAsk(parseAskArgs(args.slice(1)), repoDir, env, {
351
+ return await runAsk(parseAskArgs(args.slice(1)), repoDir, env, {
345
352
  stdout: (text) => writeAll(1, text),
346
353
  stderr: (line) => console.error(line),
347
354
  engineVersion: readVersion(),
348
355
  });
349
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
+ }
350
361
  if (mode === "doctor" || mode === "profile" || mode === "project") {
351
362
  return runAccountCommand(mode, args.slice(1), repoDir, env);
352
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
+ }
353
369
  if (mode === "setup" || mode === "init") return await runWizard(mode, args.slice(1), repoDir, env);
354
370
  if (mode === "status") {
355
371
  const parsed = parseStatusArgs(args.slice(1));
@@ -384,13 +400,39 @@ export async function main(argv: string[], env: Record<string, string | undefine
384
400
  // decision 4); the rest of the thread-only run is unchanged. Its trigger is the question's, not
385
401
  // an automatic run's, so it does not spend from the automatic ceiling.
386
402
  const effective = routeMode(mode, commentLine, env.REQUEST ?? "", loaded.mention);
387
- const config = effective === "comment" ? { ...loaded, trigger: "comment" } : effective === "threads" ? { ...loaded, trigger: "thread" } : loaded;
388
- 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);
389
405
  // The verifier is its own adapter on its own model, always at effort high (ADR 0027).
390
- 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);
391
408
  required(env, "GH_TOKEN");
392
409
  const repo = required(env, "GITHUB_REPOSITORY");
393
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
+ }
394
436
  const costs: CallCost[] = [];
395
437
  const ledgerNotes: string[] = [];
396
438
  const deps: Deps = {
@@ -405,18 +447,10 @@ export async function main(argv: string[], env: Record<string, string | undefine
405
447
  log: (line) => console.log(line),
406
448
  warn: (line) => console.error(line),
407
449
  };
408
- // Before any call is paid for: a missing binary or settings file would fail every batch.
409
- try {
410
- provider.preflight();
411
- verifier?.preflight();
412
- } catch (error) {
413
- console.error(`wachiman: ${error instanceof Error ? error.message : error}`);
414
- return 1;
415
- }
416
450
  try {
417
- if (effective === "review") review(deps, repo, pr, rest);
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);
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);
420
454
  } finally {
421
455
  // Also after a failed run: the calls it made were paid for.
422
456
  writeStepSummary(costs, env, undefined, ledgerNotes);
package/src/config.ts CHANGED
@@ -14,6 +14,9 @@ export type Trigger = string;
14
14
  /** Whether a run started by `trigger` spends from the pull request's automatic ceiling. */
15
15
  export const isAutomatic = (trigger: Trigger | undefined) => trigger !== undefined && trigger !== "comment";
16
16
 
17
+ /** Where a setting's value came from: the environment (a workflow input or `WACHIMAN_*`), the repository's `.wachiman.yml`, or the built-in default. */
18
+ export type SettingSource = "env" | "file" | "default";
19
+
17
20
  export type LimitMode = "fail" | "notice";
18
21
  export type LedgerUnavailableMode = "run" | "stop";
19
22
 
@@ -64,8 +67,13 @@ export interface EngineConfig {
64
67
  * reviewed, without reading the previous-review marker. Only together with `dryRun`.
65
68
  */
66
69
  fullReview: boolean;
67
- /** The provider's default (`DEFAULT_MODELS`) when unset. */
70
+ /**
71
+ * `WACHIMAN_MODEL`, else `model` of the repository's `.wachiman.yml` (`applyRepoSettings`), else the
72
+ * provider's default (`DEFAULT_MODELS`).
73
+ */
68
74
  model: string;
75
+ /** Where `model` came from. `loadConfig` sets `env` or `default`; `applyRepoSettings` may change `default` to `file`. */
76
+ modelSource?: SettingSource;
69
77
  provider: string;
70
78
  /** `WACHIMAN_PRICE_PER_MTOK`: "input,cached_input,output" USD per million tokens, for a Codex model without a built-in price. */
71
79
  pricePerMTok?: string;
@@ -74,6 +82,8 @@ export interface EngineConfig {
74
82
  * alter reviews. Passed as `--effort` (Claude Code) or `model_reasoning_effort` (Codex).
75
83
  */
76
84
  effort: Effort;
85
+ /** Where `effort` came from, as for `modelSource`. */
86
+ effortSource?: SettingSource;
77
87
  /**
78
88
  * `WACHIMAN_MAX_TURNS`: the most agent turns one provider call may take. Passed as
79
89
  * `--max-turns` (Claude Code); Codex has no equivalent and ignores it.
@@ -149,7 +159,7 @@ export function readSetting(env: Env, name: string, warn: (line: string) => void
149
159
  * else the default. An unknown value is a configuration error: a silent fallback would run the
150
160
  * review at an effort nobody chose.
151
161
  */
152
- function readEffort(env: Env, warn: (line: string) => void): Effort {
162
+ function readEffort(env: Env, warn: (line: string) => void): { value: Effort; source: SettingSource } {
153
163
  const current = readSetting(env, "EFFORT", warn);
154
164
  const old = readSetting(env, "REASONING_EFFORT", () => {});
155
165
  let name = "WACHIMAN_EFFORT";
@@ -161,11 +171,11 @@ function readEffort(env: Env, warn: (line: string) => void): Effort {
161
171
  name = "WACHIMAN_REASONING_EFFORT";
162
172
  }
163
173
  }
164
- if (raw === undefined) return DEFAULT_EFFORT;
174
+ if (raw === undefined) return { value: DEFAULT_EFFORT, source: "default" };
165
175
  if (!(EFFORTS as readonly string[]).includes(raw)) {
166
176
  throw new UsageError(`${name} must be one of ${EFFORTS.join(", ")}, got "${raw}".`);
167
177
  }
168
- return raw as Effort;
178
+ return { value: raw as Effort, source: "env" };
169
179
  }
170
180
 
171
181
  export function loadConfig(env: Env, warn: (line: string) => void = console.error): EngineConfig {
@@ -185,6 +195,7 @@ export function loadConfig(env: Env, warn: (line: string) => void = console.erro
185
195
  throw new UsageError(`WACHIMAN_ON_PROVIDER_UNAVAILABLE must be warn or fail, got "${onProviderUnavailable}".`);
186
196
  }
187
197
  const provider = get("PROVIDER") ?? "claude-code";
198
+ const modelFromEnv = get("MODEL");
188
199
  const dryRun = get("DRY_RUN") === "1";
189
200
  const fullReview = get("FULL_REVIEW") === "1";
190
201
  if (fullReview && !dryRun) {
@@ -250,10 +261,12 @@ export function loadConfig(env: Env, warn: (line: string) => void = console.erro
250
261
  batchChars: number("BATCH_CHARS", 140000, true),
251
262
  dryRun,
252
263
  fullReview,
253
- model: get("MODEL") ?? DEFAULT_MODELS[provider as keyof typeof DEFAULT_MODELS] ?? DEFAULT_MODELS["claude-code"],
264
+ model: modelFromEnv ?? DEFAULT_MODELS[provider as keyof typeof DEFAULT_MODELS] ?? DEFAULT_MODELS["claude-code"],
265
+ modelSource: modelFromEnv === undefined ? "default" : "env",
254
266
  provider,
255
267
  pricePerMTok: get("PRICE_PER_MTOK"),
256
- effort,
268
+ effort: effort.value,
269
+ effortSource: effort.source,
257
270
  maxTurns: number("MAX_TURNS", DEFAULT_MAX_TURNS, true),
258
271
  callTimeoutS: number("CALL_TIMEOUT_S", DEFAULT_CALL_TIMEOUT_S, true),
259
272
  onProviderUnavailable,
@@ -17,6 +17,7 @@ import { UsageError } from "../config";
17
17
  import {
18
18
  instructionFileOf,
19
19
  instructionsFrom,
20
+ MAX_INSTRUCTION_BYTES,
20
21
  REVIEW_INPUT_FORMAT,
21
22
  resolveScope,
22
23
  type BaseInstructions,
@@ -24,6 +25,7 @@ import {
24
25
  type ReviewInput,
25
26
  } from "../engine";
26
27
  import { GIT_BASE_ARGS, gitEnv, spawnGit, type GitRunner } from "../evidence";
28
+ import { parseRepoSettings, SETTINGS_PATH, type RepoSettings } from "../repo-settings";
27
29
 
28
30
  const TIMEOUT_MS = 60_000;
29
31
  /** The whole branch diff is one output; a large branch can be far over the evidence step's 8 MB. */
@@ -353,6 +355,51 @@ export function localInstructions(
353
355
  );
354
356
  }
355
357
 
358
+ /** What decides the commit whose `.wachiman.yml` a local run reads: the same scope flags the review itself takes. */
359
+ export interface SettingsScope {
360
+ /** `--working-tree`: the instruction files are read at `HEAD`, and so is the settings file. */
361
+ workingTree?: "staged" | "all";
362
+ base?: string;
363
+ commit?: string;
364
+ from?: string;
365
+ maxDepth?: number;
366
+ /** `--input`: the base commit the input file names. */
367
+ inputBase?: string;
368
+ }
369
+
370
+ /**
371
+ * The commit whose `.wachiman.yml` a local run reads, the one the instruction files are read at:
372
+ * the merge-base (the start of the diff), `HEAD` for a working-tree review, or the input file's
373
+ * base. Never the head, so a branch cannot raise the model or the effort it is reviewed under.
374
+ * Undefined when the scope does not resolve; the review's own ref checks report that, with their
375
+ * message, a moment later.
376
+ */
377
+ export function localSettingsCommit(repoDir: string, scope: SettingsScope, git: GitRunner = spawnGit): string | undefined {
378
+ if (scope.inputBase !== undefined) return scope.inputBase;
379
+ try {
380
+ if (scope.workingTree) return run(git, repoDir, ["rev-parse", "--verify", "HEAD^{commit}"]).trim();
381
+ return resolveRefs(repoDir, scope.base, git, scope.maxDepth, { commit: scope.commit, from: scope.from }).mergeBase;
382
+ } catch {
383
+ return undefined;
384
+ }
385
+ }
386
+
387
+ /**
388
+ * `.wachiman.yml` as it is at `sha`, parsed, or undefined when there is none there (or `sha` is
389
+ * not in this clone: an `--input` file can name one that is not). An invalid file is a usage error.
390
+ */
391
+ export function localRepoSettings(repoDir: string, sha: string, git: GitRunner = spawnGit): RepoSettings | undefined {
392
+ let bytes: Buffer | null;
393
+ try {
394
+ bytes = blobAt(repoDir, sha, SETTINGS_PATH, git);
395
+ } catch {
396
+ return undefined;
397
+ }
398
+ if (!bytes) return undefined;
399
+ if (bytes.length > MAX_INSTRUCTION_BYTES) throw new UsageError(`${SETTINGS_PATH} at ${short(sha)} is over ${MAX_INSTRUCTION_BYTES / 1024} KB, too large for a settings file.`);
400
+ return parseRepoSettings(bytes.toString("utf8"));
401
+ }
402
+
356
403
  const names = (out: string) => out.split("\0").filter(Boolean);
357
404
 
358
405
  /**
@@ -16,10 +16,13 @@ import type { HistoryRepository } from "../history/types";
16
16
  import { detectInstall, type InstallKind } from "../install-kind";
17
17
  import { inspectIsolatedProfile } from "../profiles";
18
18
  import { buildChildEnv } from "../providers/claude-code";
19
+ import { effectiveSettings, OLD_SETTINGS_PATH, parseRepoSettings, SETTINGS_PATH } from "../repo-settings";
20
+ import { UsageError } from "../config";
21
+ import { classifyRef, compareVersions, parseTag, scanWorkflows } from "../upgrade/pin";
19
22
 
20
23
  export type CheckLevel = "required" | "optional";
21
24
  export type CheckStatus = "ok" | "fail" | "warn" | "skip";
22
- export type CheckId = "wachiman" | "bun" | "git" | "tar" | "config" | "profile" | "auth" | "environment" | "project" | "history" | "skills" | "isolation";
25
+ export type CheckId = "wachiman" | "bun" | "git" | "tar" | "config" | "profile" | "auth" | "environment" | "project" | "settings" | "workflow-pin" | "history" | "skills" | "isolation";
23
26
 
24
27
  export interface DoctorRow {
25
28
  id: CheckId;
@@ -49,6 +52,8 @@ export interface DoctorFs {
49
52
  isDirectory: (path: string) => boolean;
50
53
  /** The names in a directory; empty when it cannot be listed. */
51
54
  list: (path: string) => string[];
55
+ /** Like `list`, but throws when the directory cannot be read (used by the workflow-pin row). */
56
+ listStrict?: (path: string) => string[];
52
57
  /** Permission bits, or undefined where the platform has none. */
53
58
  mode: (path: string) => number | undefined;
54
59
  /** Used only for a managed profile's `settings.json`. */
@@ -56,6 +61,7 @@ export interface DoctorFs {
56
61
  }
57
62
 
58
63
  export const realDoctorFs: DoctorFs = {
64
+ listStrict: (p) => readdirSync(p),
59
65
  exists: (p) => existsSync(p),
60
66
  isDirectory: (p) => {
61
67
  try {
@@ -102,6 +108,10 @@ export interface DoctorContext {
102
108
  config: ConfigRead;
103
109
  /** The repository of `--repo-dir`, or why there is none. */
104
110
  repository: { ok: true; value: HistoryRepository } | { ok: false; reason: string };
111
+ /** The top of the working tree of `--repo-dir` (where `.wachiman.yml` is looked for); undefined when it is not one. */
112
+ root?: string;
113
+ /** `.wachiman.yml` differs from the last commit (new, edited or deleted): runs do not see the working copy yet. */
114
+ settingsUncommitted?: boolean;
105
115
  /** The profile the full resolution picks (or the one `--profile` names); undefined when it resolves to nothing. */
106
116
  primary: ResolvedProfile | undefined;
107
117
  /** The profile this pass of `profile`, `auth` and `isolation` looks at. */
@@ -359,6 +369,101 @@ export const CHECKS: DoctorCheck[] = [
359
369
  };
360
370
  },
361
371
  },
372
+ {
373
+ // Read-only: reports the repository's `.wachiman.yml` (the working tree is fine here; a run reads
374
+ // the base commit) and where the model and the effort of a run would come from. Never writes or moves anything.
375
+ id: "settings",
376
+ level: "optional",
377
+ run: ({ root, env, fs, settingsUncommitted }) => {
378
+ if (root === undefined) return { id: "settings", level: "optional", status: "skip", evidence: "not in a git working tree: no repository settings to read" };
379
+ const file = join(root, SETTINGS_PATH);
380
+ const old = join(root, OLD_SETTINGS_PATH);
381
+ const hasFile = fs.exists(file);
382
+ const hasOld = fs.exists(old);
383
+ let settings: ReturnType<typeof parseRepoSettings> | undefined;
384
+ if (hasFile) {
385
+ try {
386
+ settings = parseRepoSettings(fs.read(file));
387
+ } catch (error) {
388
+ const why = error instanceof UsageError ? error.message : `${SETTINGS_PATH} cannot be read (${error instanceof Error ? error.message : error})`;
389
+ return {
390
+ id: "settings",
391
+ level: "optional",
392
+ status: "warn",
393
+ evidence: `the working copy of ${SETTINGS_PATH} is invalid: ${why} Runs read it at the base commit (Actions) or the merge-base (local), so it takes effect once committed and merged; a run with a broken file at that commit ignores it with a warning and uses the defaults.`,
394
+ fix: `fix ${SETTINGS_PATH} (effort is low, medium, high, xhigh or max; model is a model name), or remove it to use the defaults`,
395
+ detail: { file, valid: false },
396
+ };
397
+ }
398
+ }
399
+ const effective = effectiveSettings(env, settings);
400
+ const from = (s: { value: string; source: string; skipped?: string }) =>
401
+ `${s.value} (${s.source === "file" ? `from ${SETTINGS_PATH}` : s.source === "env" ? "from the environment" : s.skipped !== undefined ? `default; the model "${settings?.model}" in ${SETTINGS_PATH} is skipped: ${s.skipped}` : "default"})`;
402
+ const read = hasFile ? `${SETTINGS_PATH}: kind ${settings?.kind ?? "not set"}, model ${settings?.model ?? "not set"}, effort ${settings?.effort ?? "not set"}` : `no ${SETTINGS_PATH}`;
403
+ const detail = {
404
+ file: hasFile ? file : null,
405
+ valid: true,
406
+ kind: settings?.kind ?? null,
407
+ model: settings?.model ?? null,
408
+ effort: settings?.effort ?? null,
409
+ effectiveModel: effective.model.value,
410
+ modelFrom: effective.model.source,
411
+ modelSkipped: effective.model.skipped ?? null,
412
+ effectiveEffort: effective.effort.value,
413
+ effortFrom: effective.effort.source,
414
+ uncommitted: settingsUncommitted === true,
415
+ };
416
+ // A run reads the committed file, so with uncommitted changes the working copy says what will apply once committed, not now.
417
+ const runs = settingsUncommitted
418
+ ? `${SETTINGS_PATH} has changes that are not committed, and runs read the committed file: once committed (and merged, for Actions) a run would use model ${from(effective.model)}, effort ${from(effective.effort)}`
419
+ : `a run here would use model ${from(effective.model)}, effort ${from(effective.effort)}`;
420
+ const evidence = `${read}; ${runs}. GitHub Actions reads the file from the base commit of the pull request, not from the head`;
421
+ if (hasOld) {
422
+ return {
423
+ id: "settings",
424
+ level: "optional",
425
+ status: "warn",
426
+ evidence: `${OLD_SETTINGS_PATH} exists and is never read (the settings file is ${SETTINGS_PATH} at the root); ${evidence}`,
427
+ fix: hasFile ? `merge ${OLD_SETTINGS_PATH} into ${SETTINGS_PATH}, then remove it` : `mv ${OLD_SETTINGS_PATH} ${SETTINGS_PATH}`,
428
+ detail: { ...detail, oldLocation: old },
429
+ };
430
+ }
431
+ return { id: "settings", level: "optional", status: "ok", evidence, detail };
432
+ },
433
+ },
434
+ {
435
+ id: "workflow-pin",
436
+ level: "optional",
437
+ run: ({ root, fs, version }) => {
438
+ const row = (status: CheckStatus, evidence: string, extra: Partial<DoctorRow> = {}): DoctorRow => ({ id: "workflow-pin", level: "optional", status, evidence, ...extra });
439
+ const installed = parseTag(version);
440
+ if (root === undefined) return row("skip", "not in a git repository, so no workflow was read");
441
+ const scan = scanWorkflows(root, fs);
442
+ const unreadable = [...(scan.unreadableDir ? [`${scan.unreadableDir} (directory)`] : []), ...scan.unreadable];
443
+ const unreadableNote = unreadable.length > 0 ? `; could not read ${unreadable.join(", ")}, so its pins are unknown` : "";
444
+ const pins = scan.files.flatMap(({ file, refs }) => refs.map((ref) => ({ file, ref })));
445
+ if (pins.length === 0) {
446
+ return unreadable.length > 0
447
+ ? row("warn", `no readable workflow calls a Wachiman reusable workflow${unreadableNote}`, { detail: { unreadable: unreadable.length } })
448
+ : row("skip", "no workflow in .github/workflows calls a Wachiman reusable workflow");
449
+ }
450
+ if (installed === undefined) return row("skip", `the installed version "${version}" is not a release version, so pins cannot be compared`);
451
+ const older = pins.filter((p) => classifyRef(p.ref) === "tag" && compareVersions(parseTag(p.ref)!, installed) < 0);
452
+ const fixed = pins.filter((p) => classifyRef(p.ref) === "tag");
453
+ const other = pins.filter((p) => classifyRef(p.ref) !== "tag");
454
+ const list = (items: typeof pins) => items.map((p) => `${p.file} @${classifyRef(p.ref) === "sha" ? p.ref.slice(0, 12) : p.ref}`).join(", ");
455
+ const detail = { pins: pins.length, older: older.length, notReleaseTag: other.length, unreadable: unreadable.length };
456
+ if (older.length > 0) {
457
+ return row("warn", `${list(older)} older than the installed v${version}: reviews in Actions run that older release${unreadableNote}`, {
458
+ fix: "wachiman upgrade --repo-only",
459
+ detail,
460
+ });
461
+ }
462
+ const note = (other.length > 0 ? `; ${list(other)} is a commit or branch, which is not compared` : "") + unreadableNote;
463
+ if (fixed.length === 0) return row(unreadable.length > 0 ? "warn" : "skip", `${list(other)} is a commit or branch, not a release tag, so it is not compared${unreadableNote}`, { detail });
464
+ return row(unreadable.length > 0 ? "warn" : "ok", `${list(fixed)} is not older than the installed v${version}${note}`, { detail });
465
+ },
466
+ },
362
467
  {
363
468
  id: "history",
364
469
  level: "optional",
package/src/doctor/run.ts CHANGED
@@ -9,7 +9,7 @@ import { confirmProfile, type ConfirmIo, type SpawnFn } from "../accounts/confir
9
9
  import { buildProfileList, managedDir } from "../accounts/profile-list";
10
10
  import { parseProfileRef, resolveProfile } from "../accounts/resolve";
11
11
  import { UsageError } from "../config";
12
- import { type GitRunner } from "../evidence";
12
+ import { spawnGit, type GitRunner } from "../evidence";
13
13
  import { parseFlags } from "../flags";
14
14
  import { repositoryKey } from "../history/store";
15
15
  import { CHECKS, detectInstall, PROFILE_SCOPED, realDoctorFs, tierOf, type DoctorContext, type DoctorFs, type DoctorReport, type InstallKind, type Target } from "./checks";
@@ -76,6 +76,12 @@ export function buildDoctorReport(opts: DoctorOptions, env: Record<string, strin
76
76
  } catch {
77
77
  repository = { ok: false, reason: `${opts.repoDir} is not a git repository` };
78
78
  }
79
+ // Where `.wachiman.yml` is looked for: the top of the working tree (a linked worktree has its own copy).
80
+ const top = (deps.git ?? spawnGit)(["rev-parse", "--show-toplevel"], { cwd: opts.repoDir, timeoutMs: 15_000 });
81
+ const root = top.status === 0 && top.stdout.trim() !== "" ? top.stdout.trim() : undefined;
82
+ // Runs read the committed file, so an edit not committed yet does not apply to them.
83
+ const pending = root === undefined ? undefined : (deps.git ?? spawnGit)(["status", "--porcelain", "--", ".wachiman.yml"], { cwd: root, timeoutMs: 15_000 });
84
+ const settingsUncommitted = pending !== undefined && pending.status === 0 && pending.stdout.trim() !== "";
79
85
  const binding =
80
86
  repository.ok && accounts && Object.hasOwn(accounts.projects, repository.value.key) ? accounts.projects[repository.value.key] : undefined;
81
87
 
@@ -111,6 +117,8 @@ export function buildDoctorReport(opts: DoctorOptions, env: Record<string, strin
111
117
  arch,
112
118
  config,
113
119
  repository,
120
+ root,
121
+ settingsUncommitted,
114
122
  primary,
115
123
  };
116
124