wachiman 1.10.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 (59) hide show
  1. package/README.md +139 -79
  2. package/package.json +1 -1
  3. package/skills/wachiman-loop/SKILL.md +91 -0
  4. package/skills/wachiman-review/SKILL.md +23 -1
  5. package/src/accounts/commands.ts +6 -2
  6. package/src/ask.ts +240 -0
  7. package/src/call-message.ts +26 -3
  8. package/src/cli.ts +157 -13
  9. package/src/config.ts +40 -5
  10. package/src/connectors/local-git.ts +119 -21
  11. package/src/connectors/working-tree.ts +333 -0
  12. package/src/cost.ts +20 -0
  13. package/src/doctor/checks.ts +1 -1
  14. package/src/engine.ts +988 -104
  15. package/src/estimate.ts +64 -0
  16. package/src/fidelity/block.ts +263 -0
  17. package/src/fidelity/claims-call.ts +172 -0
  18. package/src/fidelity/claims.ts +69 -0
  19. package/src/fidelity/digest.ts +80 -0
  20. package/src/fidelity/grade.ts +242 -0
  21. package/src/fidelity/inert.ts +25 -0
  22. package/src/fidelity/rules.ts +166 -0
  23. package/src/fidelity/sink.ts +135 -0
  24. package/src/fidelity/summary.ts +16 -0
  25. package/src/fidelity/types.ts +93 -0
  26. package/src/formats.ts +36 -9
  27. package/src/history/fingerprint.ts +1 -1
  28. package/src/history/index.ts +3 -0
  29. package/src/history/store.ts +39 -1
  30. package/src/init/options.ts +1 -1
  31. package/src/init/prompt.ts +4 -1
  32. package/src/init/run.ts +38 -27
  33. package/src/local-ask.ts +231 -0
  34. package/src/local.ts +274 -74
  35. package/src/loop/command.ts +441 -0
  36. package/src/loop/state.ts +88 -0
  37. package/src/loop/stop-rule.ts +98 -0
  38. package/src/providers/claude-code.ts +47 -12
  39. package/src/providers/codex.ts +20 -1
  40. package/src/providers/index.ts +5 -2
  41. package/src/providers/types.ts +10 -0
  42. package/src/risk.ts +264 -0
  43. package/src/setup/prompt.ts +28 -15
  44. package/src/setup/run.ts +14 -2
  45. package/src/sinks/common.ts +5 -1
  46. package/src/sinks/json.ts +13 -2
  47. package/src/sinks/markdown.ts +2 -0
  48. package/src/sinks/terminal.ts +2 -0
  49. package/src/skills/install.ts +4 -4
  50. package/src/status/command.ts +202 -0
  51. package/src/store/command.ts +109 -0
  52. package/src/store/figures.ts +153 -0
  53. package/src/store/html.ts +138 -0
  54. package/src/store/index.ts +298 -0
  55. package/src/wizard/command.ts +23 -0
  56. package/src/wizard/prompt.ts +22 -9
  57. package/src/wizard/style.ts +19 -0
  58. package/templates/caller-workflow.yml +90 -25
  59. package/templates/wachiman-review-caller.yml +12 -1
@@ -5,13 +5,14 @@
5
5
  * head the agent reads is a snapshot, so later edits of the working tree change nothing.
6
6
  *
7
7
  * The snapshot is a `git archive` of the head extracted into a temporary directory, with an index
8
- * of its own (`git init`, `git add -A -f`, no commit): the evidence step runs `git grep` in the
9
- * head, and in a plain directory that fails (spec correction 1 of the plan).
8
+ * of its own (`git init`, the clone's objects as alternates, `git read-tree`, trimmed to the
9
+ * extracted files, no commit): the evidence step runs `git grep` in the head, and in a plain
10
+ * directory that fails (spec correction 1 of the plan).
10
11
  */
11
12
  import { spawnSync } from "node:child_process";
12
- import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
13
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
13
14
  import { tmpdir } from "node:os";
14
- import { basename, join } from "node:path";
15
+ import { basename, dirname, join, resolve } from "node:path";
15
16
  import { UsageError } from "../config";
