wachiman 1.14.0 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +2 -1
  2. package/package.json +4 -2
  3. package/src/accounts/commands.ts +3 -2
  4. package/src/accounts/confirm.ts +63 -4
  5. package/src/accounts/profile-list.ts +24 -0
  6. package/src/cli.ts +161 -142
  7. package/src/config.ts +19 -6
  8. package/src/connectors/local-git.ts +47 -0
  9. package/src/doctor/checks.ts +106 -1
  10. package/src/doctor/run.ts +9 -1
  11. package/src/engine.ts +294 -97
  12. package/src/help.ts +637 -0
  13. package/src/init/args.ts +5 -2
  14. package/src/init/github-login.ts +13 -0
  15. package/src/init/options.ts +31 -3
  16. package/src/init/prompt.ts +46 -15
  17. package/src/init/run.ts +238 -32
  18. package/src/init/settings.ts +127 -0
  19. package/src/init/write.ts +16 -102
  20. package/src/ledger-read/command.ts +106 -0
  21. package/src/ledger-read/credentials.ts +103 -0
  22. package/src/ledger-read/files.ts +141 -0
  23. package/src/ledger-read/pull.ts +69 -0
  24. package/src/ledger-read/rows.ts +60 -0
  25. package/src/ledger-read/types.ts +127 -0
  26. package/src/ledger.ts +34 -18
  27. package/src/local-ask.ts +5 -4
  28. package/src/local.ts +55 -10
  29. package/src/loop/command.ts +5 -5
  30. package/src/pr-template/adopt.ts +434 -0
  31. package/src/pr-template/catalog.ts +429 -0
  32. package/src/pr-template/check-run.ts +328 -0
  33. package/src/pr-template/check.ts +338 -0
  34. package/src/pr-template/describe.ts +368 -0
  35. package/src/pr-template/format.ts +399 -0
  36. package/src/pr-template/gh.ts +159 -0
  37. package/src/pr-template/install.ts +288 -0
  38. package/src/pr-template/legacy-guides.ts +50 -0
  39. package/src/pr-template/pr-risk.ts +426 -0
  40. package/src/pr-template/render.ts +302 -0
  41. package/src/pr-template/resolve.ts +65 -0
  42. package/src/pr-template/run.ts +88 -0
  43. package/src/pr-template/strip.ts +171 -0
  44. package/src/pr-template/write.ts +139 -0
  45. package/src/providers/claude-code.ts +7 -8
  46. package/src/providers/codex.ts +4 -4
  47. package/src/providers/spawn.ts +95 -0
  48. package/src/providers/types.ts +5 -2
  49. package/src/repo-settings.ts +159 -0
  50. package/src/setup/prompt.ts +49 -33
  51. package/src/setup/run.ts +58 -16
  52. package/src/sinks/common.ts +10 -3
  53. package/src/sinks/markdown.ts +3 -2
  54. package/src/sinks/terminal.ts +3 -2
  55. package/src/spend/report.ts +349 -0
  56. package/src/status/command.ts +150 -36
  57. package/src/store/command.ts +20 -3
  58. package/src/store/html.ts +205 -8
  59. package/src/store/index.ts +64 -5
  60. package/src/store/rows.ts +103 -0
  61. package/src/upgrade/command.ts +286 -0
  62. package/src/upgrade/pin.ts +112 -0
  63. package/src/wizard/interactive.ts +11 -0
  64. package/src/wizard/launcher.ts +340 -0
  65. package/src/wizard/load.ts +30 -0
  66. package/src/wizard/mascot.ts +228 -0
  67. package/src/wizard/prompt-fancy.ts +135 -0
  68. package/src/wizard/prompt.ts +108 -61
  69. package/src/wizard/style.ts +93 -13
  70. package/src/wizard/tone.ts +11 -0
  71. package/src/wizard/ui.ts +80 -0
  72. package/templates/pr/sections.json +163 -0
