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/formats.ts CHANGED
@@ -20,8 +20,10 @@ import type {
20
20
  Unreviewable,
21
21
  } from "./engine";
22
22
  import type { ProviderErrorClass } from "./providers/errors";
23
+ import type { RiskMap } from "./risk";
23
24
 
24
25
  export const REVIEW_INPUT_FORMAT = "wachiman.review-input/1";
26
+ export const REVIEW_INPUT_V2 = "wachiman.review-input/2";
25
27
  /** The result as committed-change JSON consumers know it: closed root, no verification block. */
26
28
  export const REVIEW_RESULT_V1 = "wachiman.review-result/1";
27
29
  /** The result the core produces: `/1` plus origin, per-finding verification and the verification record. */
@@ -29,7 +31,7 @@ export const REVIEW_RESULT_V2 = "wachiman.review-result/2";
29
31
 
30
32
  export type { ReviewFile };
31
33
 
32
- export interface ReviewChange {
34
+ export interface CommittedReviewChange {
33
35
  kind: "pull-request" | "branch";
34
36
  /** One sentence for the prompt's first line and every report's headline. */
35
37
  describe: string;
@@ -44,8 +46,15 @@ export interface ReviewChange {
44
46
  identifier?: string;
45
47
  }
46
48
 
49
+ export type ReviewChange =
50
+ | CommittedReviewChange
51
+ | (Omit<CommittedReviewChange, "kind"> & {
52
+ kind: "working-tree";
53
+ workingTree: { mode: "staged" | "all"; baseCommit: string; tree: string };
54
+ });
55
+
47
56
  export interface ReviewInput {
48
- format: typeof REVIEW_INPUT_FORMAT;
57
+ format: typeof REVIEW_INPUT_FORMAT | typeof REVIEW_INPUT_V2;
49
58
  change: ReviewChange;
50
59
  files: ReviewFile[];
51
60
  /** Read from `change.base.sha` by the connector (ADR 0006). */
@@ -111,7 +120,7 @@ type Execution = {
111
120
  /** `wachiman.review-result/1`: the closed shape committed-change JSON keeps by default. */
112
121
  export interface ReviewResultV1 {
113
122
  format: typeof REVIEW_RESULT_V1;
114
- change: ReviewChange & { snapshot?: string };
123
+ change: CommittedReviewChange & { snapshot?: string };
115
124
  engine: { version: string };
116
125
  provider: { label: string; model: string; effort: string; profile: Profile };
117
126
  coverage: Coverage;
@@ -236,6 +245,8 @@ export interface ReviewResultV2 {
236
245
  findings: ResultFindingV2[];
237
246
  contracts: Contract[];
238
247
  summary: string;
248
+ /** The risk map (ADR 0031). Only `/2` has it: `toResultV1` leaves it out. */
249
+ riskMap?: RiskMap;
239
250
  batches: BatchReport[];
240
251
  threadReplies: ReviewOutput["thread_replies"];
241
252
  instructionChanges: { files: string[]; baseSha: string };
@@ -250,10 +261,12 @@ export type ReviewResult = ReviewResultV2;
250
261
  export type ResultFinding = ResultFindingV2;
251
262
 
252
263
  /** The core refuses a version it does not know (D15). A usage error, not an engine error. */
253
- export function assertReviewInputFormat(input: { format?: unknown }): asserts input is { format: typeof REVIEW_INPUT_FORMAT } {
254
- if (input.format !== REVIEW_INPUT_FORMAT) {
264
+ export function assertReviewInputFormat(input: { format?: unknown }): asserts input is {
265
+ format: typeof REVIEW_INPUT_FORMAT | typeof REVIEW_INPUT_V2;
266
+ } {
267
+ if (input.format !== REVIEW_INPUT_FORMAT && input.format !== REVIEW_INPUT_V2) {
255
268
  throw new UsageError(
256
- `Unknown review input format ${JSON.stringify(input.format)}; this engine reads ${REVIEW_INPUT_FORMAT}.`,
269
+ `Unknown review input format ${JSON.stringify(input.format)}; this engine reads ${REVIEW_INPUT_FORMAT} and ${REVIEW_INPUT_V2}.`,
257
270
  );
258
271
  }
259
272
  }
@@ -296,10 +309,11 @@ export function toResultV1(result: ReviewResultV2): ReviewResultV1 {
296
309
  throw new UsageError("A working-tree review has no result /1: its head is a tree id, not a commit. Use --result-version 2.");
297
310
  }
298
311
  const { account: _account, ...provider } = result.provider;
299
- const { verification, ...rest } = result;
312
+ const { verification, riskMap: _riskMap, ...rest } = result;
300
313
  return {
301
314
  ...rest,
302
315
  format: REVIEW_RESULT_V1,
316
+ change: result.change as CommittedReviewChange & { snapshot?: string },
303
317
  provider,
304
318
  findings: result.findings.map((f) => ({
305
319
  path: f.path,
@@ -37,8 +37,11 @@ export function saveRun(p: SaveRunParams): HistoryAnnotation {
37
37
 
38
38
  const head = p.result.change.head.sha;
39
39
  const ancestors = new Map<string, boolean>();
40
+ const treeHeads = new Set(runs.filter(r => r.result.change.kind === "working-tree").map(r => r.result.change.head.sha));
40
41
  // Exit 0 = ancestor (or the same commit); 1 = not; anything else (an unknown commit) cannot be proven.
41
42
  const isAncestor = (lastHead: string) => {
43
+ // Fingerprints still match; missing findings on ephemeral trees stay unknown.
44
+ if (p.result.change.kind === "working-tree" || treeHeads.has(lastHead)) return false;
42
45
  let known = ancestors.get(lastHead);
43
46
  if (known === undefined) {
44
47
  known = git(["merge-base", "--is-ancestor", lastHead, head], { cwd: p.repoDir, timeoutMs: 30_000 }).status === 0;
@@ -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.10.0"; // x-release-please-version
37
+ export const DEFAULT_WORKFLOW_REF: string | undefined = "v1.12.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/";
@@ -3,7 +3,7 @@ import type { Prompter } from "../wizard/prompt";
3
3
  import { DEFAULT_WORKFLOW_PATH, initModes, normaliseWorkflowPath, operatorProblem, tagProblem, type InitMode, type RawInitFlags } from "./options";
4
4
 
5
5
  /** The values given on the command line are held to the same rules as answers: a bad one is exit 2, never silently asked again. */
6
- function checkSupplied(flags: RawInitFlags) {
6
+ export function checkSupplied(flags: RawInitFlags) {
7
7
  if (flags.mode !== undefined && !initModes.includes(flags.mode as InitMode)) throw new UsageError(`--mode must be github, local or both, got "${flags.mode}".`);
8
8
  const problem =
9
9
  (flags.operator !== undefined ? operatorProblem(flags.operator) : undefined) ??
@@ -19,6 +19,7 @@ function checkSupplied(flags: RawInitFlags) {
19
19
  */
20
20
  export async function promptForInit(flags: RawInitFlags, ctx: { defaultWorkflowRef?: string }, prompter: Prompter): Promise<RawInitFlags | null> {
21
21
  checkSupplied(flags);
22
+ prompter.step("Review mode", 2);
22
23
  let mode = flags.mode as InitMode | undefined;
23
24
  if (mode === undefined) {
24
25
  const picked = await prompter.select<InitMode>(
@@ -35,6 +36,8 @@ export async function promptForInit(flags: RawInitFlags, ctx: { defaultWorkflowR
35
36
  }
36
37
  if (mode === "local") return { ...flags, mode };
37
38
 
39
+ prompter.step("GitHub workflow", 3, mode === "both" ? 6 : 4);
40
+
38
41
  const operator =
39
42
  flags.operator ?? (await prompter.text("GitHub login of the operator (the one person whose /wachiman comments start a run)", undefined, (v) => operatorProblem(v)));
40
43
  if (operator === null) return null;
package/src/init/run.ts CHANGED
@@ -12,8 +12,10 @@ import { spawnGit, type GitRunner } from "../evidence";
12
12
  import { repositoryKey } from "../history/store";
13
13
  import { isInteractive, type TerminalStreams } from "../wizard/interactive";
14
14
  import { createPrompter, type Prompter, type PromptIO } from "../wizard/prompt";
15
+ import { wizardIo } from "../wizard/style";
16
+ import { projectCommands } from "../wizard/command";
15
17
  import { DEFAULT_WORKFLOW_REF, resolveInitOptions, type InitOptions, type RawInitFlags } from "./options";
16
- import { promptForInit } from "./prompt";
18
+ import { checkSupplied, promptForInit } from "./prompt";
17
19
  import { callerHeader, renderCallerWorkflow } from "./render";
18
20
  import { inspectTarget, writeWorkflow, type WriteHooks } from "./write";
19
21
 
@@ -33,7 +35,7 @@ export interface InitDeps {
33
35
  /** An open prompt session; the caller closes it. Otherwise one is opened over `promptIO` or the terminal. */
34
36
  prompter?: Prompter;
35
37
  /** What `wachiman setup` means from here: runs the setup wizard in the same process, sharing `prompter`. */
36
- bindNow?: (prompter: Prompter) => Promise<number>;
38
+ bindNow?: (prompter: Prompter, mode: "local" | "both") => Promise<number>;
37
39
  /** The directory a relative `--repo-dir` was resolved against, for the `setup` line. Default: `process.cwd()`. */
38
40
  cwd?: string;
39
41
  hooks?: WriteHooks;
@@ -42,25 +44,26 @@ export interface InitDeps {
42
44
  const TEMPLATE = join(import.meta.dir, "..", "..", "templates", "wachiman-review-caller.yml");
43
45
  const readDefaultTemplate = () => readFileSync(TEMPLATE, "utf8");
44
46
 
45
- /** The line that hands over to `setup`. */
46
- export function setupLine(repoDir: string, cwd: string) {
47
- return repoDir === cwd ? "wachiman setup" : `wachiman setup --repo-dir ${repoDir}`;
48
- }
49
-
50
- const openSession = (deps: InitDeps) => {
47
+ const openSession = (deps: InitDeps, env: Record<string, string | undefined>) => {
51
48
  if (deps.prompter) return { prompter: deps.prompter, close: () => {} };
52
- const prompter = createPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr });
49
+ const prompter = createPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr }, env);
53
50
  return { prompter, close: () => prompter.close() };
54
51
  };
55
52
 
56
53
  /** From the parsed flags: asks what is missing when a person can be asked, resolves, and runs. */
57
54
  export async function runInitCommand(flags: RawInitFlags, env: Record<string, string | undefined>, io: CommandIo, deps: InitDeps = {}): Promise<number> {
55
+ // Fail before asking for an operator or account in an unusable target.
56
+ const root = worktreeRoot(flags.repoDir ?? ".", deps.git);
58
57
  const interactive = deps.interactive ?? isInteractive(flags, env, deps.streams ?? { stdin: process.stdin, stdout: process.stdout });
58
+ if (interactive) io = wizardIo(io, (deps.promptIO?.output ?? process.stderr) as { isTTY?: boolean }, env);
59
59
  const defaultWorkflowRef = "defaultWorkflowRef" in deps ? deps.defaultWorkflowRef : DEFAULT_WORKFLOW_REF;
60
- const session = interactive ? openSession(deps) : undefined;
60
+ const session = interactive ? openSession(deps, env) : undefined;
61
61
  try {
62
62
  let answered = flags;
63
63
  if (session) {
64
+ checkSupplied(flags);
65
+ session.prompter.step("Project", 1);
66
+ session.prompter.say(root, "muted");
64
67
  const asked = await promptForInit(flags, { defaultWorkflowRef }, session.prompter);
65
68
  if (asked === null) {
66
69
  io.stderr("cancelled: nothing was written.");
@@ -80,14 +83,7 @@ export async function runInitCommand(flags: RawInitFlags, env: Record<string, st
80
83
  export async function runInit(options: InitOptions, io: CommandIo, deps: InitDeps = {}): Promise<number> {
81
84
  const cwd = deps.cwd ?? process.cwd();
82
85
  // Before anything is rendered or written: this must be a git repository.
83
- repositoryKey(options.repoDir, deps.git);
84
- // `--path` is relative to the repository top level: GitHub only runs workflows under <top level>/.github/workflows.
85
- const top = (deps.git ?? spawnGit)(["rev-parse", "--show-toplevel"], { cwd: options.repoDir, timeoutMs: 10_000 });
86
- if (top.status !== 0 || top.stdout.trim() === "") {
87
- // A bare repository or a directory inside .git: there is no work tree for GitHub to run a workflow from.
88
- throw new UsageError(`${options.repoDir} is not inside a git work tree; run init from the repository or pass --repo-dir <its top level>.`);
89
- }
90
- const root = top.stdout.trim();
86
+ const root = worktreeRoot(options.repoDir, deps.git);
91
87
  const { github } = options;
92
88
  const prompter = options.interactive ? deps.prompter : undefined;
93
89
  let written: string | undefined;
@@ -128,25 +124,40 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
128
124
  const result = writeWorkflow({ repoDir: root, relativePath: github.path, content: rendered, inspected, now, hooks: deps.hooks });
129
125
  written = shown;
130
126
  io.stderr(`wrote ${shown}${result.backup ? `; the earlier file is kept as ${join(dirname(github.path), basename(result.backup))}` : ""}.`);
127
+ if (options.mode === "github") prompter?.step("Checks and next actions", 4, 4);
131
128
  io.stderr("Two things are left to do in GitHub:");
132
129
  io.stderr(" 1. Add the repository secret ANTHROPIC_API_KEY (a Console key; Actions runs are billed to it): Settings, Secrets and variables, Actions.");
133
130
  io.stderr(` 2. Open a pull request that adds ${shown}. init does not commit, push or open one.`);
134
131
  io.stderr("Local runs use your signed-in claude, never this key.");
135
132
  }
136
133
 
137
- if (options.mode === "github") return 0;
134
+ if (options.mode === "github") {
135
+ io.stderr("github: pending; workflow written, add the secret and submit the workflow. Remote readiness was not checked.");
136
+ return 0;
137
+ }
138
138
  if (prompter && deps.bindNow) {
139
- const answer = await prompter.confirm("Run wachiman setup now to bind this repository to a Claude account?", true);
140
- if (answer === null) {
141
- io.stderr(written ? `cancelled: ${written} was written and stays; nothing else was changed.` : "cancelled: nothing was written.");
142
- return 130;
143
- }
144
- if (answer) {
145
- const code = await deps.bindNow(prompter);
139
+ try {
140
+ const code = await deps.bindNow(prompter, options.mode);
146
141
  if (code === 130 && written) io.stderr(`${written} was written before setup was cancelled and stays in place.`);
142
+ if (code !== 130 && written) io.stderr(`github: pending; ${written} is written. Secret and workflow submission still require action in GitHub.`);
147
143
  return code;
144
+ } catch (error) {
145
+ if (written) io.stderr(`${written} was written before setup failed and stays in place.`);
146
+ throw error;
148
147
  }
149
148
  }
150
- io.stderr(`Next, on this machine: ${setupLine(options.repoDir, cwd)} (binds this repository to a Claude account)`);
149
+
150
+ if (written) io.stderr(`github: pending; ${written} is written. Secret and workflow submission still require action in GitHub.`);
151
+ for (const command of projectCommands("setup", options.repoDir, cwd)) io.stderr(`Next, on this machine: ${command} (binds this repository to a Claude account)`);
151
152
  return 0;
152
153
  }
154
+
155
+ /** Workflows belong at the Git top level, including when init starts below it. */
156
+ function worktreeRoot(repoDir: string, git: GitRunner = spawnGit): string {
157
+ repositoryKey(repoDir, git);
158
+ const top = git(["rev-parse", "--show-toplevel"], { cwd: repoDir, timeoutMs: 10_000 });
159
+ if (top.status !== 0 || top.stdout.trim() === "") {
160
+ throw new UsageError(`${repoDir} is not inside a git work tree; run init from the repository or pass --repo-dir <its top level>.`);
161
+ }
162
+ return top.stdout.trim();
163
+ }
@@ -0,0 +1,231 @@
1
+ /**
2
+ * `wachiman ask` (ADR 0032, decisions 1, 6, 7 and 8): one question about the local change, or its
3
+ * walkthrough when no question is given. It is the same core a pull request comment uses, fed with
4
+ * the change the scope flags select and with the latest stored review of that change (ADR 0020).
5
+ *
6
+ * One provider call, on the signed-in `claude` as `local` runs (ADR 0019 decision 4), and no GitHub
7
+ * call: this module never builds a `gh` function. The command never runs a review. It reads the
8
+ * repository, reads the history store, and writes its material to a temporary directory it removes.
9
+ *
10
+ * Exit codes: 0 answered (an answer that says what it could not answer is still an answer); 1 no
11
+ * answer (the call failed, or its output was not an answer); 2 usage error; 130 after Ctrl-C.
12
+ */
13
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
14
+ import { tmpdir } from "node:os";
15
+ import { join, resolve } from "node:path";
16
+ import { wachimanHome } from "./accounts/config";
17
+ import { ASK_SCHEMA, buildAskPrompt, checkRefs, isAskAnswer, renderAnswer } from "./ask";
18
+ import { repoLineCounter } from "./contracts";
19
+ import { UsageError } from "./config";
20
+ import { annotateDiff, DEFAULT_EXCLUDE, filterFiles, renderInstructions, runProvider, type ReviewInput, type ReviewResult } from "./engine";
21
+ import { historyRoot, readRuns, repositoryKey } from "./history/store";
22
+ import { type LocalArgs, type LocalDeps, localScopeInput, openLocalSession, parseFlags } from "./local";
23
+ import { costSentence } from "./sinks/common";
24
+ import { renderJson } from "./sinks/json";
25
+ import { renderMarkdown } from "./sinks/markdown";
26
+
27
+ export const ASK_FORMAT = "wachiman.ask-result/1";
28
+
29
+ export const askUsage = `wachiman ask [question…] [--base <ref> | --from <commit> | --commit <commit> | --working-tree staged|all]
30
+ [--max-depth <n>] [--repo-dir <dir>] [--profile <name>]
31
+ [--format terminal|markdown|json] [--output <file>]`;
32
+
33
+ /** The flags `ask` takes: the scope flags `local` has, and the output and account ones. */
34
+ const ASK_FLAGS = ["--base", "--from", "--commit", "--working-tree", "--max-depth", "--profile", "--format", "--output"] as const;
35
+
36
+ export interface AskArgs extends LocalArgs {
37
+ /** The question's words joined with spaces; "" asks for the walkthrough. */
38
+ question: string;
39
+ }
40
+
41
+ /** The arguments after `ask` (`--repo-dir` is already taken out). Every word that is not a flag is the question. */
42
+ export function parseAskArgs(argv: string[]): AskArgs {
43
+ const args = parseFlags(argv, "ask", ASK_FLAGS);
44
+ return { ...args, paths: [], question: args.paths.join(" ").trim() };
45
+ }
46
+
47
+ export const NO_REVIEW_NOTICE =
48
+ 'No stored review of this change: answering from the diff alone. Run "wachiman local --history" first to ground answers in a review.';
49
+
50
+ /**
51
+ * The latest stored review of this change, or undefined. It must be of the same repository (the
52
+ * store's key), the same kind of change, the same base and head commits (a tree for `--working-tree`),
53
+ * and the same files kept for review. A review of another range, another head or another scope is
54
+ * not this change, so it is not used.
55
+ */
56
+ export function storedReviewOf(
57
+ root: string,
58
+ repoDir: string,
59
+ input: ReviewInput,
60
+ keptFiles: string[],
61
+ warn: (line: string) => void,
62
+ ): ReviewResult | undefined {
63
+ const runs = readRuns(root, repositoryKey(repoDir).key, warn);
64
+ const files = [...keptFiles].sort();
65
+ for (let i = runs.length - 1; i >= 0; i--) {
66
+ const { result } = runs[i];
67
+ if (
68
+ result.change.kind !== input.change.kind ||
69
+ result.change.base.sha !== input.change.base.sha ||
70
+ result.change.head.sha !== input.change.head.sha
71
+ )
72
+ continue;
73
+ // The files the review was given: its expected ones and the binaries it left out of them.
74
+ const expected = [...result.coverage.expected, ...(result.coverage.unreviewable ?? []).map((u) => u.path)].sort();
75
+ if (expected.length === files.length && expected.every((f, j) => f === files[j])) return result;
76
+ }
77
+ return undefined;
78
+ }
79
+
80
+ export function runAsk(
81
+ args: AskArgs,
82
+ repoDir: string,
83
+ env: Record<string, string | undefined>,
84
+ io: {
85
+ stdout: (text: string) => void;
86
+ stderr: (line: string) => void;
87
+ engineVersion: string;
88
+ },
89
+ deps: LocalDeps = {},
90
+ ): number {
91
+ // The account, the provider and the settings are checked before the change is read, as `local` does.
92
+ const { config, provider, state } = openLocalSession({
93
+ profile: args.profile,
94
+ verify: false,
95
+ repoDir,
96
+ env,
97
+ stderr: io.stderr,
98
+ deps,
99
+ });
100
+ const onSigint = () => {
101
+ state.interrupted = true;
102
+ };
103
+ process.on("SIGINT", onSigint);
104
+ let release: (() => void) | undefined;
105
+ let material: string | undefined;
106
+ try {
107
+ const scope = localScopeInput({
108
+ repoDir,
109
+ workingTree: args.workingTree,
110
+ base: args.base,
111
+ commit: args.commit,
112
+ from: args.from,
113
+ maxDepth: args.maxDepth,
114
+ paths: args.paths,
115
+ log: io.stderr,
116
+ warn: io.stderr,
117
+ });
118
+ release = scope.release;
119
+ const { input } = scope;
120
+ // The same files the review would send (its excludes and its scope), so both read one change.
121
+ const { kept, dropped } = filterFiles(input.files, [...DEFAULT_EXCLUDE, ...config.exclude], input.scope);
122
+ if (kept.length === 0) {
123
+ throw new UsageError(`No file in this scope is kept for review (${dropped.length} excluded): there is nothing to ask about.`);
124
+ }
125
+
126
+ material = mkdtempSync(join(tmpdir(), "wachiman-ask-"));
127
+ writeFileSync(join(material, "ask.diff"), annotateDiff(kept));
128
+ writeFileSync(
129
+ join(material, "ask.json"),
130
+ `${JSON.stringify(
131
+ {
132
+ change: input.change.describe,
133
+ kind: input.change.kind,
134
+ scope: input.scope,
135
+ files: kept.map((f) => ({ path: f.filename, additions: f.additions, deletions: f.deletions })),
136
+ excludedFiles: dropped.length,
137
+ },
138
+ null,
139
+ 2,
140
+ )}\n`,
141
+ );
142
+ const stored = storedReviewOf(historyRoot(wachimanHome(env)), repoDir, input, kept.map((f) => f.filename), io.stderr);
143
+ if (stored) {
144
+ writeFileSync(join(material, "review.json"), renderJson(stored, 2));
145
+ writeFileSync(join(material, "review.md"), renderMarkdown(stored));
146
+ } else io.stderr(NO_REVIEW_NOTICE);
147
+
148
+ const prompt = buildAskPrompt({
149
+ changeDescription: `the local change in repository ${input.change.repository.name}: ${input.change.describe}`,
150
+ materialPaths: {
151
+ meta: join(material, "ask.json"),
152
+ diff: join(material, "ask.diff"),
153
+ review: stored ? join(material, "review.md") : undefined,
154
+ },
155
+ instructions: renderInstructions(input.instructions),
156
+ question: args.question,
157
+ hasReview: stored !== undefined,
158
+ local: true,
159
+ });
160
+
161
+ // One call, read-only, in the snapshot of the head: the same place the review reads from.
162
+ let result: ReturnType<typeof runProvider> | undefined;
163
+ let failure = "";
164
+ try {
165
+ result = runProvider(
166
+ { provider, log: io.stderr, warn: io.stderr },
167
+ config,
168
+ input.headDir,
169
+ { operation: "on-demand", label: args.question ? "question" : "walkthrough" },
170
+ prompt,
171
+ material,
172
+ config.answerBudgetUsd,
173
+ ASK_SCHEMA,
174
+ );
175
+ } catch (error) {
176
+ failure = error instanceof Error ? error.message : String(error);
177
+ }
178
+ if (state.interrupted) {
179
+ io.stderr("Interrupted: the answer was not produced.");
180
+ return 130;
181
+ }
182
+ const parsed = result && !result.isError ? result.structuredOutput : undefined;
183
+ if (!result || !isAskAnswer(parsed)) {
184
+ const reason = result ? (result.isError ? result.terminalReason || "the call failed" : "its output was not an answer") : failure;
185
+ io.stderr(`Wachiman could not answer (${reason}).`);
186
+ return 1;
187
+ }
188
+
189
+ // A reference is kept only if its file exists in the head snapshot and the line is in the file.
190
+ const lineCount = repoLineCounter(input.headDir);
191
+ const checked = checkRefs(parsed, (path, line) => {
192
+ const count = lineCount(path);
193
+ return count !== null && line <= count;
194
+ });
195
+ const cost = { costUsdEstimate: result.costUsd, calls: 1, turns: result.turns, durationMs: result.durationMs };
196
+ const text =
197
+ args.format === "json"
198
+ ? `${JSON.stringify(
199
+ {
200
+ format: ASK_FORMAT,
201
+ question: args.question,
202
+ walkthrough: args.question === "",
203
+ hasReview: stored !== undefined,
204
+ sections: checked.answer.sections.map((s) => ({
205
+ title: s.title,
206
+ body: s.body,
207
+ refs: s.refs.map((r) => ({ path: r.path, line: r.line })),
208
+ })),
209
+ notAnswered: checked.answer.not_answered,
210
+ removedRefs: checked.removed,
211
+ provider: { label: provider.modelLabel(), model: config.model, costUsd: result.costUsd },
212
+ },
213
+ null,
214
+ 2,
215
+ )}\n`
216
+ : `${renderAnswer(checked.answer, {
217
+ removed: checked.removed,
218
+ style: args.format === "markdown" ? "markdown" : "plain",
219
+ })}\n\n${costSentence(cost)}\n`;
220
+ if (args.output !== undefined) {
221
+ const path = resolve(args.output);
222
+ writeFileSync(path, text);
223
+ io.stderr(`report: ${path}`);
224
+ } else io.stdout(text);
225
+ return 0;
226
+ } finally {
227
+ process.off("SIGINT", onSigint);
228
+ release?.();
229
+ if (material !== undefined) rmSync(material, { recursive: true, force: true });
230
+ }
231
+ }