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/risk.ts ADDED
@@ -0,0 +1,264 @@
1
+ /**
2
+ * The risk map of a review (ADR 0031). The level is computed here from path rules and from the
3
+ * risk facts the batch calls reported; the model never states a level. Judgement items say where
4
+ * a person must decide, and they never change the level. Pure: no I/O, so every rule is tested
5
+ * directly.
6
+ */
7
+ import { fileKind, JUDGEMENT_KINDS, neutralise, RISK_KINDS, riskScore, RISK_RULES } from "./engine";
8
+
9
+ export { JUDGEMENT_KINDS, RISK_KINDS };
10
+ export type RiskKind = (typeof RISK_KINDS)[number];
11
+ export type JudgementKind = (typeof JUDGEMENT_KINDS)[number];
12
+
13
+ export type RiskLevel = "low" | "medium" | "high";
14
+
15
+ export interface RiskFact {
16
+ kind: RiskKind;
17
+ path: string;
18
+ line: number;
19
+ why: string;
20
+ }
21
+
22
+ export interface JudgementItem {
23
+ kind: JudgementKind;
24
+ path: string;
25
+ line: number;
26
+ why: string;
27
+ }
28
+
29
+ /** The level a fact kind sets, whatever its path (ADR 0031). */
30
+ export const KIND_LEVEL: Record<RiskKind, RiskLevel> = {
31
+ "data-migration": "high",
32
+ irreversible: "high",
33
+ auth: "high",
34
+ money: "high",
35
+ concurrency: "medium",
36
+ "public-contract": "medium",
37
+ "config-or-ci": "medium",
38
+ dependency: "low",
39
+ };
40
+
41
+ /*
42
+ * Uncalibrated defaults (ADR 0031). The plan calibrates them on merged pull requests of the
43
+ * consumer repositories before release; change them together with their tests.
44
+ */
45
+ export const HIGH_PATH_WEIGHT = 8;
46
+ export const MEDIUM_PATH_WEIGHT = 6;
47
+
48
+ /** At most this many judgement items are kept per review. */
49
+ const JUDGEMENT_CAP = 3;
50
+ /** At most this many paths are listed under "Read first". */
51
+ const READ_FIRST_CAP = 5;
52
+
53
+ const LEVEL_RANK: Record<RiskLevel, number> = { low: 0, medium: 1, high: 2 };
54
+ const LEVEL_WORD: Record<RiskLevel, string> = { low: "Low", medium: "Medium", high: "High" };
55
+
56
+ export function pathLevel(weight: number): RiskLevel {
57
+ if (weight >= HIGH_PATH_WEIGHT) return "high";
58
+ if (weight >= MEDIUM_PATH_WEIGHT) return "medium";
59
+ return "low";
60
+ }
61
+
62
+ /*
63
+ * Built on first use, not at load: `RISK_RULES` lives in `engine.ts`, which imports this module,
64
+ * so reading it while this module loads could find it not yet initialised.
65
+ */
66
+ let riskGlobs: { weight: number; why: string; matcher: Bun.Glob }[] | undefined;
67
+
68
+ /**
69
+ * The RISK_RULES entry that sets a file's `riskScore`: the highest-weight match, the first one on
70
+ * a tie. Undefined for tests and docs, which score by their kind, not by a rule.
71
+ */
72
+ export function matchingRule(path: string): { weight: number; why: string } | undefined {
73
+ if (fileKind(path) !== "code") return undefined;
74
+ riskGlobs ??= RISK_RULES.map((r) => ({ weight: r.weight, why: r.why, matcher: new Bun.Glob(r.glob) }));
75
+ let best: { weight: number; why: string } | undefined;
76
+ for (const r of riskGlobs) {
77
+ if (r.matcher.match(path) && (!best || r.weight > best.weight)) {
78
+ best = { weight: r.weight, why: r.why };
79
+ }
80
+ }
81
+ return best;
82
+ }
83
+
84
+ export interface RiskMap {
85
+ level: RiskLevel;
86
+ /** True when some files were not reviewed: the level is then "at least" `level`. */
87
+ floor: boolean;
88
+ /** Kept facts, most severe kind first. */
89
+ facts: RiskFact[];
90
+ /** Kept judgement items, at most three. */
91
+ judgement: JudgementItem[];
92
+ /** Files whose path rule gives medium or high. */
93
+ pathReasons: { path: string; why: string }[];
94
+ /** Up to five paths, most worth reading first. */
95
+ readFirst: string[];
96
+ unreadFiles: number;
97
+ /** Facts and judgement items dropped because their path or line is not in the change. */
98
+ droppedFacts: number;
99
+ }
100
+
101
+ export function buildRiskMap(input: {
102
+ files: { path: string; changedLines: number }[];
103
+ facts: RiskFact[];
104
+ judgement: JudgementItem[];
105
+ unreadFiles: number;
106
+ lineExists: (path: string, line: number) => boolean;
107
+ }): RiskMap {
108
+ const paths = new Set(input.files.map((f) => f.path));
109
+ const anchored = (item: { path: string; line: number }) =>
110
+ paths.has(item.path) && input.lineExists(item.path, item.line);
111
+
112
+ let droppedFacts = 0;
113
+ const seen = new Set<string>();
114
+ const facts: RiskFact[] = [];
115
+ for (const fact of input.facts) {
116
+ if (!anchored(fact)) {
117
+ droppedFacts++;
118
+ continue;
119
+ }
120
+ const key = `${fact.kind}\u0000${fact.path}\u0000${fact.line}`;
121
+ if (seen.has(key)) continue;
122
+ seen.add(key);
123
+ facts.push(fact);
124
+ }
125
+ // Array.prototype.sort is stable: facts of one severity keep the order the model gave them.
126
+ facts.sort((a, b) => LEVEL_RANK[KIND_LEVEL[b.kind]] - LEVEL_RANK[KIND_LEVEL[a.kind]]);
127
+
128
+ const judgement: JudgementItem[] = [];
129
+ for (const item of input.judgement) {
130
+ if (!anchored(item)) {
131
+ droppedFacts++;
132
+ continue;
133
+ }
134
+ judgement.push(item);
135
+ }
136
+
137
+ let level: RiskLevel = "low";
138
+ for (const f of input.files) {
139
+ const fromPath = pathLevel(riskScore(f.path));
140
+ if (LEVEL_RANK[fromPath] > LEVEL_RANK[level]) level = fromPath;
141
+ }
142
+ for (const f of facts) {
143
+ if (LEVEL_RANK[KIND_LEVEL[f.kind]] > LEVEL_RANK[level]) level = KIND_LEVEL[f.kind];
144
+ }
145
+
146
+ const pathReasons: { path: string; why: string }[] = [];
147
+ for (const f of input.files) {
148
+ const rule = matchingRule(f.path);
149
+ if (rule && pathLevel(rule.weight) !== "low") pathReasons.push({ path: f.path, why: rule.why });
150
+ }
151
+
152
+ // Each path's most severe kept fact, as a rank; -1 for a path with no fact.
153
+ const factRank = new Map<string, number>();
154
+ for (const f of facts) {
155
+ const rank = LEVEL_RANK[KIND_LEVEL[f.kind]];
156
+ factRank.set(f.path, Math.max(rank, factRank.get(f.path) ?? -1));
157
+ }
158
+ const readFirst = [...input.files]
159
+ .sort(
160
+ (a, b) =>
161
+ (factRank.get(b.path) ?? -1) - (factRank.get(a.path) ?? -1) ||
162
+ riskScore(b.path) - riskScore(a.path) ||
163
+ b.changedLines - a.changedLines ||
164
+ (a.path < b.path ? -1 : a.path > b.path ? 1 : 0),
165
+ )
166
+ .slice(0, READ_FIRST_CAP)
167
+ .map((f) => f.path);
168
+
169
+ return {
170
+ level,
171
+ floor: input.unreadFiles > 0,
172
+ facts,
173
+ judgement: judgement.slice(0, JUDGEMENT_CAP),
174
+ pathReasons,
175
+ readFirst,
176
+ unreadFiles: input.unreadFiles,
177
+ droppedFacts,
178
+ };
179
+ }
180
+
181
+ /**
182
+ * Keeps the well-formed items of a batch's `risk_facts` or `judgement` array. The schema makes the
183
+ * arrays optional, so a missing one is empty; a malformed item is ignored, never guessed at.
184
+ */
185
+ export function wellFormed<T extends { kind: string; path: string; line: number; why: string }>(
186
+ items: unknown,
187
+ kinds: readonly string[],
188
+ ): T[] {
189
+ if (!Array.isArray(items)) return [];
190
+ return items.filter(
191
+ (item): item is T =>
192
+ item !== null &&
193
+ typeof item === "object" &&
194
+ kinds.includes((item as T).kind) &&
195
+ typeof (item as T).path === "string" &&
196
+ Number.isInteger((item as T).line) &&
197
+ (item as T).line >= 1 &&
198
+ typeof (item as T).why === "string",
199
+ );
200
+ }
201
+
202
+ /** How the map's words are marked up: Markdown for GitHub and the Markdown file, plain for the terminal. */
203
+ export interface RiskMapStyle {
204
+ strong(text: string): string;
205
+ code(text: string): string;
206
+ }
207
+
208
+ export const MARKDOWN_STYLE: RiskMapStyle = {
209
+ strong: (text) => `**${text}**`,
210
+ code: (text) => `\`${neutralise(text)}\``,
211
+ };
212
+
213
+ export const PLAIN_STYLE: RiskMapStyle = { strong: (text) => text, code: (text) => neutralise(text) };
214
+
215
+ const notReviewed = (n: number) => (n === 1 ? "1 file was not reviewed." : `${n} files were not reviewed.`);
216
+
217
+ /**
218
+ * The map as text: `heading` is the title line when the map has content (`### Risk map` on GitHub,
219
+ * `## Risk map` in Markdown, `Risk map:` in the terminal); the two-line form for a change with no
220
+ * facts has none. `pushOnly` puts "This push only." in front of the level line, for a review that
221
+ * covers one push of a pull request (ADR 0011).
222
+ */
223
+ export function renderRiskMap(
224
+ map: RiskMap,
225
+ heading: string,
226
+ opts: { pushOnly?: boolean; style?: RiskMapStyle } = {},
227
+ ): string {
228
+ const { strong, code } = opts.style ?? MARKDOWN_STYLE;
229
+ const lead = opts.pushOnly ? "This push only. " : "";
230
+ const readFirst =
231
+ map.readFirst.length > 0
232
+ ? `${strong("Read first:")} ${map.readFirst.map(code).join(", ")}.`
233
+ : undefined;
234
+
235
+ if (map.facts.length === 0 && map.judgement.length === 0 && map.pathReasons.length === 0) {
236
+ const summary = map.floor
237
+ ? `${lead}${strong("Risk map:")} at least ${map.level} — no risk facts in the files read; ${notReviewed(map.unreadFiles)}`
238
+ : `${lead}${strong("Risk map:")} ${map.level} — no risk facts in this change.`;
239
+ return [summary, readFirst].filter((line) => line !== undefined).join("\n");
240
+ }
241
+
242
+ const covered = new Set(map.facts.map((f) => f.path));
243
+ const bullets = [
244
+ ...map.facts.map((f) => `- ${code(f.kind)} · ${code(`${f.path}:${f.line}`)} — ${neutralise(f.why)}`),
245
+ ...map.pathReasons
246
+ .filter((r) => !covered.has(r.path))
247
+ .map((r) => `- ${code(r.path)} — ${neutralise(r.why)}`),
248
+ ];
249
+
250
+ const level = map.floor
251
+ ? `${lead}${strong(`At least ${map.level}.`)} ${notReviewed(map.unreadFiles)}`
252
+ : `${lead}${strong(`${LEVEL_WORD[map.level]}.`)}`;
253
+
254
+ const blocks = [heading, level];
255
+ if (bullets.length > 0) blocks.push(bullets.join("\n"));
256
+ if (map.judgement.length > 0) {
257
+ const items = map.judgement.map(
258
+ (j) => `- ${code(`${j.path}:${j.line}`)} (${code(j.kind)}) — ${neutralise(j.why)}`,
259
+ );
260
+ blocks.push(`${strong("Needs a person:")}\n\n${items.join("\n")}`);
261
+ }
262
+ if (readFirst !== undefined) blocks.push(readFirst);
263
+ return blocks.join("\n\n");
264
+ }
@@ -7,7 +7,7 @@
7
7
  import { basename, join } from "node:path";