@@ -0,0 +1,69 @@
1
+ /**
2
+ * `GET /v1/entries`: the only network request the laptop makes to the ledger, made only by
3
+ * `wachiman ledger pull` and by `--refresh`. The fetch function is injected so tests use no network.
4
+ * Errors never include the token.
5
+ */
6
+ import { UsageError } from "../config";
7
+ import { resolveCredentials } from "./credentials";
8
+ import { storePull } from "./files";
9
+ import { parseEntriesResponse } from "./types";
10
+
11
+ export const DEFAULT_PULL_DAYS = 35;
12
+ export const MAX_PULL_DAYS = 92;
13
+ const TIMEOUT_MS = 30_000;
14
+ const REDIRECT_MESSAGE = (url: string) => `the ledger URL ${url} redirected; the token is not sent to another address. Connect again with the final URL.`;
15
+
16
+ export interface PullDeps {
17
+ fetch: typeof fetch;
18
+ now: () => Date;
19
+ }
20
+ export const realPullDeps: PullDeps = { fetch: (input, init) => fetch(input, init), now: () => new Date() };
21
+
22
+ export interface PullResult {
23
+ account: string;
24
+ from: string;
25
+ to: string;
26
+ entries: number;
27
+ daysWritten: number;
28
+ /** Days inside the pulled range whose local file was deleted because the ledger returned no entries for them. */
29
+ daysRemoved: number;
30
+ url: string;
31
+ }
32
+
33
+ const dayOf = (d: Date) => d.toISOString().slice(0, 10);
34
+
35
+ export async function pullLedger(home: string, env: Record<string, string | undefined>, sinceDays: number | undefined, deps: PullDeps = realPullDeps): Promise<PullResult> {
36
+ const credentials = resolveCredentials(home, env);
37
+ if (!credentials) throw new UsageError("No ledger is connected: run `wachiman ledger connect <url>` first.");
38
+ const days = sinceDays ?? DEFAULT_PULL_DAYS;
39
+ if (!Number.isInteger(days) || days < 1 || days > MAX_PULL_DAYS) throw new UsageError(`--since takes 1 to ${MAX_PULL_DAYS} days, got ${days}.`);
40
+ const now = deps.now();
41
+ const to = dayOf(now);
42
+ const from = dayOf(new Date(now.getTime() - (days - 1) * 86_400_000));
43
+ const url = `${credentials.url}/v1/entries?from=${from}&to=${to}`;
44
+ let res: Response;
45
+ try {
46
+ res = await deps.fetch(url, { headers: { authorization: `Bearer ${credentials.token}`, accept: "application/json" }, signal: AbortSignal.timeout(TIMEOUT_MS), redirect: "error" });
47
+ } catch (error) {
48
+ if (error instanceof Error && /redirect/i.test(error.message)) throw new Error(REDIRECT_MESSAGE(credentials.url));
49
+ throw new Error(`could not reach the ledger at ${credentials.url}: ${error instanceof Error ? error.name : "network error"}`);
50
+ }
51
+ if (res.status >= 300 && res.status < 400) throw new Error(REDIRECT_MESSAGE(credentials.url));
52
+ if (res.status === 401) throw new Error("the ledger refused the read token (401); run `wachiman ledger connect <url>` with a valid one.");
53
+ if (!res.ok) throw new Error(`the ledger answered HTTP ${res.status}.`);
54
+ let body: unknown;
55
+ try {
56
+ body = await res.json();
57
+ } catch {
58
+ throw new Error("the ledger answer is not JSON.");
59
+ }
60
+ const response = (() => {
61
+ try {
62
+ return parseEntriesResponse(body);
63
+ } catch (error) {
64
+ throw new Error(`unexpected ledger answer: ${error instanceof Error ? error.message : "invalid"}.`);
65
+ }
66
+ })();
67
+ const stored = storePull(home, response, from, to, now.toISOString());
68
+ return { account: response.account, from, to, entries: stored.entries, daysWritten: stored.daysWritten, daysRemoved: stored.daysRemoved, url: credentials.url };
69
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Ledger entries as spend rows (ADR 0039), read straight from the pulled day files. `status` uses this,
3
+ * so it never depends on the index; the index holds the same entries for the dashboard.
4
+ */
5
+ import { mergeRanges, weekStart, type Limits, type Range, type SpendRow } from "../spend/report";
6
+ import { listLedgerAccounts, readDayFile } from "./files";
7
+ import type { LedgerEntry } from "./types";
8
+
9
+ /** A finished run keeps its calls and its dollars; a hold (`reserved`, `unsettled`) is not spend and has no calls. */
10
+ export function entryToRow(e: LedgerEntry): SpendRow {
11
+ const finished = e.state === "settled" || e.state === "unreserved";
12
+ return {
13
+ source: "actions",
14
+ state: e.state,
15
+ day: e.day,
16
+ week: e.week || weekStart(e.day),
17
+ repositoryKey: e.repository,
18
+ repository: e.repository,
19
+ pr: e.pr,
20
+ runId: e.run_id === null ? e.id : String(e.run_id),
21
+ profile: "",
22
+ costUsd: finished ? (e.settledUsd ?? 0) : 0,
23
+ reservedUsd: finished ? 0 : e.reservedUsd,
24
+ calls: finished ? e.calls.map((c) => ({ model: c.model, auth: c.auth, costUsd: c.cost_usd ?? 0, costKnown: c.costKnown })) : [],
25
+ };
26
+ }
27
+
28
+ export interface LedgerFromFiles {
29
+ rows: SpendRow[];
30
+ /** The days the pulls covered, merged over accounts. */
31
+ ranges: Range[];
32
+ limits: Limits | null;
33
+ pulledAt: string | null;
34
+ }
35
+
36
+ export function readLedgerFromFiles(home: string, warn: (line: string) => void): LedgerFromFiles {
37
+ const accounts = listLedgerAccounts(home);
38
+ const rows: SpendRow[] = [];
39
+ for (const a of accounts) {
40
+ const seen = new Set<string>();
41
+ for (const path of a.dayFiles) {
42
+ const entries = readDayFile(path);
43
+ if (!entries) {
44
+ warn(`status: ${path} is not a ledger day file; skipped`);
45
+ continue;
46
+ }
47
+ for (const e of entries) {
48
+ if (seen.has(e.id)) continue;
49
+ seen.add(e.id);
50
+ rows.push(entryToRow(e));
51
+ }
52
+ }
53
+ }
54
+ return {
55
+ rows,
56
+ ranges: mergeRanges(accounts.flatMap((a) => a.meta.ranges)),
57
+ limits: accounts.length ? accounts[0].meta.limits : null,
58
+ pulledAt: accounts.length ? accounts.map((a) => a.meta.pulledAt).sort().at(-1)! : null,
59
+ };
60
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * What the laptop reads from the ledger (`GET /v1/entries`, ledger API contract v1). Parsed leniently
3
+ * on the fields the report uses; a response that is not the documented shape is an error, never zero.
4
+ */
5
+ export const ENTRY_STATES = ["reserved", "settled", "unsettled", "unreserved"] as const;
6
+ export type EntryState = (typeof ENTRY_STATES)[number];
7
+
8
+ export interface LedgerCall {
9
+ operation: string;
10
+ label: string;
11
+ model: string;
12
+ turns: number;
13
+ duration_ms: number;
14
+ input_tokens: number;
15
+ output_tokens: number;
16
+ cache_read_tokens: number;
17
+ cache_write_tokens: number;
18
+ /** Null when the call died without a result and its real cost is unknown. */
19
+ cost_usd: number | null;
20
+ costKnown: boolean;
21
+ terminal_reason: string | null;
22
+ auth: string;
23
+ }
24
+
25
+ export interface LedgerEntry {
26
+ id: string;
27
+ day: string;
28
+ week: string;
29
+ repository: string;
30
+ repository_id: number | string;
31
+ pr: number | null;
32
+ run_id: number | string | null;
33
+ run_attempt: number | null;
34
+ trigger: string;
35
+ forced: boolean;
36
+ state: EntryState;
37
+ reservedUsd: number;
38
+ settledUsd: number | null;
39
+ created_at: string;
40
+ settled_at: string | null;
41
+ calls: LedgerCall[];
42
+ }
43
+
44
+ export interface LedgerLimits {
45
+ dailyUsd: number | null;
46
+ weeklyUsd: number | null;
47
+ }
48
+
49
+ export interface EntriesResponse {
50
+ account: string;
51
+ limits: LedgerLimits;
52
+ entries: LedgerEntry[];
53
+ }
54
+
55
+ export const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
56
+ /** An account name becomes a directory name; anything else is refused. */
57
+ export const ACCOUNT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
58
+
59
+ const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
60
+ const num = (v: unknown, fallback = 0) => (typeof v === "number" && Number.isFinite(v) ? v : fallback);
61
+ const str = (v: unknown, fallback = "") => (typeof v === "string" ? v : fallback);
62
+ /** A number, or a string that is one (the service sends `run_attempt` as a string). */
63
+ const numOrNumericString = (v: unknown) => {
64
+ if (typeof v === "number" && Number.isFinite(v)) return v;
65
+ if (typeof v === "string" && /^\d+$/.test(v.trim())) return Number.parseInt(v, 10);
66
+ return null;
67
+ };
68
+ const nullableNum = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null);
69
+
70
+ function parseCall(raw: unknown): LedgerCall {
71
+ const c = isObject(raw) ? raw : {};
72
+ const cost = nullableNum(c.cost_usd);
73
+ return {
74
+ operation: str(c.operation),
75
+ label: str(c.label),
76
+ model: str(c.model),
77
+ turns: num(c.turns),
78
+ duration_ms: num(c.duration_ms),
79
+ input_tokens: num(c.input_tokens),
80
+ output_tokens: num(c.output_tokens),
81
+ cache_read_tokens: num(c.cache_read_tokens),
82
+ cache_write_tokens: num(c.cache_write_tokens),
83
+ cost_usd: cost,
84
+ costKnown: c.costKnown !== false && cost !== null,
85
+ terminal_reason: typeof c.terminal_reason === "string" ? c.terminal_reason : null,
86
+ auth: str(c.auth, "api-key"),
87
+ };
88
+ }
89
+
90
+ function parseEntry(raw: unknown): LedgerEntry {
91
+ if (!isObject(raw)) throw new Error("an entry is not an object");
92
+ const state = raw.state;
93
+ if (!(ENTRY_STATES as readonly unknown[]).includes(state)) throw new Error(`an entry has the unknown state ${JSON.stringify(state)}`);
94
+ if (typeof raw.id !== "string" || raw.id === "") throw new Error("an entry has no id");
95
+ if (typeof raw.day !== "string" || !DAY_PATTERN.test(raw.day)) throw new Error("an entry has no valid day");
96
+ if (typeof raw.week !== "string" || !DAY_PATTERN.test(raw.week)) throw new Error("an entry has no valid week");
97
+ return {
98
+ id: raw.id,
99
+ day: raw.day,
100
+ week: raw.week,
101
+ repository: str(raw.repository),
102
+ repository_id: typeof raw.repository_id === "number" || typeof raw.repository_id === "string" ? raw.repository_id : "",
103
+ pr: typeof raw.pr === "number" && Number.isInteger(raw.pr) ? raw.pr : null,
104
+ run_id: typeof raw.run_id === "number" || typeof raw.run_id === "string" ? raw.run_id : null,
105
+ run_attempt: numOrNumericString(raw.run_attempt),
106
+ trigger: str(raw.trigger),
107
+ forced: raw.forced === true,
108
+ state: state as EntryState,
109
+ reservedUsd: num(raw.reservedUsd),
110
+ settledUsd: nullableNum(raw.settledUsd),
111
+ created_at: str(raw.created_at),
112
+ settled_at: typeof raw.settled_at === "string" ? raw.settled_at : null,
113
+ calls: Array.isArray(raw.calls) ? raw.calls.map(parseCall) : [],
114
+ };
115
+ }
116
+
117
+ export function parseEntriesResponse(body: unknown): EntriesResponse {
118
+ if (!isObject(body)) throw new Error("the ledger answered with something that is not a JSON object");
119
+ if (typeof body.account !== "string" || !ACCOUNT_PATTERN.test(body.account)) throw new Error("the ledger answer has no usable account name");
120
+ if (!Array.isArray(body.entries)) throw new Error("the ledger answer has no entries list");
121
+ const limits = isObject(body.limits) ? body.limits : {};
122
+ return {
123
+ account: body.account,
124
+ limits: { dailyUsd: nullableNum(limits.dailyUsd), weeklyUsd: nullableNum(limits.weeklyUsd) },
125
+ entries: body.entries.map(parseEntry),
126
+ };
127
+ }
package/src/ledger.ts CHANGED
@@ -11,15 +11,34 @@
11
11
  import { spawnSync } from "node:child_process";
12
12
  import { createPublicKey, verify } from "node:crypto";
13
13
 
14
- /** `curl`'s exit status and output; the HTTP status is read from the output (see `call`). */
15
- export type CurlFn = (args: string[]) => { status: number; stdout: string; stderr: string };
14
+ /**
15
+ * `curl`'s exit status and output; the HTTP status is read from the output (see `call`). `stdin` is the
16
+ * text curl reads as its configuration (`--config -`): every secret and every payload travels there,
17
+ * never in `args`, because the argument list of a process is readable by every other process on the
18
+ * machine and capped at 128 KB per argument. Copy this split for any new route.
19
+ */
20
+ export type CurlFn = (args: string[], stdin?: string) => { status: number; stdout: string; stderr: string };
16
21
 
17
- export const defaultCurl: CurlFn = (args) => {
18
- const run = spawnSync("curl", ["--silent", "--show-error", "--max-time", "20", ...args], { encoding: "utf8" });
22
+ /**
23
+ * Twenty seconds at most, and no redirect is followed (curl's default: no `--location`). `-q` must
24
+ * come first: it keeps the machine's `~/.curlrc` from changing either (a `location`, a `proxy`).
25
+ */
26
+ export const defaultCurl: CurlFn = (args, stdin) => {
27
+ const run = spawnSync("curl", ["-q", "--silent", "--show-error", "--max-time", "20", ...args], { encoding: "utf8", input: stdin });
19
28
  return { status: run.status ?? 1, stdout: run.stdout ?? "", stderr: run.stderr ?? run.error?.message ?? "" };
20
29
  };
21
30
 
31
+ const ESCAPES: Record<string, string> = { "\\": "\\\\", '"': '\\"', "\t": "\\t", "\n": "\\n", "\r": "\\r", "\v": "\\v" };
32
+
33
+ /**
34
+ * One curl configuration file (`curl --config -`): `option = "value"` lines. Inside the double quotes
35
+ * curl reads `\\`, `\"`, `\t`, `\n`, `\r` and `\v` as escapes, so these are the only characters changed.
36
+ */
37
+ export const curlConfig = (entries: [option: string, value: string][]): string =>
38
+ entries.map(([option, value]) => `${option} = "${value.replace(/[\\"\t\n\r\v]/g, (c) => ESCAPES[c]!)}"\n`).join("");
39
+
22
40
  export interface LedgerEnv {
41
+ GITHUB_ACTIONS?: string;
23
42
  ACTIONS_ID_TOKEN_REQUEST_URL?: string;
24
43
  ACTIONS_ID_TOKEN_REQUEST_TOKEN?: string;
25
44
  }
@@ -121,9 +140,12 @@ function unusable(route: string, status: number, what: string): Error {
121
140
  );
122
141
  }
123
142
 
124
- /** One request. The HTTP status is the last line of the output (`-w "\n%{http_code}"`). */
125
- function call(curl: CurlFn, args: string[]): { status: number; body: string } {
126
- const run = curl(["-o", "-", "-w", "\n%{http_code}", ...args]);
143
+ /**
144
+ * One request. `args` ends with the url; `secret` is what must not appear in argv (headers, data) and
145
+ * goes to curl on stdin. The HTTP status is the last line of the output (`-w "\n%{http_code}"`).
146
+ */
147
+ function call(curl: CurlFn, args: string[], secret: [option: string, value: string][]): { status: number; body: string } {
148
+ const run = curl(["--config", "-", "-o", "-", "-w", "\n%{http_code}", ...args], curlConfig(secret));
127
149
  if (run.status !== 0) throw new LedgerUnavailable(`curl failed (exit ${run.status}): ${run.stderr.trim()}`);
128
150
  const cut = run.stdout.lastIndexOf("\n");
129
151
  const status = Number(run.stdout.slice(cut + 1).trim());
@@ -141,16 +163,10 @@ const parseObject = (body: string): Record<string, unknown> | undefined => {
141
163
  };
142
164
 
143
165
  const post = (ledgerUrl: string, route: string, token: string, payload: unknown, curl: CurlFn) =>
144
- call(curl, [
145
- "-X",
146
- "POST",
147
- "-H",
148
- `Authorization: Bearer ${token}`,
149
- "-H",
150
- "Content-Type: application/json",
151
- "--data",
152
- JSON.stringify(payload),
153
- `${base(ledgerUrl)}${route}`,
166
+ call(curl, ["-X", "POST", `${base(ledgerUrl)}${route}`], [
167
+ ["header", `Authorization: Bearer ${token}`],
168
+ ["header", "Content-Type: application/json"],
169
+ ["data", JSON.stringify(payload)],
154
170
  ]);
155
171
 
156
172
  /**
@@ -161,7 +177,7 @@ export function requestIdToken(env: LedgerEnv, audience: string, curl: CurlFn):
161
177
  const url = env.ACTIONS_ID_TOKEN_REQUEST_URL;
162
178
  const bearer = env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
163
179
  if (!url || !bearer) throw new LedgerNotPermitted("this job has no OIDC token: id-token: write is not granted");
164
- const { status, body } = call(curl, ["-H", `Authorization: Bearer ${bearer}`, `${url}&audience=${encodeURIComponent(audience)}`]);
180
+ const { status, body } = call(curl, [`${url}&audience=${encodeURIComponent(audience)}`], [["header", `Authorization: Bearer ${bearer}`]]);
165
181
  const value = parseObject(body)?.value;
166
182
  if (status !== 200 || typeof value !== "string" || value === "") {
167
183
  if (isOutage(status)) throw new LedgerUnavailable(`GitHub did not issue an id token (HTTP ${status}).`);
package/src/local-ask.ts CHANGED
@@ -77,7 +77,7 @@ export function storedReviewOf(
77
77
  return undefined;
78
78
  }
79
79
 
80
- export function runAsk(
80
+ export async function runAsk(
81
81
  args: AskArgs,
82
82
  repoDir: string,
83
83
  env: Record<string, string | undefined>,
@@ -87,7 +87,7 @@ export function runAsk(
87
87
  engineVersion: string;
88
88
  },
89
89
  deps: LocalDeps = {},
90
- ): number {
90
+ ): Promise<number> {
91
91
  // The account, the provider and the settings are checked before the change is read, as `local` does.
92
92
  const { config, provider, state } = openLocalSession({
93
93
  profile: args.profile,
@@ -96,6 +96,7 @@ export function runAsk(
96
96
  env,
97
97
  stderr: io.stderr,
98
98
  deps,
99
+ scope: { workingTree: args.workingTree, base: args.base, commit: args.commit, from: args.from, maxDepth: args.maxDepth },
99
100
  });
100
101
  const onSigint = () => {
101
102
  state.interrupted = true;
@@ -159,10 +160,10 @@ export function runAsk(
159
160
  });
160
161
 
161
162
  // One call, read-only, in the snapshot of the head: the same place the review reads from.
162
- let result: ReturnType<typeof runProvider> | undefined;
163
+ let result: Awaited<ReturnType<typeof runProvider>> | undefined;
163
164
  let failure = "";
164
165
  try {
165
- result = runProvider(
166
+ result = await runProvider(
166
167
  { provider, log: io.stderr, warn: io.stderr },
167
168
  config,
168
169
  input.headDir,
package/src/local.ts CHANGED
@@ -13,13 +13,16 @@
13
13
  */
14
14
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
15
15
  import { resolve } from "node:path";
16
- import { loadConfig, UsageError } from "./config";
16
+ import { loadConfig, UsageError, type EngineConfig } from "./config";
17
17
  import {
18
18
  buildLocalInput,
19
19
  DEFAULT_MAX_DEPTH,
20
20
  EMPTY_TREE_LABEL,
21
+ localRepoSettings,
22
+ localSettingsCommit,
21
23
  type LocalRefs,
22
24
  removeSnapshot,
25
+ type SettingsScope,
23
26
  snapshotHead,
24
27
  warnSnapshotDifferences,
25
28
  } from "./connectors/local-git";
@@ -27,6 +30,7 @@ import { DEFAULT_EXCLUDE, estimateFor, filterFiles, planBatches, reviewChange, r
27
30
  import { sizeGate, type ReviewEstimate } from "./estimate";
28
31
  import { spawnGit } from "./evidence";
29
32
  import { assertReviewInputFormat, REVIEW_INPUT_V2 } from "./formats";
33
+ import { applyRepoSettings, fileSettingsNote, ignoredSettingsNote, wantsRepoSettings, type RepoSettings } from "./repo-settings";
30
34
  import { workingTreeInput, snapshotWorkingTree } from "./connectors/working-tree";
31
35
  import { historyRoot, historySettings, saveRun } from "./history";
32
36
  import { readConfig, wachimanHome } from "./accounts/config";
@@ -248,10 +252,10 @@ export function interruptible(provider: ProviderAdapter, state: { interrupted: b
248
252
  preflight: () => provider.preflight(),
249
253
  modelLabel: () => provider.modelLabel(),
250
254
  leaksSecret: (texts) => provider.leaksSecret(texts),
251
- run: (request) => {
255
+ run: async (request) => {
252
256
  if (state.interrupted) throw new InterruptedError("the review was interrupted");
253
257
  try {
254
- return provider.run(request);
258
+ return await provider.run(request);
255
259
  } catch (error) {
256
260
  if (error instanceof InterruptedError) state.interrupted = true;
257
261
  throw error;
@@ -281,6 +285,34 @@ export interface LocalSession {
281
285
  state: { interrupted: boolean };
282
286
  }
283
287
 
288
+ /**
289
+ * `config` with the model and the effort the repository's `.wachiman.yml` sets where nothing explicit
290
+ * did. The file is read at the commit the instruction files are read at (`localSettingsCommit`),
291
+ * never from the working tree or the head, for the same reason as in Actions: the change under
292
+ * review cannot choose what it is reviewed under. One stderr line says when the file decided. A
293
+ * broken file at that commit is ignored with a warning and the run continues on the environment and
294
+ * the defaults, so the change that fixes it can be reviewed.
295
+ */
296
+ export function withLocalSettings(config: EngineConfig, repoDir: string, scope: SettingsScope, stderr: (line: string) => void): EngineConfig {
297
+ if (!wantsRepoSettings(config)) return config;
298
+ const sha = localSettingsCommit(repoDir, scope);
299
+ if (sha === undefined) return config;
300
+ const where = `${scope.inputBase !== undefined ? "the input's base" : scope.workingTree ? "HEAD" : "the merge-base"} ${short(sha)}`;
301
+ let settings: RepoSettings | undefined;
302
+ try {
303
+ settings = localRepoSettings(repoDir, sha);
304
+ } catch (error) {
305
+ if (!(error instanceof UsageError)) throw error;
306
+ stderr(ignoredSettingsNote(error.message, where));
307
+ return config;
308
+ }
309
+ if (!settings) return config;
310
+ const next = applyRepoSettings(config, settings, { where, warn: stderr });
311
+ const note = fileSettingsNote(next, where);
312
+ if (note) stderr(`settings: ${note}`);
313
+ return next;
314
+ }
315
+
284
316
  /**
285
317
  * The settings, the account (ADR 0029), the subscription-mode provider and, with `--verify`, the
286
318
  * verifier, all checked before any call. Nothing in the reviewed repository takes part: a corrupt
@@ -293,12 +325,15 @@ export function openLocalSession(p: {
293
325
  env: Record<string, string | undefined>;
294
326
  stderr: (line: string) => void;
295
327
  deps: LocalDeps;
328
+ /** The scope flags: they decide the commit whose `.wachiman.yml` is read (the one the instruction files are read at). */
329
+ scope?: SettingsScope;
296
330
  }): LocalSession {
297
331
  const { env, repoDir, deps } = p;
298
- const loaded = loadConfig(env, p.stderr);
299
- if (loaded.provider !== "claude-code") {
300
- throw new UsageError(`WACHIMAN_PROVIDER=${loaded.provider}: the local review runs only on Claude Code, your signed-in \`claude\`.`);
332
+ const loadedEnv = loadConfig(env, p.stderr);
333
+ if (loadedEnv.provider !== "claude-code") {
334
+ throw new UsageError(`WACHIMAN_PROVIDER=${loadedEnv.provider}: the local review runs only on Claude Code, your signed-in \`claude\`.`);
301
335
  }
336
+ const loaded = withLocalSettings(loadedEnv, repoDir, p.scope ?? {}, p.stderr);
302
337
  // A person ran it: no automatic ceiling (decision 14).
303
338
  const config = {
304
339
  ...loaded,
@@ -444,7 +479,7 @@ export function sizeWarning(estimate: ReviewEstimate, gate: number, budgetUsd: n
444
479
  return `warning: reviewing all of this would cost about $${estimate.usd.toFixed(2)} at API prices (${estimate.batches} batches × $${estimate.perBatchUsd.toFixed(2)} for ${model}), above the $${gate.toFixed(2)} size gate. Local runs are never refused; this one continues and stops at its budget, $${budgetUsd.toFixed(2)} (WACHIMAN_BUDGET_USD).`;
445
480
  }
446
481
 
447
- export function runLocal(
482
+ export async function runLocal(
448
483
  args: LocalArgs,
449
484
  repoDir: string,
450
485
  env: Record<string, string | undefined>,
@@ -454,7 +489,7 @@ export function runLocal(
454
489
  engineVersion: string;
455
490
  },
456
491
  deps: LocalDeps = {},
457
- ): number {
492
+ ): Promise<number> {
458
493
  const fileInput = args.input === undefined ? undefined : readInputFile(args.input);
459
494
  if ((args.workingTree || fileInput?.change.kind === "working-tree") && args.resultVersion === 1) {
460
495
  throw new UsageError("Working-tree reviews require --result-version 2; a tree is not a commit.");
@@ -470,6 +505,14 @@ export function runLocal(
470
505
  env,
471
506
  stderr: io.stderr,
472
507
  deps,
508
+ scope: {
509
+ workingTree: args.workingTree,
510
+ base: args.base,
511
+ commit: args.commit,
512
+ from: args.from,
513
+ maxDepth: args.maxDepth,
514
+ inputBase: fileInput?.change.base.sha,
515
+ },
473
516
  });
474
517
 
475
518
  let release: (() => void) | undefined;
@@ -529,7 +572,7 @@ export function runLocal(
529
572
  : "verify: off",
530
573
  );
531
574
 
532
- const result = reviewChange(input, reviewOptionsOf(config, config.budgetUsd, profile.kind === "managed" ? "isolated" : "default"), {
575
+ const result = await reviewChange(input, reviewOptionsOf(config, config.budgetUsd, profile.kind === "managed" ? "isolated" : "default"), {
533
576
  provider,
534
577
  ...(verifier ? { verifier } : {}),
535
578
  // The verifier reads the code before the change too; made once, only when there is something to check.
@@ -575,6 +618,7 @@ export function runLocal(
575
618
  io.stderr(thisRunText(result, annotation));
576
619
  io.stderr(sinceLastRunText(annotation));
577
620
  }
621
+ const settingsFrom = { model: config.modelSource === "file", effort: config.effortSource === "file" };
578
622
  const text =
579
623
  args.format === "json"
580
624
  ? renderJson(
@@ -584,9 +628,10 @@ export function runLocal(
584
628
  annotation ? result.findings.map((_, i) => annotation!.byIndex.get(i)?.id) : undefined,
585
629
  )
586
630
  : args.format === "markdown"
587
- ? renderMarkdown(result, { profileNote, history: annotation })
631
+ ? renderMarkdown(result, { profileNote, history: annotation, settingsFrom })
588
632
  : renderTerminal(result, {
589
633
  profileNote,
634
+ settingsFrom,
590
635
  agentPrompt: args.agentPrompt,
591
636
  history: annotation,
592
637
  });
@@ -155,11 +155,11 @@ type IdentifiedResult = ReviewResult & { findings: { id: string }[] };
155
155
  type Attempt = { ok: true; result: IdentifiedResult } | { ok: false; why: string } | { interrupted: true };
156
156
 
157
157
  /** One review call: succeeds only with a complete `/2` result in which every finding has a history id. */
158
- function attempt(args: LocalArgs, repoDir: string, env: Record<string, string | undefined>, io: LoopIo, deps: LoopDeps): Attempt {
158
+ async function attempt(args: LocalArgs, repoDir: string, env: Record<string, string | undefined>, io: LoopIo, deps: LoopDeps): Promise<Attempt> {
159
159
  let out = "";
160
160
  let code: number;
161
161
  try {
162
- code = (deps.review ?? runLocal)(args, repoDir, env, { stdout: (t) => (out += t), stderr: io.stderr, engineVersion: io.engineVersion }, deps);
162
+ code = await (deps.review ?? runLocal)(args, repoDir, env, { stdout: (t) => (out += t), stderr: io.stderr, engineVersion: io.engineVersion }, deps);
163
163
  } catch (error) {
164
164
  if (error instanceof UsageError) throw error;
165
165
  return { ok: false, why: error instanceof Error ? error.message : String(error) };
@@ -188,7 +188,7 @@ interface LoopIo {
188
188
  const withVerdicts = (ledger: LedgerEntry[], verdicts: ReturnType<typeof readVerdicts>): LoopFinding[] =>
189
189
  ledger.map((e) => ({ ...e, ...(verdicts.get(e.id) ? { verdict: { verdict: verdicts.get(e.id)!.verdict, reason: verdicts.get(e.id)!.reason } } : {}) }));
190
190
 
191
- export function runLoop(args: LoopArgs, repoDir: string, env: Record<string, string | undefined>, io: LoopIo, deps: LoopDeps = {}): number {
191
+ export async function runLoop(args: LoopArgs, repoDir: string, env: Record<string, string | undefined>, io: LoopIo, deps: LoopDeps = {}): Promise<number> {
192
192
  const root = historyRoot(wachimanHome(env));
193
193
  const key = repositoryKey(repoDir).key;
194
194
  const branch = currentBranch(repoDir);
@@ -258,10 +258,10 @@ export function runLoop(args: LoopArgs, repoDir: string, env: Record<string, str
258
258
  ...(args.profile !== undefined ? { profile: args.profile } : {}),
259
259
  ...(args.maxDepth !== undefined ? { maxDepth: args.maxDepth } : {}),
260
260
  };
261
- let made = attempt(localArgs, repoDir, env, io, deps);
261
+ let made = await attempt(localArgs, repoDir, env, io, deps);
262
262
  if ("ok" in made && !made.ok) {
263
263
  io.stderr(`loop: the review failed (${made.why}); trying once more.`);
264
- made = attempt(localArgs, repoDir, env, io, deps);
264
+ made = await attempt(localArgs, repoDir, env, io, deps);
265
265
  }
266
266
  if ("interrupted" in made) return 130;
267
267
  if (!made.ok) {