wachiman 1.13.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -185,7 +185,7 @@ This is not a sandbox. What is enforced, what the tests show and what is still u
185
185
  The current release is on [npm](https://www.npmjs.com/package/wachiman) and in
186
186
  [CHANGELOG.md](CHANGELOG.md). The command-line contract ([docs/cli.md](docs/cli.md)) and the
187
187
  provider adapter boundary are in place. The older `CLAUDE_REVIEW_*` variables,
188
- `.github/agent-review.md`, `.github/claude-review.md`, `/wachi` and the `@claude` mention are still
188
+ `.github/claude-review.md`, `/wachi` and the `@claude` mention are still
189
189
  read with a notice; see [docs/upgrading.md](docs/upgrading.md).
190
190
 
191
191
  - **Claude Code** (`claude -p`) is the provider the reusable workflow installs and runs, with
package/bin/wachiman.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // The npm `bin` for `wachiman` and `agent-review`: finds Bun on PATH and runs this package's
2
+ // The npm `bin` for `wachiman`: finds Bun on PATH and runs this package's
3
3
  // TypeScript engine with it. All logic is in ./launcher-args.js.
4
4
  import { dirname } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wachiman",
3
- "version": "1.13.0",
3
+ "version": "1.14.0",
4
4
  "description": "Advisory pull request reviews by an agent CLI, run in your own GitHub Actions with your own key, or locally on your own Claude subscription",
5
5
  "private": false,
6
6
  "type": "module",
@@ -10,8 +10,7 @@
10
10
  "url": "git+https://github.com/niway-dev/wachiman.git"
11
11
  },
12
12
  "bin": {
13
- "wachiman": "bin/wachiman.js",
14
- "agent-review": "bin/wachiman.js"
13
+ "wachiman": "bin/wachiman.js"
15
14
  },
