wachiman 1.10.0 → 1.12.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/src/local.ts CHANGED
@@ -7,26 +7,30 @@
7
7
  * Exit codes (plan decision 8): 0 when a report was produced (complete, partial, or stopped by a
8
8
  * usage limit); 1 when no call produced a review (sign-in refused, an unclassified error, every
9
9
  * batch failed); 2 for a usage error; 130 after Ctrl-C.
10
+ *
11
+ * The parts `wachiman ask` shares (`parseFlags`, `openLocalSession`, `localScopeInput`) live here, so
12
+ * both commands read the same flags, pick the same account and provider, and read the same change.
10
13
  */
11
14
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
12
15
  import { resolve } from "node:path";
13
16
  import { loadConfig, UsageError } from "./config";
14
- import { buildLocalInput, DEFAULT_MAX_DEPTH, EMPTY_TREE_LABEL, type LocalRefs, removeSnapshot, snapshotHead, warnSnapshotDifferences } from "./connectors/local-git";
15
17
  import {
16
- DEFAULT_EXCLUDE,
17
- filterFiles,
18
- planBatches,
19
- reviewChange,
20
- reviewOptionsOf,
21
- type ReviewInput,
22
- type ReviewResult,
23
- } from "./engine";
18
+ buildLocalInput,
19
+ DEFAULT_MAX_DEPTH,
20
+ EMPTY_TREE_LABEL,
21
+ type LocalRefs,
22
+ removeSnapshot,
23
+ snapshotHead,
24
+ warnSnapshotDifferences,
25
+ } from "./connectors/local-git";
26
+ import { DEFAULT_EXCLUDE, filterFiles, planBatches, reviewChange, reviewOptionsOf, type ReviewInput, type ReviewResult } from "./engine";
24
27
  import { spawnGit } from "./evidence";
25
- import { assertReviewInputFormat } from "./formats";
28
+ import { assertReviewInputFormat, REVIEW_INPUT_V2 } from "./formats";
29
+ import { workingTreeInput, snapshotWorkingTree } from "./connectors/working-tree";
26
30
  import { historyRoot, historySettings, saveRun } from "./history";
27
31
  import { readConfig, wachimanHome } from "./accounts/config";
28
32
  import { confirmProfile, type SpawnFn } from "./accounts/confirm";
29
- import { failureText, profileLine, resolveProfile } from "./accounts/resolve";
33
+ import { failureText, profileLine, resolveProfile, type ResolvedProfile } from "./accounts/resolve";
30
34
  import { repositoryKey } from "./history/store";
31
35
  import { inspectIsolatedProfile, parseProfile, populatedProfileError, profileDir } from "./profiles";
32
36
  import { getProvider as defaultGetProvider, type ProviderAdapter } from "./providers";
@@ -40,6 +44,7 @@ export const FORMATS = ["terminal", "markdown", "json"] as const;
40
44
  export type LocalFormat = (typeof FORMATS)[number];
41
45
 
