wachiman 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +132 -101
  2. package/package.json +1 -1
  3. package/skills/wachiman-loop/SKILL.md +91 -0
  4. package/src/call-message.ts +26 -3
  5. package/src/cli.ts +81 -5
  6. package/src/config.ts +19 -0
  7. package/src/connectors/local-git.ts +101 -13
  8. package/src/cost.ts +20 -0
  9. package/src/doctor/checks.ts +1 -1
  10. package/src/engine.ts +532 -55
  11. package/src/estimate.ts +64 -0
  12. package/src/fidelity/block.ts +263 -0
  13. package/src/fidelity/claims-call.ts +172 -0
  14. package/src/fidelity/claims.ts +69 -0
  15. package/src/fidelity/digest.ts +80 -0
  16. package/src/fidelity/grade.ts +242 -0
  17. package/src/fidelity/inert.ts +25 -0
  18. package/src/fidelity/rules.ts +166 -0
  19. package/src/fidelity/sink.ts +135 -0
  20. package/src/fidelity/summary.ts +16 -0
  21. package/src/fidelity/types.ts +93 -0
  22. package/src/formats.ts +16 -3
  23. package/src/history/fingerprint.ts +1 -1
  24. package/src/history/store.ts +39 -1
  25. package/src/init/options.ts +1 -1
  26. package/src/local.ts +20 -2
  27. package/src/loop/command.ts +441 -0
  28. package/src/loop/state.ts +88 -0
  29. package/src/loop/stop-rule.ts +98 -0
  30. package/src/providers/claude-code.ts +47 -12
  31. package/src/providers/codex.ts +3 -2
  32. package/src/providers/index.ts +5 -2
  33. package/src/providers/types.ts +10 -0
  34. package/src/sinks/json.ts +13 -2
  35. package/src/skills/install.ts +4 -4
  36. package/src/store/command.ts +109 -0
  37. package/src/store/figures.ts +153 -0
  38. package/src/store/html.ts +138 -0
  39. package/src/store/index.ts +298 -0
  40. package/templates/caller-workflow.yml +45 -15
  41. package/templates/wachiman-review-caller.yml +8 -0
