revgraph 0.0.0-stage → 0.2.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.
@@ -0,0 +1,765 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ /**
6
+ * Run a command safely without shell interpolation.
7
+ */
8
+ export function runCmd(bin, args, cwd, { allowFailure = false, maxBuffer = 64 * 1024 * 1024 } = {}) {
9
+ try {
10
+ const out = execFileSync(bin, args, {
11
+ cwd,
12
+ encoding: "utf8",
13
+ maxBuffer,
14
+ stdio: ["ignore", "pipe", "pipe"],
15
+ });
16
+ return { ok: true, stdout: out, stderr: "", code: 0 };
17
+ } catch (err) {
18
+ if (allowFailure) {
19
+ return {
20
+ ok: false,
21
+ stdout: err.stdout ? String(err.stdout) : "",
22
+ stderr: err.stderr ? String(err.stderr) : err.message,
23
+ code: typeof err.status === "number" ? err.status : 1,
24
+ };
25
+ }
26
+ const detail = err.stderr ? String(err.stderr).trim() : err.message;
27
+ throw new Error(`Command failed: ${bin} ${args.join(" ")}\n${detail}`);
28
+ }
29
+ }
30
+
31
+ export function git(repoDir, args, opts = {}) {
32
+ return runCmd("git", ["--no-pager", ...args], repoDir, opts);
33
+ }
34
+
35
+ /**
36
+ * Convert a glob pattern (*, **, ?) into a RegExp matching posix paths.
37
+ */
38
+ export function globToRegex(pattern) {
39
+ const normalized = pattern.trim().replace(/\\/g, "/");
40
+ let re = "^";
41
+ let i = 0;
42
+ while (i < normalized.length) {
43
+ const ch = normalized[i];
44
+ if (ch === "*") {
45
+ if (normalized[i + 1] === "*") {
46
+ if (normalized[i + 2] === "/") {
47
+ re += "(?:.*/)?";
48
+ i += 3;
49
+ } else {
50
+ re += ".*";
51
+ i += 2;
52
+ }
53
+ } else {
54
+ re += "[^/]*";
55
+ i += 1;
56
+ }
57
+ } else if (ch === "?") {
58
+ re += "[^/]";
59
+ i += 1;
60
+ } else if ("+.^$|()[]{}\\".includes(ch)) {
61
+ re += "\\" + ch;
62
+ i += 1;
63
+ } else {
64
+ re += ch;
65
+ i += 1;
66
+ }
67
+ }
68
+ re += "$";
69
+ return new RegExp(re);
70
+ }
71
+
72
+ export function matchesAnyGlob(relPath, patterns) {
73
+ const p = relPath.replace(/\\/g, "/");
74
+ const base = path.posix.basename(p);
75
+ for (const pat of patterns) {
76
+ if (!pat) continue;
77
+ const regex = globToRegex(pat);
78
+ if (regex.test(p)) return pat;
79
+ if (!pat.includes("/") && regex.test(base)) return pat;
80
+ }
81
+ return null;
82
+ }
83
+
84
+ export function parsePrInput(raw) {
85
+ if (!raw) return null;
86
+ const trimmed = String(raw).trim();
87
+ const numOnly = trimmed.match(/^#?(\d+)$/);
88
+ if (numOnly) return { number: Number(numOnly[1]), raw: trimmed };
89
+ const urlMatch = trimmed.match(/github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)/i);
90
+ if (urlMatch) {
91
+ return { repo: urlMatch[1], number: Number(urlMatch[2]), raw: trimmed };
92
+ }
93
+ throw new Error(`Invalid --pr value "${raw}". Expected PR number (e.g. 123) or GitHub PR URL.`);
94
+ }
95
+
96
+ export function extractLinkedIssues(prJson) {
97
+ const selfNum = Number(prJson.number);
98
+ const closingSet = new Set();
99
+ const referencedSet = new Set();
100
+
101
+ if (Array.isArray(prJson.closingIssuesReferences)) {
102
+ for (const ref of prJson.closingIssuesReferences) {
103
+ const n = Number(ref?.number);
104
+ if (Number.isInteger(n) && n > 0 && n !== selfNum) closingSet.add(n);
105
+ }
106
+ }
107
+
108
+ // Strip HTML comments (e.g. PR template examples) before scanning
109
+ const cleanBody = String(prJson.body || "").replace(/<!--[\s\S]*?-->/g, "");
110
+ const fullText = `${prJson.title || ""}\n${cleanBody}`;
111
+ const closingRe =
112
+ /\b(?:fix(?:es|ed)?|close[sd]?|resolve[sd]?)\s*:?\s*(?:https?:\/\/github\.com\/[^/\s]+\/[^/\s]+\/issues\/|#)(\d+)\b/gi;
113
+ for (const m of fullText.matchAll(closingRe)) {
114
+ const n = Number(m[1]);
115
+ if (Number.isInteger(n) && n > 0 && n !== selfNum) closingSet.add(n);
116
+ }
117
+
118
+ const anyRefRe = /(?:^|[\s([,:;/(,、])(?:#|https?:\/\/github\.com\/[^/\s]+\/[^/\s]+\/(?:issues|pull)\/)(\d+)\b/g;
119
+ for (const m of fullText.matchAll(anyRefRe)) {
120
+ const n = Number(m[1]);
121
+ if (Number.isInteger(n) && n > 0 && n !== selfNum && !closingSet.has(n)) {
122
+ referencedSet.add(n);
123
+ }
124
+ }
125
+
126
+ return {
127
+ closing: Array.from(closingSet).sort((a, b) => a - b),
128
+ referenced: Array.from(referencedSet).sort((a, b) => a - b),
129
+ };
130
+ }
131
+
132
+ const SCOPE_STOPWORDS = new Set([
133
+ "add", "adds", "fix", "fixes", "feat", "feature", "chore", "docs", "test", "tests",
134
+ "refactor", "perf", "style", "build", "ci", "support", "supports", "update", "updates",
135
+ "improve", "improves", "allow", "enable", "disable", "remove", "drop", "keep", "use",
136
+ "show", "hide", "make", "handle", "prevent", "avoid", "ensure", "check", "read", "write",
137
+ "sync", "with", "from", "into", "when", "only", "more", "some", "each", "over", "under",
138
+ "after", "before", "instead", "without", "across", "based", "using", "their", "them",
139
+ "this", "that", "these", "those", "for", "and", "the", "not", "all", "new", "old", "via",
140
+ "default", "custom", "native", "local", "page", "view", "list", "mode", "file", "files",
141
+ "data", "state", "error", "errors", "issue", "issues", "app", "apps", "cli", "api",
142
+ "config", "settings", "client", "clients", "server", "first", "last", "time", "type",
143
+ "name", "item", "items", "row", "rows", "line", "lines", "key", "keys", "path", "paths",
144
+ "dir", "edit", "open", "close", "load", "save", "run", "set", "get", "include",
145
+ "request", "requests", "output", "input",
146
+ ]);
147
+
148
+ const BROAD_SCOPES = new Set([
149
+ "api", "ui", "ux", "db", "database", "ci", "cd", "docs", "test", "tests", "deps",
150
+ "misc", "config", "settings", "refactor", "chore", "perf", "sync", "auth", "security",
151
+ "core", "cli", "web", "app", "apps", "server", "client", "sdk", "i18n", "build",
152
+ ]);
153
+
154
+ function parseConventionalScope(title) {
155
+ const m = String(title || "").match(/^[a-z]+\(([^)]+)\)\s*:/i);
156
+ if (!m) return null;
157
+ const raw = m[1].trim().toLowerCase();
158
+ const base = raw.split(/[-_/]/)[0];
159
+ return { raw, base };
160
+ }
161
+
162
+ function extractDomainTokens(text) {
163
+ const tokens = new Set();
164
+ const parts = String(text || "")
165
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
166
+ .split(/[^a-zA-Z0-9\u4e00-\u9fff]+/);
167
+ for (const part of parts) {
168
+ const norm = part.toLowerCase();
169
+ if (!norm || norm.length < 3 || /^\d+$/.test(norm) || SCOPE_STOPWORDS.has(norm)) continue;
170
+ tokens.add(norm);
171
+ }
172
+ return tokens;
173
+ }
174
+
175
+ export function buildOverlapSearchQueries(prMeta) {
176
+ const queries = [];
177
+ const seen = new Set();
178
+ const add = (q) => {
179
+ const clean = q.trim().toLowerCase();
180
+ if (!clean || seen.has(clean)) return;
181
+ seen.add(clean);
182
+ queries.push(clean);
183
+ };
184
+ const scope = parseConventionalScope(prMeta?.title);
185
+ if (scope && !BROAD_SCOPES.has(scope.raw)) {
186
+ add(scope.base.length >= 3 ? scope.base : scope.raw);
187
+ }
188
+ const titleNoPrefix = String(prMeta?.title || "").replace(/^[a-z]+(?:\([^)]+\))?\s*:\s*/i, "");
189
+ for (const tok of extractDomainTokens(titleNoPrefix)) {
190
+ if (queries.length >= 2) break;
191
+ if (tok.length >= 4) add(tok);
192
+ }
193
+ return queries.slice(0, 2);
194
+ }
195
+
196
+ export function findOverlappingOpenPrs(prMeta, openPrs) {
197
+ if (!prMeta || !Array.isArray(openPrs) || openPrs.length === 0) return [];
198
+ const selfNum = Number(prMeta.number);
199
+ const selfScope = parseConventionalScope(prMeta.title);
200
+ const selfTitleNoPrefix = String(prMeta.title || "").replace(/^[a-z]+(?:\([^)]+\))?\s*:\s*/i, "");
201
+ const selfTokens = extractDomainTokens(selfTitleNoPrefix);
202
+
203
+ const matches = [];
204
+ const seenNums = new Set();
205
+ for (const cand of openPrs) {
206
+ const num = Number(cand?.number);
207
+ if (!Number.isInteger(num) || num <= 0 || num === selfNum || seenNums.has(num)) continue;
208
+ seenNums.add(num);
209
+ const candScope = parseConventionalScope(cand.title);
210
+ const candTitleNoPrefix = String(cand.title || "").replace(/^[a-z]+(?:\([^)]+\))?\s*:\s*/i, "");
211
+ const candTokens = extractDomainTokens(candTitleNoPrefix);
212
+
213
+ const sharedTokens = [];
214
+ for (const t of selfTokens) {
215
+ if (candTokens.has(t)) sharedTokens.push(t);
216
+ }
217
+
218
+ let score = 0;
219
+ const reasons = [];
220
+
221
+ const sameNarrowScope =
222
+ selfScope &&
223
+ candScope &&
224
+ !BROAD_SCOPES.has(selfScope.raw) &&
225
+ (selfScope.raw === candScope.raw ||
226
+ (selfScope.base.length >= 3 && selfScope.base === candScope.base));
227
+
228
+ const sameBroadScope =
229
+ selfScope &&
230
+ candScope &&
231
+ BROAD_SCOPES.has(selfScope.raw) &&
232
+ selfScope.raw === candScope.raw;
233
+
234
+ if (sameNarrowScope) {
235
+ score += 4;
236
+ reasons.push(`same scope (${selfScope.raw} ↔ ${candScope.raw})`);
237
+ } else if (sameBroadScope && sharedTokens.length >= 2) {
238
+ score += 2;
239
+ reasons.push(`same scope (${selfScope.raw})`);
240
+ }
241
+
242
+ if (sharedTokens.length > 0) {
243
+ score += sharedTokens.length * 1.5;
244
+ reasons.push(`shared terms: ${sharedTokens.slice(0, 5).join(", ")}`);
245
+ }
246
+
247
+ const passes =
248
+ sameNarrowScope ||
249
+ (sameBroadScope && sharedTokens.length >= 2) ||
250
+ sharedTokens.length >= 3;
251
+
252
+ if (passes) {
253
+ matches.push({
254
+ number: num,
255
+ title: cand.title || "",
256
+ is_draft: Boolean(cand.isDraft),
257
+ url: cand.url || "",
258
+ score,
259
+ reason: reasons.join("; "),
260
+ });
261
+ }
262
+ }
263
+
264
+ return matches
265
+ .sort((a, b) => b.score - a.score || a.number - b.number)
266
+ .slice(0, 5)
267
+ .map(({ score: _score, ...rest }) => rest);
268
+ }
269
+
270
+ export function resolveRefExists(repoDir, ref) {
271
+ if (!ref) return false;
272
+ return git(repoDir, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { allowFailure: true }).ok;
273
+ }
274
+
275
+ function parseNumstat(stdout) {
276
+ const map = new Map();
277
+ for (const line of stdout.split("\n")) {
278
+ if (!line.trim()) continue;
279
+ const parts = line.split("\t");
280
+ if (parts.length < 3) continue;
281
+ const [insStr, delStr, ...rest] = parts;
282
+ const rawPath = rest.join("\t");
283
+ let filePath = rawPath;
284
+ if (rawPath.includes(" => ")) {
285
+ filePath = rawPath.replace(/\{[^{}]*=>\s*([^{}]*)\}/g, "$1").replace(/^.*=>\s*/, "");
286
+ }
287
+ const binary = insStr === "-" || delStr === "-";
288
+ const insertions = binary ? 0 : Number.parseInt(insStr, 10) || 0;
289
+ const deletions = binary ? 0 : Number.parseInt(delStr, 10) || 0;
290
+ map.set(filePath, { insertions, deletions, binary });
291
+ }
292
+ return map;
293
+ }
294
+
295
+ function parseNameStatus(stdout) {
296
+ const entries = [];
297
+ for (const line of stdout.split("\n")) {
298
+ if (!line.trim()) continue;
299
+ const parts = line.split("\t");
300
+ const rawStatus = parts[0];
301
+ const code = rawStatus[0];
302
+ if ((code === "R" || code === "C") && parts.length >= 3) {
303
+ entries.push({ status: code === "R" ? "renamed" : "copied", oldPath: parts[1], path: parts[2] });
304
+ } else if (parts.length >= 2) {
305
+ const statusMap = { A: "added", M: "modified", D: "deleted", T: "typechange" };
306
+ entries.push({ status: statusMap[code] || rawStatus, path: parts[1] });
307
+ }
308
+ }
309
+ return entries;
310
+ }
311
+
312
+ function parseUnifiedDiffStats(diffText) {
313
+ const fileMap = new Map();
314
+ let current = null;
315
+ for (const line of diffText.split("\n")) {
316
+ if (line.startsWith("diff --git ")) {
317
+ const m = line.match(/^diff --git a\/(.+?) b\/(.+)$/);
318
+ if (m) {
319
+ current = {
320
+ path: m[2],
321
+ oldPath: m[1] !== m[2] ? m[1] : undefined,
322
+ status: "modified",
323
+ insertions: 0,
324
+ deletions: 0,
325
+ binary: false,
326
+ patchLines: [line],
327
+ };
328
+ fileMap.set(current.path, current);
329
+ }
330
+ continue;
331
+ }
332
+ if (!current) continue;
333
+ current.patchLines.push(line);
334
+ if (line.startsWith("new file mode ")) current.status = "added";
335
+ else if (line.startsWith("deleted file mode ")) current.status = "deleted";
336
+ else if (line.startsWith("rename to ")) current.status = "renamed";
337
+ else if (line.startsWith("Binary files ")) current.binary = true;
338
+ else if (line.startsWith("+") && !line.startsWith("+++ ")) current.insertions += 1;
339
+ else if (line.startsWith("-") && !line.startsWith("--- ")) current.deletions += 1;
340
+ }
341
+ return fileMap;
342
+ }
343
+
344
+ function isLikelyBinaryFile(absPath) {
345
+ try {
346
+ const fd = fs.openSync(absPath, "r");
347
+ const buf = Buffer.alloc(4096);
348
+ const bytes = fs.readSync(fd, buf, 0, buf.length, 0);
349
+ fs.closeSync(fd);
350
+ for (let i = 0; i < bytes; i++) {
351
+ if (buf[i] === 0) return true;
352
+ }
353
+ return false;
354
+ } catch {
355
+ return false;
356
+ }
357
+ }
358
+
359
+ /**
360
+ * Parse `git status --porcelain=v1 -z -uall` to preserve exact paths (spaces/unicode)
361
+ * and keep distinct (path, status) pairs when a deleted file is recreated untracked.
362
+ */
363
+ function parseWorkspacePorcelainZ(repoRoot, statusZ, numstat) {
364
+ const tokens = statusZ.split("\0");
365
+ const rawFiles = [];
366
+ const seen = new Set();
367
+
368
+ for (let i = 0; i < tokens.length; i++) {
369
+ const entry = tokens[i];
370
+ if (!entry || entry.length < 4) continue;
371
+ const xy = entry.slice(0, 2);
372
+ let filePath = entry.slice(3);
373
+ let oldPath;
374
+
375
+ // For renames/copies in -z mode, the next NUL token is the original path
376
+ if (xy[0] === "R" || xy[0] === "C" || xy[1] === "R" || xy[1] === "C") {
377
+ oldPath = tokens[++i];
378
+ }
379
+
380
+ if (xy === "??") {
381
+ const key = `${filePath}::untracked`;
382
+ if (seen.has(key)) continue;
383
+ seen.add(key);
384
+ const abs = path.join(repoRoot, filePath);
385
+ let lines = 0;
386
+ let binary = false;
387
+ if (fs.existsSync(abs) && fs.statSync(abs).isFile()) {
388
+ binary = isLikelyBinaryFile(abs);
389
+ if (!binary) {
390
+ try {
391
+ lines = fs.readFileSync(abs, "utf8").split("\n").length;
392
+ } catch {
393
+ lines = 0;
394
+ }
395
+ }
396
+ }
397
+ rawFiles.push({ path: filePath, status: "untracked", insertions: lines, deletions: 0, binary });
398
+ continue;
399
+ }
400
+
401
+ let status = "modified";
402
+ if (xy.includes("D")) status = "deleted";
403
+ else if (xy.includes("A")) status = "added";
404
+ else if (xy.includes("R")) status = "renamed";
405
+ else if (xy.includes("C")) status = "copied";
406
+
407
+ const key = `${filePath}::${status}`;
408
+ if (seen.has(key)) continue;
409
+ seen.add(key);
410
+ const stats = numstat.get(filePath) || { insertions: 0, deletions: 0, binary: false };
411
+ rawFiles.push({ path: filePath, ...(oldPath ? { oldPath } : {}), status, ...stats });
412
+ }
413
+ return rawFiles;
414
+ }
415
+
416
+ /**
417
+ * Resolve review target (PR / range / commit / workspace) and return structured preview metadata.
418
+ */
419
+ export function collectReviewTarget(repoDir, opts, excludePatterns = []) {
420
+ const repoRoot = git(repoDir, ["rev-parse", "--show-toplevel"]).stdout.trim();
421
+ const warnings = [];
422
+ let mode = "workspace";
423
+ let prMeta = null;
424
+ let fromRef = null;
425
+ let toRef = null;
426
+ let commitRef = null;
427
+ let mergeBase = null;
428
+ let headGitRef = null;
429
+ let fallbackDiffMap = null;
430
+ let rawFiles = [];
431
+
432
+ if (opts.pr) {
433
+ mode = "pr";
434
+ const parsedPr = parsePrInput(opts.pr);
435
+ const ghArgs = [
436
+ "pr",
437
+ "view",
438
+ String(parsedPr.number),
439
+ "--json",
440
+ "number,title,body,author,baseRefName,headRefName,baseRefOid,headRefOid,url,additions,deletions,isDraft,labels,closingIssuesReferences",
441
+ ];
442
+ if (parsedPr.repo) ghArgs.push("--repo", parsedPr.repo);
443
+ const prRes = runCmd("gh", ghArgs, repoRoot);
444
+ const prJson = JSON.parse(prRes.stdout);
445
+ const rawBody = prJson.body || "";
446
+ prMeta = {
447
+ number: prJson.number,
448
+ title: prJson.title,
449
+ author: prJson.author?.login || "unknown",
450
+ url: prJson.url,
451
+ is_draft: Boolean(prJson.isDraft),
452
+ labels: Array.isArray(prJson.labels) ? prJson.labels.map((l) => l.name).filter(Boolean) : [],
453
+ additions: Number(prJson.additions) || 0,
454
+ deletions: Number(prJson.deletions) || 0,
455
+ base_ref: prJson.baseRefName,
456
+ head_ref: prJson.headRefName,
457
+ base_oid: prJson.baseRefOid,
458
+ head_oid: prJson.headRefOid,
459
+ body: rawBody.slice(0, 4000),
460
+ body_truncated: rawBody.length > 4000,
461
+ linked_issues: extractLinkedIssues(prJson),
462
+ overlapping_prs: [],
463
+ };
464
+
465
+ if (!opts.noOverlapCheck) {
466
+ const candidatePool = [];
467
+ for (const term of buildOverlapSearchQueries(prMeta)) {
468
+ const searchArgs = [
469
+ "pr", "list", "--state", "open", "--search", `${term} in:title`,
470
+ "--limit", "50", "--json", "number,title,isDraft,url",
471
+ ];
472
+ if (parsedPr.repo) searchArgs.push("--repo", parsedPr.repo);
473
+ const searchRes = runCmd("gh", searchArgs, repoRoot, { allowFailure: true });
474
+ if (searchRes.ok) {
475
+ try { candidatePool.push(...JSON.parse(searchRes.stdout)); } catch {}
476
+ }
477
+ }
478
+ if (candidatePool.length === 0) {
479
+ const listArgs = ["pr", "list", "--state", "open", "--limit", "100", "--json", "number,title,isDraft,url"];
480
+ if (parsedPr.repo) listArgs.push("--repo", parsedPr.repo);
481
+ const listRes = runCmd("gh", listArgs, repoRoot, { allowFailure: true });
482
+ if (listRes.ok) {
483
+ try { candidatePool.push(...JSON.parse(listRes.stdout)); } catch {}
484
+ }
485
+ }
486
+ prMeta.overlapping_prs = findOverlappingOpenPrs(prMeta, candidatePool);
487
+ }
488
+
489
+ // Fetch PR head into git object store without modifying working tree
490
+ if (resolveRefExists(repoRoot, prJson.headRefOid)) {
491
+ headGitRef = prJson.headRefOid;
492
+ } else {
493
+ const fetchRes = git(
494
+ repoRoot,
495
+ ["fetch", "--no-tags", "origin", `pull/${prJson.number}/head`],
496
+ { allowFailure: true },
497
+ );
498
+ if (fetchRes.ok) {
499
+ headGitRef = git(repoRoot, ["rev-parse", "FETCH_HEAD"]).stdout.trim();
500
+ } else {
501
+ warnings.push(
502
+ `Could not fetch origin pull/${prJson.number}/head (${fetchRes.stderr.trim()}); falling back to 'gh pr diff'.`,
503
+ );
504
+ }
505
+ }
506
+
507
+ const baseCandidates = [prJson.baseRefOid, `origin/${prJson.baseRefName}`, prJson.baseRefName];
508
+ let resolvedBase = baseCandidates.find((r) => resolveRefExists(repoRoot, r)) || null;
509
+ if (!resolvedBase && headGitRef) {
510
+ const fetchBase = git(
511
+ repoRoot,
512
+ ["fetch", "--no-tags", "origin", prJson.baseRefName],
513
+ { allowFailure: true },
514
+ );
515
+ if (fetchBase.ok && resolveRefExists(repoRoot, `origin/${prJson.baseRefName}`)) {
516
+ resolvedBase = `origin/${prJson.baseRefName}`;
517
+ }
518
+ }
519
+
520
+ fromRef = resolvedBase || prJson.baseRefName;
521
+ toRef = headGitRef || prJson.headRefName;
522
+
523
+ if (headGitRef && resolvedBase) {
524
+ const mbRes = git(repoRoot, ["merge-base", resolvedBase, headGitRef], { allowFailure: true });
525
+ mergeBase = mbRes.ok ? mbRes.stdout.trim() : resolvedBase;
526
+ const ns = git(repoRoot, ["diff", "--name-status", "-M", `${mergeBase}..${headGitRef}`]).stdout;
527
+ const numstat = parseNumstat(
528
+ git(repoRoot, ["diff", "--numstat", "-M", `${mergeBase}..${headGitRef}`]).stdout,
529
+ );
530
+ rawFiles = parseNameStatus(ns).map((entry) => ({
531
+ ...entry,
532
+ ...(numstat.get(entry.path) || { insertions: 0, deletions: 0, binary: false }),
533
+ }));
534
+ } else {
535
+ const diffArgs = ["pr", "diff", String(parsedPr.number)];
536
+ if (parsedPr.repo) diffArgs.push("--repo", parsedPr.repo);
537
+ const ghDiff = runCmd("gh", diffArgs, repoRoot).stdout;
538
+ fallbackDiffMap = parseUnifiedDiffStats(ghDiff);
539
+ rawFiles = Array.from(fallbackDiffMap.values()).map(({ patchLines: _, ...rest }) => rest);
540
+ }
541
+ } else if (opts.commit) {
542
+ mode = "commit";
543
+ commitRef = git(repoRoot, ["rev-parse", `${opts.commit}^{commit}`]).stdout.trim();
544
+ headGitRef = commitRef;
545
+ const parentRes = git(repoRoot, ["rev-parse", "--verify", "--quiet", `${commitRef}^`], {
546
+ allowFailure: true,
547
+ });
548
+ fromRef = parentRes.ok ? parentRes.stdout.trim() : null;
549
+ toRef = commitRef;
550
+ const ns = git(repoRoot, ["show", "--format=", "--name-status", "-M", commitRef]).stdout;
551
+ const numstat = parseNumstat(
552
+ git(repoRoot, ["show", "--format=", "--numstat", "-M", commitRef]).stdout,
553
+ );
554
+ rawFiles = parseNameStatus(ns).map((entry) => ({
555
+ ...entry,
556
+ ...(numstat.get(entry.path) || { insertions: 0, deletions: 0, binary: false }),
557
+ }));
558
+ } else if (opts.from || opts.to) {
559
+ mode = "range";
560
+ fromRef = opts.from || "main";
561
+ toRef = opts.to || "HEAD";
562
+ headGitRef = git(repoRoot, ["rev-parse", `${toRef}^{commit}`]).stdout.trim();
563
+ const mbRes = git(repoRoot, ["merge-base", fromRef, headGitRef], { allowFailure: true });
564
+ mergeBase = mbRes.ok ? mbRes.stdout.trim() : fromRef;
565
+ const ns = git(repoRoot, ["diff", "--name-status", "-M", `${mergeBase}..${headGitRef}`]).stdout;
566
+ const numstat = parseNumstat(
567
+ git(repoRoot, ["diff", "--numstat", "-M", `${mergeBase}..${headGitRef}`]).stdout,
568
+ );
569
+ rawFiles = parseNameStatus(ns).map((entry) => ({
570
+ ...entry,
571
+ ...(numstat.get(entry.path) || { insertions: 0, deletions: 0, binary: false }),
572
+ }));
573
+ } else {
574
+ mode = "workspace";
575
+ const hasHead = resolveRefExists(repoRoot, "HEAD");
576
+ const statusZ = git(repoRoot, ["status", "--porcelain=v1", "-z", "-uall"]).stdout;
577
+ const numstat = hasHead
578
+ ? parseNumstat(git(repoRoot, ["diff", "--numstat", "HEAD"]).stdout)
579
+ : parseNumstat(git(repoRoot, ["diff", "--cached", "--numstat"]).stdout);
580
+ rawFiles = parseWorkspacePorcelainZ(repoRoot, statusZ, numstat);
581
+ }
582
+
583
+ const reviewableFiles = [];
584
+ const excludedFiles = [];
585
+
586
+ for (const f of rawFiles) {
587
+ if (f.binary) {
588
+ excludedFiles.push({ path: f.path, status: f.status, reason: "binary file" });
589
+ continue;
590
+ }
591
+ const matchedExclude = matchesAnyGlob(f.path, excludePatterns);
592
+ if (matchedExclude) {
593
+ excludedFiles.push({ path: f.path, status: f.status, reason: `matches exclude: ${matchedExclude}` });
594
+ continue;
595
+ }
596
+
597
+ let diffCmd = "";
598
+ if (mode === "pr" || mode === "range") {
599
+ if (mergeBase && headGitRef) {
600
+ diffCmd = `git --no-pager diff --no-ext-diff --no-textconv --no-color ${mergeBase}..${headGitRef} -- "${f.path}"`;
601
+ } else if (prMeta) {
602
+ diffCmd = `gh pr diff ${prMeta.number}`;
603
+ }
604
+ } else if (mode === "commit") {
605
+ diffCmd = `git --no-pager show --no-ext-diff --no-textconv --no-color ${commitRef} -- "${f.path}"`;
606
+ } else if (f.status === "untracked") {
607
+ diffCmd = `cat "${f.path}"`;
608
+ } else if (resolveRefExists(repoRoot, "HEAD")) {
609
+ diffCmd = `git --no-pager diff --no-ext-diff --no-textconv --no-color HEAD -- "${f.path}"`;
610
+ } else {
611
+ diffCmd = `git --no-pager diff --cached --no-ext-diff --no-textconv --no-color -- "${f.path}"`;
612
+ }
613
+
614
+ reviewableFiles.push({
615
+ path: f.path,
616
+ ...(f.oldPath ? { old_path: f.oldPath } : {}),
617
+ status: f.status,
618
+ insertions: f.insertions,
619
+ deletions: f.deletions,
620
+ diff_cmd: diffCmd,
621
+ });
622
+ }
623
+
624
+ return {
625
+ repo_root: repoRoot,
626
+ mode,
627
+ ...(prMeta ? { pr: prMeta } : {}),
628
+ from: fromRef,
629
+ to: toRef,
630
+ commit: commitRef,
631
+ merge_base: mergeBase,
632
+ head_git_ref: headGitRef,
633
+ reviewable_files: reviewableFiles,
634
+ excluded_files: excludedFiles,
635
+ warnings,
636
+ _fallbackDiffMap: fallbackDiffMap,
637
+ };
638
+ }
639
+
640
+ /**
641
+ * List repository files at the target snapshot using git (respects .gitignore and any monorepo layout).
642
+ */
643
+ export function listRepoFiles(target) {
644
+ let raw = "";
645
+ if (target.mode !== "workspace" && target.head_git_ref) {
646
+ const res = git(target.repo_root, ["ls-tree", "-r", "--name-only", "-z", target.head_git_ref], {
647
+ allowFailure: true,
648
+ });
649
+ if (res.ok) raw = res.stdout;
650
+ }
651
+ if (!raw) {
652
+ const res = git(target.repo_root, ["ls-files", "-co", "--exclude-standard", "-z"], {
653
+ allowFailure: true,
654
+ });
655
+ if (res.ok) raw = res.stdout;
656
+ }
657
+ const files = raw
658
+ .split("\0")
659
+ .filter(Boolean)
660
+ .map((p) => p.replace(/\\/g, "/"));
661
+ return Array.from(new Set(files)).sort();
662
+ }
663
+
664
+ /**
665
+ * Read file text at the target snapshot without modifying the working tree.
666
+ */
667
+ export function readFileAtTarget(target, relPath, cache = new Map()) {
668
+ if (cache.has(relPath)) return cache.get(relPath);
669
+ let content = null;
670
+ if (target.mode === "workspace" || !target.head_git_ref) {
671
+ const abs = path.join(target.repo_root, relPath);
672
+ if (fs.existsSync(abs) && fs.statSync(abs).isFile()) {
673
+ try {
674
+ content = fs.readFileSync(abs, "utf8");
675
+ } catch {
676
+ content = null;
677
+ }
678
+ }
679
+ } else {
680
+ const res = git(target.repo_root, ["show", `${target.head_git_ref}:${relPath}`], {
681
+ allowFailure: true,
682
+ });
683
+ if (res.ok) content = res.stdout;
684
+ }
685
+ cache.set(relPath, content);
686
+ return content;
687
+ }
688
+
689
+ /**
690
+ * Get zero-context unified diff for a file and extract changed line ranges and +/- text.
691
+ */
692
+ export function getFileDiffInfo(target, fileEntry) {
693
+ const relPath = fileEntry.path;
694
+ let patch = "";
695
+
696
+ if (fileEntry.status === "untracked") {
697
+ const content = readFileAtTarget(target, relPath);
698
+ const lines = content ? content.split("\n") : [];
699
+ return {
700
+ patch: content || "",
701
+ added_lines: lines.length > 0 ? [{ start: 1, end: lines.length }] : [],
702
+ removed_lines: [],
703
+ added_text: lines,
704
+ removed_text: [],
705
+ };
706
+ }
707
+
708
+ if (target._fallbackDiffMap && target._fallbackDiffMap.has(relPath)) {
709
+ patch = target._fallbackDiffMap.get(relPath).patchLines.join("\n");
710
+ } else if ((target.mode === "pr" || target.mode === "range") && target.merge_base && target.head_git_ref) {
711
+ patch = git(
712
+ target.repo_root,
713
+ ["diff", "--no-ext-diff", "--no-textconv", "--no-color", "-U0", `${target.merge_base}..${target.head_git_ref}`, "--", relPath],
714
+ { allowFailure: true },
715
+ ).stdout;
716
+ } else if (target.mode === "commit" && target.commit) {
717
+ patch = git(
718
+ target.repo_root,
719
+ ["show", "--format=", "--no-ext-diff", "--no-textconv", "--no-color", "-U0", target.commit, "--", relPath],
720
+ { allowFailure: true },
721
+ ).stdout;
722
+ } else if (target.mode === "workspace") {
723
+ const args = resolveRefExists(target.repo_root, "HEAD")
724
+ ? ["diff", "--no-ext-diff", "--no-textconv", "--no-color", "-U0", "HEAD", "--", relPath]
725
+ : ["diff", "--cached", "--no-ext-diff", "--no-textconv", "--no-color", "-U0", "--", relPath];
726
+ patch = git(target.repo_root, args, { allowFailure: true }).stdout;
727
+ }
728
+
729
+ const addedRanges = [];
730
+ const removedRanges = [];
731
+ const addedText = [];
732
+ const removedText = [];
733
+
734
+ for (const line of patch.split("\n")) {
735
+ const hunk = line.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
736
+ if (hunk) {
737
+ const oldStart = Number(hunk[1]);
738
+ const oldCount = hunk[2] === undefined ? 1 : Number(hunk[2]);
739
+ const newStart = Number(hunk[3]);
740
+ const newCount = hunk[4] === undefined ? 1 : Number(hunk[4]);
741
+ if (newCount > 0) {
742
+ addedRanges.push({ start: newStart, end: newStart + newCount - 1 });
743
+ } else {
744
+ addedRanges.push({ start: Math.max(1, newStart), end: Math.max(1, newStart) });
745
+ }
746
+ if (oldCount > 0) {
747
+ removedRanges.push({ start: oldStart, end: oldStart + oldCount - 1 });
748
+ }
749
+ continue;
750
+ }
751
+ if (line.startsWith("+") && !line.startsWith("+++ ")) {
752
+ addedText.push(line.slice(1));
753
+ } else if (line.startsWith("-") && !line.startsWith("--- ")) {
754
+ removedText.push(line.slice(1));
755
+ }
756
+ }
757
+
758
+ return {
759
+ patch,
760
+ added_lines: addedRanges,
761
+ removed_lines: removedRanges,
762
+ added_text: addedText,
763
+ removed_text: removedText,
764
+ };
765
+ }