42
46
  export interface LocalArgs {
47
+ workingTree?: "staged" | "all";
43
48
  base?: string;
44
49
  commit?: string;
45
50
  from?: string;
@@ -51,7 +56,7 @@ export interface LocalArgs {
51
56
  profile?: string;
52
57
  agentPrompt: boolean;
53
58
  history: boolean;
54
- /** `--verify` forces the verifier on, `--no-verify` off; unset follows `AGENT_REVIEW_VERIFY` (on by default, ADR 0027). */
59
+ /** `--verify` forces the verifier on, `--no-verify` off; unset follows `AGENT_REVIEW_VERIFY` (off by default, ADR 0027). */
55
60
  verify: boolean | undefined;
56
61
  /** `--result-version`: with `--format json`, which result version to write (default 1 for a committed change). */
57
62
  resultVersion?: 1 | 2;
@@ -61,11 +66,46 @@ export interface LocalArgs {
61
66
  export const localUsage = `wachiman local [paths…] [--base <ref> | --from <commit> | --commit <commit>] [--max-depth <n>] [--repo-dir <dir>]
62
67
  [--input <file>] [--format terminal|markdown|json] [--output <file>]
63
68
  [--profile <name>] [--agent-prompt] [--history] [--verify | --no-verify]
64
- [--result-version 1|2]`;
69
+ [--result-version 1|2] [--working-tree staged|all]`;
70
+
71
+ /** Every flag `local` takes. `ask` takes the subset it names in `ask-command`. */
72
+ export const LOCAL_FLAGS = [
73
+ "--agent-prompt",
74
+ "--history",
75
+ "--verify",
76
+ "--no-verify",
77
+ "--result-version",
78
+ "--working-tree",
79
+ "--base",
80
+ "--commit",
81
+ "--from",
82
+ "--max-depth",
83
+ "--output",
84
+ "--profile",
85
+ "--format",
86
+ "--input",
87
+ ] as const;
65
88
 
66
89
  /** The arguments after `local` (`--repo-dir` is already taken out). Both `--x v` and `--x=v`. */
67
90
  export function parseLocalArgs(argv: string[]): LocalArgs {
68
- const args: LocalArgs = { paths: [], format: "terminal", profile: undefined, agentPrompt: false, history: false, verify: undefined, input: undefined };
91
+ return parseFlags(argv, "local", LOCAL_FLAGS);
92
+ }
93
+
94
+ /**
95
+ * The flags `local` and `ask` share, read by this one parser so both mean the same by each. A flag
96
+ * not in `accepted` is a usage error for `command`. Every argument that is not a flag goes to
97
+ * `paths`: the paths of `local`, the words of an `ask` question.
98
+ */
99
+ export function parseFlags(argv: string[], command: string, accepted: readonly string[]): LocalArgs {
100
+ const args: LocalArgs = {
101
+ paths: [],
102
+ format: "terminal",
103
+ profile: undefined,
104
+ agentPrompt: false,
105
+ history: false,
106
+ verify: undefined,
107
+ input: undefined,
108
+ };
69
109
  let base: string | undefined;
70
110
  let sawVerify = false;
71
111
  let sawNoVerify = false;
@@ -78,6 +118,7 @@ export function parseLocalArgs(argv: string[]): LocalArgs {
78
118
  }
79
119
  const eq = arg.indexOf("=");
80
120
  const name = eq === -1 ? arg : arg.slice(0, eq);
121
+ if (!accepted.includes(name)) throw new UsageError(`Unknown option ${name} for ${command}.`);
81
122
  const value = () => {
82
123
  const v = eq === -1 ? argv[++i] : arg.slice(eq + 1);
83
124
  if (v === undefined || v === "" || (eq === -1 && v.startsWith("--"))) throw new UsageError(`${name} needs a value.`);
@@ -91,22 +132,25 @@ export function parseLocalArgs(argv: string[]): LocalArgs {
91
132
  } else if (name === "--no-verify" && eq === -1) {
92
133
  args.verify = false;
93
134
  sawNoVerify = true;
94
- }
95
- else if (name === "--result-version") {
135
+ } else if (name === "--result-version") {
96
136
  const v = value();
97
137
  if (v !== "1" && v !== "2") throw new UsageError(`--result-version must be 1 or 2, got "${v}".`);
98
138
  args.resultVersion = v === "1" ? 1 : 2;
99
- }
100
- else if (name === "--base") {
139
+ } else if (name === "--working-tree") {
140
+ const v = value();
141
+ if (v !== "staged" && v !== "all") throw new UsageError("--working-tree must be staged or all.");
142
+ args.workingTree = v;
143
+ picked.push(name);
144
+ } else if (name === "--base") {
101
145
  base = value();
102
146
  picked.push(name);
103
147
  } else if (name === "--commit" || name === "--from") {
104
148
  args[name === "--commit" ? "commit" : "from"] = value();
105
149
  picked.push(name);
106
- }
107
- else if (name === "--max-depth") {
150
+ } else if (name === "--max-depth") {
108
151
  const v = value();
109
- if (!/^[1-9]\d*$/.test(v) || !Number.isSafeInteger(Number(v))) throw new UsageError(`--max-depth must be a positive integer, got "${v}".`);
152
+ if (!/^[1-9]\d*$/.test(v) || !Number.isSafeInteger(Number(v)))
153
+ throw new UsageError(`--max-depth must be a positive integer, got "${v}".`);
110
154
  args.maxDepth = Number(v);
111
155
  } else if (name === "--output") args.output = value();
112
156
  else if (name === "--profile") args.profile = parseProfile(value());
@@ -118,7 +162,7 @@ export function parseLocalArgs(argv: string[]): LocalArgs {
118
162
  const v = value();
119
163
  if (!existsSync(v)) throw new UsageError(`--input ${v} does not exist.`);
120
164
  args.input = v;
121
- } else throw new UsageError(`Unknown option ${name} for local.`);
165
+ } else throw new UsageError(`Unknown option ${name} for ${command}.`);
122
166
  }
123
167
  if (sawVerify && sawNoVerify) throw new UsageError("--verify and --no-verify cannot be used together.");
124
168
  if (args.resultVersion !== undefined && args.format !== "json") throw new UsageError("--result-version applies only with --format json.");
@@ -128,6 +172,7 @@ export function parseLocalArgs(argv: string[]): LocalArgs {
128
172
  if (args.input !== undefined && (picked.length > 0 || args.paths.length > 0)) {
129
173
  throw new UsageError("--input reviews the file's change as it is: it takes no --base, --from or --commit, and no paths.");
130
174
  }
175
+ if (args.workingTree && args.resultVersion === 1) throw new UsageError("Working-tree reviews require --result-version 2.");
131
176
  return args;
132
177
  }
133
178
 
@@ -153,6 +198,18 @@ export function readInputFile(path: string): Omit<ReviewInput, "headDir"> {
153
198
  const change = input.change;
154
199
  if (!change || typeof change !== "object") problems.push("change");
155
200
  else {
201
+ if (!["pull-request", "branch", "working-tree"].includes(change.kind)) problems.push("change.kind");
202
+ if (change.kind === "working-tree") {
203
+ const w = change.workingTree;
204
+ if (
205
+ input.format !== REVIEW_INPUT_V2 ||
206
+ !w ||
207
+ !["staged", "all"].includes(w.mode) ||
208
+ w.tree !== change.head?.sha ||
209
+ w.baseCommit !== change.base?.sha
210
+ )
211
+ problems.push("change.workingTree");
212
+ } else if (change.workingTree !== undefined) problems.push("change.workingTree");
156
213
  if (!isString(change.describe)) problems.push("change.describe");
157
214
  if (!isString(change.repository?.name)) problems.push("change.repository.name");
158
215
  if (!isString(change.head?.sha) || !HEX_SHA.test(change.head.sha)) problems.push("change.head.sha");
@@ -183,7 +240,7 @@ export function exitCodeOf(result: ReviewResult) {
183
240
  * The provider, with Ctrl-C turned into "stop the review": after an interrupted call every later
184
241
  * call fails at once, without starting `claude`, so the core winds down in milliseconds.
185
242
  */
186
- function interruptible(provider: ProviderAdapter, state: { interrupted: boolean }): ProviderAdapter {
243
+ export function interruptible(provider: ProviderAdapter, state: { interrupted: boolean }): ProviderAdapter {
187
244
  return {
188
245
  name: provider.name,
189
246
  preflight: () => provider.preflight(),
@@ -211,26 +268,43 @@ export interface LocalDeps {
211
268
  getProvider?: typeof defaultGetProvider;
212
269
  }
213
270
 
214
- export function runLocal(
215
- args: LocalArgs,
216
- repoDir: string,
217
- env: Record<string, string | undefined>,
218
- io: { stdout: (text: string) => void; stderr: (line: string) => void; engineVersion: string },
219
- deps: LocalDeps = {},
220
- ): number {
221
- const loaded = loadConfig(env, io.stderr);
271
+ /** What a local command settles before any call: the settings, the account and the providers. */
272
+ export interface LocalSession {
273
+ config: ReturnType<typeof loadConfig>;
274
+ profile: ResolvedProfile["profile"];
275
+ profileNote?: string;
276
+ provider: ProviderAdapter;
277
+ verifier?: ProviderAdapter;
278
+ /** Set by Ctrl-C: every later call then fails at once. */
279
+ state: { interrupted: boolean };
280
+ }
281
+
282
+ /**
283
+ * The settings, the account (ADR 0029), the subscription-mode provider and, with `--verify`, the
284
+ * verifier, all checked before any call. Nothing in the reviewed repository takes part: a corrupt
285
+ * store, a value that resolves to nothing, or a profile that does not confirm is a usage error.
286
+ */
287
+ export function openLocalSession(p: {
288
+ profile?: string;
289
+ verify: boolean | undefined;
290
+ repoDir: string;
291
+ env: Record<string, string | undefined>;
292
+ stderr: (line: string) => void;
293
+ deps: LocalDeps;
294
+ }): LocalSession {
295
+ const { env, repoDir, deps } = p;
296
+ const loaded = loadConfig(env, p.stderr);
222
297
  if (loaded.provider !== "claude-code") {
223
- throw new UsageError(
224
- `AGENT_REVIEW_PROVIDER=${loaded.provider}: the local review runs only on Claude Code, your signed-in \`claude\`.`,
225
- );
298
+ throw new UsageError(`AGENT_REVIEW_PROVIDER=${loaded.provider}: the local review runs only on Claude Code, your signed-in \`claude\`.`);
226
299
  }
227
300
  // A person ran it: no automatic ceiling (decision 14).
228
- const config = { ...loaded, trigger: undefined, verify: args.verify ?? loaded.verify };
301
+ const config = {
302
+ ...loaded,
303
+ trigger: undefined,
304
+ verify: p.verify ?? loaded.verify,
305
+ };
229
306
  // Before the provider exists; the adapter's own check in preflight() is the second line.
230
307
  if (env.ANTHROPIC_API_KEY) throw new UsageError(SUBSCRIPTION_KEY_REFUSAL);
231
- // Off unless asked for (ADR 0020): without this, nothing below touches ~/.wachiman/history.
232
- // A bad AGENT_REVIEW_HISTORY_DAYS stops here, before any call is paid for.
233
- const history = historySettings(env, args.history);
234
308
 
235
309
  // Which account (ADR 0029): nothing in the reviewed repository takes part. A corrupt store, a
236
310
  // value that resolves to nothing, or a profile that does not confirm is exit 2 before any call.
@@ -240,7 +314,7 @@ export function runLocal(
240
314
  const accounts = stored.kind === "ok" ? stored.config : undefined;
241
315
  const bindingKey = accounts && Object.keys(accounts.projects).length > 0 ? repositoryKey(repoDir).key : undefined;
242
316
  const resolution = resolveProfile({
243
- flag: args.profile,
317
+ flag: p.profile,
244
318
  binding: bindingKey !== undefined && Object.hasOwn(accounts!.projects, bindingKey) ? accounts!.projects[bindingKey] : undefined,
245
319
  env: { WACHIMAN_PROFILE: env.WACHIMAN_PROFILE },
246
320
  config: accounts,
@@ -249,7 +323,7 @@ export function runLocal(
249
323
  });
250
324
  if (!resolution.ok) throw new UsageError(failureText(resolution.failure));
251
325
  const { resolved } = resolution;
252
- io.stderr(profileLine(resolved));
326
+ p.stderr(profileLine(resolved));
253
327
  const { profile } = resolved;
254
328
 
255
329
  let configDir: string | undefined;
@@ -294,8 +368,100 @@ export function runLocal(
294
368
  )
295
369
  : undefined;
296
370
  verifier?.preflight();
371
+ return { config, profile, profileNote, provider, verifier, state };
372
+ }
373
+
374
+ /**
375
+ * The change the scope flags select (ADR 0019 decision 2): the tracked working tree with
376
+ * `--working-tree`, else the committed range. The input reads from a snapshot of the head; `release`
377
+ * removes it, and the caller runs it once the change is no longer read.
378
+ */
379
+ export function localScopeInput(p: {
380
+ repoDir: string;
381
+ workingTree?: "staged" | "all";
382
+ base?: string;
383
+ commit?: string;
384
+ from?: string;
385
+ maxDepth?: number;
386
+ paths: string[];
387
+ log: (line: string) => void;
388
+ warn: (line: string) => void;
389
+ }): { input: ReviewInput; release: () => void } {
390
+ if (p.workingTree) {
391
+ const built = workingTreeInput({
392
+ repoDir: p.repoDir,
393
+ mode: p.workingTree,
394
+ paths: p.paths,
395
+ log: p.log,
396
+ warn: p.warn,
397
+ });
398
+ p.log(`mode: working tree (${p.workingTree})`);
399
+ p.log(`base: HEAD (${short(built.input.change.base.sha)})`);
400
+ p.log(`tree: ${short(built.input.change.head.sha)}`);
401
+ return { input: built.input, release: built.release };
402
+ }
403
+ const maxDepth = p.maxDepth ?? DEFAULT_MAX_DEPTH;
404
+ const built = buildLocalInput({
405
+ repoDir: p.repoDir,
406
+ base: p.base,
407
+ commit: p.commit,
408
+ from: p.from,
409
+ maxDepth,
410
+ paths: p.paths,
411
+ log: p.log,
412
+ warn: p.warn,
413
+ });
414
+ const { refs } = built;
415
+ const commits = `${refs.depth} commit${refs.depth === 1 ? "" : "s"}`;
416
+ const max = `(max ${maxDepth})`;
417
+ if (refs.mode?.kind === "commit") {
418
+ p.log(`mode: one commit (${short(refs.mode.rev)})${refs.mode.merge ? ", a merge commit: first parent" : ""}`);
419
+ p.log(`start: ${startText(refs)}`);
420
+ p.log(`depth: ${commits}`);
421
+ p.log(`head: ${short(refs.headSha)}`);
422
+ } else if (refs.mode?.kind === "from") {
423
+ p.log(`mode: from ${short(refs.mode.rev)} to HEAD`);
424
+ p.log(`start: ${startText(refs)}`);
425
+ p.log(`depth: ${commits} ${max}`);
426
+ p.log(`head: ${refs.headRef} (${short(refs.headSha)})`);
427
+ } else {
428
+ p.log(`base: ${refs.baseRef} (${short(refs.baseSha)})`);
429
+ p.log(`merge-base: ${short(refs.mergeBase)}`);
430
+ p.log(`depth: ${commits} ${max}`);
431
+ p.log(`head: ${refs.headRef} (${short(refs.headSha)})`);
432
+ }
433
+ return { input: built.input, release: () => removeSnapshot(built.snapshotDir) };
434
+ }
435
+
436
+ export function runLocal(
437
+ args: LocalArgs,
438
+ repoDir: string,
439
+ env: Record<string, string | undefined>,
440
+ io: {
441
+ stdout: (text: string) => void;
442
+ stderr: (line: string) => void;
443
+ engineVersion: string;
444
+ },
445
+ deps: LocalDeps = {},
446
+ ): number {
447
+ const fileInput = args.input === undefined ? undefined : readInputFile(args.input);
448
+ if ((args.workingTree || fileInput?.change.kind === "working-tree") && args.resultVersion === 1) {
449
+ throw new UsageError("Working-tree reviews require --result-version 2; a tree is not a commit.");
450
+ }
451
+ // Off unless asked for (ADR 0020): without this, nothing below touches ~/.wachiman/history.
452
+ // A bad AGENT_REVIEW_HISTORY_DAYS stops here, before any call is paid for.
453
+ const history = historySettings(env, args.history);
454
+ const home = wachimanHome(env);
455
+ const { config, profile, profileNote, provider, verifier, state } = openLocalSession({
456
+ profile: args.profile,
457
+ verify: args.verify,
458
+ repoDir,
459
+ env,
460
+ stderr: io.stderr,
461
+ deps,
462
+ });
297
463
 
298
- let snapshotDir: string | undefined;
464
+ let release: (() => void) | undefined;
299
465
  const onSigint = () => {
300
466
  state.interrupted = true;
301
467
  };
@@ -303,45 +469,52 @@ export function runLocal(
303
469
  try {
304
470
  let input: ReviewInput;
305
471
  if (args.input === undefined) {
306
- const built = buildLocalInput({ repoDir, base: args.base, commit: args.commit, from: args.from, maxDepth: args.maxDepth ?? DEFAULT_MAX_DEPTH, paths: args.paths, log: io.stderr, warn: io.stderr });
307
- snapshotDir = built.snapshotDir;
308
- input = built.input;
309
- const { refs } = built;
310
- const commits = `${refs.depth} commit${refs.depth === 1 ? "" : "s"}`;
311
- const max = `(max ${args.maxDepth ?? DEFAULT_MAX_DEPTH})`;
312
- if (refs.mode?.kind === "commit") {
313
- io.stderr(`mode: one commit (${short(refs.mode.rev)})${refs.mode.merge ? ", a merge commit: first parent" : ""}`);
314
- io.stderr(`start: ${startText(refs)}`);
315
- io.stderr(`depth: ${commits}`);
316
- io.stderr(`head: ${short(refs.headSha)}`);
317
- } else if (refs.mode?.kind === "from") {
318
- io.stderr(`mode: from ${short(refs.mode.rev)} to HEAD`);
319
- io.stderr(`start: ${startText(refs)}`);
320
- io.stderr(`depth: ${commits} ${max}`);
321
- io.stderr(`head: ${refs.headRef} (${short(refs.headSha)})`);
322
- } else {
323
- io.stderr(`base: ${refs.baseRef} (${short(refs.baseSha)})`);
324
- io.stderr(`merge-base: ${short(refs.mergeBase)}`);
325
- io.stderr(`depth: ${commits} ${max}`);
326
- io.stderr(`head: ${refs.headRef} (${short(refs.headSha)})`);
327
- }
472
+ const scope = localScopeInput({
473
+ repoDir,
474
+ workingTree: args.workingTree,
475
+ base: args.base,
476
+ commit: args.commit,
477
+ from: args.from,
478
+ maxDepth: args.maxDepth,
479
+ paths: args.paths,
480
+ log: io.stderr,
481
+ warn: io.stderr,
482
+ });
483
+ input = scope.input;
484
+ release = scope.release;
328
485
  } else {
329
- const fromFile = readInputFile(args.input);
486
+ const fromFile = fileInput!;
330
487
  const head = fromFile.change.head.sha;
331
- if (spawnGit(["cat-file", "-e", `${head}^{commit}`], { cwd: repoDir, timeoutMs: 60_000 }).status !== 0) {
488
+ if (
489
+ fromFile.change.kind !== "working-tree" &&
490
+ spawnGit(["cat-file", "-e", `${head}^{commit}`], {
491
+ cwd: repoDir,
492
+ timeoutMs: 60_000,
493
+ }).status !== 0
494
+ ) {
332
495
  throw new UsageError(`The input's head ${short(head)} is not a commit in ${repoDir}; pass the clone that has it with --repo-dir.`);
333
496
  }
334
- const snapshot = snapshotHead(repoDir, head);
335
- snapshotDir = snapshot.dir;
497
+ const snapshot =
498
+ fromFile.change.kind === "working-tree"
499
+ ? { ...snapshotWorkingTree(repoDir, head), missing: [], extra: [] }
500
+ : snapshotHead(repoDir, head);
501
+ release = () => removeSnapshot(snapshot.dir);
336
502
  warnSnapshotDifferences(snapshot, io.stderr);
337
503
  input = { ...fromFile, headDir: snapshot.dir };
338
504
  io.stderr(`head: ${short(head)}`);
339
505
  }
340
506
  const { kept, dropped } = filterFiles(input.files, [...DEFAULT_EXCLUDE, ...config.exclude], input.scope);
341
- const batches = planBatches(kept, { maxLines: config.batchLines, maxChars: config.batchChars });
507
+ const batches = planBatches(kept, {
508
+ maxLines: config.batchLines,
509
+ maxChars: config.batchChars,
510
+ });
342
511
  io.stderr(`files: ${kept.length} (${dropped.length} excluded)`);
343
512
  io.stderr(`batches: ${batches.length}`);
344
- io.stderr(config.verify ? `verify: on (${config.verifierModel}, reserve $${Math.min(config.verifyBudgetUsd, config.budgetUsd / 2).toFixed(2)})` : "verify: off");
513
+ io.stderr(
514
+ config.verify
515
+ ? `verify: on (${config.verifierModel}, reserve $${Math.min(config.verifyBudgetUsd, config.budgetUsd / 2).toFixed(2)})`
516
+ : "verify: off",
517
+ );
345
518
 
346
519
  const result = reviewChange(input, reviewOptionsOf(config, config.budgetUsd, profile.kind === "managed" ? "isolated" : "default"), {
347
520
  provider,
@@ -350,8 +523,13 @@ export function runLocal(
350
523
  ...(verifier
351
524
  ? {
352
525
  baseSnapshot: () => {
353
- const base = snapshotHead(repoDir, input.change.base.sha);
354
- return { dir: base.dir, release: () => removeSnapshot(base.dir) };
526
+ const base = input.change.kind === "working-tree"
527
+ ? snapshotWorkingTree(repoDir, `${input.change.base.sha}^{tree}`)
528
+ : snapshotHead(repoDir, input.change.base.sha);
529
+ return {
530
+ dir: base.dir,
531
+ release: () => removeSnapshot(base.dir),
532
+ };
355
533
  },
356
534
  }
357
535
  : {}),
@@ -386,10 +564,14 @@ export function runLocal(
386
564
  }
387
565
  const text =
388
566
  args.format === "json"
389
- ? renderJson(result, args.resultVersion ?? 1)
567
+ ? renderJson(result, args.resultVersion ?? (input.change.kind === "working-tree" ? 2 : 1))
390
568
  : args.format === "markdown"
391
569
  ? renderMarkdown(result, { profileNote, history: annotation })
392
- : renderTerminal(result, { profileNote, agentPrompt: args.agentPrompt, history: annotation });
570
+ : renderTerminal(result, {
571
+ profileNote,
572
+ agentPrompt: args.agentPrompt,
573
+ history: annotation,
574
+ });
393
575
  if (args.output !== undefined) {
394
576
  const path = resolve(args.output);
395
577
  writeFileSync(path, text);
@@ -398,6 +580,6 @@ export function runLocal(
398
580
  return exitCodeOf(result);
399
581
  } finally {
400
582
  process.off("SIGINT", onSigint);
401
- if (snapshotDir) removeSnapshot(snapshotDir);
583
+ release?.();
402
584
  }
403
585
  }
@@ -170,6 +170,24 @@ export function buildChildEnv(
170
170
  }
171
171
 
172
172
  /** The `codex exec` arguments. The prompt always goes through stdin (`-`). */
173
+ /**
174
+ * The top-level properties the engine leaves optional in a batch's schema (ADR 0031). Codex's
175
+ * structured output is strict: every property must be `required`, so these are required in the
176
+ * schema Codex receives. The model then answers an empty array when a batch has none, and a
177
+ * missing one parses as empty (`risk.ts`). Other properties of other schemas are not touched.
178
+ */
179
+ const RISK_ARRAYS = ["risk_facts", "judgement"];
180
+
181
+ export function strictSchema(schema: unknown): unknown {
182
+ if (schema === null || typeof schema !== "object") return schema;
183
+ const { properties, required } = schema as { properties?: object; required?: unknown };
184
+ if (properties === null || typeof properties !== "object") return schema;
185
+ const names = Array.isArray(required) ? required : [];
186
+ const missing = RISK_ARRAYS.filter((name) => name in properties && !names.includes(name));
187
+ if (missing.length === 0) return schema;
188
+ return { ...schema, required: [...names, ...missing] };
189
+ }
190
+
173
191
  export function buildCodexArgs(opts: {
174
192
  model: string;
175
193
  workDir: string;
@@ -304,7 +322,7 @@ export class CodexProvider implements ProviderAdapter {
304
322
  let schemaFile: string | undefined;
305
323
  if (request.outputSchema) {
306
324
  schemaFile = join(scratch, "schema.json");
307
- writeFileSync(schemaFile, JSON.stringify(request.outputSchema));
325
+ writeFileSync(schemaFile, JSON.stringify(strictSchema(request.outputSchema)));
308
326
  }
309
327
  const lastMessageFile = join(scratch, "last-message.txt");
310
328
  const started = Date.now();
@@ -9,7 +9,7 @@ export const DEFAULT_PROVIDER = "claude-code";
9
9
 
10
10
  /** The model each provider uses when `AGENT_REVIEW_MODEL` is not set. */
11
11
  export const DEFAULT_MODELS: Record<(typeof PROVIDER_NAMES)[number], string> = {
12
- "claude-code": "claude-haiku-5-5",
12
+ "claude-code": "claude-opus-5-5",
13
13
  codex: "gpt-6.1-sol",
14
14
  };
15
15