8
8
  import { binaryProblem, checkExternalConfigDir, checkNewProfileName } from "../accounts/commands";
9
9
  import type { ProjectBinding, WachimanConfigV1 } from "../accounts/config";
10
- import { buildProfileList, managedDir, refersTo } from "../accounts/profile-list";
10
+ import { buildProfileList, managedDir, refersTo, type ProfileListEntry } from "../accounts/profile-list";
11
11
  import { checkProfileName, ISOLATED_NAME, parseProfileRef } from "../accounts/resolve";
12
12
  import { UsageError } from "../config";
13
13
  import type { HistoryRepository } from "../history/types";
@@ -30,6 +30,9 @@ export interface SetupPromptContext {
30
30
  userHome: string;
31
31
  /** Creates the managed directory and runs the sign-in; called only after the person confirmed that side effect. */
32
32
  createManaged: (name: string) => void;
33
+ /** init already collected the local-mode choice; still confirm the final write. */
34
+ fromInit?: boolean;
35
+ initMode?: "local" | "both";
33
36
  }
34
37
 
35
38
  export type SetupAnswers =
@@ -78,31 +81,40 @@ export async function promptForSetup(flags: RawSetupFlags, ctx: SetupPromptConte
78
81
  const registered = (name: string) => Object.hasOwn(config?.profiles ?? {}, name);
79
82
  const say = (line: string) => prompter.say(line);
80
83
 
81
- say(`repository: ${repo.name} (${repo.keyedBy === "remote" ? `origin ${repo.remote ?? "(unparsed)"}` : `path ${repo.path}`})`);
82
- if (ctx.current) say(`currently bound to ${ctx.current.profile}`);
83
- const go = await prompter.confirm("Set up this repository?", true);
84
- if (go === null) return { kind: "cancelled" };
85
- if (!go) return { kind: "declined" };
84
+ const total = ctx.fromInit ? (ctx.initMode === "both" ? 6 : 5) : 4;
85
+ if (!ctx.fromInit) {
86
+ prompter.step("Project", 1, total);
87
+ say(`repository: ${repo.name} (${repo.keyedBy === "remote" ? `origin ${repo.remote ?? "(unparsed)"}` : `path ${repo.path}`})`);
88
+ if (ctx.current) say(`currently bound to ${ctx.current.profile}`);
89
+ const go = await prompter.confirm("Set up this repository?", true);
90
+ if (go === null) return { kind: "cancelled" };
91
+ if (!go) return { kind: "declined" };
92
+ }
86
93
 
87
94
  let name = flags.profile;
95
+ prompter.step("Claude account", total - 2, total);
96
+ if (ctx.fromInit && ctx.current) say(`currently bound to ${ctx.current.profile}`);
88
97
  let pending: PendingProfile | undefined;
89
98
  while (name === undefined) {
90
99
  const list = buildProfileList(home, config);
91
- const rows: { label: string; value: string | typeof REGISTER | typeof CREATE }[] = list.profiles.map((p) => {
100
+ const profiles: ProfileListEntry[] = [{ name: "default", kind: "default", registered: true, usedBy: [] }, ...list.profiles];
101
+ const rows: { label: string; description?: string; value: string | typeof REGISTER | typeof CREATE }[] = profiles.map((p) => {
92
102
  const marks = [
93
- ctx.current && refersTo(ctx.current.profile, p.name) ? "(current)" : "",
94
- list.defaultProfile !== undefined && refersTo(list.defaultProfile, p.name) ? "(global default)" : "",
103
+ ctx.current && (ctx.current.profile === p.name || refersTo(ctx.current.profile, p.name)) ? "(current)" : "",
104
+ list.defaultProfile !== undefined && (list.defaultProfile === p.name || refersTo(list.defaultProfile, p.name)) ? "(global default)" : "",
95
105
  p.registered ? "" : "(unregistered)",
96
106
  ].filter(Boolean);
97
107
  const where = p.kind === "external" ? `${p.configDir}, ${p.binary ? `binary ${p.binary}` : "claude from PATH"}` : p.configDir;
98
- return { label: `${p.name} ${p.kind} ${where}${marks.length ? ` ${marks.join(" ")}` : ""}`, value: p.name };
108
+ const label = p.kind === "default" ? "Use my current Claude session" : `${p.name} ${p.kind}`;
109
+ return { label: `${label}${marks.length ? ` ${marks.join(" ")}` : ""}`, description: p.kind === "default" ? "Shares your normal Claude settings." : where, value: p.name };
99
110
  });
100
- rows.push({ label: "Register an existing Claude configuration directory (external)", value: REGISTER });
101
111
  rows.push({ label: "Create a new isolated profile (managed)", value: CREATE });
102
- const currentIndex = ctx.current ? list.profiles.findIndex((p) => refersTo(ctx.current!.profile, p.name)) : -1;
103
- const globalIndex = list.defaultProfile !== undefined ? list.profiles.findIndex((p) => refersTo(list.defaultProfile!, p.name)) : -1;
104
- const defaultIndex = currentIndex >= 0 ? currentIndex : globalIndex >= 0 ? globalIndex : list.profiles.length;
105
- const label = list.profiles.length > 0 ? "Which account profile should this repository use?" : "No profile is registered yet. What do you want to do?";
112
+ rows.push({ label: "Register an existing Claude configuration directory (external)", value: REGISTER });
113
+ const indexOf = (ref: string) => profiles.findIndex((p) => ref === p.name || refersTo(ref, p.name));
114
+ const currentIndex = ctx.current ? indexOf(ctx.current.profile) : -1;
115
+ const globalIndex = list.defaultProfile !== undefined ? indexOf(list.defaultProfile) : -1;
116
+ const defaultIndex = currentIndex >= 0 ? currentIndex : globalIndex >= 0 ? globalIndex : 0;
117
+ const label = "Which account profile should this repository use?";
106
118
  const picked = await prompter.select(label, rows, defaultIndex);
107
119
  if (picked === null) return { kind: "cancelled" };
108
120
 
@@ -155,6 +167,7 @@ export async function promptForSetup(flags: RawSetupFlags, ctx: SetupPromptConte
155
167
  const kind = p?.kind ?? known?.kind ?? (name === "default" ? "default" : "managed");
156
168
  const directory = p?.configDir ?? known?.configDir ?? (name === "default" ? undefined : join(home, `claude-${name.replace(/^isolated:/, "")}`));
157
169
  const binary = p?.kind === "external" ? p.binary : known?.kind === "external" ? known.binary : undefined;
170
+ prompter.step("Confirm binding", total - 1, total);
158
171
  say("Bind this repository:");
159
172
  say(` profile: ${name}`);
160
173
  say(` kind: ${kind}`);
package/src/setup/run.ts CHANGED
@@ -30,10 +30,17 @@ import { repositoryKey } from "../history/store";
30
30
  import { claimManagedProfile, setupProfile } from "../profiles";
31
31
  import { isInteractive, type TerminalStreams } from "../wizard/interactive";
32
32
  import { createPrompter, type Prompter, type PromptIO } from "../wizard/prompt";
33
+ import { wizardIo } from "../wizard/style";
33
34
  import { resolveSetupOptions, type RawSetupFlags } from "./options";
34
35
  import { promptForSetup, type PendingProfile } from "./prompt";
35
36
 
36
37
  export interface SetupDeps extends AccountDeps {
38
+ /** The person already chose local setup in init. */
39
+ fromInit?: boolean;
40
+ /** Both mode has one extra workflow stage before account setup. */
41
+ initMode?: "local" | "both";
42
+ /** The commands that bind later; printed when a run started from init ends without saving a binding. */
43
+ unboundHints?: readonly string[];
37
44
  streams?: TerminalStreams;
38
45
  promptIO?: PromptIO;
39
46
  /** An open prompt session (shared with `init`); the caller closes it. */
@@ -52,6 +59,7 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
52
59
  }
53
60
 
54
61
  const repoDir = flags.repoDir ?? ".";
62
+ io = wizardIo(io, (deps.promptIO?.output ?? process.stderr) as { isTTY?: boolean }, env);
55
63
  const home = wachimanHome(env);
56
64
  const userHome = deps.userHome ?? homedir();
57
65
  const now = deps.now ?? (() => new Date().toISOString());
@@ -65,7 +73,7 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
65
73
  if (!found.ok) throw new UsageError(found.problem);
66
74
  }
67
75
 
68
- const prompter = deps.prompter ?? createPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr });
76
+ const prompter = deps.prompter ?? createPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr }, env);
69
77
  const ownsPrompter = deps.prompter === undefined;
