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.
@@ -259,7 +259,7 @@ export function localFiles(repoDir: string, mergeBase: string, head: string, git
259
259
  const range = [mergeBase, head];
260
260
  const raw = run(git, repoDir, [...DIFF, "--raw", "-z", "--no-abbrev", ...range], DIFF_MAX_BYTES).split("\0");
261
261
  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));
262
+ const rawSections = splitPatches(run(git, repoDir, [...DIFF, ...PATCH, ...range], DIFF_MAX_BYTES));
263
263
 
264
264
  const entries: { status: string; dstSha: string; from?: string; to: string }[] = [];
265
265
  for (let i = 0; i < raw.length; ) {
@@ -270,6 +270,21 @@ export function localFiles(repoDir: string, mergeBase: string, head: string, git
270
270
  const from = raw[i++];
271
271
  entries.push(two ? { status, dstSha, from, to: raw[i++] } : { status, dstSha, to: from });
272
272
  }
273
+ // Git emits a deletion and an addition patch for one raw T (type-change) entry.
274
+ // Keep both hunks: each carries its own old/new line origin, including +0,0
275
+ // for the deleted side. Evidence and head-line annotations can then use them unchanged.
276
+ let sectionIndex = 0;
277
+ const sections = entries.map((e) => {
278
+ const parts = rawSections.slice(sectionIndex, sectionIndex + (e.status === "T" ? 2 : 1));
279
+ sectionIndex += e.status === "T" ? 2 : 1;
280
+ for (const part of parts) {
281
+ if (!part.header.includes('"') && !part.header.endsWith(` b/${e.to}`)) {
282
+ throw new Error(`git diff sections are out of order: expected ${e.to}, got "${part.header}".`);
283
+ }
284
+ }
285
+ const patches = parts.flatMap((p) => p.patch === undefined ? [] : [p.patch]);
286
+ return { header: parts[0]?.header ?? "", patch: patches.length ? patches.join("\n") : undefined };
287
+ });
273
288
  const counts: { additions: number; deletions: number }[] = [];
274
289
  for (let i = 0; i < numstat.length; ) {
275
290
  const meta = numstat[i++];
@@ -280,17 +295,12 @@ export function localFiles(repoDir: string, mergeBase: string, head: string, git
280
295
  const n = (v: string) => (v === "-" ? 0 : Number(v));
281
296
  counts.push({ additions: n(added), deletions: n(deleted) });
282
297
  }
283
- if (counts.length !== entries.length || sections.length !== entries.length) {
298
+ if (counts.length !== entries.length || sectionIndex !== rawSections.length || sections.some((s) => !s.header)) {
284
299
  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.`,
300
+ `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
301
  );
287
302
  }
288
303
  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
304
  const patch = sections[i].patch;
295
305
  return {
296
306
  filename: e.to,
@@ -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
+ }