wachiman 1.13.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +2 -2
  2. package/bin/wachiman.js +1 -1
  3. package/package.json +5 -4
  4. package/skills/wachiman-review/SKILL.md +2 -2
  5. package/src/accounts/confirm.ts +62 -3
  6. package/src/cli.ts +136 -132
  7. package/src/config.ts +83 -35
  8. package/src/connectors/local-git.ts +1 -1
  9. package/src/cost.ts +28 -1
  10. package/src/engine.ts +396 -38
  11. package/src/help.ts +555 -0
  12. package/src/history/store.ts +5 -5
  13. package/src/init/options.ts +1 -1
  14. package/src/init/run.ts +43 -17
  15. package/src/ledger-read/command.ts +106 -0
  16. package/src/ledger-read/credentials.ts +103 -0
  17. package/src/ledger-read/files.ts +141 -0
  18. package/src/ledger-read/pull.ts +69 -0
  19. package/src/ledger-read/rows.ts +60 -0
  20. package/src/ledger-read/types.ts +127 -0
  21. package/src/ledger.ts +322 -0
  22. package/src/local.ts +4 -4
  23. package/src/providers/claude-code.ts +1 -1
  24. package/src/providers/codex.ts +5 -5
  25. package/src/providers/index.ts +1 -1
  26. package/src/providers/types.ts +3 -3
  27. package/src/setup/run.ts +27 -10
  28. package/src/sinks/common.ts +3 -3
  29. package/src/spend/report.ts +349 -0
  30. package/src/status/command.ts +151 -37
  31. package/src/store/command.ts +20 -3
  32. package/src/store/html.ts +205 -8
  33. package/src/store/index.ts +64 -5
  34. package/src/store/rows.ts +103 -0
  35. package/src/wizard/interactive.ts +11 -0
  36. package/src/wizard/launcher.ts +340 -0
  37. package/src/wizard/load.ts +30 -0
  38. package/src/wizard/mascot.ts +223 -0
  39. package/src/wizard/prompt-fancy.ts +127 -0
  40. package/src/wizard/prompt.ts +95 -61
  41. package/src/wizard/style.ts +93 -13
  42. package/src/wizard/tone.ts +11 -0
  43. package/src/wizard/ui.ts +78 -0
  44. package/templates/caller-workflow.yml +44 -47
  45. package/templates/wachiman-review-caller.yml +5 -0