16
17
  import {
17
18
  instructionFileOf,
@@ -259,7 +260,7 @@ export function localFiles(repoDir: string, mergeBase: string, head: string, git
259
260
  const range = [mergeBase, head];
260
261
  const raw = run(git, repoDir, [...DIFF, "--raw", "-z", "--no-abbrev", ...range], DIFF_MAX_BYTES).split("\0");
261
262
  const numstat = run(git, repoDir, [...DIFF, "--numstat", "-z", ...range], DIFF_MAX_BYTES).split("\0");
262
- const sections = splitPatches(run(git, repoDir, [...DIFF, ...PATCH, ...range], DIFF_MAX_BYTES));
263
+ const rawSections = splitPatches(run(git, repoDir, [...DIFF, ...PATCH, ...range], DIFF_MAX_BYTES));
263
264
 
264
265
  const entries: { status: string; dstSha: string; from?: string; to: string }[] = [];
265
266
  for (let i = 0; i < raw.length; ) {
@@ -270,6 +271,21 @@ export function localFiles(repoDir: string, mergeBase: string, head: string, git
270
271
  const from = raw[i++];
271
272
  entries.push(two ? { status, dstSha, from, to: raw[i++] } : { status, dstSha, to: from });
272
273
  }
274
+ // Git emits a deletion and an addition patch for one raw T (type-change) entry.
275
+ // Keep both hunks: each carries its own old/new line origin, including +0,0
276
+ // for the deleted side. Evidence and head-line annotations can then use them unchanged.
277
+ let sectionIndex = 0;
278
+ const sections = entries.map((e) => {
279
+ const parts = rawSections.slice(sectionIndex, sectionIndex + (e.status === "T" ? 2 : 1));
280
+ sectionIndex += e.status === "T" ? 2 : 1;
281
+ for (const part of parts) {
282
+ if (!part.header.includes('"') && !part.header.endsWith(` b/${e.to}`)) {
283
+ throw new Error(`git diff sections are out of order: expected ${e.to}, got "${part.header}".`);
284
+ }
285
+ }
286
+ const patches = parts.flatMap((p) => p.patch === undefined ? [] : [p.patch]);
287
+ return { header: parts[0]?.header ?? "", patch: patches.length ? patches.join("\n") : undefined };
288
+ });
273
289
  const counts: { additions: number; deletions: number }[] = [];
274
290
  for (let i = 0; i < numstat.length; ) {
275
291
  const meta = numstat[i++];
@@ -280,17 +296,12 @@ export function localFiles(repoDir: string, mergeBase: string, head: string, git
280
296
  const n = (v: string) => (v === "-" ? 0 : Number(v));
281
297
  counts.push({ additions: n(added), deletions: n(deleted) });
282
298
  }
283
- if (counts.length !== entries.length || sections.length !== entries.length) {
299
+ if (counts.length !== entries.length || sectionIndex !== rawSections.length || sections.some((s) => !s.header)) {
284
300
  throw new Error(
285
- `git diff disagreed with itself on ${mergeBase.slice(0, 7)}..${head.slice(0, 7)}: ${entries.length} raw entries, ${counts.length} counts, ${sections.length} patches.`,
301
+ `git diff disagreed with itself on ${mergeBase.slice(0, 7)}..${head.slice(0, 7)}: ${entries.length} raw entries, ${counts.length} counts, ${rawSections.length} patches.`,
286
302
  );
287
303
  }
288
304
  const files = entries.map((e, i): ReviewFile => {
289
- const header = sections[i].header;
290
- // A quoted header (a name with a tab, a newline or a quote) cannot be checked this simply.
291
- if (!header.includes('"') && !header.endsWith(` b/${e.to}`)) {
292
- throw new Error(`git diff sections are out of order: expected ${e.to}, got "${header}".`);
293
- }
294
305
  const patch = sections[i].patch;
295
306
  return {
296
307
  filename: e.to,
@@ -357,29 +368,80 @@ export function tarCommand(platform: string = process.platform, env: Record<stri
357
368
  }
358
369
 
359
370
  /**
360
- * The committed `head` as a directory: `git archive` extracted with the system `tar`, then an
361
- * index of its own so `git grep` sees exactly the archived files. `missing` and `extra` compare the
362
- * snapshot with `git ls-tree` of the head (export-ignore and submodules make them differ).
371
+ * Time allowed to each snapshot step (archive, tar, read-tree, ls-files, update-index) for a head of
372
+ * `fileCount` files: the old 60 s floor plus 3 ms per file. `tar -xf` was measured at 9 s for 31.9k
373
+ * files / 660 MB (about 0.3 ms per file) on a loaded laptop; 3 ms per file is 10x that rate, so 31.9k
374
+ * files get about 156 s.
375
+ */
376
+ export const snapshotTimeoutMs = (fileCount: number) => 60_000 + fileCount * 3;
377
+
378
+ /** The error for a snapshot step that ran out of time: which step, on how many files, what to do. */
379
+ function snapshotTimeout(step: string, ms: number, fileCount: number) {
380
+ return new Error(
381
+ `Snapshot step "${step}" timed out after ${Math.round(ms / 1000)} s on a head of ${fileCount.toLocaleString("en-US")} files. ` +
382
+ `The machine may be busy or the disk slow; retry when it is less loaded, or free space in the temporary directory (${tmpdir()}).`,
383
+ );
384
+ }
385
+
386
+ /**
387
+ * The committed `head` as a directory: `git archive` extracted with the system `tar`, then an index
388
+ * of its own so `git grep` sees exactly the archived files. The index is not built by hashing the
389
+ * files (`git add -A -f` took ~50 s on 32k files): the snapshot borrows the clone's objects through
390
+ * `objects/info/alternates` (read-only; nothing is written to the clone), `git read-tree <head>`
391
+ * fills the index from the tree, and the index is trimmed to what `tar` extracted (read-tree also
392
+ * lists submodule gitlinks and export-ignore paths). If read-tree fails (a partial clone lacks tree
393
+ * objects) the old `git add -A -f` runs instead: slower, same result. `missing` and `extra` compare
394
+ * the snapshot with `git ls-tree` of the head (export-ignore and submodules make them differ).
395
+ * Steps get `snapshotTimeoutMs` of the head's file count.
363
396
  */
364
397
  export function snapshotHead(repoDir: string, head: string, git: GitRunner = spawnGit): { dir: string; missing: string[]; extra: string[] } {
365
398
  const dir = realpathSync(mkdtempSync(join(tmpdir(), "wachiman-snapshot-")));
366
399
  // Beside the snapshot, not inside it: a file of the same name in the head would collide.
367
400
  const tar = `${dir}.tar`;
368
401
  try {
402
+ const tree = new Set(names(run(git, repoDir, ["ls-tree", "-r", "-z", "--name-only", head], DIFF_MAX_BYTES)));
403
+ const files = tree.size;
404
+ const limit = snapshotTimeoutMs(files);
405
+ const step = (label: string, cwd: string, args: string[]) => {
406
+ const out = git(args, { cwd, timeoutMs: limit, maxBytes: DIFF_MAX_BYTES });
407
+ if (out.timedOut) throw snapshotTimeout(label, limit, files);
408
+ if (out.status !== 0 || out.error || out.outputCut) {
409
+ const why = out.outputCut ? "output too large" : (out.error ?? out.stderr?.trim() ?? `status ${out.status}`);
410
+ throw new Error(`git ${args.join(" ")} failed in ${cwd}: ${why}`);
411
+ }
412
+ return out.stdout;
413
+ };
369
414
  // core.autocrlf=true (the Git for Windows default) and core.eol=native with a `text=auto` attribute
370
415
  // would both write CRLF into the archive. The snapshot should hold the committed bytes, so both are
371
416
  // switched off for this one command (a file with an explicit `eol=crlf` attribute is still converted).
372
- run(git, repoDir, ["-c", "core.autocrlf=false", "-c", "core.eol=lf", "archive", "--format=tar", `--output=${tar}`, head]);
373
- const untar = spawnSync(tarCommand(), ["-xf", tar], { cwd: dir, encoding: "utf8", timeout: TIMEOUT_MS });
417
+ step("git archive", repoDir, ["-c", "core.autocrlf=false", "-c", "core.eol=lf", "archive", "--format=tar", `--output=${tar}`, head]);
418
+ const untar = spawnSync(tarCommand(), ["-xf", tar], { cwd: dir, encoding: "utf8", timeout: limit });
419
+ if ((untar.error as NodeJS.ErrnoException | undefined)?.code === "ETIMEDOUT") throw snapshotTimeout("tar -xf", limit, files);
374
420
  if (untar.status !== 0) throw new Error(`tar -xf failed: ${untar.stderr || untar.error}`);
375
421
  rmSync(tar, { force: true });
376
- run(git, dir, ["init", "-q", "--template="]);
422
+ step("git init", dir, ["init", "-q", "--template="]);
377
423
  // No clean or smudge filter (LFS, git-crypt) runs on the copy: the index only lists the files.
378
424
  mkdirSync(join(dir, ".git", "info"), { recursive: true });
379
425
  writeFileSync(join(dir, ".git", "info", "attributes"), "* -filter\n");
380
- run(git, dir, ["add", "-A", "-f"]);
381
- const tree = new Set(names(run(git, repoDir, ["ls-tree", "-r", "-z", "--name-only", head], DIFF_MAX_BYTES)));
382
- const copied = new Set(names(run(git, dir, ["ls-files", "-z"], DIFF_MAX_BYTES)));
426
+ // `--git-path objects` is the common dir's objects for a linked worktree, and may be relative to `repoDir`.
427
+ const objects = resolve(repoDir, run(git, repoDir, ["rev-parse", "--git-path", "objects"]).trim());
428
+ const alternates = join(dir, ".git", "objects", "info", "alternates");
429
+ mkdirSync(dirname(alternates), { recursive: true });
430
+ writeFileSync(alternates, `${objects}\n`);
431
+ const read = git(["read-tree", head], { cwd: dir, timeoutMs: limit });
432
+ if (read.timedOut) throw snapshotTimeout("git read-tree", limit, files);
433
+ if (read.status !== 0 || read.error) {
434
+ // Tree objects missing here (a partial clone): hash the files instead. Never fetch.
435
+ rmSync(alternates, { force: true });
436
+ rmSync(join(dir, ".git", "index"), { force: true });
437
+ rmSync(join(dir, ".git", "index.lock"), { force: true });
438
+ step("git add", dir, ["add", "-A", "-f"]);
439
+ } else {
440
+ trimIndex(dir, git, limit, files);
441
+ }
442
+ const copied = new Set(names(step("git ls-files", dir, ["ls-files", "-z"])));
443
+ // Files on disk that the head does not have (what `git add -A -f` used to add): a directory walk, no hashing.
444
+ for (const f of names(step("git ls-files --others", dir, ["ls-files", "-z", "--others"]))) copied.add(f);
383
445
  return {
384
446
  dir,
385
447
  missing: [...tree].filter((f) => !copied.has(f)),
@@ -391,6 +453,42 @@ export function snapshotHead(repoDir: string, head: string, git: GitRunner = spa
391
453
  }
392
454
  }
393
455
 
456
+ /**
457
+ * Drops from the snapshot's index what `tar` did not extract as a file or a symlink: submodule
458
+ * gitlinks (mode 160000), export-ignore paths and anything else not on disk.
459
+ */
460
+ function trimIndex(dir: string, git: GitRunner, limit: number, files: number) {
461
+ const listing = git(["ls-files", "-s", "-z"], { cwd: dir, timeoutMs: limit, maxBytes: DIFF_MAX_BYTES });
462
+ if (listing.timedOut) throw snapshotTimeout("git ls-files -s", limit, files);
463
+ if (listing.status !== 0 || listing.error || listing.outputCut) throw new Error(`git ls-files -s failed in ${dir}: ${listing.error ?? listing.stderr?.trim() ?? `status ${listing.status}`}`);
464
+ const drop: string[] = [];
465
+ for (const entry of names(listing.stdout)) {
466
+ // `<mode> <sha> <stage>\t<path>`
467
+ const tab = entry.indexOf("\t");
468
+ const path = entry.slice(tab + 1);
469
+ if (entry.startsWith("160000 ")) {
470
+ drop.push(path);
471
+ continue;
472
+ }
473
+ try {
474
+ const stat = lstatSync(join(dir, path));
475
+ if (!stat.isFile() && !stat.isSymbolicLink()) drop.push(path);
476
+ } catch {
477
+ drop.push(path);
478
+ }
479
+ }
480
+ if (drop.length === 0) return;
481
+ const out = spawnSync("git", [...GIT_BASE_ARGS, "update-index", "--force-remove", "-z", "--stdin"], {
482
+ cwd: dir,
483
+ env: gitEnv(),
484
+ input: `${drop.join("\0")}\0`,
485
+ timeout: limit,
486
+ maxBuffer: DIFF_MAX_BYTES,
487
+ });
488
+ if ((out.error as NodeJS.ErrnoException | undefined)?.code === "ETIMEDOUT") throw snapshotTimeout("git update-index", limit, files);
489
+ if (out.status !== 0) throw new Error(`git update-index --force-remove failed in ${dir}: ${out.stderr?.toString() || out.error}`);
490
+ }
491
+
394
492
  export function removeSnapshot(dir: string) {
395
493
  rmSync(dir, { recursive: true, force: true });
396
494
  rmSync(`${dir}.tar`, { force: true });
@@ -0,0 +1,333 @@
1
+ /** Tracked-only working-tree capture. All Git writes live in a disposable repository. */
2
+ import { spawnSync } from "node:child_process";
3
+ import {
4
+ constants,
5
+ closeSync,
6
+ fstatSync,
7
+ lstatSync,
8
+ mkdirSync,
9
+ mkdtempSync,
10
+ openSync,
11
+ readFileSync,
12
+ readlinkSync,
13
+ realpathSync,
14
+ rmSync,
15
+ writeFileSync,
16
+ } from "node:fs";
17
+ import { tmpdir } from "node:os";
18
+ import { basename, dirname, join, resolve } from "node:path";
19
+ import { createHash } from "node:crypto";
20
+ import { UsageError } from "../config";
21
+ import { GIT_BASE_ARGS, gitEnv, spawnGit, type GitRunner } from "../evidence";
22
+ import { REVIEW_INPUT_V2, type ReviewInput } from "../formats";
23
+ import { resolveScope } from "../engine";
24
+ import { localFiles, localInstructions } from "./local-git";
25
+
26
+ type Spawn = typeof spawnSync;
27
+ const hash = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex");
28
+ const identity = (s: ReturnType<typeof lstatSync>) => [s.dev, s.ino, s.mode, s.size, s.mtimeMs, s.ctimeMs].join(":");
29
+ const failure = () => new UsageError("The index, HEAD or tracked files changed during capture; retry --working-tree.");
30
+ /** Index the materialized bytes directly; git add would apply repository attributes. */
31
+ function indexRawSnapshot(dir: string, entries: string[], exec: (args: string[], input?: Buffer) => Buffer) {
32
+ exec(["init", "-q", "--template="]);
33
+ for (const entry of entries) {
34
+ const tab = entry.indexOf("\t");
35
+ const mode = entry.slice(0, tab).split(" ")[0];
36
+ const path = entry.slice(tab + 1);
37
+ const sha = exec(["hash-object", "-w", "--stdin", "--no-filters"], readFileSync(join(dir, path))).toString().trim();
38
+ // Links are materialized as regular text for evidence, never as live links.
39
+ exec(["update-index", "--add", "--cacheinfo", mode === "100755" ? mode : "100644", sha, path]);
40
+ }
41
+ }
42
+
43
+ export function workingTreeInput(p: {
44
+ repoDir: string;
45
+ mode: "staged" | "all";
46
+ paths: string[];
47
+ log: (s: string) => void;
48
+ warn: (s: string) => void;
49
+ git?: GitRunner;
50
+ spawn?: Spawn;
51
+ afterCapture?: () => void;
52
+ afterManifest?: () => void;
53
+ }): { input: ReviewInput; release: () => void } {
54
+ const source = p.git ?? spawnGit;
55
+ const runSource = (args: string[]) => {
56
+ const r = source(args, { cwd: p.repoDir, timeoutMs: 60000 });
57
+ if (r.status !== 0 || r.error || r.outputCut)
58
+ throw new UsageError(`Cannot capture working tree: git ${args[0]} failed: ${r.stderr ?? r.error}`);
59
+ return r.stdout.replace(/\r?\n$/, "");
60
+ };
61
+ let base: string;
62
+ try {
63
+ base = runSource(["rev-parse", "--verify", "HEAD^{commit}"]);
64
+ } catch {
65
+ throw new UsageError("Working-tree review requires an existing HEAD commit.");
66
+ }
67
+ const top = realpathSync(runSource(["rev-parse", "--show-toplevel"]));
68
+ const index = resolve(p.repoDir, runSource(["rev-parse", "--git-path", "index"]));
69
+ if (runSource(["rev-parse", "--shared-index-path"]))
70
+ throw new UsageError("Working-tree review does not support a split index; disable split-index first.");
71
+ // Read only these semantic settings; never import source hooks, filters or other config.
72
+ const fileMode = p.mode !== "all" || runSource(["config", "--type=bool", "--default=true", "--get", "core.fileMode"]) === "true";
73
+ const symlinks = p.mode !== "all" || runSource(["config", "--type=bool", "--default=true", "--get", "core.symlinks"]) === "true";
74
+ const beforeIdentity = identity(lstatSync(index));
75
+ const before = readFileSync(index);
76
+ const root = realpathSync(mkdtempSync(join(tmpdir(), "wachiman-working-tree-")));
77
+ const release = () => rmSync(root, { recursive: true, force: true });
78
+ const spawn = p.spawn ?? spawnSync;
79
+ try {
80
+ const gitDir = join(root, "repository");
81
+ const snapshot = join(root, "snapshot");
82
+ mkdirSync(snapshot);
83
+ const exec = (args: string[], input?: Buffer, cwd = top) => {
84
+ const out = spawn("git", [...GIT_BASE_ARGS, "-c", "core.hooksPath=/dev/null", "-c", "core.attributesFile=/dev/null", ...args], {
85
+ cwd,
86
+ input,
87
+ env: {
88
+ ...gitEnv(),
89
+ GIT_CONFIG_NOSYSTEM: "1",
90
+ GIT_CONFIG_GLOBAL: "/dev/null",
91
+ GIT_NO_REPLACE_OBJECTS: "1",
92
+ GIT_NO_LAZY_FETCH: "1",
93
+ },
94
+ timeout: 60000,
95
+ maxBuffer: 512 * 1024 * 1024,
96
+ });
97
+ if (out.status !== 0 || out.error) throw new UsageError(`Working-tree git ${args[0]} failed: ${out.stderr?.toString() ?? out.error}`);
98
+ return Buffer.from(out.stdout ?? "");
99
+ };
100
+ const format = runSource(["rev-parse", "--show-object-format"]);
101
+ exec(["init", "--bare", "--template=", "--object-format=" + format, gitDir]);
102
+ const objects = resolve(p.repoDir, runSource(["rev-parse", "--git-path", "objects"]));
103
+ // Alternates are read-only: no command runs with the source repository as its git-dir.
104
+ writeFileSync(join(gitDir, "objects/info/alternates"), JSON.stringify(objects) + "\n");
105
+ // Git must consume the same bytes checked below, never a later live index.
106
+ writeFileSync(join(gitDir, "index"), before);
107
+ const args = (a: string[]) => ["--git-dir=" + gitDir, ...a];
108
+ const raw = (a: string[], input?: Buffer) => exec(args(a), input);
109
+ const text = (a: string[]) => {
110
+ const bytes = raw(a);
111
+ try {
112
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
113
+ } catch {
114
+ throw new UsageError("Working-tree review requires UTF-8 Git paths.");
115
+ }
116
+ };
117
+ const git: GitRunner = (a, o) => {
118
+ try {
119
+ return {
120
+ status: 0,
121
+ stdout: exec(args(a), undefined, o.cwd).toString("utf8"),
122
+ };
123
+ } catch (e) {
124
+ return { status: 1, stdout: "", stderr: String(e) };
125
+ }
126
+ };
127
+ if (text(["ls-files", "--unmerged", "-z"]))
128
+ throw new UsageError("Working-tree review refuses an unmerged index. Resolve conflicts first.");
129
+ if (
130
+ text(["ls-files", "-v", "-z"])
131
+ .split("\0")
132
+ .some((s) => s.slice(0, 2).toUpperCase() === "S ")
133
+ )
134
+ throw new UsageError("Working-tree review does not support sparse checkout/skip-worktree entries.");
135
+ const entries = text(["ls-files", "--stage", "-z"])
136
+ .split("\0")
137
+ .filter(Boolean)
138
+ .map((s) => {
139
+ const tab = s.indexOf("\t");
140
+ const [mode, sha, stage] = s.slice(0, tab).split(" ");
141
+ return { mode, sha, stage, path: s.slice(tab + 1) };
142
+ });
143
+ for (const e of entries) {
144
+ if (e.mode === "160000") throw new UsageError("Working-tree review does not support submodule/gitlink snapshot content.");
145
+ if (!["100644", "100755", "120000"].includes(e.mode)) throw new UsageError("Unsupported index mode " + e.mode);
146
+ }
147
+ // Read every parent with lstat; never follow a tracked path through a symlink.
148
+ const read = (entry: (typeof entries)[number], metadataOnly = false) => {
149
+ const path = entry.path;
150
+ const parts = path.split("/");
151
+ if (parts.some((s) => !s || s === "." || s === ".." || s.toLowerCase() === ".git"))
152
+ throw new UsageError("Unsafe tracked path " + path);
153
+ let parent = top;
154
+ const parents: string[] = [];
155
+ for (const part of parts.slice(0, -1)) {
156
+ parent = join(parent, part);
157
+ try {
158
+ const s = lstatSync(parent);
159
+ if (!s.isDirectory() || s.isSymbolicLink()) throw new UsageError("Tracked path has a non-directory or symlink parent: " + path);
160
+ parents.push(identity(s));
161
+ } catch (e) {
162
+ if ((e as NodeJS.ErrnoException).code === "ENOENT") return null;
163
+ throw e;
164
+ }
165
+ }
166
+ const file = join(top, path);
167
+ let stat;
168
+ try {
169
+ stat = lstatSync(file);
170
+ } catch (e) {
171
+ if ((e as NodeJS.ErrnoException).code === "ENOENT") return null;
172
+ throw e;
173
+ }
174
+ // Like git add -u, a directory replacing a tracked leaf deletes that file.
175
+ // Its children are untracked and must never be traversed. Parent checks above remain strict.
176
+ if (stat.isDirectory()) return null;
177
+ let bytes: Buffer;
178
+ let mode: string;
179
+ if (stat.isSymbolicLink()) {
180
+ bytes = metadataOnly ? Buffer.alloc(0) : Buffer.from(readlinkSync(file));
181
+ mode = "120000";
182
+ } else if (stat.isFile()) {
183
+ if (metadataOnly) {
184
+ bytes = Buffer.alloc(0);
185
+ } else {
186
+ const fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
187
+ try {
188
+ if (identity(fstatSync(fd)) !== identity(stat)) throw failure();
189
+ bytes = readFileSync(fd);
190
+ if (identity(fstatSync(fd)) !== identity(stat)) throw failure();
191
+ } finally {
192
+ closeSync(fd);
193
+ }
194
+ }
195
+ // Match Git: an emulated link keeps its index type; untrusted exec bits
196
+ // preserve regular index modes, but a real type change still takes effect.
197
+ if (!symlinks && entry.mode === "120000") mode = "120000";
198
+ else if (!fileMode) mode = entry.mode === "100755" ? "100755" : "100644";
199
+ else mode = stat.mode & 0o100 ? "100755" : "100644";
200
+ } else throw new UsageError("Unsupported tracked file type: " + path);
201
+ return {
202
+ bytes,
203
+ mode,
204
+ identity: parents.join("|") + "|" + identity(stat),
205
+ manifest: parents.join("|") + "|" + identity(stat) + "|" + hash(bytes),
206
+ };
207
+ };
208
+ // Freeze identities for the complete path set before reading any file contents.
209
+ const manifest = p.mode === "all" ? entries.map((e) => read(e, true)?.identity) : [];
210
+ p.afterManifest?.();
211
+ const captured =
212
+ p.mode === "all"
213
+ ? entries.map((e, i) => {
214
+ const content = read(e);
215
+ if (content?.identity !== manifest[i]) throw failure();
216
+ return { ...e, content };
217
+ })
218
+ : [];
219
+ if (p.mode === "all") {
220
+ // Rebuild from the index's tracked path set. update-index --cacheinfo never invokes filters.
221
+ raw(["read-tree", "--empty"]);
222
+ for (const e of captured) {
223
+ if (!e.content) continue;
224
+ const sha = raw(["hash-object", "-w", "--stdin", "--no-filters"], e.content.bytes).toString().trim();
225
+ raw(["update-index", "--add", "--cacheinfo", e.content.mode, sha, e.path]);
226
+ }
227
+ }
228
+ const tree = text(["write-tree"]).trim();
229
+ p.afterCapture?.();
230
+ try {
231
+ if (
232
+ identity(lstatSync(index)) !== beforeIdentity ||
233
+ !readFileSync(index).equals(before) ||
234
+ runSource(["rev-parse", "--verify", "HEAD^{commit}"]) !== base
235
+ )
236
+ throw failure();
237
+ for (const e of captured) {
238
+ if (read(e)?.manifest !== e.content?.manifest) throw failure();
239
+ }
240
+ } catch {
241
+ throw failure();
242
+ }
243
+ const files = localFiles(top, base, tree, git);
244
+ const { paths, ignored } = resolveScope(
245
+ p.paths,
246
+ files.map((f) => f.filename),
247
+ );
248
+ if (ignored.length) p.log("Not paths in this change, ignored: " + ignored.join(" "));
249
+ // Materialize raw blobs directly: no archive attributes, filters, tar traversal or live symlinks.
250
+ const treeEntries = text(["ls-tree", "-r", "-z", tree]).split("\0").filter(Boolean);
251
+ for (const entry of treeEntries) {
252
+ const tab = entry.indexOf("\t");
253
+ const [mode, type, sha] = entry.slice(0, tab).split(" ");
254
+ const path = entry.slice(tab + 1);
255
+ if (type !== "blob") throw new UsageError("Unsupported snapshot entry " + path);
256
+ if (path.split("/").some((s) => !s || s === ".." || s === "." || s.toLowerCase() === ".git"))
257
+ throw new UsageError("Unsafe snapshot path " + path);
258
+ const dest = join(snapshot, path);
259
+ mkdirSync(dirname(dest), { recursive: true });
260
+ writeFileSync(dest, raw(["cat-file", "blob", sha]), {
261
+ mode: mode === "100755" ? 0o755 : 0o644,
262
+ });
263
+ }
264
+ // Evidence uses git grep in its own index; symlink entries remain textual blobs there too.
265
+ indexRawSnapshot(snapshot, treeEntries, (a, input) => exec(["-C", snapshot, ...a], input));
266
+ const name = basename(top);
267
+ const input: ReviewInput = {
268
+ format: REVIEW_INPUT_V2,
269
+ change: {
270
+ kind: "working-tree",
271
+ describe: p.mode === "staged" ? `the staged changes of ${name}` : `the working tree of ${name}`,
272
+ repository: { name },
273
+ base: { sha: base, ref: "HEAD" },
274
+ head: { sha: tree, ref: `working tree (${p.mode})` },
275
+ workingTree: { mode: p.mode, baseCommit: base, tree },
276
+ },
277
+ files,
278
+ instructions: localInstructions(top, base, p.warn, git),
279
+ headDir: snapshot,
280
+ scope: paths,
281
+ };
282
+ return { input, release };
283
+ } catch (e) {
284
+ release();
285
+ throw e;
286
+ }
287
+ }
288
+
289
+ /** A portable /2 input refers to a tree already present in this clone. Copy only raw blobs. */
290
+ export function snapshotWorkingTree(repoDir: string, tree: string, spawn: Spawn = spawnSync) {
291
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "wachiman-tree-input-")));
292
+ try {
293
+ const exec = (args: string[], cwd = repoDir, input?: Buffer) => {
294
+ const r = spawn("git", [...GIT_BASE_ARGS, ...args], {
295
+ cwd,
296
+ input,
297
+ env: {
298
+ ...gitEnv(),
299
+ GIT_CONFIG_NOSYSTEM: "1",
300
+ GIT_CONFIG_GLOBAL: "/dev/null",
301
+ GIT_NO_LAZY_FETCH: "1",
302
+ GIT_NO_REPLACE_OBJECTS: "1",
303
+ },
304
+ timeout: 60000,
305
+ maxBuffer: 512 * 1024 * 1024,
306
+ });
307
+ if (r.status !== 0 || r.error) throw new UsageError("Cannot read working-tree input: " + (r.stderr?.toString() ?? r.error));
308
+ return Buffer.from(r.stdout ?? "");
309
+ };
310
+ if (exec(["cat-file", "-t", tree]).toString().trim() !== "tree")
311
+ throw new UsageError("Working-tree input head must be an existing tree object.");
312
+ const entries = exec(["ls-tree", "-r", "-z", tree]).toString().split("\0").filter(Boolean);
313
+ for (const entry of entries) {
314
+ const tab = entry.indexOf("\t");
315
+ const [mode, type, sha] = entry.slice(0, tab).split(" ");
316
+ const path = entry.slice(tab + 1);
317
+ if (type !== "blob" || !["100644", "100755", "120000"].includes(mode))
318
+ throw new UsageError("Unsupported working-tree snapshot entry " + path);
319
+ if (path.split("/").some((s) => !s || s === "." || s === ".." || s.toLowerCase() === ".git"))
320
+ throw new UsageError("Unsafe snapshot path " + path);
321
+ const dest = join(dir, path);
322
+ mkdirSync(dirname(dest), { recursive: true });
323
+ writeFileSync(dest, exec(["cat-file", "blob", sha]), {
324
+ mode: mode === "100755" ? 0o755 : 0o644,
325
+ });
326
+ }
327
+ indexRawSnapshot(dir, entries, (a, input) => exec(["-c", "core.hooksPath=/dev/null", ...a], dir, input));
328
+ return { dir };
329
+ } catch (e) {
330
+ rmSync(dir, { recursive: true, force: true });
331
+ throw e;
332
+ }
333
+ }
package/src/cost.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * be grepped and summed across runs), and a table in the GitHub Actions job summary.
8
8
  */
9
9
  import { appendFileSync } from "node:fs";
10
+ import type { ProviderAuth } from "./providers/types";
10
11
 
11
12
  /**
12
13
  * What a call was for.
@@ -46,6 +47,15 @@ export function addUsage(a: TokenUsage, b: TokenUsage): TokenUsage {
46
47
 
47
48
  export const hasUsage = (u: TokenUsage) => u.input + u.output + u.cacheRead + u.cacheWrite > 0;
48
49
 
50
+ /**
51
+ * True when the dollar figure of a call is an API-price equivalent, not a charge: a run on a
52
+ * Claude subscription, locally or with a CI token (ADR 0019 decision 6, ADR 0037 decision 5).
53
+ */
54
+ export const isEstimate = (auth: ProviderAuth | undefined) => auth === "oauth-token" || auth === "subscription";
55
+
56
+ /** The footer's wording for an estimate; the same idea as the local mode's "API-equivalent estimate … not a bill". */
57
+ export const ESTIMATE_NOTE = "Claude subscription: API-equivalent estimate, not a bill";
58
+
49
59
  /** One model call, as reported by the provider and tagged by the engine. */
50
60
  export interface CallCost {
51
61
  operation: Operation;
@@ -60,6 +70,8 @@ export interface CallCost {
60
70
  /** False when the call died without a result: its real cost is unknown and `costUsd` is its cap. Default true. */
61
71
  costKnown?: boolean;
62
72
  terminalReason: string;
73
+ /** What paid for the call; absent means `api-key`. */
74
+ auth?: ProviderAuth;
63
75
  repo?: string;
64
76
  pr?: number;
65
77
  }
@@ -84,6 +96,8 @@ export function costLine(parts: {
84
96
  /** Anything else for the line, e.g. `2 batches`, `answers 2 thread(s)` or `PR so far $0.77 over 3 automatic runs`. */
85
97
  extra?: string[];
86
98
  usage?: TokenUsage;
99
+ /** The amount is an API-price estimate on a Claude subscription: said before the figure, which stays last. */
100
+ estimate?: boolean;
87
101
  costUsd: number;
88
102
  }) {
89
103
  const { usage } = parts;
@@ -99,6 +113,7 @@ export function costLine(parts: {
99
113
  ...(parts.operation ? [parts.operation] : []),
100
114
  ...(parts.extra ?? []),
101
115
  ...tokens,
116
+ ...(parts.estimate ? [ESTIMATE_NOTE] : []),
102
117
  `$${parts.costUsd.toFixed(2)}`,
103
118
  ];
104
119
  return `<sub>${segments.join(" · ")}</sub>`;
@@ -126,6 +141,8 @@ export function costLogLine(call: CallCost, extra: { trigger?: string } = {}) {
126
141
  cost_usd: call.costKnown === false ? null : Number(call.costUsd.toFixed(6)),
127
142
  ...(call.costKnown === false ? { countedUsd: Number(call.costUsd.toFixed(6)) } : {}),
128
143
  terminal_reason: call.terminalReason,
144
+ // `cost_usd` on `oauth-token` or `subscription` is an API-price estimate, not a charge.
145
+ auth: call.auth ?? "api-key",
129
146
  })}`;
130
147
  }
131
148
 
@@ -149,6 +166,9 @@ export function renderCostSummary(calls: CallCost[]) {
149
166
  "| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |",
150
167
  ...rows,
151
168
  `| **Total** | | ${turns} | ${total.input} | ${total.output} | ${total.cacheRead} | ${total.cacheWrite} | **$${usd.toFixed(4)}** |`,
169
+ ...(calls.some((c) => isEstimate(c.auth))
170
+ ? ["", "These runs used a Claude subscription: the dollars above are API-price estimates (what the calls would cost at API prices), not a bill."]
171
+ : []),
152
172
  ...(unknown.length
153
173
  ? [
154
174
  "",
@@ -382,7 +382,7 @@ export const CHECKS: DoctorCheck[] = [
382
382
  id: "skills",
383
383
  level: "optional",
384
384
  run: ({ userHome, fs }) => {
385
- const names = ["wachiman-review", "wachiman-audit"] as const;
385
+ const names = ["wachiman-review", "wachiman-loop", "wachiman-audit"] as const;
386
386
  const found = Object.fromEntries(names.map((n) => [n, fs.isDirectory(join(userHome, ".claude", "skills", n))])) as Record<(typeof names)[number], boolean>;
387
387
  const where = join(userHome, ".claude", "skills");
388
388
  if (!names.some((n) => found[n])) return { id: "skills", level: "optional", status: "skip", evidence: `no Wachiman skill in ${where}`, detail: found };