@@ -0,0 +1,88 @@
1
+ /**
2
+ * What `wachiman loop` keeps per branch beside the history (ADR 0034): the base the loop started
3
+ * from, the head of every round and the findings it has seen. It is read at the start of a call
4
+ * and rewritten at its end; the review itself is saved by the history, not here.
5
+ */
6
+ import { UsageError } from "../config";
7
+ import { SEVERITY, TOPIC } from "../engine";
8
+ import { readLoopFile, writeLoopFile } from "../history/store";
9
+ import type { LoopStatus } from "./stop-rule";
10
+
11
+ export const LOOP_STATE_FORMAT = "wachiman.loop-state/1";
12
+
13
+ /** A finding the loop has seen, as of the last round. The verdict is read fresh from the history every time. */
14
+ export interface LedgerEntry {
15
+ id: string;
16
+ path: string;
17
+ line: number;
18
+ severity: keyof typeof SEVERITY;
19
+ topic: keyof typeof TOPIC;
20
+ title: string;
21
+ status: LoopStatus;
22
+ /** The verifier dropped it with a checked disproof; stays true until a round reports it again. */
23
+ refuted: boolean;
24
+ /** Only in states written by the first version of the loop: a `not-repeated` entry whose lines changed counted as released. */
25
+ linesChanged?: boolean;
26
+ /** The cited line without whitespace, or the file's blob when there is no such line: what a later round compares. */
27
+ lineText?: string;
28
+ blobSha?: string;
29
+ }
30
+
31
+ export interface LoopRound {
32
+ round: number;
33
+ /** The full sha of HEAD when the round ran. */
34
+ head: string;
35
+ at: string;
36
+ }
37
+
38
+ export interface LoopState {
39
+ format: typeof LOOP_STATE_FORMAT;
40
+ branch: string;
41
+ /** The ref the loop started from, as typed after `--base`. */
42
+ base: string;
43
+ /** `open` until a round converges. */
44
+ status: "open" | "converged";
45
+ rounds: LoopRound[];
46
+ ledger: LedgerEntry[];
47
+ }
48
+
49
+ const STATUSES: readonly string[] = ["new", "open", "probably-fixed", "not-repeated", "unknown"];
50
+
51
+ function valid(s: any, branch: string): s is LoopState {
52
+ return (
53
+ s &&
54
+ typeof s === "object" &&
55
+ s.format === LOOP_STATE_FORMAT &&
56
+ s.branch === branch &&
57
+ typeof s.base === "string" &&
58
+ (s.status === "open" || s.status === "converged") &&
59
+ Array.isArray(s.rounds) &&
60
+ s.rounds.every((r: any) => r && Number.isInteger(r.round) && typeof r.head === "string" && typeof r.at === "string") &&
61
+ Array.isArray(s.ledger) &&
62
+ s.ledger.every(
63
+ (e: any) =>
64
+ e &&
65
+ typeof e.id === "string" &&
66
+ typeof e.path === "string" &&
67
+ typeof e.line === "number" &&
68
+ e.severity in SEVERITY &&
69
+ e.topic in TOPIC &&
70
+ typeof e.title === "string" &&
71
+ STATUSES.includes(e.status) &&
72
+ typeof e.refuted === "boolean" &&
73
+ (e.linesChanged === undefined || typeof e.linesChanged === "boolean") &&
74
+ (e.lineText === undefined || typeof e.lineText === "string") &&
75
+ (e.blobSha === undefined || typeof e.blobSha === "string"),
76
+ )
77
+ );
78
+ }
79
+
80
+ /** The branch's loop, or undefined when none was started. A file that does not read as a loop state is a usage error naming what to do. */
81
+ export function readLoop(root: string, key: string, branch: string): LoopState | undefined {
82
+ const raw = readLoopFile(root, key, branch);
83
+ if (raw === undefined) return undefined;
84
+ if (!valid(raw, branch)) throw new UsageError(`The loop state of ${branch} is not readable by this version; start a new loop with \`wachiman loop --base <ref>\`.`);
85
+ return raw;
86
+ }
87
+
88
+ export const writeLoop = (root: string, key: string, state: LoopState) => writeLoopFile(root, key, state.branch, state);
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The stop rule of `wachiman loop` (ADR 0034 decision 5), pure: no filesystem, no git, no model.
3
+ * The command gathers one `LoopFinding` per finding the loop has seen and this module says which
4
+ * of them keep the loop open.
5
+ *
6
+ * The loop stays open while a 🔴 Blocker or 🟠 Fix is new, open or not-repeated, not refuted by the
7
+ * verifier and not judged `wrong` with a reason. 🟡 Consider and ⚪ Info are listed as notes and
8
+ * never count.
9
+ *
10
+ * The command sets the status from the round's own result and the code, not from the history: a
11
+ * finding the round reported again is `open`; in a file the round read, one it did not report is
12
+ * `probably-fixed` when its cited line is gone and `not-repeated` (still counts) when the line is
13
+ * still there; a file the round did not read keeps the previous status, so an `unknown` Blocker or
14
+ * Fix from a state written by the first version stays open until its file is read. When the cited
15
+ * line is short, repeated or line 0, the file's blob is fingerprinted instead and any edit to the
16
+ * file releases the finding. `linesChanged` exists only in states written by the first version.
17
+ */
18
+ import type { Severity, Topic } from "../engine";
19
+ import type { VerdictWord } from "../history/types";
20
+
21
+ export type LoopStatus = "new" | "open" | "probably-fixed" | "not-repeated" | "unknown";
22
+
23
+ export interface LoopFinding {
24
+ /** The history id, the finding's first id. */
25
+ id: string;
26
+ path: string;
27
+ line: number;
28
+ severity: Severity;
29
+ topic: Topic;
30
+ title: string;
31
+ /** The status after this round, decided by the loop. */
32
+ status: LoopStatus;
33
+ /** The verifier dropped this finding with a checked disproof in this round. */
34
+ refuted: boolean;
35
+ /** Only from a state written by the first version of the loop: a `not-repeated` finding whose lines changed counts as released. */
36
+ linesChanged?: boolean;
37
+ verdict?: { verdict: VerdictWord; reason?: string };
38
+ }
39
+
40
+ export type ReleaseWhy = "probably-fixed" | "refuted" | "judged wrong";
41
+
42
+ export interface OpenFinding extends LoopFinding {
43
+ /** Judged `wrong` with no reason: it is listed and still counts. */
44
+ unreasonedWrong?: true;
45
+ }
46
+
47
+ export interface Released {
48
+ finding: LoopFinding;
49
+ why: ReleaseWhy;
50
+ /** The reason the developer or agent gave, for `judged wrong`. */
51
+ reason?: string;
52
+ }
53
+
54
+ export interface Decision {
55
+ open: OpenFinding[];
56
+ released: Released[];
57
+ /** 🟡 and ⚪ that are not released: listed, never counted. */
58
+ notes: LoopFinding[];
59
+ converged: boolean;
60
+ }
61
+
62
+ const COUNTS: readonly Severity[] = ["blocker", "fix"];
63
+
64
+ export function evaluate(findings: LoopFinding[]): Decision {
65
+ const open: OpenFinding[] = [];
66
+ const released: Released[] = [];
67
+ const notes: LoopFinding[] = [];
68
+ for (const f of findings) {
69
+ const reason = f.verdict?.verdict === "wrong" ? f.verdict.reason?.trim() : undefined;
70
+ if (!COUNTS.includes(f.severity)) {
71
+ // A note a verdict, the verifier or a fix already settled is not worth listing again.
72
+ if (f.status === "probably-fixed" || f.refuted || reason) continue;
73
+ notes.push(f);
74
+ } else if (reason) released.push({ finding: f, why: "judged wrong", reason });
75
+ else if (f.refuted) released.push({ finding: f, why: "refuted" });
76
+ else if (f.status === "probably-fixed" || (f.status === "not-repeated" && f.linesChanged)) released.push({ finding: f, why: "probably-fixed" });
77
+ else open.push(f.verdict?.verdict === "wrong" ? { ...f, unreasonedWrong: true } : f);
78
+ }
79
+ return { open, released, notes, converged: open.length === 0 };
80
+ }
81
+
82
+ /** A loop that already ran `max` rounds stops before another one: three by default. */
83
+ export const roundCapReached = (roundsRun: number, max: number) => roundsRun >= max;
84
+
85
+ /**
86
+ * Whether a candidate the verifier dropped with a checked disproof is a finding the loop already
87
+ * tracks. A dropped candidate has no history id (it was never reported), so it is matched the way
88
+ * the history matches a title: the same file, the same topic and the same title key. Nothing weaker
89
+ * is used, because here a match closes a finding: a line number or a cited line is shared by
90
+ * different claims, and a disproof of one must not release another. A finding the verifier
91
+ * re-titled stays open, and the agent can judge it `wrong` with a reason.
92
+ */
93
+ export function isRefutedBy(
94
+ dropped: { path: string; topic: Topic; titleKey: string },
95
+ tracked: { path: string; topic: Topic; titleKey: string },
96
+ ): boolean {
97
+ return dropped.path === tracked.path && dropped.topic === tracked.topic && dropped.titleKey === tracked.titleKey;
98
+ }
@@ -10,7 +10,7 @@ import { UsageError } from "../config";
10
10
  import type { TokenUsage } from "../cost";