70
78
  /** What already happened on disk or in Claude and cannot be rolled back; reported whenever the run ends early. */
71
79
  const effects: string[] = [];
@@ -103,7 +111,7 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
103
111
  try {
104
112
  let answers;
105
113
  try {
106
- answers = await promptForSetup(flags, { repo, current, config, home, userHome, createManaged }, prompter);
114
+ answers = await promptForSetup(flags, { repo, current, config, home, userHome, createManaged, fromInit: deps.fromInit, initMode: deps.initMode }, prompter);
107
115
  } catch (error) {
108
116
  // A failed sign-in step still leaves the managed directory behind; say so before the error surfaces.
109
117
  reportEffects();
@@ -112,11 +120,13 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
112
120
  if (answers.kind === "cancelled") {
113
121
  io.stderr("cancelled: no configuration changes saved.");
114
122
  reportEffects();
123
+ for (const hint of deps.unboundHints ?? []) io.stderr(`Next, on this machine: ${hint} (binds this repository to a Claude account)`);
115
124
  return 130;
116
125
  }
117
126
  if (answers.kind === "declined") {
118
127
  io.stderr("nothing saved: the configuration is unchanged.");
119
128
  reportEffects();
129
+ for (const hint of deps.unboundHints ?? []) io.stderr(`Next, on this machine: ${hint} (binds this repository to a Claude account)`);
120
130
  return 0;
121
131
  }
122
132
  const resolved = resolveSetupOptions(answers.flags, { interactive: true });
@@ -167,6 +177,8 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
167
177
  if (status.ok) io.stderr(`account: signed in (${status.auth.authMethod}; claude ${status.binary.version})`);
168
178
  else if (!explained) io.stderr(`warning: ${status.problem} Fix: ${status.fix}`);
169
179
 
180
+ const total = deps.fromInit ? (deps.initMode === "both" ? 6 : 5) : 4;
181
+ prompter.step("Checks and next actions", total, total);
170
182
  const code = closeSetup(repoDir, env, io, deps);
171
183
  if (flags.json) io.stdout(`${JSON.stringify(projectShow(repoDir, env, deps), null, 2)}\n`);
172
184
  return code;
@@ -118,7 +118,11 @@ export const dollars = (usd: number) => `$${usd > 0 && usd < 0.01 ? usd.toFixed(
118
118
 
119
119
  /** The cost, said for what it is (spec D12): the same sentence in every local rendering. */
120
120
  export function estimateLine(result: ReviewResult) {
121
- const e = result.execution;
121
+ return costSentence(result.execution);
122
+ }
123
+
124
+ /** The cost sentence for any run of calls; `wachiman ask` uses it for one answer. */
125
+ export function costSentence(e: { costUsdEstimate: number; calls: number; turns: number; durationMs: number }) {
122
126
  return `Cost: ${dollars(e.costUsdEstimate)}, an API-equivalent estimate (what these calls would cost at API prices), not a bill. ${e.calls} call(s), ${e.turns} turn(s), ${seconds(e.durationMs)}.`;
123
127
  }
124
128
 
@@ -3,6 +3,7 @@
3
3
  * no size limit, so it holds every finding, and it ends with the prompt for the developer's agent.
4
4
  */
5
5
  import { countLine, neutralise, renderContracts, type ReviewResult } from "../engine";
6
+ import { renderRiskMap } from "../risk";
6
7
  import { agentPrompt } from "./agent-prompt";
7
8
  import {
8
9
  coverageText,
@@ -38,6 +39,7 @@ export function renderMarkdown(result: ReviewResult, opts: { profileNote?: strin
38
39
  parts.push(`${sentenceCase(coverageText(result))}.`, `Profile: ${profileText(result, opts.profileNote)}`, countLine(result.findings));
39
40
  const note = instructionNote(result);
40
41
  if (note) parts.push(note);
42
+ if (result.riskMap) parts.push(renderRiskMap(result.riskMap, "## Risk map"));
41
43
  const grouped = sections(result);
42
44
  const finding = ({ f, index }: (typeof grouped.main)[number]) => {
43
45
  parts.push(`### ${markdownLabel(f)}`, `\`${location(f)}\``);
@@ -3,6 +3,7 @@
3
3
  * the same in a pipe, a log or a screen reader. Progress goes to stderr, never here.
4
4
  */
5
5
  import { countLine, neutralise, type ReviewResult } from "../engine";
6
+ import { PLAIN_STYLE, renderRiskMap } from "../risk";
6
7
  import { agentPrompt } from "./agent-prompt";
7
8
  import {
8
9
  coverageText,
@@ -34,6 +35,7 @@ export function renderTerminal(result: ReviewResult, opts: { profileNote?: strin
34
35
  );
35
36
  const note = instructionNote(result);
36
37
  if (note) blocks.push(note);
38
+ if (result.riskMap) blocks.push(renderRiskMap(result.riskMap, "Risk map:", { style: PLAIN_STYLE }));
37
39
  const grouped = sections(result);
38
40
  const finding = ({ f, index }: (typeof grouped.main)[number]) => {
39
41
  const entry = opts.history?.byIndex.get(index);
@@ -0,0 +1,202 @@
1
+ /**
2
+ * `wachiman status`: what this laptop knows about its own local runs, and what they cost. It reads
3
+ * the history files (`local --history`) and local git metadata only: no `claude`, no GitHub, no
4
+ * network. Damaged history files are moved aside with a warning. Runs made by the GitHub Actions workflow are not in these files and are not counted.
5
+ */
6
+ import { UsageError } from "../config";
7
+ import { wachimanHome } from "../accounts/config";
8
+ import { historySettings, historyRoot, listKeys, readRuns, repositoryKey } from "../history/store";
9
+ import type { HistoryRun } from "../history/types";
10
+
11
+ export const STATUS_FORMAT = "wachiman.status/1";
12
+
13
+ export const statusUsage = `wachiman status [--json] [--since <n>d] [--all-repos] [--repo <name|key>] [--model <text>]
14
+ [--profile <name>] [--by day|repo|model|profile] [--repo-dir <dir>]`;
15
+
16
+ export const GROUPS = ["day", "repo", "model", "profile"] as const;
17
+ export type Group = (typeof GROUPS)[number];
18
+
19
+ export interface StatusArgs {
20
+ json: boolean;
21
+ allRepos: boolean;
22
+ sinceDays?: number;
23
+ repo?: string;
24
+ model?: string;
25
+ profile?: string;
26
+ by: Group;
27
+ }
28
+
29
+ /** The arguments after `status` (`--repo-dir` is already taken out). Both `--x v` and `--x=v`. */
30
+ export function parseStatusArgs(argv: string[]): StatusArgs | { help: true } {
31
+ const args: StatusArgs = { json: false, allRepos: false, by: "day" };
32
+ for (let i = 0; i < argv.length; i++) {
33
+ const arg = argv[i];
34
+ if (arg === "--help" || arg === "-h") return { help: true };
35
+ if (!arg.startsWith("--")) throw new UsageError(`status takes no argument "${arg}".`);
36
+ const eq = arg.indexOf("=");
37
+ const name = eq === -1 ? arg : arg.slice(0, eq);
38
+ const value = () => {
39
+ const v = eq === -1 ? argv[++i] : arg.slice(eq + 1);
40
+ if (v === undefined || v === "" || (eq === -1 && v.startsWith("--"))) throw new UsageError(`${name} needs a value.`);
41
+ return v;
42
+ };
43
+ const flag = () => {
44
+ if (eq !== -1) throw new UsageError(`${name} takes no value.`);
45
+ };
46
+ if (name === "--json") (flag(), (args.json = true));
47
+ else if (name === "--all-repos") (flag(), (args.allRepos = true));
48
+ else if (name === "--repo") args.repo = value();
49
+ else if (name === "--model") args.model = value();
50
+ else if (name === "--profile") args.profile = value();
51
+ else if (name === "--since") {
52
+ const v = value();
53
+ if (!/^\d+d$/.test(v)) throw new UsageError(`--since takes a number of days such as 7d, got "${v}".`);
54
+ args.sinceDays = Number.parseInt(v, 10);
55
+ } else if (name === "--by") {
56
+ const v = value();
57
+ if (!(GROUPS as readonly string[]).includes(v)) throw new UsageError(`--by is one of ${GROUPS.join(", ")}; got "${v}".`);
58
+ args.by = v as Group;
59
+ } else throw new UsageError(`Unknown option ${name} for status.`);
60
+ }
61
+ if (args.repo !== undefined && args.allRepos) throw new UsageError("--repo and --all-repos cannot be used together: --repo already names the repository.");
62
+ return args;
63
+ }
64
+
65
+ /** One local run, flattened to the attributes a developer filters and groups by. */
66
+ export interface StatusRun {
67
+ at: string;
68
+ repositoryKey: string;
69
+ repository: string;
70
+ change: string;
71
+ head: string;
72
+ model: string;
73
+ effort: string;
74
+ profile: string;
75
+ engineVersion: string;
76
+ costUsdEstimate: number;
77
+ tokens: { input: number; output: number; cacheRead: number; cacheWrite: number };
78
+ findings: number;
79
+ }
80
+
81
+ export function flatten(run: HistoryRun): StatusRun {
82
+ const { result } = run;
83
+ const usage = result.execution?.usage;
84
+ return {
85
+ at: run.savedAt,
86
+ repositoryKey: run.repository.key,
87
+ repository: run.repository.name,
88
+ change: result.change?.head?.ref ?? result.change?.title ?? "",
89
+ head: result.change?.head?.sha ?? "",
90
+ model: result.provider?.model ?? "",
91
+ effort: result.provider?.effort ?? "",
92
+ profile: (result.format === "wachiman.review-result/2" ? result.provider.account?.name : undefined) ?? result.provider?.profile ?? "",
93
+ engineVersion: run.engine.version,
94
+ costUsdEstimate: result.execution?.costUsdEstimate ?? 0,
95
+ tokens: { input: usage?.input ?? 0, output: usage?.output ?? 0, cacheRead: usage?.cacheRead ?? 0, cacheWrite: usage?.cacheWrite ?? 0 },
96
+ findings: result.findings?.length ?? 0,
97
+ };
98
+ }
99
+
100
+ const keyOf: Record<Group, (r: StatusRun) => string> = {
101
+ day: (r) => r.at.slice(0, 10),
102
+ repo: (r) => r.repositoryKey,
103
+ model: (r) => (r.effort ? `${r.model} (${r.effort})` : r.model),
104
+ profile: (r) => r.profile || "(none)",
105
+ };
106
+
107
+ export interface StatusGroup {
108
+ key: string;
109
+ runs: number;
110
+ costUsdEstimate: number;
111
+ }
112
+
113
+ export function group(runs: StatusRun[], by: Group): StatusGroup[] {
114
+ const map = new Map<string, StatusGroup>();
115
+ for (const r of runs) {
116
+ const key = keyOf[by](r);
117
+ const g = map.get(key) ?? { key, runs: 0, costUsdEstimate: 0 };
118
+ g.runs++;
119
+ g.costUsdEstimate += r.costUsdEstimate;
120
+ map.set(key, g);
121
+ }
122
+ return [...map.values()].sort((a, b) => (by === "day" ? b.key.localeCompare(a.key) : b.costUsdEstimate - a.costUsdEstimate));
123
+ }
124
+
125
+ export function filterRuns(runs: StatusRun[], args: StatusArgs, now: Date): StatusRun[] {
126
+ const cutoff = args.sinceDays === undefined ? undefined : now.getTime() - args.sinceDays * 86_400_000;
127
+ return runs.filter(
128
+ (r) =>
129
+ (cutoff === undefined || Date.parse(r.at) >= cutoff) &&
130
+ (args.repo === undefined || r.repository === args.repo || r.repositoryKey === args.repo) &&
131
+ (args.model === undefined || r.model.includes(args.model)) &&
132
+ (args.profile === undefined || r.profile === args.profile),
133
+ );
134
+ }
135
+
136
+ const usd = (n: number) => `$${n.toFixed(2)}`;
137
+ const pad = (text: string, width: number) => text + " ".repeat(Math.max(0, width - text.length));
138
+
139
+ export const LOCAL_ONLY = "Local runs only: those kept by `wachiman local --history`. Runs by the GitHub Actions workflow are not counted.";
140
+
141
+ export interface StatusIo {
142
+ stdout: (text: string) => void;
143
+ stderr: (line: string) => void;
144
+ now?: () => Date;
145
+ version: string;
146
+ }
147
+
148
+ export function runStatus(args: StatusArgs, repoDir: string, env: Record<string, string | undefined>, io: StatusIo): number {
149
+ const home = wachimanHome(env);
150
+ const root = historyRoot(home);
151
+ const now = io.now?.() ?? new Date();
152
+ const keys = args.allRepos || args.repo !== undefined ? listKeys(root) : [repositoryKey(repoDir).key];
153
+ const all = keys.flatMap((key) => readRuns(root, key, io.stderr)).map(flatten);
154
+ const retentionDays = historySettings(env, true).days;
155
+ if (args.repo !== undefined && !all.some(r => r.repositoryKey === args.repo)) {
156
+ const matches = [...new Set(all.filter(r => r.repository === args.repo).map(r => r.repositoryKey))];
157
+ if (matches.length > 1) throw new UsageError(`Repository name "${args.repo}" is ambiguous; use a key: ${matches.join(", ")}.`);
158
+ }
159
+ const effectiveArgs = args.repo !== undefined && all.some(r => r.repositoryKey === args.repo) ? { ...args, repo: undefined } : args;
160
+ const scoped = effectiveArgs !== args ? all.filter(r => r.repositoryKey === args.repo) : all;
161
+ const runs = filterRuns(scoped, effectiveArgs, now).sort((a, b) => a.at.localeCompare(b.at));
162
+ const groups = group(runs, args.by);
163
+ const total = runs.reduce((sum, r) => sum + r.costUsdEstimate, 0);
164
+ const filters = {
165
+ scope: args.allRepos ? "all-repos" : args.repo !== undefined ? "repo" : "this-repo",
166
+ ...(args.repo !== undefined ? { repo: args.repo } : {}),
167
+ ...(args.sinceDays !== undefined ? { sinceDays: args.sinceDays } : {}),
168
+ ...(args.model !== undefined ? { model: args.model } : {}),
169
+ ...(args.profile !== undefined ? { profile: args.profile } : {}),
170
+ };
171
+
172
+ if (args.json) {
173
+ const doc = {
174
+ format: STATUS_FORMAT,
175
+ version: io.version,
176
+ home,
177
+ scope: LOCAL_ONLY,
178
+ retentionDays,
179
+ filters,
180
+ by: args.by,
181
+ totals: { runs: runs.length, costUsdEstimate: total },
182
+ groups,
183
+ runs,
184
+ };
185
+ io.stdout(`${JSON.stringify(doc, null, 2)}\n`);
186
+ return 0;
187
+ }
188
+
189
+ const lines = [`Wachiman ${io.version} (home ${home})`, LOCAL_ONLY, ""];
190
+ if (runs.length === 0) {
191
+ lines.push(all.length === 0 ? "No local runs kept yet: run `wachiman local --history` to start. Run `wachiman doctor` to check this machine." : `No run matches the filters (${all.length} kept before filtering).`);
192
+ io.stdout(`${lines.join("\n")}\n`);
193
+ return 0;
194
+ }
195
+ const w = Math.max(args.by.length, ...groups.map((g) => g.key.length));
196
+ lines.push(`${runs.length} run${runs.length === 1 ? "" : "s"}, ${usd(total)} estimated (API-equivalent, not a bill), ${runs[0].at.slice(0, 10)} → ${runs.at(-1)!.at.slice(0, 10)}`, "");
197
+ lines.push(` ${pad(args.by, w)} runs cost`);
198
+ for (const g of groups) lines.push(` ${pad(g.key, w)} ${pad(String(g.runs), 4)} ${usd(g.costUsdEstimate)}`);
199
+ lines.push("", retentionDays === 0 ? "New `--history` runs keep all runs (AGENT_REVIEW_HISTORY_DAYS=0). `--json` lists every run with its attributes." : `A new \`--history\` run deletes runs older than ${retentionDays} days (AGENT_REVIEW_HISTORY_DAYS changes that). \`--json\` lists every run with its attributes.`);
200
+ io.stdout(`${lines.join("\n")}\n`);
201
+ return 0;
202
+ }