16
15
  "files": [
17
16
  "bin/wachiman.js",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: wachiman-review
3
- description: Use when the developer asks to review, audit or "analyse" their own code with Wachiman (or agent-review) on their laptop — a branch, one commit, or a range from a commit — including on employer code that must not reach GitHub, when they ask Wachiman to explain or answer a question about such a change ("explain this change", "ask about this branch"), and when they judge a finding from such a review as right or wrong.
3
+ description: Use when the developer asks to review, audit or "analyse" their own code with Wachiman on their laptop — a branch, one commit, or a range from a commit — including on employer code that must not reach GitHub, when they ask Wachiman to explain or answer a question about such a change ("explain this change", "ask about this branch"), and when they judge a finding from such a review as right or wrong.
4
4
  ---
5
5
 
6
6
  # Review local code with Wachiman
@@ -119,7 +119,7 @@ wachiman history --repo-dir <clone> --verdict <id> correct|partial|wrong --reaso
119
119
 
120
120
  | Tempting | Instead |
121
121
  | --- | --- |
122
- | `wachiman review <pr>`, `AGENT_REVIEW_DRY_RUN`, `gh`, a GitHub token | `local`: the GitHub modes post to the PR and need the code on GitHub |
122
+ | `wachiman review <pr>`, `WACHIMAN_DRY_RUN`, `gh`, a GitHub token | `local`: the GitHub modes post to the PR and need the code on GitHub |
123
123
  | A verdict as a PR comment or `Verdict:` reply | `history --verdict`: it stays on the laptop |
124
124
  | Running with `ANTHROPIC_API_KEY` set | `env -u ANTHROPIC_API_KEY wachiman local ...`: `local` refuses a key; the subscription pays |
125
125
  | `--max-depth 1000` because "review everything" | A closer start commit, or the number the developer chose |
package/src/cli.ts CHANGED
@@ -27,7 +27,9 @@
27
27
  * wachiman skills install|uninstall copy the agent skills into place, or remove what was copied
28
28
  * wachiman --setup-profile [name] sign in an isolated Claude Code profile under the Wachiman home
29
29
  *
30
- * Exit codes: 0 posted or nothing to do; 1 engine error (nothing posted); 2 usage error;
30
+ * Exit codes: 0 posted or nothing to do; 1 engine error (nothing posted); 2 usage error; 3 the spend
31
+ * ledger stopped the run before any model call (a limit with `limit_mode: fail`, a repository it does
32
+ * not know, a job without an OIDC token, or an unreachable ledger with `ledger_unavailable: stop`);
31
33
  * 130 cancelled (`local`, `loop`, `setup`, `init`); `loop` also exits 10 and 11 (see its help).
32
34
  * The settings are documented in docs/cli.md.
33
35
  */
@@ -38,7 +40,7 @@ import { loadConfig, UsageError } from "./config";
38
40
  import { historyUsage, parseHistoryArgs, runHistory } from "./history/command";
39
41
  import { parseStatusArgs, runStatus, statusUsage } from "./status/command";
40
42
  import { dashboardUsage, parseDashboardArgs, runDashboard } from "./store/command";
41
- import { comment, defaultGh, isThreadQuestion, review, threadReplies, type Deps, type GhFn, type ReviewLineComment } from "./engine";
43
+ import { LedgerStopped, SpendLimitReached, comment, defaultGh, isThreadQuestion, review, threadReplies, type Deps, type GhFn, type ReviewLineComment } from "./engine";
42
44
  import { localUsage, parseLocalArgs, runLocal } from "./local";
43
45
  import { loopUsage, parseLoopArgs, runLoop } from "./loop/command";
44
46
  import { askUsage, parseAskArgs, runAsk } from "./local-ask";
@@ -61,7 +63,7 @@ export const USAGE = `Usage:
61
63
  wachiman comment <pr> [--repo-dir <dir>] Handle the comment in $REQUEST (a review or an answer)
62
64
  wachiman threads <pr> [--repo-dir <dir>] Answer the pending Wachiman threads (an automatic run)
63
65
  wachiman reset-confidence <pr> [--commit <sha>] Write "cannot say" into the PR Confidence block (no model call;
64
- the first step of a review run, with AGENT_REVIEW_CONFIDENCE=1)
66
+ the first step of a review run, with WACHIMAN_CONFIDENCE=1)
65
67
  ${localUsage}
66
68
  Review the committed branch of a clone on your
67
69
  signed-in claude, and print it; nothing is posted.
@@ -139,10 +141,12 @@ Environment:
139
141
  CLAUDE_CODE_OAUTH_TOKEN a Claude subscription token (\`claude setup-token\`); if set, it is
140
142
  used and ANTHROPIC_API_KEY never reaches the agent
141
143
  REQUEST the comment text, for \`comment\`
142
- AGENT_REVIEW_COMMENT_AUTHOR the login of the comment's author, for \`comment\` and \`threads\`
143
- AGENT_REVIEW_* optional settings; see docs/cli.md
144
+ WACHIMAN_COMMENT_AUTHOR the login of the comment's author, for \`comment\` and \`threads\`
145
+ WACHIMAN_* optional settings; see docs/cli.md
144
146
 
145
- Exit codes: 0 posted or nothing to do, 1 engine error, 2 usage error.
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.
146
150
  \`local\`: 0 a report was printed, 1 no call returned a review, 2 usage error, 130 interrupted.
147
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.
148
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.
@@ -160,7 +164,7 @@ export function readVersion(dir = import.meta.dir) {
160
164
  const path = join(dir, "..", "package.json");
161
165
  if (!existsSync(path)) return "unknown";
162
166
  const pkg = JSON.parse(readFileSync(path, "utf8"));
163
- return pkg.name === "wachiman" || pkg.name === "agent-review" ? String(pkg.version) : "unknown";
167
+ return pkg.name === "wachiman" ? String(pkg.version) : "unknown";
164
168
  } catch {
165
169
  return "unknown";
166
170
  }
@@ -225,7 +229,7 @@ export function routeMode(mode: string, commentLine: ReviewLineComment | undefin
225
229
  * comment's text is `REQUEST`.
226
230
  */
227
231
  export function readCommentLine(env: Record<string, string | undefined>): ReviewLineComment | undefined {
228
- const id = env.AGENT_REVIEW_COMMENT_ID ?? "";
232
+ const id = env.WACHIMAN_COMMENT_ID ?? "";
229
233
  if (id === "") return undefined;
230
234
  const number = (name: string) => {
231
235
  const raw = env[name] ?? "";
@@ -233,12 +237,12 @@ export function readCommentLine(env: Record<string, string | undefined>): Review
233
237
  if (!/^\d+$/.test(raw)) throw new UsageError(`${name} must be a comment id or a line number, got "${raw}".`);
234
238
  return Number(raw);
235
239
  };
236
- if (!/^\d+$/.test(id)) throw new UsageError(`AGENT_REVIEW_COMMENT_ID must be a comment id, got "${id}".`);
240
+ if (!/^\d+$/.test(id)) throw new UsageError(`WACHIMAN_COMMENT_ID must be a comment id, got "${id}".`);
237
241
  return {
238
242
  id: Number(id),
239
- replyTo: number("AGENT_REVIEW_COMMENT_IN_REPLY_TO"),
240
- path: env.AGENT_REVIEW_COMMENT_PATH || null,
241
- line: number("AGENT_REVIEW_COMMENT_LINE"),
243
+ replyTo: number("WACHIMAN_COMMENT_IN_REPLY_TO"),
244
+ path: env.WACHIMAN_COMMENT_PATH || null,
245
+ line: number("WACHIMAN_COMMENT_LINE"),
242
246
  };
243
247
  }
244
248
 
@@ -284,7 +288,7 @@ async function runWizard(mode: "setup" | "init", args: string[], repoDir: string
284
288
  * before the push wait, so a run cancelled during it leaves no letter from an older commit. No
285
289
  * model, no provider. A failure inside the reset itself (reading or writing the description) is a
286
290
  * warning and the exit code stays 0. A usage or configuration error is not: a bad pull request
287
- * number or flag, an invalid `AGENT_REVIEW_*` value, or a missing `GH_TOKEN` or
291
+ * number or flag, an invalid `WACHIMAN_*` value, or a missing `GH_TOKEN` or
288
292
  * `GITHUB_REPOSITORY` exits non-zero. The workflow steps run it with `continue-on-error`.
289
293
  */
290
294
  export function runResetConfidence(args: string[], env: Record<string, string | undefined>, gh: GhFn = defaultGh): number {
@@ -402,8 +406,10 @@ export async function main(argv: string[], env: Record<string, string | undefine
402
406
  const repo = required(env, "GITHUB_REPOSITORY");
403
407
  const request = effective === "comment" ? required(env, "REQUEST") : "";
404
408
  const costs: CallCost[] = [];
409
+ const ledgerNotes: string[] = [];
405
410
  const deps: Deps = {
406
411
  costs,
412
+ ledgerNotes,
407
413
  gh: defaultGh,
408
414
  provider,
409
415
  ...(verifier ? { verifier } : {}),
@@ -423,11 +429,11 @@ export async function main(argv: string[], env: Record<string, string | undefine
423
429
  }
424
430
  try {
425
431
  if (effective === "review") review(deps, repo, pr, rest);
426
- else if (effective === "threads") threadReplies(deps, repo, pr, env.AGENT_REVIEW_COMMENT_AUTHOR || undefined);
427
- else comment(deps, repo, pr, request, env.AGENT_REVIEW_COMMENT_AUTHOR || undefined, commentLine);
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);
428
434
  } finally {
429
435
  // Also after a failed run: the calls it made were paid for.
430
- writeStepSummary(costs, env);
436
+ writeStepSummary(costs, env, undefined, ledgerNotes);
431
437
  }
432
438
  return 0;
433
439
  } catch (error) {
@@ -435,6 +441,19 @@ export async function main(argv: string[], env: Record<string, string | undefine
435
441
  console.error(`wachiman: ${error.message}\n\n${USAGE}`);
436
442
  return 2;
437
443
  }
444
+ if (error instanceof SpendLimitReached) {
445
+ // The notice is already posted. `notice` mode keeps the job green.
446
+ if (error.mode === "notice") {
447
+ console.log(`wachiman: spend limit reached: ${error.message}`);
448
+ return 0;
449
+ }
450
+ console.error(`wachiman: spend limit reached: ${error.message}`);
451
+ return 3;
452
+ }
453
+ if (error instanceof LedgerStopped) {
454
+ console.error(`wachiman: ledger: ${error.message}`);
455
+ return 3;
456
+ }
438
457
  console.error(`wachiman: ${error instanceof Error ? error.message : error}`);
439
458
  return 1;
440
459
  }
package/src/config.ts CHANGED
@@ -1,4 +1,4 @@
1
- /** The `AGENT_REVIEW_*` settings, read once, with the old `CLAUDE_REVIEW_*` names as a fallback. */
1
+ /** The `WACHIMAN_*` settings, read once, with the old `CLAUDE_REVIEW_*` names as a fallback. */
2
2
  import { DEFAULT_MODELS } from "./providers";
3
3
  import { DEFAULT_CALL_TIMEOUT_S, DEFAULT_EFFORT, DEFAULT_MAX_TURNS, EFFORTS, type Effort } from "./providers/types";
4
4
 
@@ -14,25 +14,43 @@ 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
+ export type LimitMode = "fail" | "notice";
18
+ export type LedgerUnavailableMode = "run" | "stop";
19
+
17
20
  export interface EngineConfig {
18
21
  /** Total per review invocation, USD. */
19
22
  budgetUsd: number;
20
23
  /**
21
- * `AGENT_REVIEW_AUTO_BUDGET_USD`: the most all automatic runs on one pull request may spend
24
+ * `WACHIMAN_AUTO_BUDGET_USD`: the most all automatic runs on one pull request may spend
22
25
  * together (the first review, push reviews, thread runs), summed from the engine's own signed
23
26
  * footers. The operator's `comment` is not limited by it.
24
27
  */
25
28
  autoBudgetUsd: number;
26
29
  /**
27
- * `AGENT_REVIEW_SIZE_GATE_USD`: the most a review's estimate may be before a GitHub run skips it
30
+ * `WACHIMAN_SIZE_GATE_USD`: the most a review's estimate may be before a GitHub run skips it
28
31
  * and posts one comment instead. The effective gate is never below what the run may spend
29
32
  * (`sizeGate` in estimate.ts), so raising the budgets lifts it. Local runs only warn.
30
33
  */
31
34
  sizeGateUsd: number;
32
- /** `AGENT_REVIEW_THREADS_BUDGET_USD`: the one provider call of a thread-only run. */
35
+ /**
36
+ * `WACHIMAN_LEDGER_URL`: the spend ledger service, trimmed, without a trailing slash. Unset
37
+ * means no ledger call of any kind. It is also the OIDC audience, as configured.
38
+ */
39
+ ledgerUrl?: string;
40
+ /** `WACHIMAN_DAILY_BUDGET_USD`: a stricter daily number for this repository; it never raises the account's limit. */
41
+ dailyBudgetUsd?: number;
42
+ /** `WACHIMAN_WEEKLY_BUDGET_USD`: the same, per week. */
43
+ weeklyBudgetUsd?: number;
44
+ /** `WACHIMAN_LIMIT_MODE`: when a limit refuses a run, `fail` exits 3 (red job); `notice` posts the comment and passes. */
45
+ limitMode: LimitMode;
46
+ /** `WACHIMAN_LIMIT_BYPASS`: `1` or `true` skips the ledger for this run. */
47
+ limitBypass: boolean;
48
+ /** `WACHIMAN_LEDGER_UNAVAILABLE`: with an unreachable ledger, `run` reviews anyway (and says so); `stop` exits 3 before any model call. */
49
+ ledgerUnavailable: LedgerUnavailableMode;
50
+ /** `WACHIMAN_THREADS_BUDGET_USD`: the one provider call of a thread-only run. */
33
51
  threadsBudgetUsd: number;
34
52
  /**
35
- * `AGENT_REVIEW_TRIGGER`: why this run started (see `Trigger`). Unset means a person ran the
53
+ * `WACHIMAN_TRIGGER`: why this run started (see `Trigger`). Unset means a person ran the
36
54
  * CLI by hand: not automatic, so the ceiling does not apply. `comment` mode ignores it.
37
55
  */
38
56
  trigger?: Trigger;
@@ -42,32 +60,32 @@ export interface EngineConfig {
42
60
  batchChars: number;
43
61
  dryRun: boolean;
44
62
  /**
45
- * `AGENT_REVIEW_FULL_REVIEW`: a dry run reviews the whole pull request, as if it had never been
63
+ * `WACHIMAN_FULL_REVIEW`: a dry run reviews the whole pull request, as if it had never been
46
64
  * reviewed, without reading the previous-review marker. Only together with `dryRun`.
47
65
  */
48
66
  fullReview: boolean;
49
67
  /** The provider's default (`DEFAULT_MODELS`) when unset. */
50
68
  model: string;
51
69
  provider: string;
52
- /** `AGENT_REVIEW_PRICE_PER_MTOK`: "input,cached_input,output" USD per million tokens, for a Codex model without a built-in price. */
70
+ /** `WACHIMAN_PRICE_PER_MTOK`: "input,cached_input,output" USD per million tokens, for a Codex model without a built-in price. */
53
71
  pricePerMTok?: string;
54
72
  /**
55
- * `AGENT_REVIEW_EFFORT`: the reasoning effort, always explicit so a CLI default change cannot
73
+ * `WACHIMAN_EFFORT`: the reasoning effort, always explicit so a CLI default change cannot
56
74
  * alter reviews. Passed as `--effort` (Claude Code) or `model_reasoning_effort` (Codex).
57
75
  */
58
76
  effort: Effort;
59
77
  /**
60
- * `AGENT_REVIEW_MAX_TURNS`: the most agent turns one provider call may take. Passed as
78
+ * `WACHIMAN_MAX_TURNS`: the most agent turns one provider call may take. Passed as
61
79
  * `--max-turns` (Claude Code); Codex has no equivalent and ignores it.
62
80
  */
63
81
  maxTurns: number;
64
82
  /**
65
- * `AGENT_REVIEW_CALL_TIMEOUT_S`: wall-clock limit on one provider call, in seconds. The call is
83
+ * `WACHIMAN_CALL_TIMEOUT_S`: wall-clock limit on one provider call, in seconds. The call is
66
84
  * killed when it passes and ends as `timeout`.
67
85
  */
68
86
  callTimeoutS: number;
69
87
  /**
70
- * `AGENT_REVIEW_ON_PROVIDER_UNAVAILABLE`: what a run does when the provider rejects every call
88
+ * `WACHIMAN_ON_PROVIDER_UNAVAILABLE`: what a run does when the provider rejects every call
71
89
  * because the reviewer's own account cannot pay or authenticate (or stays rate-limited). `warn`
72
90
  * posts a notice and finishes green; `fail` posts it and fails the job.
73
91
  */
@@ -76,29 +94,29 @@ export interface EngineConfig {
76
94
  /** Login allowed to command the tool. `comment` refuses to run when it is empty or a placeholder. */
77
95
  operator: string;
78
96
  /**
79
- * `AGENT_REVIEW_ASKERS`: who may ask a question (ADR 0032 decision 5). `operator` (default): only
97
+ * `WACHIMAN_ASKERS`: who may ask a question (ADR 0032 decision 5). `operator` (default): only
80
98
  * the operator. `write`: also a collaborator whose permission on the repository is admin,
81
99
  * maintain or write, checked by the engine on each question. Reviews stay operator-only.
82
100
  */
83
101
  askers: "operator" | "write";
84
102
  /**
85
- * `AGENT_REVIEW_ASK_CEILING_USD`: the most the questions of everyone but the operator may spend
103
+ * `WACHIMAN_ASK_CEILING_USD`: the most the questions of everyone but the operator may spend
86
104
  * on one pull request, summed from the engine's own footers. The operator's questions are not limited.
87
105
  */
88
106
  askCeilingUsd: number;
89
107
  /** Extra exclude globs on top of the built-in ones. */
90
108
  exclude: string[];
91
109
  /**
92
- * `AGENT_REVIEW_VERIFY`: after the batches, one more call tries to refute every finding above
110
+ * `WACHIMAN_VERIFY`: after the batches, one more call tries to refute every finding above
93
111
  * `info` before it is posted (ADR 0027). Off by default; enabled only by `1` or `true`.
94
112
  */
95
113
  verify: boolean;
96
- /** `AGENT_REVIEW_VERIFY_BUDGET_USD`: the verifier's reserve, taken out of `budgetUsd` (at most half of it). */
114
+ /** `WACHIMAN_VERIFY_BUDGET_USD`: the verifier's reserve, taken out of `budgetUsd` (at most half of it). */
97
115
  verifyBudgetUsd: number;
98
- /** `AGENT_REVIEW_VERIFIER_MODEL`: the verifier's model; it always runs at effort `high`. */
116
+ /** `WACHIMAN_VERIFIER_MODEL`: the verifier's model; it always runs at effort `high`. */
99
117
  verifierModel: string;
100
118
  /**
101
- * `AGENT_REVIEW_CONFIDENCE`: PR Confidence (ADR 0033). A full review of a pull request lists the
119
+ * `WACHIMAN_CONFIDENCE`: PR Confidence (ADR 0033). A full review of a pull request lists the
102
120
  * claims in its title and body with one more small call, grades the change against them and
103
121
  * writes the grade into the description. Off by default; enabled only by `1` or `true`. Read by
104
122
  * the pull request review only: `wachiman local` never grades.
@@ -106,41 +124,41 @@ export interface EngineConfig {
106
124
  confidence: boolean;
107
125
  }
108
126
 
109
- /** The verifier's model when `AGENT_REVIEW_VERIFIER_MODEL` is unset (Claude Code only). */
127
+ /** The verifier's model when `WACHIMAN_VERIFIER_MODEL` is unset (Claude Code only). */
110
128
  export const DEFAULT_VERIFIER_MODEL = "claude-opus-5-5";
111
129
 
112
130
  type Env = Record<string, string | undefined>;
113
131
 
114
132
  /**
115
- * `AGENT_REVIEW_<name>`, else the deprecated `CLAUDE_REVIEW_<name>` (with a one-line notice on
133
+ * `WACHIMAN_<name>`, else the deprecated `CLAUDE_REVIEW_<name>` (with a one-line notice on
116
134
  * stderr), else undefined. An empty value counts as unset.
117
135
  */
118
136
  export function readSetting(env: Env, name: string, warn: (line: string) => void) {
119
- const current = env[`AGENT_REVIEW_${name}`];
137
+ const current = env[`WACHIMAN_${name}`];
120
138
  if (current !== undefined && current !== "") return current;
121
139
  const old = env[`CLAUDE_REVIEW_${name}`];
122
140
  if (old !== undefined && old !== "") {
123
- warn(`CLAUDE_REVIEW_${name} is deprecated; use AGENT_REVIEW_${name}.`);
141
+ warn(`CLAUDE_REVIEW_${name} is deprecated; use WACHIMAN_${name}.`);
124
142
  return old;
125
143
  }
126
144
  return undefined;
127
145
  }
128
146
 
129
147
  /**
130
- * `AGENT_REVIEW_EFFORT`, else the deprecated `AGENT_REVIEW_REASONING_EFFORT` (Codex only before),
148
+ * `WACHIMAN_EFFORT`, else the deprecated `WACHIMAN_REASONING_EFFORT` (Codex only before),
131
149
  * else the default. An unknown value is a configuration error: a silent fallback would run the
132
150
  * review at an effort nobody chose.
133
151
  */
134
152
  function readEffort(env: Env, warn: (line: string) => void): Effort {
135
153
  const current = readSetting(env, "EFFORT", warn);
136
154
  const old = readSetting(env, "REASONING_EFFORT", () => {});
137
- let name = "AGENT_REVIEW_EFFORT";
155
+ let name = "WACHIMAN_EFFORT";
138
156
  let raw = current;
139
157
  if (old !== undefined) {
140
- warn("AGENT_REVIEW_REASONING_EFFORT is deprecated; use AGENT_REVIEW_EFFORT.");
158
+ warn("WACHIMAN_REASONING_EFFORT is deprecated; use WACHIMAN_EFFORT.");
141
159
  if (raw === undefined) {
142
160
  raw = old;
143
- name = "AGENT_REVIEW_REASONING_EFFORT";
161
+ name = "WACHIMAN_REASONING_EFFORT";
144
162
  }
145
163
  }
146
164
  if (raw === undefined) return DEFAULT_EFFORT;
@@ -157,44 +175,68 @@ export function loadConfig(env: Env, warn: (line: string) => void = console.erro
157
175
  if (raw === undefined) return fallback;
158
176
  const value = Number(raw);
159
177
  if (!Number.isFinite(value) || value <= 0 || (integer && !Number.isInteger(value))) {
160
- throw new UsageError(`AGENT_REVIEW_${name} must be a positive ${integer ? "integer" : "number"}, got "${raw}".`);
178
+ throw new UsageError(`WACHIMAN_${name} must be a positive ${integer ? "integer" : "number"}, got "${raw}".`);
161
179
  }
162
180
  return value;
163
181
  };
164
182
  const effort = readEffort(env, warn);
165
183
  const onProviderUnavailable = get("ON_PROVIDER_UNAVAILABLE") ?? "warn";
166
184
  if (onProviderUnavailable !== "warn" && onProviderUnavailable !== "fail") {
167
- throw new UsageError(`AGENT_REVIEW_ON_PROVIDER_UNAVAILABLE must be warn or fail, got "${onProviderUnavailable}".`);
185
+ throw new UsageError(`WACHIMAN_ON_PROVIDER_UNAVAILABLE must be warn or fail, got "${onProviderUnavailable}".`);
168
186
  }
169
187
  const provider = get("PROVIDER") ?? "claude-code";
170
188
  const dryRun = get("DRY_RUN") === "1";
171
189
  const fullReview = get("FULL_REVIEW") === "1";
172
190
  if (fullReview && !dryRun) {
173
191
  throw new UsageError(
174
- "AGENT_REVIEW_FULL_REVIEW=1 works only with AGENT_REVIEW_DRY_RUN=1: a full review ignores the previous-review marker, so it is printed, never posted.",
192
+ "WACHIMAN_FULL_REVIEW=1 works only with WACHIMAN_DRY_RUN=1: a full review ignores the previous-review marker, so it is printed, never posted.",
175
193
  );
176
194
  }
177
195
  const verifyRaw = get("VERIFY");
178
196
  if (verifyRaw !== undefined && verifyRaw !== "0" && verifyRaw !== "1" && verifyRaw !== "true" && verifyRaw !== "false") {
179
- throw new UsageError(`AGENT_REVIEW_VERIFY must be 1, true, 0 or false (unset means off), got "${verifyRaw}".`);
197
+ throw new UsageError(`WACHIMAN_VERIFY must be 1, true, 0 or false (unset means off), got "${verifyRaw}".`);
180
198
  }
181
199
  const verifierModel = get("VERIFIER_MODEL") ?? (provider === "claude-code" ? DEFAULT_VERIFIER_MODEL : undefined);
182
200
  // Verification is opt-in, including when a verifier model is configured.
183
201
  const verify = verifyRaw === "1" || verifyRaw === "true";
184
202
  if (verify && verifierModel === undefined) {
185
- throw new UsageError(`AGENT_REVIEW_VERIFY needs AGENT_REVIEW_VERIFIER_MODEL with the ${provider} provider: the default verifier is a Claude model.`);
203
+ throw new UsageError(`WACHIMAN_VERIFY needs WACHIMAN_VERIFIER_MODEL with the ${provider} provider: the default verifier is a Claude model.`);
186
204
  }
187
205
  const confidenceRaw = get("CONFIDENCE");
188
206
  if (confidenceRaw !== undefined && !["0", "1", "true", "false"].includes(confidenceRaw)) {
189
- throw new UsageError(`AGENT_REVIEW_CONFIDENCE must be 1, true, 0 or false (unset means off), got "${confidenceRaw}".`);
207
+ throw new UsageError(`WACHIMAN_CONFIDENCE must be 1, true, 0 or false (unset means off), got "${confidenceRaw}".`);
190
208
  }
191
209
  const askers = get("ASKERS") ?? "operator";
192
210
  if (askers !== "operator" && askers !== "write") {
193
- throw new UsageError(`AGENT_REVIEW_ASKERS must be operator or write, got "${askers}".`);
211
+ throw new UsageError(`WACHIMAN_ASKERS must be operator or write, got "${askers}".`);
194
212
  }
195
213
  const trigger = get("TRIGGER")?.trim();
196
214
  if (trigger !== undefined && !/^[a-z_]+$/.test(trigger)) {
197
- throw new UsageError(`AGENT_REVIEW_TRIGGER must be a lowercase event action such as synchronize, got "${trigger}".`);
215
+ throw new UsageError(`WACHIMAN_TRIGGER must be a lowercase event action such as synchronize, got "${trigger}".`);
216
+ }
217
+ const limitMode = get("LIMIT_MODE") ?? "fail";
218
+ if (limitMode !== "fail" && limitMode !== "notice") {
219
+ throw new UsageError(`WACHIMAN_LIMIT_MODE must be fail or notice, got "${limitMode}".`);
220
+ }
221
+ const ledgerUnavailable = get("LEDGER_UNAVAILABLE") ?? "run";
222
+ if (ledgerUnavailable !== "run" && ledgerUnavailable !== "stop") {
223
+ throw new UsageError(`WACHIMAN_LEDGER_UNAVAILABLE must be run or stop, got "${ledgerUnavailable}".`);
224
+ }
225
+ const bypass = get("LIMIT_BYPASS")?.trim();
226
+ const ledgerUrl = get("LEDGER_URL")?.trim().replace(/\/+$/, "") || undefined;
227
+ // The job's OIDC token is sent to this address: never over cleartext, except to the local machine for tests.
228
+ if (ledgerUrl !== undefined && !/^https:\/\/\S/i.test(ledgerUrl) && !/^http:\/\/(localhost|127\.0\.0\.1)(?=[:/]|$)/i.test(ledgerUrl)) {
229
+ throw new UsageError(
230
+ `WACHIMAN_LEDGER_URL must start with https:// (http://localhost and http://127.0.0.1 are allowed for tests), got "${ledgerUrl}".`,
231
+ );
232
+ }
233
+ // With a ledger, `review-platform.yml` grants `id-token: write`, so the request token is in the
234
+ // engine's environment; a Codex sandbox could read it from /proc and mint tokens as this job.
235
+ // Without `ledger_url` nothing uses the token and the guard does not apply.
236
+ if (ledgerUrl !== undefined && provider !== "claude-code" && env.ACTIONS_ID_TOKEN_REQUEST_TOKEN !== undefined) {
237
+ throw new UsageError(
238
+ `WACHIMAN_PROVIDER ${provider} cannot run in a job that holds an OIDC request token: its sandbox can read it from the engine's environment. Use claude-code, or call review.yml instead of review-platform.yml.`,
239
+ );
198
240
  }