11
11
  import { locatePrompt } from "./locate";
12
12
  import { classifyProviderError } from "./errors";
13
- import { DEFAULT_CALL_TIMEOUT_S, DEFAULT_EFFORT, type Effort, type NeutralTool, type ProviderAdapter, ProviderRequest, ProviderResult } from "./types";
13
+ import { DEFAULT_CALL_TIMEOUT_S, DEFAULT_EFFORT, type Effort, type NeutralTool, type ProviderAdapter, type ProviderAuth, ProviderRequest, ProviderResult } from "./types";
14
14
 
15
15
  const BINARY = "claude";
16
16
  const SETTINGS_FILE = "claude-code.settings.json";
@@ -36,8 +36,14 @@ export function prettyModel(model: string): string {
36
36
  return `Claude ${family} ${match[2].replaceAll("-", ".")}`;
37
37
  }
38
38
 
39
- export function leaksKey(texts: string[], key: string) {
40
- return texts.some((t) => (key !== "" && t.includes(key)) || KEY_SHAPE.test(t));
39
+ /**
40
+ * True when a text holds a credential: the exact value of any of `exact` (the key, the CI token),
41
+ * or anything shaped like an Anthropic key. The shape is not loosened for the CI token: Anthropic's
42
+ * documentation does not state the token's shape, so the exact value is what the check relies on.
43
+ */
44
+ export function leaksKey(texts: string[], ...exact: string[]) {
45
+ const values = exact.filter((v) => v !== "");
46
+ return texts.some((t) => values.some((v) => t.includes(v)) || KEY_SHAPE.test(t));
41
47
  }
42
48
 
43
49
  /**
@@ -58,6 +64,9 @@ export const CHILD_ENV_ALLOWLIST = [
58
64
  "GITHUB_ACTIONS",
59
65
  ] as const;
60
66
 
67
+ /** The variable `claude setup-token` documents for CI; allowlisted only in the `oauth-token` mode. */
68
+ export const OAUTH_TOKEN_VAR = "CLAUDE_CODE_OAUTH_TOKEN";
69
+
61
70
  /**
62
71
  * What a child process needs on Windows to start and find its own sign-in: the profile and
63
72
  * application-data directories, the system root, the temporary directories and the executable
@@ -80,10 +89,22 @@ export const WINDOWS_CHILD_ENV_ALLOWLIST = [
80
89
  const LOCALE_PREFIX = "LC_";
81
90
 
82
91
  /**
83
- * `api-key`: the CI path, billed to `ANTHROPIC_API_KEY`. `subscription`: the local review, on the
84
- * developer's own signed-in `claude` (ADR 0019 decision 3); the key is refused and never forwarded.
92
+ * `api-key`: the CI path, billed to `ANTHROPIC_API_KEY`. `oauth-token`: the CI path on a
93
+ * subscription, with the token `claude setup-token` made, in `CLAUDE_CODE_OAUTH_TOKEN` (ADR 0037);
94
+ * the key is never forwarded. `subscription`: the local review, on the developer's own signed-in
95
+ * `claude` (ADR 0019 decision 3); the key is refused and never forwarded.
85
96
  */
86
- export type ClaudeAuth = "api-key" | "subscription";
97
+ export type ClaudeAuth = ProviderAuth;
98
+
99
+ /**
100
+ * The CI credential by presence, the token first: with both set, `claude -p` would bill the key
101
+ * (it outranks the token in Claude Code's precedence), so the token wins here and the key never
102
+ * reaches the child. An empty value counts as absent: a workflow that does not pass a secret still
103
+ * sets the variable, to the empty string.
104
+ */
105
+ export function resolveClaudeAuth(env: Record<string, string | undefined>): "api-key" | "oauth-token" {
106
+ return env[OAUTH_TOKEN_VAR] ? "oauth-token" : "api-key";
107
+ }
87
108
 
88
109
  /** D10: set in every local call; what each one switches off is in docs/providers/claude-code.md. */
89
110
  export const SUBSCRIPTION_ENV = {
@@ -96,7 +117,9 @@ export const SUBSCRIPTION_ENV = {
96
117
  } as const;
97
118
 
98
119
  /**
99
- * The child's environment. In subscription mode the allowlist loses `ANTHROPIC_API_KEY` and gains
120
+ * The child's environment. In `oauth-token` mode the allowlist loses `ANTHROPIC_API_KEY` and gains
121
+ * `CLAUDE_CODE_OAUTH_TOKEN`, and nothing else changes: the extras below are the local mode's. In
122
+ * subscription mode the allowlist loses `ANTHROPIC_API_KEY` and gains
100
123
  * `USER` (without it, `claude` on macOS cannot find its own sign-in: spec D17) and the D10
101
124
  * switches; `configDir` (an isolated profile) replaces any `CLAUDE_CONFIG_DIR` of the parent. The
102
125
  * sign-in itself is never read here: the binary finds it through `HOME`, `USER` and
@@ -107,14 +130,17 @@ export function buildChildEnv(
107
130
  opts: { auth?: ClaudeAuth; configDir?: string; platform?: string } = {},
108
131
  ) {
109
132
  const subscription = opts.auth === "subscription";
133
+ const token = opts.auth === "oauth-token";
110
134
  // Windows names are case-insensitive and the search path is usually `Path`, so match them so.
111
135
  const windows = (opts.platform ?? process.platform) === "win32";
112
- const allowed = new Set<string>([...CHILD_ENV_ALLOWLIST, ...(windows ? WINDOWS_CHILD_ENV_ALLOWLIST : [])].map((n) => (windows ? n.toUpperCase() : n)));
136
+ const allowed = new Set<string>(
137
+ [...CHILD_ENV_ALLOWLIST, ...(token ? [OAUTH_TOKEN_VAR] : []), ...(windows ? WINDOWS_CHILD_ENV_ALLOWLIST : [])].map((n) => (windows ? n.toUpperCase() : n)),
138
+ );
113
139
  const child: Record<string, string> = {};
114
140
  for (const [name, value] of Object.entries(env)) {
115
141
  if (value === undefined) continue;
116
142
  const key = windows ? name.toUpperCase() : name;
117
- if (subscription && key === "ANTHROPIC_API_KEY") continue;
143
+ if ((subscription || token) && key === "ANTHROPIC_API_KEY") continue;
118
144
  if (allowed.has(key) || name.startsWith(LOCALE_PREFIX)) {
119
145
  child[name] = value;
120
146
  }
@@ -278,6 +304,11 @@ export class ClaudeCodeProvider implements ProviderAdapter {
278
304
  return this.opts.auth === "subscription";
279
305
  }
280
306
 
307
+ /** What pays for the calls (`api-key` unless the constructor said otherwise). */
308
+ get auth(): ProviderAuth {
309
+ return this.opts.auth ?? "api-key";
310
+ }
311
+
281
312
  private childEnv() {
282
313
  return buildChildEnv(process.env, { auth: this.opts.auth, configDir: this.opts.configDir });
283
314
  }
@@ -301,8 +332,11 @@ export class ClaudeCodeProvider implements ProviderAdapter {
301
332
  );
302
333
  }
303
334
  this.version = probe.stdout.match(/\d+\.\d+\.\d+/)?.[0] ?? null;
304
- if (this.opts.requireApiKey && !process.env.ANTHROPIC_API_KEY) {
305
- throw new Error("ANTHROPIC_API_KEY is not set");
335
+ if (this.opts.requireApiKey) {
336
+ if (this.auth === "oauth-token" && !process.env[OAUTH_TOKEN_VAR]) throw new Error(`${OAUTH_TOKEN_VAR} is not set`);
337
+ if (this.auth === "api-key" && !process.env.ANTHROPIC_API_KEY) {
338
+ throw new Error(`Neither ANTHROPIC_API_KEY nor ${OAUTH_TOKEN_VAR} is set: pass a Console API key, or a token from \`claude setup-token\` to review on a Claude subscription.`);
339
+ }
306
340
  }
307
341
  }
308
342
 
@@ -311,7 +345,8 @@ export class ClaudeCodeProvider implements ProviderAdapter {
311
345
  }
312
346
 
313
347
  leaksSecret(texts: string[]) {
314
- return leaksKey(texts, process.env.ANTHROPIC_API_KEY ?? "");
348
+ // The token is checked too in the CI modes: it is a credential in the engine's environment.
349
+ return leaksKey(texts, process.env.ANTHROPIC_API_KEY ?? "", this.auth === "oauth-token" ? (process.env[OAUTH_TOKEN_VAR] ?? "") : "");
315
350
  }
316
351
 
317
352
  run(request: ProviderRequest): ProviderResult {
@@ -171,12 +171,13 @@ export function buildChildEnv(
171
171
 
172
172
  /** The `codex exec` arguments. The prompt always goes through stdin (`-`). */
173
173
  /**
174
- * The top-level properties the engine leaves optional in a batch's schema (ADR 0031). Codex's
174
+ * The top-level properties the engine leaves optional in a batch's schema (ADR 0031; the claim
175
+ * assignments of ADR 0033 are asked for only when PR Confidence is on). Codex's
175
176
  * structured output is strict: every property must be `required`, so these are required in the
176
177
  * schema Codex receives. The model then answers an empty array when a batch has none, and a
177
178
  * missing one parses as empty (`risk.ts`). Other properties of other schemas are not touched.
178
179
  */
179
- const RISK_ARRAYS = ["risk_facts", "judgement"];
180
+ const RISK_ARRAYS = ["risk_facts", "judgement", "claim_assignments"];
180
181
 
181
182
  export function strictSchema(schema: unknown): unknown {
182
183
  if (schema === null || typeof schema !== "object") return schema;
@@ -1,4 +1,4 @@
1
- import { ClaudeCodeProvider, type ClaudeAuth } from "./claude-code";
1
+ import { ClaudeCodeProvider, resolveClaudeAuth, type ClaudeAuth } from "./claude-code";
2
2
  import { CodexProvider } from "./codex";
3
3
  import type { Effort, ProviderAdapter } from "./types";
4
4
 
@@ -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-opus-5-5",
12
+ "claude-code": "claude-sonnet-5-5",
13
13
  codex: "gpt-6.1-sol",
14
14
  };
15
15
 
@@ -31,11 +31,14 @@ export function getProvider(
31
31
  ): ProviderAdapter {
32
32
  if (name === "claude-code") {
33
33
  const subscription = options.auth === "subscription";
34
+ // GitHub mode names no auth: the credential in the environment decides (ADR 0037 decision 1).
35
+ const auth = options.auth ?? resolveClaudeAuth(process.env);
34
36
  return new ClaudeCodeProvider({
35
37
  model: options.model,
36
38
  requireApiKey: !subscription && !options.dryRun,
37
39
  effort: options.effort,
38
40
  ...(subscription ? { auth: options.auth, configDir: options.configDir, binary: options.binary } : {}),
41
+ ...(auth === "oauth-token" ? { auth } : {}),
39
42
  });
40
43
  }
41
44
  if (name === "codex") {
@@ -99,9 +99,19 @@ export interface ProviderResult {
99
99
  raw: unknown;
100
100
  }
101
101
 
102
+ /**
103
+ * What pays for a call: `api-key` (a Console key, billed per token), `oauth-token` (a Claude Code
104
+ * token made with `claude setup-token`, the CI route on a subscription: ADR 0037) or `subscription`
105
+ * (the developer's own sign-in, the local mode: ADR 0019). The last two report a dollar figure that
106
+ * is an API-price equivalent, not a charge.
107
+ */
108
+ export type ProviderAuth = "api-key" | "oauth-token" | "subscription";
109
+
102
110
  export interface ProviderAdapter {
103
111
  /** The value of `AGENT_REVIEW_PROVIDER` that selects it. */
104
112
  readonly name: string;
113
+ /** What pays for the calls. Absent means `api-key`. */
114
+ readonly auth?: ProviderAuth;
105
115
  /** Throws when the call would fail anyway: missing binary, settings file or credential. */
106
116
  preflight(): void;
107
117
  /** For the review footer, e.g. "Claude Sonnet 5.5 via Claude Code 2.1.304". */
package/src/sinks/json.ts CHANGED
@@ -5,5 +5,16 @@
5
5
  import type { ReviewResult } from "../engine";
6
6
  import { toResultV1 } from "../formats";
7
7
 
8
- export const renderJson = (result: ReviewResult, version: 1 | 2 = 1) =>
9
- `${JSON.stringify(version === 1 ? toResultV1(result) : result, null, 2)}\n`;
8
+ /**
9
+ * `ids[i]` is the history id of `result.findings[i]` (ADR 0034). Only `/2` carries it, as an
10
+ * optional `id` on a finding; `/1` is never changed.
11
+ */
12
+ export const renderJson = (result: ReviewResult, version: 1 | 2 = 1, ids?: (string | undefined)[]) => {
13
+ const out =
14
+ version === 1
15
+ ? toResultV1(result)
16
+ : ids
17
+ ? { ...result, findings: result.findings.map((f, i) => (ids[i] === undefined ? f : { ...f, id: ids[i] })) }
18
+ : result;
19
+ return `${JSON.stringify(out, null, 2)}\n`;
20
+ };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `wachiman skills install|uninstall`: copies the two agent skills into the directories where
2
+ * `wachiman skills install|uninstall`: copies the agent skills into the directories where
3
3
  * coding agents look for them, marks each copy so it can be told from anyone else's, and removes
4
4
  * only what it installed (command contract section 5.9).
5
5
  */
@@ -10,7 +10,7 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
10
10
  import { wachimanHome } from "../accounts/config";
11
11
  import { UsageError } from "../config";
12
12
 
13
- export const SKILL_NAMES = ["wachiman-review", "wachiman-audit"] as const;
13
+ export const SKILL_NAMES = ["wachiman-review", "wachiman-loop", "wachiman-audit"] as const;
14
14
  export const MARKER_FILE = ".wachiman-skill.json";
15
15
 
16
16
  export interface SkillsOptions { action: "install" | "uninstall"; dirs: string[]; json: boolean }
@@ -28,7 +28,7 @@ interface SkillInstallMarker {
28
28
 
29
29
  export interface SkillsDeps {
30
30
  userHome?: string;
31
- /** The directory that holds `wachiman-review/` and `wachiman-audit/`. */
31
+ /** The directory that holds `wachiman-review/`, `wachiman-loop/` and `wachiman-audit/`. */
32
32
  sourceDir?: string;
33
33
  version?: string;
34
34
  now?: () => Date;
@@ -309,7 +309,7 @@ function uninstallOne(dest: string): Entry | undefined {
309
309
  }
310
310
 
311
311
  /**
312
- * Installs or removes both skills in every target directory. A target under the Wachiman home
312
+ * Installs or removes every skill in every target directory. A target under the Wachiman home
313
313
  * throws a UsageError before anything is written. A copy that is not ours (no marker, a symlink, a
314
314
  * file, a modified file) is reported `preserved` and warned about, never overwritten or followed.
315
315
  */
@@ -0,0 +1,109 @@
1
+ /**
2
+ * `wachiman dashboard`: brings the local index up to date from the history files, then prints the
3
+ * figures as `wachiman.dashboard/1` JSON or writes them as one static HTML file (ADR 0035). It writes
4
+ * only the index and, without `--json`, the page; like `wachiman history`, it moves a damaged run
5
+ * file aside. No `claude`, no GitHub, no network, no server, and it never opens a browser.
6
+ */
7
+ import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from "node:fs";
8
+ import { dirname, join, resolve } from "node:path";
9
+ import { wachimanHome } from "../accounts/config";
10
+ import { UsageError } from "../config";
11
+ import { readFigures, type Figures } from "./figures";
12
+ import { renderHtml, type DashboardDocument } from "./html";
13
+ import { refreshIndex } from "./index";
14
+
15
+ export const DASHBOARD_FORMAT = "wachiman.dashboard/1";
16
+ export const DASHBOARD_FILE = "dashboard.html";
17
+
18
+ export const dashboardUsage = `wachiman dashboard [--json] [--out <file>] [--repo-dir <dir>]`;
19
+
20
+ export const LOCAL_ONLY = "Local runs only: those kept by `wachiman local --history` and `wachiman loop`. Runs by the GitHub Actions workflow are not counted.";
21
+
22
+ export interface DashboardArgs {
23
+ json: boolean;
24
+ out?: string;
25
+ }
26
+
27
+ /** The arguments after `dashboard` (`--repo-dir` is already taken out). Both `--x v` and `--x=v`. */
28
+ export function parseDashboardArgs(argv: string[]): DashboardArgs | { help: true } {
29
+ const args: DashboardArgs = { json: false };
30
+ for (let i = 0; i < argv.length; i++) {
31
+ const arg = argv[i];
32
+ if (arg === "--help" || arg === "-h") return { help: true };
33
+ if (!arg.startsWith("--")) throw new UsageError(`dashboard takes no argument "${arg}".`);
34
+ const eq = arg.indexOf("=");
35
+ const name = eq === -1 ? arg : arg.slice(0, eq);
36
+ if (name === "--json") {
37
+ if (eq !== -1) throw new UsageError("--json takes no value.");
38
+ args.json = true;
39
+ } else if (name === "--out") {
40
+ const v = eq === -1 ? argv[++i] : arg.slice(eq + 1);
41
+ if (v === undefined || v === "" || (eq === -1 && v.startsWith("--"))) throw new UsageError("--out needs a file name.");
42
+ args.out = v;
43
+ } else throw new UsageError(`Unknown option ${name} for dashboard.`);
44
+ }
45
+ if (args.json && args.out !== undefined) throw new UsageError("--out writes the HTML page; --json prints to stdout and takes no --out.");
46
+ return args;
47
+ }
48
+
49
+ /** Writes `text` to `path` at 0600 through a temporary name beside it: all or nothing. */
50
+ function writeFileAtomic(path: string, text: string) {
51
+ mkdirSync(dirname(path), { recursive: true });
52
+ const tmp = `${path}.tmp-${process.pid}`;
53
+ const fd = openSync(tmp, "w", 0o600);
54
+ try {
55
+ try {
56
+ writeSync(fd, text);
57
+ fsyncSync(fd);
58
+ } finally {
59
+ closeSync(fd);
60
+ }
61
+ chmodSync(tmp, 0o600);
62
+ renameSync(tmp, path);
63
+ } catch (error) {
64
+ try {
65
+ unlinkSync(tmp);
66
+ } catch {
67
+ // Already gone.
68
+ }
69
+ throw error;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * The figures from an up-to-date index. If reading them fails (a damaged or half-built index that
75
+ * looked current), the index is rebuilt once and read again; a second failure is the caller's.
76
+ */
77
+ export function loadFigures(home: string, warn: (line: string) => void, read: (path: string) => Figures = readFigures): Figures {
78
+ const { path } = refreshIndex(home, warn);
79
+ try {
80
+ return read(path);
81
+ } catch {
82
+ refreshIndex(home, warn, { force: true });
83
+ return read(path);
84
+ }
85
+ }
86
+
87
+ export interface DashboardIo {
88
+ stdout: (text: string) => void;
89
+ stderr: (line: string) => void;
90
+ now?: () => Date;
91
+ }
92
+
93
+ export function runDashboard(args: DashboardArgs, env: Record<string, string | undefined>, io: DashboardIo): number {
94
+ const home = wachimanHome(env);
95
+ const doc: DashboardDocument = {
96
+ format: DASHBOARD_FORMAT,
97
+ generatedAt: (io.now?.() ?? new Date()).toISOString(),
98
+ scope: LOCAL_ONLY,
99
+ ...loadFigures(home, io.stderr),
100
+ };
101
+ if (args.json) {
102
+ io.stdout(`${JSON.stringify(doc, null, 2)}\n`);
103
+ return 0;
104
+ }
105
+ const out = args.out === undefined ? join(home, DASHBOARD_FILE) : resolve(args.out);
106
+ writeFileAtomic(out, renderHtml(doc));
107
+ io.stdout(`${out}\n`);
108
+ return 0;
109
+ }