wachiman 1.12.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 +132 -101
- package/bin/wachiman.js +1 -1
- package/package.json +2 -3
- package/skills/wachiman-loop/SKILL.md +91 -0
- package/skills/wachiman-review/SKILL.md +2 -2
- package/src/call-message.ts +26 -3
- package/src/cli.ts +113 -18
- package/src/config.ts +99 -32
- package/src/connectors/local-git.ts +102 -14
- package/src/cost.ts +48 -1
- package/src/doctor/checks.ts +1 -1
- package/src/engine.ts +910 -89
- package/src/estimate.ts +64 -0
- package/src/fidelity/block.ts +263 -0
- package/src/fidelity/claims-call.ts +172 -0
- package/src/fidelity/claims.ts +69 -0
- package/src/fidelity/digest.ts +80 -0
- package/src/fidelity/grade.ts +242 -0
- package/src/fidelity/inert.ts +25 -0
- package/src/fidelity/rules.ts +166 -0
- package/src/fidelity/sink.ts +135 -0
- package/src/fidelity/summary.ts +16 -0
- package/src/fidelity/types.ts +93 -0
- package/src/formats.ts +16 -3
- package/src/history/fingerprint.ts +1 -1
- package/src/history/store.ts +44 -6
- package/src/init/options.ts +1 -1
- package/src/ledger.ts +306 -0
- package/src/local.ts +23 -5
- package/src/loop/command.ts +441 -0
- package/src/loop/state.ts +88 -0
- package/src/loop/stop-rule.ts +98 -0
- package/src/providers/claude-code.ts +48 -13
- package/src/providers/codex.ts +8 -7
- package/src/providers/index.ts +6 -3
- package/src/providers/types.ts +13 -3
- package/src/sinks/common.ts +3 -3
- package/src/sinks/json.ts +13 -2
- package/src/skills/install.ts +4 -4
- package/src/status/command.ts +1 -1
- package/src/store/command.ts +109 -0
- package/src/store/figures.ts +153 -0
- package/src/store/html.ts +138 -0
- package/src/store/index.ts +298 -0
- package/templates/caller-workflow.yml +84 -57
- package/templates/wachiman-review-caller.yml +13 -0
package/src/formats.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import { UsageError } from "./config";
|
|
9
9
|
import type { Contract } from "./contracts";
|
|
10
10
|
import type { TokenUsage } from "./cost";
|
|
11
|
+
import type { Fidelity } from "./fidelity/types";
|
|
11
12
|
import type {
|
|
12
13
|
BaseInstructions,
|
|
13
14
|
BatchReport,
|
|
@@ -65,9 +66,11 @@ export interface ReviewInput {
|
|
|
65
66
|
scope: string[];
|
|
66
67
|
/**
|
|
67
68
|
* Incremental context: the last reviewed commit, whether the change was rebased since, and
|
|
68
|
-
* (optional) the commits since it, oldest first, for the report's headline.
|
|
69
|
+
* (optional) the commits since it, oldest first, for the report's headline. `carried` names
|
|
70
|
+
* the files of `files` that the previous review did not reach: they carry their whole diff, not
|
|
71
|
+
* only what changed since, and are reviewed whole.
|
|
69
72
|
*/
|
|
70
|
-
since?: { sha: string; rebased: boolean; commits?: string[] };
|
|
73
|
+
since?: { sha: string; rebased: boolean; commits?: string[]; carried?: string[] };
|
|
71
74
|
/** Open threads for the model to answer. */
|
|
72
75
|
conversation?: Thread[];
|
|
73
76
|
}
|
|
@@ -181,6 +184,11 @@ export interface VerifiedFields {
|
|
|
181
184
|
export interface ResultFindingV2 extends Finding, VerifiedFields {
|
|
182
185
|
/** Whether the line is one a diff-anchored comment can target (`commentableLines`). */
|
|
183
186
|
anchor: "diff" | "outside";
|
|
187
|
+
/**
|
|
188
|
+
* The finding's history id, the one `wachiman history --verdict` takes (ADR 0034). Only a
|
|
189
|
+
* `local` JSON `/2` written with history on carries it; the core never sets it.
|
|
190
|
+
*/
|
|
191
|
+
id?: string;
|
|
184
192
|
}
|
|
185
193
|
|
|
186
194
|
export interface VerificationEntryV2 {
|
|
@@ -247,6 +255,11 @@ export interface ReviewResultV2 {
|
|
|
247
255
|
summary: string;
|
|
248
256
|
/** The risk map (ADR 0031). Only `/2` has it: `toResultV1` leaves it out. */
|
|
249
257
|
riskMap?: RiskMap;
|
|
258
|
+
/**
|
|
259
|
+
* PR Confidence (ADR 0033): the claims, the unexplained files and the grade. Only the `/2` result
|
|
260
|
+
* of a GitHub pull request review has it; a local review never does, and `toResultV1` leaves it out.
|
|
261
|
+
*/
|
|
262
|
+
fidelity?: Fidelity;
|
|
250
263
|
batches: BatchReport[];
|
|
251
264
|
threadReplies: ReviewOutput["thread_replies"];
|
|
252
265
|
instructionChanges: { files: string[]; baseSha: string };
|
|
@@ -309,7 +322,7 @@ export function toResultV1(result: ReviewResultV2): ReviewResultV1 {
|
|
|
309
322
|
throw new UsageError("A working-tree review has no result /1: its head is a tree id, not a commit. Use --result-version 2.");
|
|
310
323
|
}
|
|
311
324
|
const { account: _account, ...provider } = result.provider;
|
|
312
|
-
const { verification, riskMap: _riskMap, ...rest } = result;
|
|
325
|
+
const { verification, riskMap: _riskMap, fidelity: _fidelity, ...rest } = result;
|
|
313
326
|
return {
|
|
314
327
|
...rest,
|
|
315
328
|
format: REVIEW_RESULT_V1,
|
|
@@ -11,7 +11,7 @@ const sha256 = (text: string) => createHash("sha256").update(text).digest("hex")
|
|
|
11
11
|
export const stripWhitespace = (s: string) => s.replace(/\s+/g, "");
|
|
12
12
|
|
|
13
13
|
/** A cited line shorter than this, once stripped, is too common to identify anything. */
|
|
14
|
-
const MIN_LINE_CHARS = 8;
|
|
14
|
+
export const MIN_LINE_CHARS = 8;
|
|
15
15
|
|
|
16
16
|
/** The title lowercased, backticks and punctuation removed, every digit run a `#`, whitespace collapsed. */
|
|
17
17
|
export function titleKey(title: string): string {
|
package/src/history/store.ts
CHANGED
|
@@ -44,16 +44,16 @@ export interface HistorySettings {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
/**
|
|
47
|
-
* Whether the history is on (`--history` or `
|
|
47
|
+
* Whether the history is on (`--history` or `WACHIMAN_HISTORY=1`) and how long it is kept.
|
|
48
48
|
* Read here, not in `loadConfig`: that one rejects `0`, and GitHub mode must not see the variable.
|
|
49
|
-
* A bad `
|
|
49
|
+
* A bad `WACHIMAN_HISTORY_DAYS` is checked only when the history is on.
|
|
50
50
|
*/
|
|
51
51
|
export function historySettings(env: Record<string, string | undefined>, flag: boolean): HistorySettings {
|
|
52
|
-
const enabled = flag || env.
|
|
53
|
-
const raw = env.
|
|
52
|
+
const enabled = flag || env.WACHIMAN_HISTORY === "1";
|
|
53
|
+
const raw = env.WACHIMAN_HISTORY_DAYS;
|
|
54
54
|
if (!enabled || raw === undefined || raw === "") return { enabled, days: DEFAULT_HISTORY_DAYS };
|
|
55
55
|
if (!/^\d+$/.test(raw)) {
|
|
56
|
-
throw new UsageError(`
|
|
56
|
+
throw new UsageError(`WACHIMAN_HISTORY_DAYS must be 0 (keep forever) or a whole number of days, got "${raw}".`);
|
|
57
57
|
}
|
|
58
58
|
return { enabled, days: Number(raw) };
|
|
59
59
|
}
|
|
@@ -208,7 +208,7 @@ function parseRun(path: string): HistoryRun {
|
|
|
208
208
|
return parsed as HistoryRun;
|
|
209
209
|
}
|
|
210
210
|
|
|
211
|
-
const runFiles = (root: string, key: string) => {
|
|
211
|
+
export const runFiles = (root: string, key: string) => {
|
|
212
212
|
const dir = runsDir(root, key);
|
|
213
213
|
if (!existsSync(dir)) return [];
|
|
214
214
|
return readdirSync(dir)
|
|
@@ -316,6 +316,44 @@ export function readVerdicts(root: string, key: string): Map<string, VerdictLine
|
|
|
316
316
|
return out;
|
|
317
317
|
}
|
|
318
318
|
|
|
319
|
+
/**
|
|
320
|
+
* One file per branch under `<root>/<repo-key>/loops/` for `wachiman loop` (ADR 0034): the loop's
|
|
321
|
+
* state lives beside the runs it reads, so `history --forget` removes both. The branch name is only
|
|
322
|
+
* a label in the file name; the hash keeps two names that sanitise alike apart.
|
|
323
|
+
*/
|
|
324
|
+
const loopPath = (root: string, key: string, branch: string) =>
|
|
325
|
+
join(keyDir(root, key), "loops", `${safeName(branch)}-${sha256(branch).slice(0, 8)}.json`);
|
|
326
|
+
|
|
327
|
+
/** Every loop state file of a repository, in name order: what the local index replays. */
|
|
328
|
+
export function loopFiles(root: string, key: string): string[] {
|
|
329
|
+
const dir = join(keyDir(root, key), "loops");
|
|
330
|
+
if (!existsSync(dir)) return [];
|
|
331
|
+
return readdirSync(dir)
|
|
332
|
+
.filter((n) => n.endsWith(".json"))
|
|
333
|
+
.sort()
|
|
334
|
+
.map((n) => join(dir, n));
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** The stored loop state of a branch as parsed JSON, or undefined when there is none. A file that is not JSON is an error naming it. */
|
|
338
|
+
export function readLoopFile(root: string, key: string, branch: string): unknown | undefined {
|
|
339
|
+
const path = loopPath(root, key, branch);
|
|
340
|
+
if (!existsSync(path)) return undefined;
|
|
341
|
+
try {
|
|
342
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
343
|
+
} catch (error) {
|
|
344
|
+
throw new UsageError(`${path} is not a loop state file (${error instanceof Error ? error.message : error}); remove it to start the loop again.`);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export function writeLoopFile(root: string, key: string, branch: string, state: unknown): string {
|
|
349
|
+
ensureKeyDirs(root, key);
|
|
350
|
+
privateDirs(join(keyDir(root, key), "loops"));
|
|
351
|
+
chmodSync(join(keyDir(root, key), "loops"), 0o700);
|
|
352
|
+
const path = loopPath(root, key, branch);
|
|
353
|
+
writeAtomic(path, `${JSON.stringify(state, null, 2)}\n`);
|
|
354
|
+
return path;
|
|
355
|
+
}
|
|
356
|
+
|
|
319
357
|
/** Removes one repository's history, or all of it; returns what was removed. Never leaves `root`. */
|
|
320
358
|
export function forget(root: string, key?: string): string[] {
|
|
321
359
|
const target = key === undefined ? root : keyDir(root, key);
|
package/src/init/options.ts
CHANGED
|
@@ -34,7 +34,7 @@ export type ResolveResult<T> = { ok: true; options: T } | { ok: false; error: st
|
|
|
34
34
|
* docs/releasing.md); the CLI's own version is never a substitute,
|
|
35
35
|
* because an unreleased or unrelated version would pin a workflow that does not exist.
|
|
36
36
|
*/
|
|
37
|
-
export const DEFAULT_WORKFLOW_REF: string | undefined = "v1.
|
|
37
|
+
export const DEFAULT_WORKFLOW_REF: string | undefined = "v1.14.0"; // x-release-please-version
|
|
38
38
|
|
|
39
39
|
export const DEFAULT_WORKFLOW_PATH = ".github/workflows/wachiman-review.yml";
|
|
40
40
|
const WORKFLOWS_DIR = ".github/workflows/";
|
package/src/ledger.ts
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
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
|
+
/** `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 };
|
|
16
|
+
|
|
17
|
+
export const defaultCurl: CurlFn = (args) => {
|
|
18
|
+
const run = spawnSync("curl", ["--silent", "--show-error", "--max-time", "20", ...args], { encoding: "utf8" });
|
|
19
|
+
return { status: run.status ?? 1, stdout: run.stdout ?? "", stderr: run.stderr ?? run.error?.message ?? "" };
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export interface LedgerEnv {
|
|
23
|
+
ACTIONS_ID_TOKEN_REQUEST_URL?: string;
|
|
24
|
+
ACTIONS_ID_TOKEN_REQUEST_TOKEN?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The ledger cannot answer: a network error, a timeout, a 5xx or a 429. Only these are an outage. */
|
|
28
|
+
export class LedgerUnavailable extends Error {}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Something answered, but not the way the ledger does: a redirect, a 400, 404 or 405, a 200 whose body
|
|
32
|
+
* is not the documented JSON, a grant that is not a sane amount. That is a wrong `ledger_url` or a
|
|
33
|
+
* broken service, not an outage, so `ledger_unavailable` does not apply: the run stops. The message is
|
|
34
|
+
* ready to show.
|
|
35
|
+
*/
|
|
36
|
+
export class LedgerBadAnswer extends Error {}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The job cannot ask the ledger at all: it holds no OIDC request token. A configuration error that
|
|
40
|
+
* retrying does not fix, so it is not an outage (`ledger_unavailable` does not apply to it).
|
|
41
|
+
*/
|
|
42
|
+
export class LedgerNotPermitted extends Error {}
|
|
43
|
+
|
|
44
|
+
export type RefusalReason = "limit" | "weekly_limit" | "repository_limit" | "not_linked" | "unauthorized";
|
|
45
|
+
|
|
46
|
+
export interface Refusal {
|
|
47
|
+
reason: RefusalReason;
|
|
48
|
+
period?: "day" | "week";
|
|
49
|
+
accountSpentUsd?: number;
|
|
50
|
+
accountLimitUsd?: number;
|
|
51
|
+
day?: string;
|
|
52
|
+
week?: string;
|
|
53
|
+
resetsAt?: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The ledger answered and said no. */
|
|
57
|
+
export class LedgerRefused extends Error {
|
|
58
|
+
constructor(readonly refusal: Refusal) {
|
|
59
|
+
super(`The ledger refused the run: ${refusal.reason}.`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface Reservation {
|
|
64
|
+
reservationId: string;
|
|
65
|
+
grantedUsd: number;
|
|
66
|
+
accountLeftUsd: number;
|
|
67
|
+
repositoryLeftUsd: number | null;
|
|
68
|
+
day: string;
|
|
69
|
+
week: string;
|
|
70
|
+
weekLeftUsd: number | null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface Receipt {
|
|
74
|
+
account: string;
|
|
75
|
+
repository: string;
|
|
76
|
+
run_id: string;
|
|
77
|
+
usd: number;
|
|
78
|
+
day: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface ReserveRequest {
|
|
82
|
+
wantedUsd: number;
|
|
83
|
+
callerLimitUsd?: number;
|
|
84
|
+
callerWeeklyLimitUsd?: number;
|
|
85
|
+
trigger: string;
|
|
86
|
+
forced: boolean;
|
|
87
|
+
pr?: number;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** One model call, with the field names of the `wachiman-cost` line (`ledgerCall` in `cost.ts`). */
|
|
91
|
+
export interface LedgerCall {
|
|
92
|
+
operation: string;
|
|
93
|
+
label: string;
|
|
94
|
+
model: string;
|
|
95
|
+
turns: number;
|
|
96
|
+
duration_ms: number;
|
|
97
|
+
input_tokens: number;
|
|
98
|
+
output_tokens: number;
|
|
99
|
+
cache_read_tokens: number;
|
|
100
|
+
cache_write_tokens: number;
|
|
101
|
+
cost_usd: number | null;
|
|
102
|
+
costKnown: boolean;
|
|
103
|
+
terminal_reason: string;
|
|
104
|
+
auth: string;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const b64url = (text: string) => Buffer.from(text, "utf8").toString("base64url");
|
|
108
|
+
|
|
109
|
+
/** The ledger url as configured, minus any trailing slashes, so `${base}/v1/...` has one slash. */
|
|
110
|
+
const base = (ledgerUrl: string) => ledgerUrl.replace(/\/+$/, "");
|
|
111
|
+
|
|
112
|
+
/** Whether an HTTP status means "try later": a server error or a rate limit. Anything else unexpected is not an outage. */
|
|
113
|
+
const isOutage = (status: number) => status >= 500 || status === 429;
|
|
114
|
+
|
|
115
|
+
/** The error for an answer the client cannot use: an outage for 5xx and 429, a wrong-address problem for the rest. */
|
|
116
|
+
function unusable(route: string, status: number, what: string): Error {
|
|
117
|
+
return isOutage(status)
|
|
118
|
+
? new LedgerUnavailable(`The ledger could not ${what} (HTTP ${status}).`)
|
|
119
|
+
: new LedgerBadAnswer(
|
|
120
|
+
`\`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.`,
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
|
|
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]);
|
|
127
|
+
if (run.status !== 0) throw new LedgerUnavailable(`curl failed (exit ${run.status}): ${run.stderr.trim()}`);
|
|
128
|
+
const cut = run.stdout.lastIndexOf("\n");
|
|
129
|
+
const status = Number(run.stdout.slice(cut + 1).trim());
|
|
130
|
+
if (cut < 0 || !Number.isInteger(status)) throw new LedgerUnavailable("curl returned no HTTP status.");
|
|
131
|
+
return { status, body: run.stdout.slice(0, cut) };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const parseObject = (body: string): Record<string, unknown> | undefined => {
|
|
135
|
+
try {
|
|
136
|
+
const value: unknown = JSON.parse(body);
|
|
137
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
|
138
|
+
} catch {
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
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}`,
|
|
154
|
+
]);
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* A GitHub OIDC token for `audience`. Needs `id-token: write` in the job, which only
|
|
158
|
+
* `review-platform.yml` grants; without the request variables there is nothing to retry.
|
|
159
|
+
*/
|
|
160
|
+
export function requestIdToken(env: LedgerEnv, audience: string, curl: CurlFn): string {
|
|
161
|
+
const url = env.ACTIONS_ID_TOKEN_REQUEST_URL;
|
|
162
|
+
const bearer = env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
|
|
163
|
+
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)}`]);
|
|
165
|
+
const value = parseObject(body)?.value;
|
|
166
|
+
if (status !== 200 || typeof value !== "string" || value === "") {
|
|
167
|
+
if (isOutage(status)) throw new LedgerUnavailable(`GitHub did not issue an id token (HTTP ${status}).`);
|
|
168
|
+
throw new LedgerBadAnswer(
|
|
169
|
+
`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.`,
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
return value;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const REASONS: readonly RefusalReason[] = ["limit", "weekly_limit", "repository_limit", "not_linked", "unauthorized"];
|
|
176
|
+
const DEFAULT_REASON: Record<number, RefusalReason> = { 402: "limit", 401: "unauthorized", 403: "not_linked" };
|
|
177
|
+
|
|
178
|
+
/** A refusal from the documented JSON, or from the status alone when the body is something else. */
|
|
179
|
+
function refusalOf(status: number, body: string): Refusal | null {
|
|
180
|
+
const json = parseObject(body) ?? {};
|
|
181
|
+
const reason = REASONS.find((r) => r === json.reason) ?? DEFAULT_REASON[status];
|
|
182
|
+
if (!reason) return null;
|
|
183
|
+
const refusal: Refusal = { reason };
|
|
184
|
+
if (json.period === "day" || json.period === "week") refusal.period = json.period;
|
|
185
|
+
if (typeof json.accountSpentUsd === "number") refusal.accountSpentUsd = json.accountSpentUsd;
|
|
186
|
+
if (typeof json.accountLimitUsd === "number") refusal.accountLimitUsd = json.accountLimitUsd;
|
|
187
|
+
if (typeof json.day === "string") refusal.day = json.day;
|
|
188
|
+
if (typeof json.week === "string") refusal.week = json.week;
|
|
189
|
+
if (typeof json.resetsAt === "string") refusal.resetsAt = json.resetsAt;
|
|
190
|
+
return refusal;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function reserve(ledgerUrl: string, token: string, req: ReserveRequest, curl: CurlFn): Reservation {
|
|
194
|
+
const payload = {
|
|
195
|
+
wantedUsd: req.wantedUsd,
|
|
196
|
+
...(req.callerLimitUsd === undefined ? {} : { callerLimitUsd: req.callerLimitUsd }),
|
|
197
|
+
...(req.callerWeeklyLimitUsd === undefined ? {} : { callerWeeklyLimitUsd: req.callerWeeklyLimitUsd }),
|
|
198
|
+
trigger: req.trigger,
|
|
199
|
+
forced: req.forced,
|
|
200
|
+
...(req.pr === undefined ? {} : { pr: req.pr }),
|
|
201
|
+
};
|
|
202
|
+
const { status, body } = post(ledgerUrl, "/v1/reserve", token, payload, curl);
|
|
203
|
+
if (status >= 400 && status < 500) {
|
|
204
|
+
const refusal = refusalOf(status, body);
|
|
205
|
+
if (refusal) throw new LedgerRefused(refusal);
|
|
206
|
+
}
|
|
207
|
+
const json = parseObject(body);
|
|
208
|
+
if (status !== 200 || !json || typeof json.reservationId !== "string" || typeof json.grantedUsd !== "number") {
|
|
209
|
+
throw unusable("/v1/reserve", status, "reserve");
|
|
210
|
+
}
|
|
211
|
+
// A grant that is not a finite, non-negative amount is a malformed answer: never a budget.
|
|
212
|
+
if (!Number.isFinite(json.grantedUsd) || json.grantedUsd < 0) {
|
|
213
|
+
throw new LedgerBadAnswer(
|
|
214
|
+
`\`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.`,
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
return {
|
|
218
|
+
reservationId: json.reservationId,
|
|
219
|
+
grantedUsd: json.grantedUsd,
|
|
220
|
+
accountLeftUsd: Number(json.accountLeftUsd),
|
|
221
|
+
repositoryLeftUsd: typeof json.repositoryLeftUsd === "number" ? json.repositoryLeftUsd : null,
|
|
222
|
+
day: String(json.day),
|
|
223
|
+
week: String(json.week),
|
|
224
|
+
weekLeftUsd: typeof json.weekLeftUsd === "number" ? json.weekLeftUsd : null,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export function settle(
|
|
229
|
+
ledgerUrl: string,
|
|
230
|
+
token: string,
|
|
231
|
+
reservationId: string,
|
|
232
|
+
spentUsd: number,
|
|
233
|
+
calls: LedgerCall[],
|
|
234
|
+
curl: CurlFn,
|
|
235
|
+
): { receipt: Receipt; signature: string } {
|
|
236
|
+
const { status, body } = post(ledgerUrl, "/v1/settle", token, { reservationId, spentUsd, calls }, curl);
|
|
237
|
+
const json = parseObject(body);
|
|
238
|
+
const receipt = json?.receipt;
|
|
239
|
+
if (status !== 200 || !isReceipt(receipt) || typeof json?.signature !== "string") {
|
|
240
|
+
throw unusable("/v1/settle", status, "settle");
|
|
241
|
+
}
|
|
242
|
+
return { receipt, signature: json.signature };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Records a run that could not reserve because the ledger was unreachable, now that it may be
|
|
247
|
+
* reachable again. Stored apart from reserved runs; idempotent per run on the server.
|
|
248
|
+
*/
|
|
249
|
+
export function record(
|
|
250
|
+
ledgerUrl: string,
|
|
251
|
+
token: string,
|
|
252
|
+
run: { spentUsd: number; calls: LedgerCall[]; trigger: string; pr?: number },
|
|
253
|
+
curl: CurlFn,
|
|
254
|
+
): void {
|
|
255
|
+
const payload = {
|
|
256
|
+
spentUsd: run.spentUsd,
|
|
257
|
+
calls: run.calls,
|
|
258
|
+
trigger: run.trigger,
|
|
259
|
+
...(run.pr === undefined ? {} : { pr: run.pr }),
|
|
260
|
+
reason: "unreserved",
|
|
261
|
+
};
|
|
262
|
+
const { status } = post(ledgerUrl, "/v1/record", token, payload, curl);
|
|
263
|
+
if (status !== 200) throw unusable("/v1/record", status, "record the run");
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function isReceipt(value: unknown): value is Receipt {
|
|
267
|
+
const r = value as Record<string, unknown> | null;
|
|
268
|
+
return (
|
|
269
|
+
typeof r === "object" &&
|
|
270
|
+
r !== null &&
|
|
271
|
+
typeof r.account === "string" &&
|
|
272
|
+
typeof r.repository === "string" &&
|
|
273
|
+
typeof r.run_id === "string" &&
|
|
274
|
+
typeof r.usd === "number" &&
|
|
275
|
+
typeof r.day === "string"
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export const receiptFooter = (receipt: Receipt, signature: string) => `<!-- wachi:receipt ${b64url(JSON.stringify(receipt))}.${signature} -->`;
|
|
280
|
+
|
|
281
|
+
const RECEIPT_LINE = /<!-- wachi:receipt ([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+) -->/g;
|
|
282
|
+
|
|
283
|
+
/** The last receipt line in `body`, or null when there is none or it is damaged. */
|
|
284
|
+
export function readReceipt(body: string): { receipt: Receipt; signature: string } | null {
|
|
285
|
+
const last = [...body.matchAll(RECEIPT_LINE)].pop();
|
|
286
|
+
if (!last) return null;
|
|
287
|
+
try {
|
|
288
|
+
const receipt: unknown = JSON.parse(Buffer.from(last[1]!, "base64url").toString("utf8"));
|
|
289
|
+
return isReceipt(receipt) ? { receipt, signature: last[2]! } : null;
|
|
290
|
+
} catch {
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** The bytes the ledger signs: JSON with keys in a fixed order (shared contract with the Worker). */
|
|
296
|
+
export const canonicalReceipt = (r: Receipt): Uint8Array =>
|
|
297
|
+
new TextEncoder().encode(JSON.stringify({ account: r.account, repository: r.repository, run_id: r.run_id, usd: r.usd, day: r.day }));
|
|
298
|
+
|
|
299
|
+
/** Whether `signature` (base64url Ed25519) is the ledger's over `receipt`. A bad key or signature is false. */
|
|
300
|
+
export function verifyReceipt(receipt: Receipt, signature: string, publicKeyPem: string): boolean {
|
|
301
|
+
try {
|
|
302
|
+
return verify(null, canonicalReceipt(receipt), createPublicKey(publicKeyPem), Buffer.from(signature, "base64url"));
|
|
303
|
+
} catch {
|
|
304
|
+
return false;
|
|
305
|
+
}
|
|
306
|
+
}
|
package/src/local.ts
CHANGED
|
@@ -23,7 +23,8 @@ import {
|
|
|
23
23
|
snapshotHead,
|
|
24
24
|
warnSnapshotDifferences,
|
|
25
25
|
} from "./connectors/local-git";
|
|
26
|
-
import { DEFAULT_EXCLUDE, filterFiles, planBatches, reviewChange, reviewOptionsOf, type ReviewInput, type ReviewResult } from "./engine";
|
|
26
|
+
import { DEFAULT_EXCLUDE, estimateFor, filterFiles, planBatches, reviewChange, reviewOptionsOf, type ReviewInput, type ReviewResult } from "./engine";
|
|
27
|
+
import { sizeGate, type ReviewEstimate } from "./estimate";
|
|
27
28
|
import { spawnGit } from "./evidence";
|
|
28
29
|
import { assertReviewInputFormat, REVIEW_INPUT_V2 } from "./formats";
|
|
29
30
|
import { workingTreeInput, snapshotWorkingTree } from "./connectors/working-tree";
|
|
@@ -56,7 +57,7 @@ export interface LocalArgs {
|
|
|
56
57
|
profile?: string;
|
|
57
58
|
agentPrompt: boolean;
|
|
58
59
|
history: boolean;
|
|
59
|
-
/** `--verify` forces the verifier on, `--no-verify` off; unset follows `
|
|
60
|
+
/** `--verify` forces the verifier on, `--no-verify` off; unset follows `WACHIMAN_VERIFY` (off by default, ADR 0027). */
|
|
60
61
|
verify: boolean | undefined;
|
|
61
62
|
/** `--result-version`: with `--format json`, which result version to write (default 1 for a committed change). */
|
|
62
63
|
resultVersion?: 1 | 2;
|
|
@@ -243,6 +244,7 @@ export function exitCodeOf(result: ReviewResult) {
|
|
|
243
244
|
export function interruptible(provider: ProviderAdapter, state: { interrupted: boolean }): ProviderAdapter {
|
|
244
245
|
return {
|
|
245
246
|
name: provider.name,
|
|
247
|
+
auth: provider.auth,
|
|
246
248
|
preflight: () => provider.preflight(),
|
|
247
249
|
modelLabel: () => provider.modelLabel(),
|
|
248
250
|
leaksSecret: (texts) => provider.leaksSecret(texts),
|
|
@@ -295,7 +297,7 @@ export function openLocalSession(p: {
|
|
|
295
297
|
const { env, repoDir, deps } = p;
|
|
296
298
|
const loaded = loadConfig(env, p.stderr);
|
|
297
299
|
if (loaded.provider !== "claude-code") {
|
|
298
|
-
throw new UsageError(`
|
|
300
|
+
throw new UsageError(`WACHIMAN_PROVIDER=${loaded.provider}: the local review runs only on Claude Code, your signed-in \`claude\`.`);
|
|
299
301
|
}
|
|
300
302
|
// A person ran it: no automatic ceiling (decision 14).
|
|
301
303
|
const config = {
|
|
@@ -433,6 +435,15 @@ export function localScopeInput(p: {
|
|
|
433
435
|
return { input: built.input, release: () => removeSnapshot(built.snapshotDir) };
|
|
434
436
|
}
|
|
435
437
|
|
|
438
|
+
/**
|
|
439
|
+
* The one warning a local run prints when its estimate is above the size gate, or null. Local runs
|
|
440
|
+
* are never refused: the run continues and stops at its budget.
|
|
441
|
+
*/
|
|
442
|
+
export function sizeWarning(estimate: ReviewEstimate, gate: number, budgetUsd: number, model: string): string | null {
|
|
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)} (WACHIMAN_BUDGET_USD).`;
|
|
445
|
+
}
|
|
446
|
+
|
|
436
447
|
export function runLocal(
|
|
437
448
|
args: LocalArgs,
|
|
438
449
|
repoDir: string,
|
|
@@ -449,7 +460,7 @@ export function runLocal(
|
|
|
449
460
|
throw new UsageError("Working-tree reviews require --result-version 2; a tree is not a commit.");
|
|
450
461
|
}
|
|
451
462
|
// Off unless asked for (ADR 0020): without this, nothing below touches ~/.wachiman/history.
|
|
452
|
-
// A bad
|
|
463
|
+
// A bad WACHIMAN_HISTORY_DAYS stops here, before any call is paid for.
|
|
453
464
|
const history = historySettings(env, args.history);
|
|
454
465
|
const home = wachimanHome(env);
|
|
455
466
|
const { config, profile, profileNote, provider, verifier, state } = openLocalSession({
|
|
@@ -510,6 +521,8 @@ export function runLocal(
|
|
|
510
521
|
});
|
|
511
522
|
io.stderr(`files: ${kept.length} (${dropped.length} excluded)`);
|
|
512
523
|
io.stderr(`batches: ${batches.length}`);
|
|
524
|
+
const warning = sizeWarning(estimateFor(kept, config), sizeGate(config, false), config.budgetUsd, config.model);
|
|
525
|
+
if (warning) io.stderr(warning);
|
|
513
526
|
io.stderr(
|
|
514
527
|
config.verify
|
|
515
528
|
? `verify: on (${config.verifierModel}, reserve $${Math.min(config.verifyBudgetUsd, config.budgetUsd / 2).toFixed(2)})`
|
|
@@ -564,7 +577,12 @@ export function runLocal(
|
|
|
564
577
|
}
|
|
565
578
|
const text =
|
|
566
579
|
args.format === "json"
|
|
567
|
-
? renderJson(
|
|
580
|
+
? renderJson(
|
|
581
|
+
result,
|
|
582
|
+
args.resultVersion ?? (input.change.kind === "working-tree" ? 2 : 1),
|
|
583
|
+
// ADR 0034: with history on, a `/2` finding names itself by the id `history --verdict` takes.
|
|
584
|
+
annotation ? result.findings.map((_, i) => annotation!.byIndex.get(i)?.id) : undefined,
|
|
585
|
+
)
|
|
568
586
|
: args.format === "markdown"
|
|
569
587
|
? renderMarkdown(result, { profileNote, history: annotation })
|
|
570
588
|
: renderTerminal(result, {
|