@@ -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 ADDED
@@ -0,0 +1,322 @@
1
+ /**
2
+ * The client of the spend ledger service: one synchronous call to reserve before a run, one to
3
+ * settle after it (or to record a run that could not reserve), and the signed receipt that settling
4
+ * returns. Like `gh`, the network goes through a binary the runner has (`curl`), so the engine stays
5
+ * synchronous and dependency-free (ADR 0002). Imports only `node:` builtins.
6
+ *
7
+ * What may leave the machine is fixed by this file: a reserve carries amounts, the trigger and the
8
+ * pull request number; a settle or record carries the amount spent and the calls the engine
9
+ * already prints as `wachiman-cost` lines. No code, no finding text, no title, no credential.
10
+ */
11
+ import { spawnSync } from "node:child_process";
12
+ import { createPublicKey, verify } from "node:crypto";
13
+
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 };
21
+
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 });
28
+ return { status: run.status ?? 1, stdout: run.stdout ?? "", stderr: run.stderr ?? run.error?.message ?? "" };
29
+ };
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
+
40
+ export interface LedgerEnv {
41
+ GITHUB_ACTIONS?: string;
42
+ ACTIONS_ID_TOKEN_REQUEST_URL?: string;
43
+ ACTIONS_ID_TOKEN_REQUEST_TOKEN?: string;
44
+ }
45
+
46
+ /** The ledger cannot answer: a network error, a timeout, a 5xx or a 429. Only these are an outage. */
47
+ export class LedgerUnavailable extends Error {}
48
+
49
+ /**
50
+ * Something answered, but not the way the ledger does: a redirect, a 400, 404 or 405, a 200 whose body
51
+ * is not the documented JSON, a grant that is not a sane amount. That is a wrong `ledger_url` or a
52
+ * broken service, not an outage, so `ledger_unavailable` does not apply: the run stops. The message is
53
+ * ready to show.
54
+ */
55
+ export class LedgerBadAnswer extends Error {}
56
+
57
+ /**
58
+ * The job cannot ask the ledger at all: it holds no OIDC request token. A configuration error that
59
+ * retrying does not fix, so it is not an outage (`ledger_unavailable` does not apply to it).
60
+ */
61
+ export class LedgerNotPermitted extends Error {}
62
+
63
+ export type RefusalReason = "limit" | "weekly_limit" | "repository_limit" | "not_linked" | "unauthorized";
64
+
65
+ export interface Refusal {
66
+ reason: RefusalReason;
67
+ period?: "day" | "week";
68
+ accountSpentUsd?: number;
69
+ accountLimitUsd?: number;
70
+ day?: string;
71
+ week?: string;
72
+ resetsAt?: string;
73
+ }
74
+
75
+ /** The ledger answered and said no. */
76
+ export class LedgerRefused extends Error {
77
+ constructor(readonly refusal: Refusal) {
78
+ super(`The ledger refused the run: ${refusal.reason}.`);
79
+ }
80
+ }
81
+
82
+ export interface Reservation {
83
+ reservationId: string;
84
+ grantedUsd: number;
85
+ accountLeftUsd: number;
86
+ repositoryLeftUsd: number | null;
87
+ day: string;
88
+ week: string;
89
+ weekLeftUsd: number | null;
90
+ }
91
+
92
+ export interface Receipt {
93
+ account: string;
94
+ repository: string;
95
+ run_id: string;
96
+ usd: number;
97
+ day: string;
98
+ }
99
+
100
+ export interface ReserveRequest {
101
+ wantedUsd: number;
102
+ callerLimitUsd?: number;
103
+ callerWeeklyLimitUsd?: number;
104
+ trigger: string;
105
+ forced: boolean;
106
+ pr?: number;
107
+ }
108
+
109
+ /** One model call, with the field names of the `wachiman-cost` line (`ledgerCall` in `cost.ts`). */
110
+ export interface LedgerCall {
111
+ operation: string;
112
+ label: string;
113
+ model: string;
114
+ turns: number;
115
+ duration_ms: number;
116
+ input_tokens: number;
117
+ output_tokens: number;
118
+ cache_read_tokens: number;
119
+ cache_write_tokens: number;
120
+ cost_usd: number | null;
121
+ costKnown: boolean;
122
+ terminal_reason: string;
123
+ auth: string;
124
+ }
125
+
126
+ const b64url = (text: string) => Buffer.from(text, "utf8").toString("base64url");
127
+
128
+ /** The ledger url as configured, minus any trailing slashes, so `${base}/v1/...` has one slash. */
129
+ const base = (ledgerUrl: string) => ledgerUrl.replace(/\/+$/, "");
130
+
131
+ /** Whether an HTTP status means "try later": a server error or a rate limit. Anything else unexpected is not an outage. */
132
+ const isOutage = (status: number) => status >= 500 || status === 429;
133
+
134
+ /** The error for an answer the client cannot use: an outage for 5xx and 429, a wrong-address problem for the rest. */
135
+ function unusable(route: string, status: number, what: string): Error {
136
+ return isOutage(status)
137
+ ? new LedgerUnavailable(`The ledger could not ${what} (HTTP ${status}).`)
138
+ : new LedgerBadAnswer(
139
+ `\`ledger_url\` does not look like the spend ledger: POST ${route} answered HTTP ${status}, not the documented answer. Check that \`ledger_url\` is the ledger's address.`,
140
+ );
141
+ }
142
+
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));
149
+ if (run.status !== 0) throw new LedgerUnavailable(`curl failed (exit ${run.status}): ${run.stderr.trim()}`);
150
+ const cut = run.stdout.lastIndexOf("\n");
151
+ const status = Number(run.stdout.slice(cut + 1).trim());
152
+ if (cut < 0 || !Number.isInteger(status)) throw new LedgerUnavailable("curl returned no HTTP status.");
153
+ return { status, body: run.stdout.slice(0, cut) };
154
+ }
155
+
156
+ const parseObject = (body: string): Record<string, unknown> | undefined => {
157
+ try {
158
+ const value: unknown = JSON.parse(body);
159
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
160
+ } catch {
161
+ return undefined;
162
+ }
163
+ };
164
+
165
+ const post = (ledgerUrl: string, route: string, token: string, payload: unknown, curl: CurlFn) =>
166
+ call(curl, ["-X", "POST", `${base(ledgerUrl)}${route}`], [
167
+ ["header", `Authorization: Bearer ${token}`],
168
+ ["header", "Content-Type: application/json"],
169
+ ["data", JSON.stringify(payload)],
170
+ ]);
171
+
172
+ /**
173
+ * A GitHub OIDC token for `audience`. Needs `id-token: write` in the job, which only
174
+ * `review-platform.yml` grants; without the request variables there is nothing to retry.
175
+ */
176
+ export function requestIdToken(env: LedgerEnv, audience: string, curl: CurlFn): string {
177
+ const url = env.ACTIONS_ID_TOKEN_REQUEST_URL;
178
+ const bearer = env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
179
+ if (!url || !bearer) throw new LedgerNotPermitted("this job has no OIDC token: id-token: write is not granted");
180
+ const { status, body } = call(curl, [`${url}&audience=${encodeURIComponent(audience)}`], [["header", `Authorization: Bearer ${bearer}`]]);
181
+ const value = parseObject(body)?.value;
182
+ if (status !== 200 || typeof value !== "string" || value === "") {
183
+ if (isOutage(status)) throw new LedgerUnavailable(`GitHub did not issue an id token (HTTP ${status}).`);
184
+ throw new LedgerBadAnswer(
185
+ `GitHub did not issue an OIDC token for the ledger (HTTP ${status}). Check that the job has \`id-token: write\` and calls review-platform.yml.`,
186
+ );
187
+ }
188
+ return value;
189
+ }
190
+
191
+ const REASONS: readonly RefusalReason[] = ["limit", "weekly_limit", "repository_limit", "not_linked", "unauthorized"];
192
+ const DEFAULT_REASON: Record<number, RefusalReason> = { 402: "limit", 401: "unauthorized", 403: "not_linked" };
193
+
194
+ /** A refusal from the documented JSON, or from the status alone when the body is something else. */
195
+ function refusalOf(status: number, body: string): Refusal | null {
196
+ const json = parseObject(body) ?? {};
197
+ const reason = REASONS.find((r) => r === json.reason) ?? DEFAULT_REASON[status];
198
+ if (!reason) return null;
199
+ const refusal: Refusal = { reason };
200
+ if (json.period === "day" || json.period === "week") refusal.period = json.period;
201
+ if (typeof json.accountSpentUsd === "number") refusal.accountSpentUsd = json.accountSpentUsd;
202
+ if (typeof json.accountLimitUsd === "number") refusal.accountLimitUsd = json.accountLimitUsd;
203
+ if (typeof json.day === "string") refusal.day = json.day;
204
+ if (typeof json.week === "string") refusal.week = json.week;
205
+ if (typeof json.resetsAt === "string") refusal.resetsAt = json.resetsAt;
206
+ return refusal;
207
+ }
208
+
209
+ export function reserve(ledgerUrl: string, token: string, req: ReserveRequest, curl: CurlFn): Reservation {
210
+ const payload = {
211
+ wantedUsd: req.wantedUsd,
212
+ ...(req.callerLimitUsd === undefined ? {} : { callerLimitUsd: req.callerLimitUsd }),
213
+ ...(req.callerWeeklyLimitUsd === undefined ? {} : { callerWeeklyLimitUsd: req.callerWeeklyLimitUsd }),
214
+ trigger: req.trigger,
215
+ forced: req.forced,
216
+ ...(req.pr === undefined ? {} : { pr: req.pr }),
217
+ };
218
+ const { status, body } = post(ledgerUrl, "/v1/reserve", token, payload, curl);
219
+ if (status >= 400 && status < 500) {
220
+ const refusal = refusalOf(status, body);
221
+ if (refusal) throw new LedgerRefused(refusal);
222
+ }
223
+ const json = parseObject(body);
224
+ if (status !== 200 || !json || typeof json.reservationId !== "string" || typeof json.grantedUsd !== "number") {
225
+ throw unusable("/v1/reserve", status, "reserve");
226
+ }
227
+ // A grant that is not a finite, non-negative amount is a malformed answer: never a budget.
228
+ if (!Number.isFinite(json.grantedUsd) || json.grantedUsd < 0) {
229
+ throw new LedgerBadAnswer(
230
+ `\`ledger_url\` does not look like the spend ledger: POST /v1/reserve granted ${String(json.grantedUsd)}, which is not an amount. Check that \`ledger_url\` is the ledger's address.`,
231
+ );
232
+ }
233
+ return {
234
+ reservationId: json.reservationId,
235
+ grantedUsd: json.grantedUsd,
236
+ accountLeftUsd: Number(json.accountLeftUsd),
237
+ repositoryLeftUsd: typeof json.repositoryLeftUsd === "number" ? json.repositoryLeftUsd : null,
238
+ day: String(json.day),
239
+ week: String(json.week),
240
+ weekLeftUsd: typeof json.weekLeftUsd === "number" ? json.weekLeftUsd : null,
241
+ };
242
+ }
243
+
244
+ export function settle(
245
+ ledgerUrl: string,
246
+ token: string,
247
+ reservationId: string,
248
+ spentUsd: number,
249
+ calls: LedgerCall[],
250
+ curl: CurlFn,
251
+ ): { receipt: Receipt; signature: string } {
252
+ const { status, body } = post(ledgerUrl, "/v1/settle", token, { reservationId, spentUsd, calls }, curl);
253
+ const json = parseObject(body);
254
+ const receipt = json?.receipt;
255
+ if (status !== 200 || !isReceipt(receipt) || typeof json?.signature !== "string") {
256
+ throw unusable("/v1/settle", status, "settle");
257
+ }
258
+ return { receipt, signature: json.signature };
259
+ }
260
+
261
+ /**
262
+ * Records a run that could not reserve because the ledger was unreachable, now that it may be
263
+ * reachable again. Stored apart from reserved runs; idempotent per run on the server.
264
+ */
265
+ export function record(
266
+ ledgerUrl: string,
267
+ token: string,
268
+ run: { spentUsd: number; calls: LedgerCall[]; trigger: string; pr?: number },
269
+ curl: CurlFn,
270
+ ): void {
271
+ const payload = {
272
+ spentUsd: run.spentUsd,
273
+ calls: run.calls,
274
+ trigger: run.trigger,
275
+ ...(run.pr === undefined ? {} : { pr: run.pr }),
276
+ reason: "unreserved",
277
+ };
278
+ const { status } = post(ledgerUrl, "/v1/record", token, payload, curl);
279
+ if (status !== 200) throw unusable("/v1/record", status, "record the run");
280
+ }
281
+
282
+ function isReceipt(value: unknown): value is Receipt {
283
+ const r = value as Record<string, unknown> | null;
284
+ return (
285
+ typeof r === "object" &&
286
+ r !== null &&
287
+ typeof r.account === "string" &&
288
+ typeof r.repository === "string" &&
289
+ typeof r.run_id === "string" &&
290
+ typeof r.usd === "number" &&
291
+ typeof r.day === "string"
292
+ );
293
+ }
294
+
295
+ export const receiptFooter = (receipt: Receipt, signature: string) => `<!-- wachi:receipt ${b64url(JSON.stringify(receipt))}.${signature} -->`;
296
+
297
+ const RECEIPT_LINE = /<!-- wachi:receipt ([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+) -->/g;
298
+
299
+ /** The last receipt line in `body`, or null when there is none or it is damaged. */
300
+ export function readReceipt(body: string): { receipt: Receipt; signature: string } | null {
301
+ const last = [...body.matchAll(RECEIPT_LINE)].pop();
302
+ if (!last) return null;
303
+ try {
304
+ const receipt: unknown = JSON.parse(Buffer.from(last[1]!, "base64url").toString("utf8"));
305
+ return isReceipt(receipt) ? { receipt, signature: last[2]! } : null;
306
+ } catch {
307
+ return null;
308
+ }
309
+ }
310
+
311
+ /** The bytes the ledger signs: JSON with keys in a fixed order (shared contract with the Worker). */
312
+ export const canonicalReceipt = (r: Receipt): Uint8Array =>
313
+ new TextEncoder().encode(JSON.stringify({ account: r.account, repository: r.repository, run_id: r.run_id, usd: r.usd, day: r.day }));
314
+
315
+ /** Whether `signature` (base64url Ed25519) is the ledger's over `receipt`. A bad key or signature is false. */
316
+ export function verifyReceipt(receipt: Receipt, signature: string, publicKeyPem: string): boolean {
317
+ try {
318
+ return verify(null, canonicalReceipt(receipt), createPublicKey(publicKeyPem), Buffer.from(signature, "base64url"));
319
+ } catch {
320
+ return false;
321
+ }
322
+ }
package/src/local.ts CHANGED
@@ -57,7 +57,7 @@ export interface LocalArgs {
57
57
  profile?: string;
58
58
  agentPrompt: boolean;
59
59
  history: boolean;
60
- /** `--verify` forces the verifier on, `--no-verify` off; unset follows `AGENT_REVIEW_VERIFY` (off by default, ADR 0027). */
60
+ /** `--verify` forces the verifier on, `--no-verify` off; unset follows `WACHIMAN_VERIFY` (off by default, ADR 0027). */
61
61
  verify: boolean | undefined;
62
62
  /** `--result-version`: with `--format json`, which result version to write (default 1 for a committed change). */
63
63
  resultVersion?: 1 | 2;
@@ -297,7 +297,7 @@ export function openLocalSession(p: {
297
297
  const { env, repoDir, deps } = p;
298
298
  const loaded = loadConfig(env, p.stderr);
299
299
  if (loaded.provider !== "claude-code") {
300
- throw new UsageError(`AGENT_REVIEW_PROVIDER=${loaded.provider}: the local review runs only on Claude Code, your signed-in \`claude\`.`);
300
+ throw new UsageError(`WACHIMAN_PROVIDER=${loaded.provider}: the local review runs only on Claude Code, your signed-in \`claude\`.`);
301
301
  }
302
302
  // A person ran it: no automatic ceiling (decision 14).
303
303
  const config = {
@@ -441,7 +441,7 @@ export function localScopeInput(p: {
441
441
  */
442
442
  export function sizeWarning(estimate: ReviewEstimate, gate: number, budgetUsd: number, model: string): string | null {
443
443
  if (estimate.usd <= gate) return null;
444
- 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)} (AGENT_REVIEW_BUDGET_USD).`;
444
+ 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
445
  }
446
446
 
447
447
  export function runLocal(
@@ -460,7 +460,7 @@ export function runLocal(
460
460
  throw new UsageError("Working-tree reviews require --result-version 2; a tree is not a commit.");
461
461
  }
462
462
  // Off unless asked for (ADR 0020): without this, nothing below touches ~/.wachiman/history.
463
- // A bad AGENT_REVIEW_HISTORY_DAYS stops here, before any call is paid for.
463
+ // A bad WACHIMAN_HISTORY_DAYS stops here, before any call is paid for.
464
464
  const history = historySettings(env, args.history);
465
465
  const home = wachimanHome(env);
466
466
  const { config, profile, profileNote, provider, verifier, state } = openLocalSession({
@@ -355,7 +355,7 @@ export class ClaudeCodeProvider implements ProviderAdapter {
355
355
  // The session starts in an empty scratch directory, never in the head: Claude Code discovers
356
356
  // `CLAUDE.md` (and `.claude/`) from its working directory and its parents, and a pull request
357
357
  // must not supply instructions. The head is only an `--add-dir`, which does not load them.
358
- const workDir = mkdtempSync(join(tmpdir(), "agent-review-claude-"));
358
+ const workDir = mkdtempSync(join(tmpdir(), "wachiman-review-claude-"));
359
359
  const prompt = locatePrompt(request.prompt, request.cwd, request.addDirs, { shell: false });
360
360
  const args = buildClaudeArgs({
361
361
  addDirs: [request.cwd, ...request.addDirs],
@@ -81,7 +81,7 @@ export const CACHE_WRITE_MULTIPLIER = 2.5
81
81
 
82
82
  /**
83
83
  * List prices of the models this adapter has been set up for. A model not listed here needs
84
- * `AGENT_REVIEW_PRICE_PER_MTOK`: the engine's budgets are in dollars, and Codex reports tokens.
84
+ * `WACHIMAN_PRICE_PER_MTOK`: the engine's budgets are in dollars, and Codex reports tokens.
85
85
  */
86
86
  export const PRICES: Record<string, Price> = {
87
87
  "gpt-6.1-sol": { input: 2, cachedInput: 0.1, output: 10, cacheWrite: 5 },
@@ -93,7 +93,7 @@ export function parsePrice(raw: string): Price {
93
93
  const parts = raw.split(",").map((p) => Number(p.trim()));
94
94
  if (parts.length < 3 || parts.length > 4 || parts.some((n) => !Number.isFinite(n) || n < 0)) {
95
95
  throw new Error(
96
- `AGENT_REVIEW_PRICE_PER_MTOK must be "input,cached_input,output[,cache_write]" in USD per million tokens, got "${raw}".`,
96
+ `WACHIMAN_PRICE_PER_MTOK must be "input,cached_input,output[,cache_write]" in USD per million tokens, got "${raw}".`,
97
97
  );
98
98
  }
99
99
  return { input: parts[0], cachedInput: parts[1], output: parts[2], ...(parts.length === 4 ? { cacheWrite: parts[3] } : {}) };
@@ -270,7 +270,7 @@ export class CodexProvider implements ProviderAdapter {
270
270
  private readonly opts: {
271
271
  model: string;
272
272
  requireApiKey: boolean;
273
- /** `AGENT_REVIEW_PRICE_PER_MTOK`, for a model not in `PRICES`. */
273
+ /** `WACHIMAN_PRICE_PER_MTOK`, for a model not in `PRICES`. */
274
274
  priceOverride?: string;
275
275
  reasoningEffort?: string;
276
276
  /**
@@ -292,7 +292,7 @@ export class CodexProvider implements ProviderAdapter {
292
292
  preflight() {
293
293
  if (!this.price) {
294
294
  throw new Error(
295
- `No price is known for model "${this.opts.model}". Set AGENT_REVIEW_PRICE_PER_MTOK="input,cached_input,output[,cache_write]" (USD per million tokens).`,
295
+ `No price is known for model "${this.opts.model}". Set WACHIMAN_PRICE_PER_MTOK="input,cached_input,output[,cache_write]" (USD per million tokens).`,
296
296
  );
297
297
  }
298
298
  const probe = spawnSync(this.binary, ["--version"], { encoding: "utf8", env: { PATH: process.env.PATH ?? "" } });
@@ -314,7 +314,7 @@ export class CodexProvider implements ProviderAdapter {
314
314
  run(request: ProviderRequest): ProviderResult {
315
315
  const unknown = request.allowedTools.filter((t) => !READ_TOOLS.includes(t));
316
316
  if (unknown.length > 0) throw new Error(`The Codex adapter only grants reads; asked for ${unknown.join(", ")}.`);
317
- const scratch = mkdtempSync(join(tmpdir(), "agent-review-codex-"));
317
+ const scratch = mkdtempSync(join(tmpdir(), "wachiman-review-codex-"));
318
318
  try {
319
319
  const workDir = join(scratch, "work");
320
320
  const home = join(scratch, "home");
@@ -7,7 +7,7 @@ export type { NeutralTool, ProviderAdapter, ProviderRequest, ProviderResult } fr
7
7
  export const PROVIDER_NAMES = ["claude-code", "codex"] as const;
8
8
  export const DEFAULT_PROVIDER = "claude-code";
9
9
 
10
- /** The model each provider uses when `AGENT_REVIEW_MODEL` is not set. */
10
+ /** The model each provider uses when `WACHIMAN_MODEL` is not set. */
11
11
  export const DEFAULT_MODELS: Record<(typeof PROVIDER_NAMES)[number], string> = {
12
12
  "claude-code": "claude-sonnet-5-5",
13
13
  codex: "gpt-6.1-sol",
@@ -24,12 +24,12 @@ export type Effort = (typeof EFFORTS)[number];
24
24
  export const DEFAULT_EFFORT: Effort = "high";
25
25
 
26
26
  /**
27
- * Default cap on the agent's turns per call (`AGENT_REVIEW_MAX_TURNS`). Wachiman's batches take
27
+ * Default cap on the agent's turns per call (`WACHIMAN_MAX_TURNS`). Wachiman's batches take
28
28
  * 5–12 turns and an external agent's whole-PR reviews took 19–46, so 40 never cuts a normal batch;
29
29
  * it only stops a run that is looping.
30
30
  */
31
31
  export const DEFAULT_MAX_TURNS = 40;
32
- /** Default wall-clock limit on one provider call, in seconds (`AGENT_REVIEW_CALL_TIMEOUT_S`). */
32
+ /** Default wall-clock limit on one provider call, in seconds (`WACHIMAN_CALL_TIMEOUT_S`). */
33
33
  export const DEFAULT_CALL_TIMEOUT_S = 900;
34
34
 
35
35
  /** Tool names the engine may ask for. Each adapter maps them to its own names. */
@@ -108,7 +108,7 @@ export interface ProviderResult {
108
108
  export type ProviderAuth = "api-key" | "oauth-token" | "subscription";
109
109
 
110
110
  export interface ProviderAdapter {
111
- /** The value of `AGENT_REVIEW_PROVIDER` that selects it. */
111
+ /** The value of `WACHIMAN_PROVIDER` that selects it. */
112
112
  readonly name: string;
113
113
  /** What pays for the calls. Absent means `api-key`. */
114
114
  readonly auth?: ProviderAuth;