199
241
  return {
200
242
  budgetUsd: number("BUDGET_USD", 3),
@@ -224,6 +266,12 @@ export function loadConfig(env: Env, warn: (line: string) => void = console.erro
224
266
  verifyBudgetUsd: number("VERIFY_BUDGET_USD", 1),
225
267
  verifierModel: verifierModel ?? DEFAULT_VERIFIER_MODEL,
226
268
  confidence: confidenceRaw === "1" || confidenceRaw === "true",
269
+ ledgerUrl,
270
+ dailyBudgetUsd: get("DAILY_BUDGET_USD") === undefined ? undefined : number("DAILY_BUDGET_USD", 0),
271
+ weeklyBudgetUsd: get("WEEKLY_BUDGET_USD") === undefined ? undefined : number("WEEKLY_BUDGET_USD", 0),
272
+ limitMode,
273
+ limitBypass: bypass === "1" || bypass === "true",
274
+ ledgerUnavailable,
227
275
  };
228
276
  }
229
277
 
@@ -237,10 +285,10 @@ const PLACEHOLDER_OPERATORS = ["your-github-login"];
237
285
  */
238
286
  export function operatorProblem(operator: string | undefined): string | undefined {
239
287
  const login = (operator ?? "").trim();
240
- if (login === "") return "The operator login is empty. Set `operator` (AGENT_REVIEW_OPERATOR) to your GitHub login.";
288
+ if (login === "") return "The operator login is empty. Set `operator` (WACHIMAN_OPERATOR) to your GitHub login.";
241
289
  const lower = login.toLowerCase();
242
290
  if (lower.startsWith("edit") || PLACEHOLDER_OPERATORS.includes(lower)) {
243
- return `The operator login is still the template placeholder "${login}". Set \`operator\` (AGENT_REVIEW_OPERATOR) to your GitHub login.`;
291
+ return `The operator login is still the template placeholder "${login}". Set \`operator\` (WACHIMAN_OPERATOR) to your GitHub login.`;
244
292
  }
245
293
  return undefined;
246
294
  }
@@ -31,7 +31,7 @@ const DIFF_MAX_BYTES = 512 * 1024 * 1024;
31
31
  const short = (sha: string) => sha.slice(0, 7);
32
32
 
33
33
  /** The most commits a local review may span, from its start commit to `HEAD`; `--max-depth` changes it for one run. */
34
- export const DEFAULT_MAX_DEPTH = 50;
34
+ export const DEFAULT_MAX_DEPTH = 250;
35
35
 
36
36
  /** Which commits a local review spans; without one, the branch against its base (`merge-base(base, HEAD) → HEAD`). */
37
37
  /** `LocalRefs.baseRef` of a root commit, which has no parent to start from. */
package/src/cost.ts CHANGED
@@ -146,6 +146,30 @@ export function costLogLine(call: CallCost, extra: { trigger?: string } = {}) {
146
146
  })}`;
147
147
  }
148
148
 
149
+ /**
150
+ * One call as the spend ledger receives it: the fields of the `wachiman-cost` line that describe
151
+ * the call, nothing about where it ran. `repo` and `trigger` are the ledger's own (it knows the
152
+ * repository from the verified token and gets the trigger when it reserves); `countedUsd` is the
153
+ * spent amount the settle already carries. Same names and values as `costLogLine`.
154
+ */
155
+ export function ledgerCall(call: CallCost) {
156
+ return {
157
+ operation: call.operation,
158
+ label: call.label,
159
+ model: call.model,
160
+ turns: call.turns,
161
+ duration_ms: call.durationMs,
162
+ input_tokens: call.usage.input,
163
+ output_tokens: call.usage.output,
164
+ cache_read_tokens: call.usage.cacheRead,
165
+ cache_write_tokens: call.usage.cacheWrite,
166
+ cost_usd: call.costKnown === false ? null : Number(call.costUsd.toFixed(6)),
167
+ costKnown: call.costKnown !== false,
168
+ terminal_reason: call.terminalReason,
169
+ auth: call.auth ?? "api-key",
170
+ };
171
+ }
172
+
149
173
  /** The job summary: one row per call and a total row. Empty string when no call was made. */
150
174
  export function renderCostSummary(calls: CallCost[]) {
151
175
  if (calls.length === 0) return "";
@@ -187,9 +211,12 @@ export function writeStepSummary(
187
211
  calls: CallCost[],
188
212
  env: Record<string, string | undefined>,
189
213
  append: (path: string, text: string) => void = appendFileSync,
214
+ /** What the spend ledger did or could not do in this run, one line each (`### Wachiman spend limit`). */
215
+ ledgerNotes: string[] = [],
190
216
  ) {
191
217
  const path = env.GITHUB_STEP_SUMMARY;
192
- const text = renderCostSummary(calls);
218
+ const notes = ledgerNotes.length === 0 ? "" : ["### Wachiman spend limit", "", ...ledgerNotes.map((n) => `- ${n}`)].join("\n");
219
+ const text = [renderCostSummary(calls), notes].filter(Boolean).join("\n\n");
193
220
  if (!path || !text) return false;
194
221
  try {
195
222
  append(path, `${text}\n`);