@self-review/core 1.43.4 → 1.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -5,6 +5,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
8
11
  var __export = (target, all) => {
9
12
  for (var name in all)
10
13
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -27,54 +30,11 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
30
  ));
28
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
32
 
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- ForgeCliUnavailableError: () => ForgeCliUnavailableError,
34
- GUIDE_XSD_SCHEMA: () => GUIDE_XSD_SCHEMA,
35
- IMPLICIT_GUIDE_GROUP_NAME: () => IMPLICIT_GUIDE_GROUP_NAME,
36
- REVIEW_LEVEL_FILE_PATH: () => REVIEW_LEVEL_FILE_PATH,
37
- checkWritability: () => checkWritability,
38
- computePayloadStats: () => computePayloadStats,
39
- countTotalLines: () => countTotalLines,
40
- createGitHubProvider: () => createGitHubProvider,
41
- createGitLabProvider: () => createGitLabProvider,
42
- createIgnoreFilter: () => createIgnoreFilter,
43
- defaultGitRunner: () => defaultGitRunner,
44
- detectExistingClone: () => detectExistingClone,
45
- generateSyntheticDiffs: () => generateSyntheticDiffs,
46
- generateUntrackedDiffs: () => generateUntrackedDiffs,
47
- getGitDiffStats: () => getGitDiffStats,
48
- getLanguageFromPath: () => getLanguageFromPath,
49
- getRenderedTextMode: () => getRenderedTextMode,
50
- getRepoRoot: () => getRepoRoot,
51
- getRepoRootAsync: () => getRepoRootAsync,
52
- getUntrackedFilesAsync: () => getUntrackedFilesAsync,
53
- isHtmlFile: () => isHtmlFile,
54
- isMarkdownFile: () => isMarkdownFile,
55
- isPreviewableImage: () => isPreviewableImage,
56
- isPreviewableRenderedText: () => isPreviewableRenderedText,
57
- isPreviewableSvg: () => isPreviewableSvg,
58
- loadConfig: () => loadConfig,
59
- mapThreadsToReviewComments: () => mapThreadsToReviewComments,
60
- materialize: () => materialize,
61
- parseDiff: () => parseDiff,
62
- parseForgeUrl: () => parseForgeUrl,
63
- parseGuideXml: () => parseGuideXml,
64
- parseReviewXml: () => parseReviewXml,
65
- parseReviewXmlString: () => parseReviewXmlString,
66
- reconcileGuide: () => reconcileGuide,
67
- resolveRemoteDefaultBranch: () => resolveRemoteDefaultBranch,
68
- runGitDiff: () => runGitDiff,
69
- runGitDiffAsync: () => runGitDiffAsync,
70
- scanDirectory: () => scanDirectory,
71
- scanFile: () => scanFile,
72
- serializeReview: () => serializeReview,
73
- validateGitAvailable: () => validateGitAvailable
74
- });
75
- module.exports = __toCommonJS(index_exports);
76
-
77
33
  // src/diff-parser.ts
34
+ var diff_parser_exports = {};
35
+ __export(diff_parser_exports, {
36
+ parseDiff: () => parseDiff
37
+ });
78
38
  function parseDiff(rawDiff) {
79
39
  if (!rawDiff.trim()) {
80
40
  return [];
@@ -85,6 +45,12 @@ function parseDiff(rawDiff) {
85
45
  let currentHunk = null;
86
46
  let oldLineNumber = 0;
87
47
  let newLineNumber = 0;
48
+ let hasModeChange = false;
49
+ function flushFile() {
50
+ if (currentFile && (currentFile.oldPath || currentFile.newPath) && (currentFile.isBinary || currentFile.hunks.length > 0 || currentFile.changeType !== "modified" || hasModeChange)) {
51
+ files.push(currentFile);
52
+ }
53
+ }
88
54
  for (let i = 0; i < lines.length; i++) {
89
55
  const line = lines[i];
90
56
  if (line.startsWith("diff --git ")) {
@@ -92,11 +58,7 @@ function parseDiff(rawDiff) {
92
58
  currentFile.hunks.push(currentHunk);
93
59
  currentHunk = null;
94
60
  }
95
- if (currentFile && currentFile.oldPath !== void 0 && currentFile.newPath !== void 0) {
96
- if (currentFile.isBinary || currentFile.hunks && currentFile.hunks.length > 0 || currentFile.changeType === "added") {
97
- files.push(currentFile);
98
- }
99
- }
61
+ flushFile();
100
62
  const gitPaths = parseGitDiffHeader(line);
101
63
  currentFile = {
102
64
  oldPath: gitPaths.oldPath,
@@ -106,29 +68,41 @@ function parseDiff(rawDiff) {
106
68
  hunks: []
107
69
  };
108
70
  currentHunk = null;
71
+ hasModeChange = false;
109
72
  continue;
110
73
  }
111
74
  if (!currentFile) continue;
112
75
  if (line.startsWith("new file mode")) {
113
76
  currentFile.changeType = "added";
77
+ currentFile.oldPath = "";
114
78
  continue;
115
79
  }
116
80
  if (line.startsWith("deleted file mode")) {
117
81
  currentFile.changeType = "deleted";
82
+ currentFile.newPath = "";
83
+ continue;
84
+ }
85
+ if (line.startsWith("new mode ")) {
86
+ hasModeChange = true;
118
87
  continue;
119
88
  }
120
89
  if (line.startsWith("rename from ")) {
121
90
  currentFile.changeType = "renamed";
91
+ currentFile.oldPath = decodeGitPath(line.substring("rename from ".length));
122
92
  continue;
123
93
  }
124
- if (line.startsWith("--- ")) {
125
- const path3 = line.substring(4);
126
- currentFile.oldPath = path3 === "/dev/null" ? "" : stripPrefix(path3);
94
+ if (line.startsWith("rename to ")) {
95
+ currentFile.newPath = decodeGitPath(line.substring("rename to ".length));
127
96
  continue;
128
97
  }
129
- if (line.startsWith("+++ ")) {
130
- const path3 = line.substring(4);
131
- currentFile.newPath = path3 === "/dev/null" ? "" : stripPrefix(path3);
98
+ if (!currentHunk && line.startsWith("--- ")) {
99
+ const path4 = decodeGitPath(line.substring(4).split(" ")[0]);
100
+ currentFile.oldPath = path4 === "/dev/null" ? "" : stripPrefix(path4);
101
+ continue;
102
+ }
103
+ if (!currentHunk && line.startsWith("+++ ")) {
104
+ const path4 = decodeGitPath(line.substring(4).split(" ")[0]);
105
+ currentFile.newPath = path4 === "/dev/null" ? "" : stripPrefix(path4);
132
106
  continue;
133
107
  }
134
108
  if (line.startsWith("Binary files ")) {
@@ -139,9 +113,7 @@ function parseDiff(rawDiff) {
139
113
  if (currentHunk && currentHunk.header) {
140
114
  currentFile.hunks.push(currentHunk);
141
115
  }
142
- const match = line.match(
143
- /@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/
144
- );
116
+ const match = line.match(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/);
145
117
  if (match) {
146
118
  const oldStart = parseInt(match[1], 10);
147
119
  const oldLines = match[2] ? parseInt(match[2], 10) : 1;
@@ -206,52 +178,403 @@ function parseDiff(rawDiff) {
206
178
  if (currentHunk && currentHunk.header && currentFile) {
207
179
  currentFile.hunks.push(currentHunk);
208
180
  }
209
- if (currentFile && currentFile.oldPath !== void 0 && currentFile.newPath !== void 0) {
210
- if (currentFile.isBinary || currentFile.hunks && currentFile.hunks.length > 0 || currentFile.changeType === "added") {
211
- files.push(currentFile);
212
- }
213
- }
181
+ flushFile();
214
182
  return files;
215
183
  }
216
- function stripPrefix(path3) {
217
- if (path3.length > 2 && path3[1] === "/") {
218
- return path3.substring(2);
219
- }
220
- return path3;
184
+ function stripPrefix(path4) {
185
+ if (path4.length > 2 && path4[1] === "/") {
186
+ return path4.substring(2);
187
+ }
188
+ return path4;
189
+ }
190
+ function decodeGitPath(path4) {
191
+ if (!path4.startsWith('"') || !path4.endsWith('"')) return path4;
192
+ const escapes = {
193
+ a: "\x07",
194
+ b: "\b",
195
+ f: "\f",
196
+ n: "\n",
197
+ r: "\r",
198
+ t: " ",
199
+ v: "\v",
200
+ '"': '"',
201
+ "\\": "\\"
202
+ };
203
+ return path4.slice(1, -1).replace(/(?:\\[0-7]{1,3})+|\\[abfnrtv"\\]/g, (escape) => {
204
+ if (/^\\[0-7]/.test(escape)) {
205
+ const bytes = escape.slice(1).split("\\").map((byte) => parseInt(byte, 8));
206
+ return Buffer.from(bytes).toString("utf8");
207
+ }
208
+ return escapes[escape[1]];
209
+ });
221
210
  }
222
211
  function parseGitDiffHeader(line) {
223
- const withoutPrefix = line.substring("diff --git ".length);
224
- let bIdx = -1;
225
- for (const prefix of [" b/", " w/", " i/", " c/", " o/"]) {
226
- bIdx = withoutPrefix.indexOf(prefix);
227
- if (bIdx !== -1) break;
228
- }
229
- if (bIdx === -1) {
230
- return { oldPath: "", newPath: "" };
212
+ const paths = line.substring("diff --git ".length);
213
+ const quotedOld = paths.match(/^("(?:\\.|[^"\\])*") (.+)$/);
214
+ const quotedNew = paths.match(/^(.+) ("(?:\\.|[^"\\])*")$/);
215
+ const quoted = quotedOld || quotedNew;
216
+ if (quoted) {
217
+ return {
218
+ oldPath: stripPrefix(decodeGitPath(quoted[1])),
219
+ newPath: stripPrefix(decodeGitPath(quoted[2]))
220
+ };
231
221
  }
232
- const oldPath = stripPrefix(withoutPrefix.substring(0, bIdx));
233
- const newPath = stripPrefix(withoutPrefix.substring(bIdx + 1));
234
- return { oldPath, newPath };
222
+ const separators = [...paths.matchAll(/ [bwico]\//g)];
223
+ const boundary = separators.find(
224
+ (match) => stripPrefix(paths.substring(0, match.index)) === stripPrefix(paths.substring(match.index + 1))
225
+ ) || separators[0];
226
+ if (!boundary) return { oldPath: "", newPath: "" };
227
+ return {
228
+ oldPath: stripPrefix(paths.substring(0, boundary.index)),
229
+ newPath: stripPrefix(paths.substring(boundary.index + 1))
230
+ };
235
231
  }
232
+ var init_diff_parser = __esm({
233
+ "src/diff-parser.ts"() {
234
+ "use strict";
235
+ }
236
+ });
236
237
 
237
- // src/xml-serializer.ts
238
- var path = __toESM(require("path"), 1);
239
- var fs = __toESM(require("fs"), 1);
240
- var import_xmllint_wasm = require("xmllint-wasm");
241
- var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
242
- <xs:schema
243
- xmlns:xs="http://www.w3.org/2001/XMLSchema"
244
- xmlns:sr="urn:self-review:v3"
245
- targetNamespace="urn:self-review:v3"
246
- elementFormDefault="qualified"
247
- >
238
+ // src/synthetic-diff.ts
239
+ function needsQuoting(byte) {
240
+ return byte < 32 || byte >= 127 || byte === 34 || byte === 92;
241
+ }
242
+ function quoteGitPath(path4) {
243
+ const bytes = Buffer.from(path4, "utf-8");
244
+ if (!bytes.some(needsQuoting)) return path4;
245
+ let quoted = '"';
246
+ for (const byte of bytes) {
247
+ const escape = C_STYLE_ESCAPES[byte];
248
+ if (escape) {
249
+ quoted += escape;
250
+ } else if (byte < 32 || byte >= 127) {
251
+ quoted += `\\${byte.toString(8).padStart(3, "0")}`;
252
+ } else {
253
+ quoted += String.fromCharCode(byte);
254
+ }
255
+ }
256
+ return `${quoted}"`;
257
+ }
258
+ function generateSyntheticDiffs(paths, rootDir) {
259
+ const diffs = [];
260
+ for (const filePath of paths) {
261
+ const fullPath = (0, import_path.join)(rootDir, filePath);
262
+ let content;
263
+ try {
264
+ content = (0, import_fs2.readFileSync)(fullPath);
265
+ } catch {
266
+ continue;
267
+ }
268
+ const oldHeaderPath = quoteGitPath(`a/${filePath}`);
269
+ const newHeaderPath = quoteGitPath(`b/${filePath}`);
270
+ const sample = content.subarray(0, 8192);
271
+ const isBinary = sample.includes(0);
272
+ if (isBinary) {
273
+ diffs.push(
274
+ `diff --git ${oldHeaderPath} ${newHeaderPath}
275
+ new file mode 100644
276
+ Binary files /dev/null and ${newHeaderPath} differ`
277
+ );
278
+ continue;
279
+ }
280
+ const text = content.toString("utf-8");
281
+ const lines = text.split("\n");
282
+ if (lines.length > 0 && lines[lines.length - 1] === "") {
283
+ lines.pop();
284
+ }
285
+ const lineCount = lines.length;
286
+ const addedLines = lines.map((line) => `+${line}`).join("\n");
287
+ let diff = `diff --git ${oldHeaderPath} ${newHeaderPath}
288
+ new file mode 100644
289
+ --- /dev/null
290
+ +++ ${newHeaderPath}
291
+ @@ -0,0 +1,${lineCount} @@
292
+ ` + addedLines;
293
+ if (text.length > 0 && !text.endsWith("\n")) {
294
+ diff += "\n\";
295
+ }
296
+ diffs.push(diff);
297
+ }
298
+ return diffs.join("\n");
299
+ }
300
+ var import_fs2, import_path, C_STYLE_ESCAPES;
301
+ var init_synthetic_diff = __esm({
302
+ "src/synthetic-diff.ts"() {
303
+ "use strict";
304
+ import_fs2 = require("fs");
305
+ import_path = require("path");
306
+ C_STYLE_ESCAPES = {
307
+ 7: "\\a",
308
+ 8: "\\b",
309
+ 9: "\\t",
310
+ 10: "\\n",
311
+ 11: "\\v",
312
+ 12: "\\f",
313
+ 13: "\\r",
314
+ 34: '\\"',
315
+ 92: "\\\\"
316
+ };
317
+ }
318
+ });
248
319
 
249
- <!--
250
- self-review XML Schema v3
251
- =========================
252
- Defines the output format for the self-review application.
253
- This schema is designed to be both machine-validated and
254
- fed to an LLM so it can understand the structure of review feedback.
320
+ // src/git.ts
321
+ var git_exports = {};
322
+ __export(git_exports, {
323
+ generateUntrackedDiffs: () => generateUntrackedDiffs,
324
+ getRepoRoot: () => getRepoRoot,
325
+ getRepoRootAsync: () => getRepoRootAsync,
326
+ getUntrackedFilesAsync: () => getUntrackedFilesAsync,
327
+ readGitBlobAsync: () => readGitBlobAsync,
328
+ runGitDiff: () => runGitDiff,
329
+ runGitDiffAsync: () => runGitDiffAsync,
330
+ stripTrailingNewline: () => stripTrailingNewline,
331
+ validateGitAvailable: () => validateGitAvailable
332
+ });
333
+ function stripTrailingNewline(text) {
334
+ return text.replace(/\r?\n$/, "");
335
+ }
336
+ function runGitDiff(args) {
337
+ try {
338
+ try {
339
+ (0, import_child_process.execSync)("git --version", { stdio: "ignore" });
340
+ } catch {
341
+ console.error("Error: git is not installed or not in PATH");
342
+ process.exit(1);
343
+ }
344
+ try {
345
+ (0, import_child_process.execSync)("git rev-parse --git-dir", { stdio: "ignore" });
346
+ } catch {
347
+ console.error("Error: not a git repository (or any parent up to mount point)");
348
+ process.exit(1);
349
+ }
350
+ const result = (0, import_child_process.execFileSync)("git", ["diff", ...args], {
351
+ encoding: "utf-8",
352
+ maxBuffer: 50 * 1024 * 1024
353
+ // 50MB buffer for large diffs
354
+ });
355
+ return result;
356
+ } catch (error) {
357
+ if (error instanceof Error) {
358
+ console.error(`Error running git diff: ${error.message}`);
359
+ } else {
360
+ console.error("Error running git diff: unknown error");
361
+ }
362
+ process.exit(1);
363
+ }
364
+ }
365
+ function getRepoRoot() {
366
+ try {
367
+ const result = (0, import_child_process.execSync)("git rev-parse --show-toplevel", {
368
+ encoding: "utf-8"
369
+ });
370
+ return stripTrailingNewline(result);
371
+ } catch (error) {
372
+ if (error instanceof Error) {
373
+ console.error(`Error getting repository root: ${error.message}`);
374
+ } else {
375
+ console.error("Error getting repository root: unknown error");
376
+ }
377
+ process.exit(1);
378
+ }
379
+ }
380
+ function validateGitAvailable() {
381
+ try {
382
+ (0, import_child_process.execSync)("git --version", { stdio: "ignore" });
383
+ } catch {
384
+ console.error("Error: git is not installed or not in PATH");
385
+ process.exit(1);
386
+ }
387
+ try {
388
+ (0, import_child_process.execSync)("git rev-parse --git-dir", { stdio: "ignore" });
389
+ } catch {
390
+ console.error("Error: not a git repository (or any parent up to mount point)");
391
+ process.exit(1);
392
+ }
393
+ }
394
+ async function getRepoRootAsync(cwd) {
395
+ try {
396
+ const { stdout } = await execFileAsync("git", ["rev-parse", "--show-toplevel"], {
397
+ timeout: 1e4,
398
+ // 10 second timeout
399
+ cwd
400
+ });
401
+ return stripTrailingNewline(stdout);
402
+ } catch (error) {
403
+ if (error instanceof Error) {
404
+ console.error(`Error getting repository root: ${error.message}`);
405
+ } else {
406
+ console.error("Error getting repository root: unknown error");
407
+ }
408
+ throw error;
409
+ }
410
+ }
411
+ async function runGitDiffAsync(args, cwd) {
412
+ try {
413
+ const { stdout } = await execFileAsync("git", ["diff", ...args], {
414
+ maxBuffer: 50 * 1024 * 1024,
415
+ // 50MB buffer
416
+ timeout: 3e4,
417
+ // 30 second timeout
418
+ cwd
419
+ });
420
+ return stdout;
421
+ } catch (error) {
422
+ if (error instanceof Error) {
423
+ console.error(`Error running git diff: ${error.message}`);
424
+ } else {
425
+ console.error("Error running git diff: unknown error");
426
+ }
427
+ throw error;
428
+ }
429
+ }
430
+ async function readGitBlobAsync(repoPath, spec) {
431
+ return await new Promise((resolve7, reject) => {
432
+ (0, import_child_process.execFile)(
433
+ "git",
434
+ ["-C", repoPath, "show", spec],
435
+ { encoding: "buffer", maxBuffer: 50 * 1024 * 1024, timeout: 3e4 },
436
+ (error, stdout) => {
437
+ if (error) {
438
+ reject(error);
439
+ } else {
440
+ resolve7(stdout);
441
+ }
442
+ }
443
+ );
444
+ });
445
+ }
446
+ async function getUntrackedFilesAsync(repoRoot) {
447
+ try {
448
+ const { stdout } = await execFileAsync(
449
+ "git",
450
+ ["ls-files", "--others", "--exclude-standard", "-z"],
451
+ {
452
+ maxBuffer: 10 * 1024 * 1024,
453
+ timeout: 1e4,
454
+ cwd: repoRoot
455
+ }
456
+ );
457
+ return stdout.split("\0").filter((name) => name.length > 0);
458
+ } catch (error) {
459
+ if (error instanceof Error) {
460
+ console.error(`Warning: Failed to list untracked files: ${error.message}`);
461
+ } else {
462
+ console.error("Warning: Failed to list untracked files: unknown error");
463
+ }
464
+ return [];
465
+ }
466
+ }
467
+ function generateUntrackedDiffs(paths, repoRoot) {
468
+ return generateSyntheticDiffs(paths, repoRoot);
469
+ }
470
+ var import_child_process, import_util, execFileAsync;
471
+ var init_git = __esm({
472
+ "src/git.ts"() {
473
+ "use strict";
474
+ import_child_process = require("child_process");
475
+ import_util = require("util");
476
+ init_synthetic_diff();
477
+ execFileAsync = (0, import_util.promisify)(import_child_process.execFile);
478
+ }
479
+ });
480
+
481
+ // src/index.ts
482
+ var index_exports = {};
483
+ __export(index_exports, {
484
+ ForgeCliUnavailableError: () => ForgeCliUnavailableError,
485
+ GUIDE_XSD_SCHEMA: () => GUIDE_XSD_SCHEMA,
486
+ IMPLICIT_GUIDE_GROUP_NAME: () => IMPLICIT_GUIDE_GROUP_NAME,
487
+ REVIEW_LEVEL_FILE_PATH: () => REVIEW_LEVEL_FILE_PATH,
488
+ applyRemoteProvenance: () => applyRemoteProvenance,
489
+ applyStagedUntrackedDefault: () => applyStagedUntrackedDefault,
490
+ applySuggestion: () => applySuggestion,
491
+ applySuggestionForSession: () => applySuggestionForSession,
492
+ bootstrapRemoteDiff: () => bootstrapRemoteDiff,
493
+ buildRemoteReviewState: () => buildRemoteReviewState,
494
+ checkWritability: () => checkWritability,
495
+ commitReviewStart: () => commitReviewStart,
496
+ computePayloadStats: () => computePayloadStats,
497
+ computeRemoteDrift: () => computeRemoteDrift,
498
+ countTotalLines: () => countTotalLines,
499
+ createGitHubProvider: () => createGitHubProvider,
500
+ createGitLabProvider: () => createGitLabProvider,
501
+ createIgnoreFilter: () => createIgnoreFilter,
502
+ createReviewSession: () => createReviewSession,
503
+ defaultGitRunner: () => defaultGitRunner,
504
+ deriveGuidePath: () => deriveGuidePath,
505
+ detectExistingClone: () => detectExistingClone,
506
+ determineMode: () => determineMode,
507
+ expandContext: () => expandContext,
508
+ generateSyntheticDiffs: () => generateSyntheticDiffs,
509
+ generateUntrackedDiffs: () => generateUntrackedDiffs,
510
+ getConfigLoad: () => getConfigLoad,
511
+ getDiffLoad: () => getDiffLoad,
512
+ getFileHunks: () => getFileHunks,
513
+ getGitDiffStats: () => getGitDiffStats,
514
+ getLanguageFromPath: () => getLanguageFromPath,
515
+ getRenderedTextMode: () => getRenderedTextMode,
516
+ getRepoRoot: () => getRepoRoot,
517
+ getRepoRootAsync: () => getRepoRootAsync,
518
+ getResumeLoad: () => getResumeLoad,
519
+ getUntrackedFilesAsync: () => getUntrackedFilesAsync,
520
+ isHtmlFile: () => isHtmlFile,
521
+ isMarkdownFile: () => isMarkdownFile,
522
+ isPreviewableImage: () => isPreviewableImage,
523
+ isPreviewableRenderedText: () => isPreviewableRenderedText,
524
+ isPreviewableSvg: () => isPreviewableSvg,
525
+ loadConfig: () => loadConfig,
526
+ loadGitDiffWithUntracked: () => loadGitDiffWithUntracked,
527
+ loadGuide: () => loadGuide,
528
+ loadImage: () => loadImage,
529
+ mapThreadsToReviewComments: () => mapThreadsToReviewComments,
530
+ materialize: () => materialize,
531
+ mergeRemoteThreads: () => mergeRemoteThreads,
532
+ normalizeGitDiffArgs: () => normalizeGitDiffArgs,
533
+ parseDiff: () => parseDiff,
534
+ parseForgeUrl: () => parseForgeUrl,
535
+ parseGuideXml: () => parseGuideXml,
536
+ parseReviewXml: () => parseReviewXml,
537
+ parseReviewXmlString: () => parseReviewXmlString,
538
+ prepareDirectoryReview: () => prepareDirectoryReview,
539
+ preparePayload: () => preparePayload,
540
+ readAttachment: () => readAttachment,
541
+ reconcileGuide: () => reconcileGuide,
542
+ resolveApplyDestination: () => resolveApplyDestination,
543
+ resolveGuidePath: () => resolveGuidePath,
544
+ resolveRemoteDefaultBranch: () => resolveRemoteDefaultBranch,
545
+ resolveSourceBaseDir: () => resolveSourceBaseDir,
546
+ runFetchComments: () => runFetchComments,
547
+ runGitDiff: () => runGitDiff,
548
+ runGitDiffAsync: () => runGitDiffAsync,
549
+ scanDirectory: () => scanDirectory,
550
+ scanFile: () => scanFile,
551
+ serializeReview: () => serializeReview,
552
+ startRemoteSession: () => startRemoteSession,
553
+ submitReviewState: () => submitReviewState,
554
+ takeReviewState: () => takeReviewState,
555
+ validateGitAvailable: () => validateGitAvailable
556
+ });
557
+ module.exports = __toCommonJS(index_exports);
558
+ init_diff_parser();
559
+
560
+ // src/xml-serializer.ts
561
+ var path = __toESM(require("path"), 1);
562
+ var fs = __toESM(require("fs"), 1);
563
+ var import_xmllint_wasm = require("xmllint-wasm");
564
+ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
565
+ <xs:schema
566
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
567
+ xmlns:sr="urn:self-review:v3"
568
+ targetNamespace="urn:self-review:v3"
569
+ elementFormDefault="qualified"
570
+ >
571
+
572
+ <!--
573
+ self-review XML Schema v3
574
+ =========================
575
+ Defines the output format for the self-review application.
576
+ This schema is designed to be both machine-validated and
577
+ fed to an LLM so it can understand the structure of review feedback.
255
578
 
256
579
  Key concepts:
257
580
  - A <review> contains one <file> per file in the diff.
@@ -867,18 +1190,25 @@ function extFromMediaType(mediaType) {
867
1190
  };
868
1191
  return map[mediaType] || "png";
869
1192
  }
1193
+ function assetNameComponent(idPrefix) {
1194
+ return String(idPrefix ?? "").replace(/[^A-Za-z0-9_-]/g, "_");
1195
+ }
870
1196
  function persistAttachments(attachments, idPrefix, assetDir, onWrite) {
871
1197
  if (!attachments?.length) return attachments;
872
1198
  return attachments.map((att, index) => {
873
1199
  if (!att.data) return att;
874
1200
  onWrite();
875
1201
  const ext = extFromMediaType(att.mediaType);
876
- const fileName = `${idPrefix}-${index}.${ext}`;
1202
+ const fileName = `${assetNameComponent(idPrefix)}-${index}.${ext}`;
877
1203
  const relativePath = `.self-review-assets/${fileName}`;
1204
+ const target = path.join(assetDir, fileName);
1205
+ if (path.dirname(path.resolve(target)) !== path.resolve(assetDir)) {
1206
+ throw new Error(`Refusing to write an attachment outside ${assetDir}: ${fileName}`);
1207
+ }
878
1208
  if (!fs.existsSync(assetDir)) {
879
1209
  fs.mkdirSync(assetDir, { recursive: true });
880
1210
  }
881
- fs.writeFileSync(path.join(assetDir, fileName), Buffer.from(att.data));
1211
+ fs.writeFileSync(target, Buffer.from(att.data));
882
1212
  return { ...att, fileName: relativePath, data: void 0 };
883
1213
  });
884
1214
  }
@@ -933,9 +1263,13 @@ async function serializeReview(state, outputFilePath) {
933
1263
  throw error;
934
1264
  }
935
1265
  if (error instanceof Error) {
936
- console.error(`[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`);
1266
+ console.error(
1267
+ `[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`
1268
+ );
937
1269
  } else {
938
- console.error("[main] XML validation infrastructure failed - emitting XML without validation");
1270
+ console.error(
1271
+ "[main] XML validation infrastructure failed - emitting XML without validation"
1272
+ );
939
1273
  }
940
1274
  return xml;
941
1275
  }
@@ -1449,9 +1783,7 @@ async function parseGuideXml(xmlContent) {
1449
1783
  try {
1450
1784
  const validationResult = await (0, import_xmllint_wasm2.validateXML)({
1451
1785
  xml: [{ fileName: "guide.xml", contents: xmlContent }],
1452
- schema: [
1453
- { fileName: "self-review-guide-v1.xsd", contents: GUIDE_XSD_SCHEMA }
1454
- ]
1786
+ schema: [{ fileName: "self-review-guide-v1.xsd", contents: GUIDE_XSD_SCHEMA }]
1455
1787
  });
1456
1788
  if (!validationResult.valid) {
1457
1789
  const details = (validationResult.errors || []).map((err) => typeof err === "string" ? err : err.message).join("; ");
@@ -1526,190 +1858,19 @@ function reconcileGuide(guide, diffFilePaths) {
1526
1858
  });
1527
1859
  }
1528
1860
  }
1529
- const leftover = diffFilePaths.filter((path3) => !claimed.has(path3));
1861
+ const leftover = diffFilePaths.filter((path4) => !claimed.has(path4));
1530
1862
  if (leftover.length > 0) {
1531
1863
  resolved.push({
1532
1864
  name: IMPLICIT_GUIDE_GROUP_NAME,
1533
1865
  implicit: true,
1534
- files: leftover.map((path3) => ({ path: path3 }))
1866
+ files: leftover.map((path4) => ({ path: path4 }))
1535
1867
  });
1536
1868
  }
1537
1869
  return resolved;
1538
1870
  }
1539
1871
 
1540
- // src/git.ts
1541
- var import_child_process = require("child_process");
1542
- var import_util = require("util");
1543
-
1544
- // src/synthetic-diff.ts
1545
- var import_fs2 = require("fs");
1546
- function generateSyntheticDiffs(paths, rootDir) {
1547
- const diffs = [];
1548
- for (const filePath of paths) {
1549
- const fullPath = `${rootDir}/${filePath}`;
1550
- let content;
1551
- try {
1552
- content = (0, import_fs2.readFileSync)(fullPath);
1553
- } catch {
1554
- continue;
1555
- }
1556
- const sample = content.subarray(0, 8192);
1557
- const isBinary = sample.includes(0);
1558
- if (isBinary) {
1559
- diffs.push(
1560
- `diff --git a/${filePath} b/${filePath}
1561
- new file mode 100644
1562
- Binary files /dev/null and b/${filePath} differ`
1563
- );
1564
- continue;
1565
- }
1566
- const text = content.toString("utf-8");
1567
- const lines = text.split("\n");
1568
- if (lines.length > 0 && lines[lines.length - 1] === "") {
1569
- lines.pop();
1570
- }
1571
- const lineCount = lines.length;
1572
- const addedLines = lines.map((line) => `+${line}`).join("\n");
1573
- let diff = `diff --git a/${filePath} b/${filePath}
1574
- new file mode 100644
1575
- --- /dev/null
1576
- +++ b/${filePath}
1577
- @@ -0,0 +1,${lineCount} @@
1578
- ` + addedLines;
1579
- if (text.length > 0 && !text.endsWith("\n")) {
1580
- diff += "\n\";
1581
- }
1582
- diffs.push(diff);
1583
- }
1584
- return diffs.join("\n");
1585
- }
1586
-
1587
- // src/git.ts
1588
- var execAsync = (0, import_util.promisify)(import_child_process.exec);
1589
- var execFileAsync = (0, import_util.promisify)(import_child_process.execFile);
1590
- function runGitDiff(args) {
1591
- try {
1592
- try {
1593
- (0, import_child_process.execSync)("git --version", { stdio: "ignore" });
1594
- } catch {
1595
- console.error("Error: git is not installed or not in PATH");
1596
- process.exit(1);
1597
- }
1598
- try {
1599
- (0, import_child_process.execSync)("git rev-parse --git-dir", { stdio: "ignore" });
1600
- } catch {
1601
- console.error(
1602
- "Error: not a git repository (or any parent up to mount point)"
1603
- );
1604
- process.exit(1);
1605
- }
1606
- const result = (0, import_child_process.execFileSync)("git", ["diff", ...args], {
1607
- encoding: "utf-8",
1608
- maxBuffer: 50 * 1024 * 1024
1609
- // 50MB buffer for large diffs
1610
- });
1611
- return result;
1612
- } catch (error) {
1613
- if (error instanceof Error) {
1614
- console.error(`Error running git diff: ${error.message}`);
1615
- } else {
1616
- console.error("Error running git diff: unknown error");
1617
- }
1618
- process.exit(1);
1619
- }
1620
- }
1621
- function getRepoRoot() {
1622
- try {
1623
- const result = (0, import_child_process.execSync)("git rev-parse --show-toplevel", {
1624
- encoding: "utf-8"
1625
- });
1626
- return result.trim();
1627
- } catch (error) {
1628
- if (error instanceof Error) {
1629
- console.error(`Error getting repository root: ${error.message}`);
1630
- } else {
1631
- console.error("Error getting repository root: unknown error");
1632
- }
1633
- process.exit(1);
1634
- }
1635
- }
1636
- function validateGitAvailable() {
1637
- try {
1638
- (0, import_child_process.execSync)("git --version", { stdio: "ignore" });
1639
- } catch {
1640
- console.error("Error: git is not installed or not in PATH");
1641
- process.exit(1);
1642
- }
1643
- try {
1644
- (0, import_child_process.execSync)("git rev-parse --git-dir", { stdio: "ignore" });
1645
- } catch {
1646
- console.error(
1647
- "Error: not a git repository (or any parent up to mount point)"
1648
- );
1649
- process.exit(1);
1650
- }
1651
- }
1652
- async function getRepoRootAsync(cwd) {
1653
- try {
1654
- const { stdout } = await execAsync("git rev-parse --show-toplevel", {
1655
- timeout: 1e4,
1656
- // 10 second timeout
1657
- cwd
1658
- });
1659
- return stdout.trim();
1660
- } catch (error) {
1661
- if (error instanceof Error) {
1662
- console.error(`Error getting repository root: ${error.message}`);
1663
- } else {
1664
- console.error("Error getting repository root: unknown error");
1665
- }
1666
- throw error;
1667
- }
1668
- }
1669
- async function runGitDiffAsync(args, cwd) {
1670
- try {
1671
- const { stdout } = await execFileAsync("git", ["diff", ...args], {
1672
- maxBuffer: 50 * 1024 * 1024,
1673
- // 50MB buffer
1674
- timeout: 3e4,
1675
- // 30 second timeout
1676
- cwd
1677
- });
1678
- return stdout;
1679
- } catch (error) {
1680
- if (error instanceof Error) {
1681
- console.error(`Error running git diff: ${error.message}`);
1682
- } else {
1683
- console.error("Error running git diff: unknown error");
1684
- }
1685
- throw error;
1686
- }
1687
- }
1688
- async function getUntrackedFilesAsync(cwd) {
1689
- try {
1690
- const { stdout } = await execAsync(
1691
- "git ls-files --others --exclude-standard",
1692
- {
1693
- maxBuffer: 10 * 1024 * 1024,
1694
- timeout: 1e4,
1695
- cwd
1696
- }
1697
- );
1698
- return stdout.trim().split("\n").filter((line) => line.length > 0);
1699
- } catch (error) {
1700
- if (error instanceof Error) {
1701
- console.error(
1702
- `Warning: Failed to list untracked files: ${error.message}`
1703
- );
1704
- } else {
1705
- console.error("Warning: Failed to list untracked files: unknown error");
1706
- }
1707
- return [];
1708
- }
1709
- }
1710
- function generateUntrackedDiffs(paths, repoRoot) {
1711
- return generateSyntheticDiffs(paths, repoRoot);
1712
- }
1872
+ // src/index.ts
1873
+ init_git();
1713
1874
 
1714
1875
  // src/forge-provider.ts
1715
1876
  var ForgeCliUnavailableError = class extends Error {
@@ -1755,9 +1916,14 @@ function parseForgeUrl(url) {
1755
1916
  return null;
1756
1917
  }
1757
1918
 
1919
+ // src/index.ts
1920
+ init_synthetic_diff();
1921
+
1758
1922
  // src/directory-scanner.ts
1759
1923
  var import_promises = require("fs/promises");
1760
- var import_path = require("path");
1924
+ var import_path2 = require("path");
1925
+ init_synthetic_diff();
1926
+ init_diff_parser();
1761
1927
 
1762
1928
  // src/ignore-filter.ts
1763
1929
  var import_ignore = __toESM(require("ignore"), 1);
@@ -1772,20 +1938,14 @@ async function scanDirectory(directoryPath, ignorePatterns = []) {
1772
1938
  try {
1773
1939
  const dirStat = await (0, import_promises.stat)(directoryPath);
1774
1940
  if (!dirStat.isDirectory()) {
1775
- console.error(
1776
- `Error: "${directoryPath}" is not a directory`
1777
- );
1941
+ console.error(`Error: "${directoryPath}" is not a directory`);
1778
1942
  return [];
1779
1943
  }
1780
1944
  } catch (error) {
1781
1945
  if (error instanceof Error) {
1782
- console.error(
1783
- `Error accessing directory "${directoryPath}": ${error.message}`
1784
- );
1946
+ console.error(`Error accessing directory "${directoryPath}": ${error.message}`);
1785
1947
  } else {
1786
- console.error(
1787
- `Error accessing directory "${directoryPath}": unknown error`
1788
- );
1948
+ console.error(`Error accessing directory "${directoryPath}": unknown error`);
1789
1949
  }
1790
1950
  return [];
1791
1951
  }
@@ -1800,19 +1960,15 @@ async function scanDirectory(directoryPath, ignorePatterns = []) {
1800
1960
  continue;
1801
1961
  }
1802
1962
  const parentDir = entry.parentPath ?? entry.path;
1803
- const fullPath = (0, import_path.join)(parentDir, entry.name);
1804
- const relativePath = (0, import_path.relative)(directoryPath, fullPath);
1963
+ const fullPath = (0, import_path2.join)(parentDir, entry.name);
1964
+ const relativePath = (0, import_path2.relative)(directoryPath, fullPath);
1805
1965
  filePaths.push(relativePath);
1806
1966
  }
1807
1967
  } catch (error) {
1808
1968
  if (error instanceof Error) {
1809
- console.error(
1810
- `Error reading directory "${directoryPath}": ${error.message}`
1811
- );
1969
+ console.error(`Error reading directory "${directoryPath}": ${error.message}`);
1812
1970
  } else {
1813
- console.error(
1814
- `Error reading directory "${directoryPath}": unknown error`
1815
- );
1971
+ console.error(`Error reading directory "${directoryPath}": unknown error`);
1816
1972
  }
1817
1973
  return [];
1818
1974
  }
@@ -1840,15 +1996,15 @@ async function scanFile(filePath) {
1840
1996
  }
1841
1997
  return [];
1842
1998
  }
1843
- const fileName = (0, import_path.basename)(filePath);
1844
- const rootDir = (0, import_path.dirname)(filePath);
1999
+ const fileName = (0, import_path2.basename)(filePath);
2000
+ const rootDir = (0, import_path2.dirname)(filePath);
1845
2001
  const diffText = generateSyntheticDiffs([fileName], rootDir);
1846
2002
  return parseDiff(diffText);
1847
2003
  }
1848
2004
 
1849
2005
  // src/config.ts
1850
2006
  var import_fs3 = require("fs");
1851
- var import_path2 = require("path");
2007
+ var import_path3 = require("path");
1852
2008
  var import_os = require("os");
1853
2009
  var import_yaml = require("yaml");
1854
2010
  var defaults = {
@@ -1924,37 +2080,28 @@ var defaults = {
1924
2080
  };
1925
2081
  function loadConfig() {
1926
2082
  let config = { ...defaults };
1927
- const userConfigPath = (0, import_path2.join)(
1928
- (0, import_os.homedir)(),
1929
- ".config",
1930
- "self-review",
1931
- "config.yaml"
1932
- );
2083
+ const userConfigPath = (0, import_path3.join)((0, import_os.homedir)(), ".config", "self-review", "config.yaml");
1933
2084
  if ((0, import_fs3.existsSync)(userConfigPath)) {
1934
2085
  try {
1935
2086
  const userConfig = loadYamlConfig(userConfigPath);
1936
2087
  config = mergeConfig(config, userConfig);
1937
2088
  } catch (error) {
1938
- console.error(
1939
- `Warning: Failed to load user config from ${userConfigPath}: ${error}`
1940
- );
2089
+ console.error(`Warning: Failed to load user config from ${userConfigPath}: ${error}`);
1941
2090
  }
1942
2091
  }
1943
- const projectConfigPath = (0, import_path2.join)(process.cwd(), ".self-review.yaml");
2092
+ const projectConfigPath = (0, import_path3.join)(process.cwd(), ".self-review.yaml");
1944
2093
  if ((0, import_fs3.existsSync)(projectConfigPath)) {
1945
2094
  try {
1946
2095
  const projectConfig = loadYamlConfig(projectConfigPath);
1947
2096
  config = mergeConfig(config, projectConfig);
1948
2097
  } catch (error) {
1949
- console.error(
1950
- `Warning: Failed to load project config from ${projectConfigPath}: ${error}`
1951
- );
2098
+ console.error(`Warning: Failed to load project config from ${projectConfigPath}: ${error}`);
1952
2099
  }
1953
2100
  }
1954
2101
  return config;
1955
2102
  }
1956
- function loadYamlConfig(path3) {
1957
- const content = (0, import_fs3.readFileSync)(path3, "utf-8");
2103
+ function loadYamlConfig(path4) {
2104
+ const content = (0, import_fs3.readFileSync)(path4, "utf-8");
1958
2105
  const raw = (0, import_yaml.parse)(content);
1959
2106
  if (raw === null || raw === void 0) {
1960
2107
  return {};
@@ -1967,18 +2114,14 @@ function loadYamlConfig(path3) {
1967
2114
  if (["light", "dark", "system"].includes(raw.theme)) {
1968
2115
  config.theme = raw.theme;
1969
2116
  } else {
1970
- console.error(
1971
- `Warning: Invalid theme value "${raw.theme}", using default`
1972
- );
2117
+ console.error(`Warning: Invalid theme value "${raw.theme}", using default`);
1973
2118
  }
1974
2119
  }
1975
2120
  if ("diff-view" in raw) {
1976
2121
  if (["split", "unified"].includes(raw["diff-view"])) {
1977
2122
  config.diffView = raw["diff-view"];
1978
2123
  } else {
1979
- console.error(
1980
- `Warning: Invalid diff-view value "${raw["diff-view"]}", using default`
1981
- );
2124
+ console.error(`Warning: Invalid diff-view value "${raw["diff-view"]}", using default`);
1982
2125
  }
1983
2126
  }
1984
2127
  if ("font-size" in raw && typeof raw["font-size"] === "number") {
@@ -1988,14 +2131,19 @@ function loadYamlConfig(path3) {
1988
2131
  config.outputFormat = raw["output-format"];
1989
2132
  }
1990
2133
  if ("ignore" in raw && Array.isArray(raw.ignore)) {
1991
- config.ignore = raw.ignore.filter(
1992
- (item) => typeof item === "string"
1993
- );
2134
+ config.ignore = raw.ignore.filter((item) => typeof item === "string");
1994
2135
  }
1995
2136
  if ("categories" in raw && Array.isArray(raw.categories)) {
1996
- config.categories = raw.categories.filter(
1997
- (cat) => cat !== null && typeof cat === "object" && typeof cat.name === "string" && typeof cat.description === "string" && typeof cat.color === "string"
2137
+ const usableCategories = raw.categories.filter(
2138
+ (cat) => cat !== null && typeof cat === "object" && typeof cat.name === "string" && cat.name !== "" && typeof cat.description === "string" && typeof cat.color === "string"
1998
2139
  );
2140
+ if (usableCategories.length > 0) {
2141
+ config.categories = usableCategories;
2142
+ } else {
2143
+ console.error(
2144
+ "Warning: Category configuration has no usable categories, using default categories"
2145
+ );
2146
+ }
1999
2147
  }
2000
2148
  if ("default-diff-args" in raw && typeof raw["default-diff-args"] === "string") {
2001
2149
  config.defaultDiffArgs = raw["default-diff-args"];
@@ -2034,7 +2182,7 @@ function mergeConfig(base, override) {
2034
2182
  // src/payload-sizing.ts
2035
2183
  var import_child_process2 = require("child_process");
2036
2184
  var import_util2 = require("util");
2037
- var execAsync2 = (0, import_util2.promisify)(import_child_process2.exec);
2185
+ var execFileAsync2 = (0, import_util2.promisify)(import_child_process2.execFile);
2038
2186
  function computePayloadStats(fileCount, totalLines, config) {
2039
2187
  const maxFiles = config.maxFiles;
2040
2188
  const maxTotalLines = config.maxTotalLines;
@@ -2059,7 +2207,7 @@ function countTotalLines(files) {
2059
2207
  }
2060
2208
  async function getGitDiffStats(args, repoRoot) {
2061
2209
  try {
2062
- const { stdout } = await execAsync2(`git diff --numstat ${args.join(" ")}`, {
2210
+ const { stdout } = await execFileAsync2("git", ["diff", "--numstat", ...args], {
2063
2211
  maxBuffer: 10 * 1024 * 1024,
2064
2212
  timeout: 15e3,
2065
2213
  cwd: repoRoot
@@ -2088,10 +2236,10 @@ async function getGitDiffStats(args, repoRoot) {
2088
2236
 
2089
2237
  // src/fs-utils.ts
2090
2238
  var import_fs4 = require("fs");
2091
- var import_path3 = require("path");
2239
+ var import_path4 = require("path");
2092
2240
  function checkWritability(filePath) {
2093
2241
  try {
2094
- const dir = (0, import_path3.dirname)(filePath);
2242
+ const dir = (0, import_path4.dirname)(filePath);
2095
2243
  (0, import_fs4.accessSync)(dir, import_fs4.constants.W_OK);
2096
2244
  return true;
2097
2245
  } catch {
@@ -2099,7 +2247,109 @@ function checkWritability(filePath) {
2099
2247
  }
2100
2248
  }
2101
2249
 
2102
- // src/file-type-utils.ts
2250
+ // src/apply-suggestion.ts
2251
+ var import_fs5 = require("fs");
2252
+ var import_path5 = require("path");
2253
+ function refuse(filePath, reason, detail) {
2254
+ return { status: "refused", filePath, reason, detail };
2255
+ }
2256
+ function errorCode(error) {
2257
+ return error?.code;
2258
+ }
2259
+ function splitLines(content) {
2260
+ if (content === "") return [];
2261
+ const lines = content.split("\n");
2262
+ if (lines[lines.length - 1] === "") lines.pop();
2263
+ return lines;
2264
+ }
2265
+ function isCrlfRegion(anchored) {
2266
+ return anchored.length > 0 && anchored.every((line) => line.endsWith("\r"));
2267
+ }
2268
+ function applySuggestion(request) {
2269
+ const { destinationRoot, filePath, lineRange, suggestion } = request;
2270
+ if (!lineRange) {
2271
+ return refuse(
2272
+ filePath,
2273
+ "no-anchor",
2274
+ "This suggestion is file-level, so there are no lines to replace."
2275
+ );
2276
+ }
2277
+ if (lineRange.side === "old") {
2278
+ return refuse(
2279
+ filePath,
2280
+ "old-side-anchor",
2281
+ "This suggestion is anchored to deleted lines, which are not in the working file."
2282
+ );
2283
+ }
2284
+ if (!(0, import_path5.isAbsolute)(destinationRoot)) {
2285
+ return refuse(
2286
+ filePath,
2287
+ "destination-not-absolute",
2288
+ "The destination directory must be an absolute path."
2289
+ );
2290
+ }
2291
+ const root = (0, import_path5.resolve)(destinationRoot);
2292
+ const absolutePath = (0, import_path5.resolve)(root, filePath);
2293
+ const rel = (0, import_path5.relative)(root, absolutePath);
2294
+ if ((0, import_path5.isAbsolute)(filePath) || rel === "" || rel === ".." || rel.startsWith(`..${import_path5.sep}`)) {
2295
+ return refuse(
2296
+ filePath,
2297
+ "path-escapes-destination",
2298
+ "The file path resolves outside the destination directory."
2299
+ );
2300
+ }
2301
+ let buffer;
2302
+ try {
2303
+ buffer = (0, import_fs5.readFileSync)(absolutePath);
2304
+ } catch (error) {
2305
+ const code = errorCode(error);
2306
+ if (code === "ENOENT" || code === "ENOTDIR") {
2307
+ return refuse(filePath, "file-missing", "The file is not in the destination directory.");
2308
+ }
2309
+ return refuse(
2310
+ filePath,
2311
+ "file-unreadable",
2312
+ `The file could not be read (${code ?? "unknown"}).`
2313
+ );
2314
+ }
2315
+ const content = buffer.toString("utf8");
2316
+ if (!Buffer.from(content, "utf8").equals(buffer)) {
2317
+ return refuse(filePath, "file-not-utf8", "The file is not valid UTF-8 text.");
2318
+ }
2319
+ const lines = splitLines(content);
2320
+ const { start, end } = lineRange;
2321
+ if (start < 1 || end < start || end > lines.length) {
2322
+ return refuse(
2323
+ filePath,
2324
+ "anchor-out-of-range",
2325
+ `Lines ${start}-${end} are outside this file, which has ${lines.length} line(s).`
2326
+ );
2327
+ }
2328
+ const anchored = lines.slice(start - 1, end);
2329
+ if (anchored.join("\n") !== suggestion.originalCode) {
2330
+ return refuse(
2331
+ filePath,
2332
+ "context-mismatch",
2333
+ `Lines ${start}-${end} no longer match the code this suggestion was written against.`
2334
+ );
2335
+ }
2336
+ const proposed = suggestion.proposedCode.split("\n");
2337
+ const replacement = isCrlfRegion(anchored) ? proposed.map((line) => line.endsWith("\r") ? line : `${line}\r`) : proposed;
2338
+ const updated = [...lines.slice(0, start - 1), ...replacement, ...lines.slice(end)];
2339
+ const output = updated.join("\n") + (content.endsWith("\n") ? "\n" : "");
2340
+ try {
2341
+ (0, import_fs5.writeFileSync)(absolutePath, output, "utf8");
2342
+ } catch (error) {
2343
+ return refuse(
2344
+ filePath,
2345
+ "write-failed",
2346
+ `The file could not be written (${errorCode(error) ?? "unknown"}).`
2347
+ );
2348
+ }
2349
+ return { status: "applied", filePath, absolutePath, replacedLines: anchored.length };
2350
+ }
2351
+
2352
+ // src/file-type-utils.ts
2103
2353
  var RASTER_IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([".jpg", ".jpeg", ".png", ".gif", ".webp", ".ico", ".bmp"]);
2104
2354
  var MARKDOWN_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".markdown"]);
2105
2355
  var HTML_EXTENSIONS = /* @__PURE__ */ new Set([".html", ".htm"]);
@@ -2203,11 +2453,7 @@ async function runGh(runCommand, args) {
2203
2453
  result = await runCommand(GH_CLI, args);
2204
2454
  } catch (error) {
2205
2455
  const detail = error instanceof Error ? error.message : String(error);
2206
- throw new ForgeCliUnavailableError(
2207
- "github",
2208
- GH_CLI,
2209
- `Failed to run the gh CLI: ${detail}`
2210
- );
2456
+ throw new ForgeCliUnavailableError("github", GH_CLI, `Failed to run the gh CLI: ${detail}`);
2211
2457
  }
2212
2458
  if (result.exitCode !== 0) {
2213
2459
  const detail = result.stderr.trim() || `exit code ${result.exitCode}`;
@@ -2286,11 +2532,7 @@ function createGitHubProvider(runCommand) {
2286
2532
  ]);
2287
2533
  const parsed = parseGhJson(stdout, "pr view");
2288
2534
  if (typeof parsed?.baseRefName !== "string" || parsed.baseRefName === "") {
2289
- throw new ForgeCliUnavailableError(
2290
- "github",
2291
- GH_CLI,
2292
- "gh pr view returned no baseRefName"
2293
- );
2535
+ throw new ForgeCliUnavailableError("github", GH_CLI, "gh pr view returned no baseRefName");
2294
2536
  }
2295
2537
  return parsed.baseRefName;
2296
2538
  },
@@ -2343,6 +2585,69 @@ function mapAnchorToLineRange(anchor) {
2343
2585
  function internalId(turn) {
2344
2586
  return `remote-${turn.remoteId}`;
2345
2587
  }
2588
+ var FENCE_OPEN = /^( {0,3})(`{3,}|~{3,})(.*)$/;
2589
+ function stripCr(line) {
2590
+ return line.endsWith("\r") ? line.slice(0, -1) : line;
2591
+ }
2592
+ function stripIndent(line, width) {
2593
+ let i = 0;
2594
+ while (i < width && line[i] === " ") i++;
2595
+ return line.slice(i);
2596
+ }
2597
+ function isClosingFence(line, marker) {
2598
+ const match = FENCE_OPEN.exec(line);
2599
+ return match !== null && match[2][0] === marker[0] && match[2].length >= marker.length && match[3].trim() === "";
2600
+ }
2601
+ function findSuggestionBlocks(body) {
2602
+ const lines = body.split("\n").map(stripCr);
2603
+ const blocks = [];
2604
+ let i = 0;
2605
+ while (i < lines.length) {
2606
+ const open = FENCE_OPEN.exec(lines[i]);
2607
+ if (!open) {
2608
+ i++;
2609
+ continue;
2610
+ }
2611
+ const [, indent, marker, info] = open;
2612
+ if (marker[0] === "`" && info.includes("`")) {
2613
+ i++;
2614
+ continue;
2615
+ }
2616
+ const content = [];
2617
+ let j = i + 1;
2618
+ for (; j < lines.length && !isClosingFence(lines[j], marker); j++) {
2619
+ content.push(stripIndent(lines[j], indent.length));
2620
+ }
2621
+ if (info.trim().toLowerCase() === "suggestion") {
2622
+ blocks.push(content.join("\n"));
2623
+ }
2624
+ i = j + 1;
2625
+ }
2626
+ return blocks;
2627
+ }
2628
+ function readAnchoredLines(diffFiles, filePath, range) {
2629
+ const sidePath = (file2) => range.side === "old" ? file2.oldPath : file2.newPath;
2630
+ const file = diffFiles.find((f) => sidePath(f) === filePath) ?? diffFiles.find((f) => f.oldPath === filePath || f.newPath === filePath);
2631
+ if (!file) return null;
2632
+ const found = [];
2633
+ for (const hunk of file.hunks) {
2634
+ for (const line of hunk.lines) {
2635
+ const number = range.side === "old" ? line.oldLineNumber : line.newLineNumber;
2636
+ if (number !== null && number >= range.start && number <= range.end) {
2637
+ found.push(line.content);
2638
+ }
2639
+ }
2640
+ }
2641
+ return found.length === range.end - range.start + 1 ? found.join("\n") : null;
2642
+ }
2643
+ function extractSuggestion(body, filePath, range, diffFiles) {
2644
+ if (!range) return null;
2645
+ const blocks = findSuggestionBlocks(body);
2646
+ if (blocks.length !== 1) return null;
2647
+ const originalCode = readAnchoredLines(diffFiles, filePath, range);
2648
+ if (originalCode === null) return null;
2649
+ return { originalCode, proposedCode: blocks[0] };
2650
+ }
2346
2651
  function mapReply(turn) {
2347
2652
  return {
2348
2653
  id: internalId(turn),
@@ -2351,15 +2656,17 @@ function mapReply(turn) {
2351
2656
  remoteId: turn.remoteId
2352
2657
  };
2353
2658
  }
2354
- function mapThreadsToReviewComments(threads) {
2659
+ function mapThreadsToReviewComments(threads, diffFiles = []) {
2355
2660
  return threads.map((thread) => {
2661
+ const filePath = thread.anchor?.filePath ?? REVIEW_LEVEL_FILE_PATH;
2662
+ const lineRange = thread.anchor ? mapAnchorToLineRange(thread.anchor) : null;
2356
2663
  const comment = {
2357
2664
  id: internalId(thread.root),
2358
- filePath: thread.anchor?.filePath ?? REVIEW_LEVEL_FILE_PATH,
2359
- lineRange: thread.anchor ? mapAnchorToLineRange(thread.anchor) : null,
2665
+ filePath,
2666
+ lineRange,
2360
2667
  body: thread.root.body,
2361
2668
  category: "",
2362
- suggestion: null,
2669
+ suggestion: extractSuggestion(thread.root.body, filePath, lineRange, diffFiles),
2363
2670
  author: thread.root.author,
2364
2671
  remoteId: thread.root.remoteId
2365
2672
  };
@@ -2516,27 +2823,23 @@ var import_child_process3 = require("child_process");
2516
2823
  var fs2 = __toESM(require("fs"), 1);
2517
2824
  var os = __toESM(require("os"), 1);
2518
2825
  var path2 = __toESM(require("path"), 1);
2826
+ init_git();
2519
2827
  var LOCAL_BASE_REF = "refs/self-review/base";
2520
2828
  var LOCAL_HEAD_REF = "refs/self-review/head";
2521
2829
  var AUTH_HINT = "Hint: if this repository is private or requires authentication, run `gh auth setup-git` (GitHub) or `glab auth git-credential` (GitLab) to wire your CLI credentials into git.";
2522
- var defaultGitRunner = (command, args) => new Promise((resolve, reject) => {
2523
- (0, import_child_process3.execFile)(
2524
- command,
2525
- args,
2526
- { maxBuffer: 50 * 1024 * 1024 },
2527
- (error, stdout, stderr) => {
2528
- const spawnCode = error?.code;
2529
- if (error && typeof spawnCode === "string") {
2530
- reject(error);
2531
- return;
2532
- }
2533
- resolve({
2534
- stdout: stdout ?? "",
2535
- stderr: stderr ?? "",
2536
- exitCode: error ? typeof spawnCode === "number" ? spawnCode : 1 : 0
2537
- });
2830
+ var defaultGitRunner = (command, args) => new Promise((resolve7, reject) => {
2831
+ (0, import_child_process3.execFile)(command, args, { maxBuffer: 50 * 1024 * 1024 }, (error, stdout, stderr) => {
2832
+ const spawnCode = error?.code;
2833
+ if (error && typeof spawnCode === "string") {
2834
+ reject(error);
2835
+ return;
2538
2836
  }
2539
- );
2837
+ resolve7({
2838
+ stdout: stdout ?? "",
2839
+ stderr: stderr ?? "",
2840
+ exitCode: error ? typeof spawnCode === "number" ? spawnCode : 1 : 0
2841
+ });
2842
+ });
2540
2843
  });
2541
2844
  function headRefFor(url) {
2542
2845
  return url.forge === "github" ? `refs/pull/${url.number}/head` : `refs/merge-requests/${url.number}/head`;
@@ -2605,7 +2908,7 @@ async function detectExistingClone(url, cwd, runner = defaultGitRunner) {
2605
2908
  if (toplevel.exitCode !== 0) {
2606
2909
  return null;
2607
2910
  }
2608
- const repoPath = toplevel.stdout.trim();
2911
+ const repoPath = stripTrailingNewline(toplevel.stdout);
2609
2912
  const remotes = await runner("git", ["-C", repoPath, "remote", "-v"]);
2610
2913
  if (remotes.exitCode !== 0) {
2611
2914
  return null;
@@ -2614,9 +2917,7 @@ async function detectExistingClone(url, cwd, runner = defaultGitRunner) {
2614
2917
  return remoteName === null ? null : { repoPath, remoteName };
2615
2918
  }
2616
2919
  async function materializeIntoExistingClone(runner, url, baseBranch, repoPath, remoteName) {
2617
- console.error(
2618
- `self-review: reusing existing clone at ${repoPath} (remote "${remoteName}")`
2619
- );
2920
+ console.error(`self-review: reusing existing clone at ${repoPath} (remote "${remoteName}")`);
2620
2921
  const fetch = await runner("git", [
2621
2922
  "-C",
2622
2923
  repoPath,
@@ -2646,16 +2947,9 @@ async function materializeIntoTempClone(runner, url, baseBranch) {
2646
2947
  fs2.rmSync(tempDir, { recursive: true, force: true });
2647
2948
  };
2648
2949
  try {
2649
- console.error(
2650
- `self-review: created temporary blobless clone at ${tempDir}`
2651
- );
2950
+ console.error(`self-review: created temporary blobless clone at ${tempDir}`);
2652
2951
  const cloneUrl = cloneUrlFor(url);
2653
- const clone = await runner("git", [
2654
- "clone",
2655
- "--filter=blob:none",
2656
- cloneUrl,
2657
- tempDir
2658
- ]);
2952
+ const clone = await runner("git", ["clone", "--filter=blob:none", cloneUrl, tempDir]);
2659
2953
  if (clone.exitCode !== 0) {
2660
2954
  throw gitFailure(`clone of ${cloneUrl}`, clone, true);
2661
2955
  }
@@ -2711,27 +3005,868 @@ async function resolveRemoteDefaultBranch(url, runner = defaultGitRunner, existi
2711
3005
  }
2712
3006
  return match[1];
2713
3007
  }
3008
+
3009
+ // src/review-handlers.ts
3010
+ var fs3 = __toESM(require("fs"), 1);
3011
+ var import_path7 = __toESM(require("path"), 1);
3012
+
3013
+ // src/git-diff-args.ts
3014
+ var import_fs6 = require("fs");
3015
+ var import_path6 = require("path");
3016
+ var OPTIONS_WITH_SEPARATE_VALUES = /* @__PURE__ */ new Set([
3017
+ "--output",
3018
+ "--src-prefix",
3019
+ "--dst-prefix",
3020
+ "--line-prefix",
3021
+ "--output-indicator-new",
3022
+ "--output-indicator-old",
3023
+ "--output-indicator-context",
3024
+ "--inter-hunk-context",
3025
+ "--stat-width",
3026
+ "--stat-name-width",
3027
+ "--stat-graph-width",
3028
+ "--stat-count",
3029
+ "--diff-algorithm",
3030
+ "--word-diff-regex",
3031
+ "--ignore-matching-lines",
3032
+ "--anchored",
3033
+ "--diff-filter",
3034
+ "--find-object",
3035
+ "--rotate-to",
3036
+ "--skip-to",
3037
+ "--ws-error-highlight",
3038
+ "--color-moved-ws"
3039
+ ]);
3040
+ function consumesNextArgument(arg) {
3041
+ if (arg.startsWith("--")) return OPTIONS_WITH_SEPARATE_VALUES.has(arg);
3042
+ if (!arg.startsWith("-")) return false;
3043
+ for (let i = 1; i < arg.length; i++) {
3044
+ if ("SGOIl".includes(arg[i])) return i === arg.length - 1;
3045
+ if ("UBMC".includes(arg[i])) return false;
3046
+ }
3047
+ return false;
3048
+ }
3049
+ function classifyGitDiffArgs(args) {
3050
+ const positionalIndices = [];
3051
+ let hasSeparator = false;
3052
+ for (let i = 0; i < args.length; i++) {
3053
+ const arg = args[i];
3054
+ if (!hasSeparator) {
3055
+ if (arg === "--") {
3056
+ hasSeparator = true;
3057
+ continue;
3058
+ }
3059
+ if (consumesNextArgument(arg)) {
3060
+ i++;
3061
+ continue;
3062
+ }
3063
+ if (arg.startsWith("-")) continue;
3064
+ }
3065
+ positionalIndices.push(i);
3066
+ }
3067
+ return { positionalIndices, hasSeparator };
3068
+ }
3069
+ function normalizeGitDiffArgs(args, cwd = process.cwd()) {
3070
+ const { positionalIndices, hasSeparator } = classifyGitDiffArgs(args);
3071
+ if (hasSeparator) return args;
3072
+ for (const i of positionalIndices) {
3073
+ const arg = args[i];
3074
+ if ((0, import_fs6.existsSync)((0, import_path6.resolve)(cwd, arg))) {
3075
+ return [...args.slice(0, i), "--", ...args.slice(i)];
3076
+ }
3077
+ }
3078
+ return args;
3079
+ }
3080
+ function tokenizeGitDiffArgs(value) {
3081
+ const args = [];
3082
+ let current = "";
3083
+ let started = false;
3084
+ let quote = null;
3085
+ for (let i = 0; i < value.length; i++) {
3086
+ const char = value[i];
3087
+ if (quote === "'") {
3088
+ if (char === "'") quote = null;
3089
+ else current += char;
3090
+ continue;
3091
+ }
3092
+ if (quote === '"') {
3093
+ if (char === "\\" && (value[i + 1] === '"' || value[i + 1] === "\\")) {
3094
+ current += value[++i];
3095
+ } else if (char === '"') {
3096
+ quote = null;
3097
+ } else {
3098
+ current += char;
3099
+ }
3100
+ continue;
3101
+ }
3102
+ if (char === "'" || char === '"') {
3103
+ quote = char;
3104
+ started = true;
3105
+ continue;
3106
+ }
3107
+ if (char === "\\" && i + 1 < value.length) {
3108
+ current += value[++i];
3109
+ started = true;
3110
+ continue;
3111
+ }
3112
+ if (/\s/.test(char)) {
3113
+ if (started) {
3114
+ args.push(current);
3115
+ current = "";
3116
+ started = false;
3117
+ }
3118
+ continue;
3119
+ }
3120
+ current += char;
3121
+ started = true;
3122
+ }
3123
+ if (started) args.push(current);
3124
+ return args;
3125
+ }
3126
+ function needsQuoting2(arg) {
3127
+ return arg.length === 0 || /[\s'"\\]/.test(arg);
3128
+ }
3129
+ function formatGitDiffArgs(args) {
3130
+ return args.map((arg) => needsQuoting2(arg) ? `'${arg.replace(/'/g, "'\\''")}'` : arg).join(" ");
3131
+ }
3132
+
3133
+ // src/review-handlers.ts
3134
+ function createReviewSession() {
3135
+ return {
3136
+ reviewState: null,
3137
+ diffData: null,
3138
+ guideData: null,
3139
+ config: null,
3140
+ outputPathInfo: null,
3141
+ resumeComments: [],
3142
+ resumeViewedFiles: [],
3143
+ resumeRemoteDrift: null,
3144
+ applyDestinationRoot: null
3145
+ };
3146
+ }
3147
+ function preparePayload(payload) {
3148
+ if (payload.isLargePayload) {
3149
+ return {
3150
+ ...payload,
3151
+ files: payload.files.map((f) => ({ ...f, hunks: [], contentLoaded: false }))
3152
+ };
3153
+ }
3154
+ return {
3155
+ ...payload,
3156
+ files: payload.files.map((f) => ({ ...f, contentLoaded: true }))
3157
+ };
3158
+ }
3159
+ function getDiffLoad(session) {
3160
+ if (!session.diffData) {
3161
+ return null;
3162
+ }
3163
+ return {
3164
+ diff: preparePayload(session.diffData),
3165
+ guide: session.guideData
3166
+ };
3167
+ }
3168
+ function resolveSourceBaseDir(session) {
3169
+ const source = session.diffData?.source;
3170
+ if (!source) return null;
3171
+ if (source.type === "git") return source.repository;
3172
+ if (source.type === "directory") return source.sourcePath;
3173
+ if (source.type === "file") return import_path7.default.dirname(source.sourcePath);
3174
+ return null;
3175
+ }
3176
+ async function loadImage(session, filePath) {
3177
+ const MIME_MAP = {
3178
+ ".jpg": "image/jpeg",
3179
+ ".jpeg": "image/jpeg",
3180
+ ".png": "image/png",
3181
+ ".gif": "image/gif",
3182
+ ".webp": "image/webp",
3183
+ ".ico": "image/x-icon",
3184
+ ".bmp": "image/bmp",
3185
+ ".svg": "image/svg+xml"
3186
+ };
3187
+ const MAX_SIZE = 10 * 1024 * 1024;
3188
+ const baseDir = resolveSourceBaseDir(session) ?? process.cwd();
3189
+ const resolved = import_path7.default.isAbsolute(filePath) ? filePath : import_path7.default.resolve(baseDir, filePath);
3190
+ const ext = import_path7.default.extname(filePath).toLowerCase();
3191
+ const mimeType = MIME_MAP[ext] ?? "application/octet-stream";
3192
+ const remote = session.diffData?.remote;
3193
+ if (remote && session.diffData?.source.type === "git") {
3194
+ try {
3195
+ const { readGitBlobAsync: readGitBlobAsync2 } = await Promise.resolve().then(() => (init_git(), git_exports));
3196
+ const data = await readGitBlobAsync2(
3197
+ session.diffData.source.repository,
3198
+ `${remote.remoteHeadSha}:${filePath}`
3199
+ );
3200
+ if (data.length > MAX_SIZE) {
3201
+ return { error: "File too large to preview (>10 MB)" };
3202
+ }
3203
+ return { dataUri: `data:${mimeType};base64,${data.toString("base64")}` };
3204
+ } catch {
3205
+ return {
3206
+ error: "Image preview unavailable \u2014 blob not found at the reviewed commit."
3207
+ };
3208
+ }
3209
+ }
3210
+ try {
3211
+ const stat2 = await fs3.promises.stat(resolved);
3212
+ if (stat2.size > MAX_SIZE) {
3213
+ return { error: "File too large to preview (>10 MB)" };
3214
+ }
3215
+ const data = await fs3.promises.readFile(resolved);
3216
+ return { dataUri: `data:${mimeType};base64,${data.toString("base64")}` };
3217
+ } catch {
3218
+ return { error: "Image preview unavailable \u2014 file not found on disk." };
3219
+ }
3220
+ }
3221
+ function getFileHunks(session, filePath) {
3222
+ if (!session.diffData) return null;
3223
+ const file = session.diffData.files.find((f) => (f.newPath || f.oldPath) === filePath);
3224
+ if (!file) return null;
3225
+ return file.hunks;
3226
+ }
3227
+ function getConfigLoad(session) {
3228
+ if (!session.config) {
3229
+ return null;
3230
+ }
3231
+ return { config: session.config, outputPathInfo: session.outputPathInfo };
3232
+ }
3233
+ function submitReviewState(session, state) {
3234
+ console.error(
3235
+ "[review] Review state submitted:",
3236
+ JSON.stringify({
3237
+ timestamp: state.timestamp,
3238
+ source: state.source,
3239
+ fileCount: state.files.length
3240
+ })
3241
+ );
3242
+ session.reviewState = state;
3243
+ }
3244
+ function takeReviewState(session) {
3245
+ const state = session.reviewState;
3246
+ session.reviewState = null;
3247
+ return state;
3248
+ }
3249
+ function isTemporaryCloneSession(session) {
3250
+ return session.diffData?.remote?.temporaryClone === true;
3251
+ }
3252
+ function resolveApplyDestination(session) {
3253
+ if (isTemporaryCloneSession(session)) {
3254
+ return session.applyDestinationRoot;
3255
+ }
3256
+ return resolveSourceBaseDir(session);
3257
+ }
3258
+ function applySuggestionForSession(session, request) {
3259
+ const destinationRoot = resolveApplyDestination(session);
3260
+ if (!destinationRoot) {
3261
+ const temporary = isTemporaryCloneSession(session);
3262
+ return {
3263
+ status: "refused",
3264
+ filePath: request.filePath,
3265
+ reason: temporary ? "destination-required" : "no-destination",
3266
+ detail: temporary ? "This pull request was cloned into a temporary directory that is deleted when the review ends. Choose a destination directory to apply into." : "This review has no working directory to write into."
3267
+ };
3268
+ }
3269
+ const result = applySuggestion({
3270
+ destinationRoot,
3271
+ filePath: request.filePath,
3272
+ lineRange: request.lineRange,
3273
+ suggestion: request.suggestion
3274
+ });
3275
+ console.error(
3276
+ `[suggestion:apply] ${request.filePath}: ${result.status === "applied" ? "applied" : `refused (${result.reason})`}`
3277
+ );
3278
+ if (result.status === "applied") {
3279
+ return {
3280
+ status: "applied",
3281
+ filePath: result.filePath,
3282
+ replacedLines: result.replacedLines
3283
+ };
3284
+ }
3285
+ return {
3286
+ status: "refused",
3287
+ filePath: result.filePath,
3288
+ reason: result.reason,
3289
+ detail: result.detail
3290
+ };
3291
+ }
3292
+ async function readAttachment(filePath) {
3293
+ try {
3294
+ const buffer = await fs3.promises.readFile(filePath);
3295
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
3296
+ } catch {
3297
+ console.error(`[attachment:read] Failed to read file: ${filePath}`);
3298
+ return null;
3299
+ }
3300
+ }
3301
+ function getResumeLoad(session) {
3302
+ if (session.resumeComments.length > 0 || session.resumeViewedFiles.length > 0 || session.resumeRemoteDrift !== null) {
3303
+ const payload = {
3304
+ comments: session.resumeComments,
3305
+ viewedFiles: session.resumeViewedFiles
3306
+ };
3307
+ if (session.resumeRemoteDrift !== null) {
3308
+ payload.remoteDrift = session.resumeRemoteDrift;
3309
+ }
3310
+ return payload;
3311
+ }
3312
+ return null;
3313
+ }
3314
+ async function expandContext(session, request) {
3315
+ const diffData = session.diffData;
3316
+ if (!diffData || diffData.source.type !== "git") {
3317
+ return null;
3318
+ }
3319
+ try {
3320
+ const { runGitDiffAsync: runGitDiffAsync2 } = await Promise.resolve().then(() => (init_git(), git_exports));
3321
+ const { parseDiff: parseDiff2 } = await Promise.resolve().then(() => (init_diff_parser(), diff_parser_exports));
3322
+ const source = diffData.source;
3323
+ const originalArgs = tokenizeGitDiffArgs(source.gitDiffArgs);
3324
+ const filteredArgs = [];
3325
+ for (let i = 0; i < originalArgs.length; i++) {
3326
+ const arg = originalArgs[i];
3327
+ if (arg.match(/^-U\d+$/) || arg.match(/^--unified=\d+$/)) {
3328
+ continue;
3329
+ }
3330
+ if (arg === "-U" || arg === "--unified") {
3331
+ i++;
3332
+ continue;
3333
+ }
3334
+ if (arg === "--") {
3335
+ break;
3336
+ }
3337
+ filteredArgs.push(arg);
3338
+ }
3339
+ const expandArgs = [...filteredArgs, `-U${request.contextLines}`, "--", request.filePath];
3340
+ const rawDiff = await runGitDiffAsync2(expandArgs, source.repository);
3341
+ const parsedFiles = parseDiff2(rawDiff);
3342
+ if (parsedFiles.length === 0) {
3343
+ return null;
3344
+ }
3345
+ const expandedFile = parsedFiles[0];
3346
+ let totalLines = 0;
3347
+ try {
3348
+ const content = await fs3.promises.readFile(
3349
+ import_path7.default.resolve(source.repository, request.filePath),
3350
+ "utf-8"
3351
+ );
3352
+ totalLines = content.split("\n").length;
3353
+ if (content.endsWith("\n")) totalLines--;
3354
+ } catch {
3355
+ }
3356
+ session.diffData = {
3357
+ ...diffData,
3358
+ files: diffData.files.map((f) => {
3359
+ const fPath = f.newPath || f.oldPath;
3360
+ if (fPath === request.filePath) {
3361
+ return { ...f, hunks: expandedFile.hunks };
3362
+ }
3363
+ return f;
3364
+ })
3365
+ };
3366
+ return { hunks: expandedFile.hunks, totalLines };
3367
+ } catch (error) {
3368
+ console.error(`[review] Failed to expand context for ${request.filePath}:`, error);
3369
+ return null;
3370
+ }
3371
+ }
3372
+ async function prepareDirectoryReview(session, directoryPath) {
3373
+ console.error("[review] Starting directory review for:", directoryPath);
3374
+ let isFile = false;
3375
+ try {
3376
+ isFile = fs3.statSync(directoryPath).isFile();
3377
+ } catch {
3378
+ }
3379
+ let payload;
3380
+ if (isFile) {
3381
+ const files = await scanFile(directoryPath);
3382
+ payload = {
3383
+ files,
3384
+ source: { type: "file", sourcePath: directoryPath }
3385
+ };
3386
+ } else {
3387
+ const ignorePatterns = session.config?.ignore ?? [];
3388
+ const files = await scanDirectory(directoryPath, ignorePatterns);
3389
+ payload = {
3390
+ files,
3391
+ source: { type: "directory", sourcePath: directoryPath }
3392
+ };
3393
+ }
3394
+ if (!session.config) {
3395
+ return { payload, stats: null, exceedsThresholds: false };
3396
+ }
3397
+ const stats = computePayloadStats(
3398
+ payload.files.length,
3399
+ countTotalLines(payload.files),
3400
+ session.config
3401
+ );
3402
+ return { payload, stats, exceedsThresholds: stats.exceedsAny };
3403
+ }
3404
+ function commitReviewStart(session, payload) {
3405
+ session.diffData = payload;
3406
+ return preparePayload(payload);
3407
+ }
3408
+
3409
+ // src/startup-mode.ts
3410
+ var import_fs7 = require("fs");
3411
+ var import_child_process4 = require("child_process");
3412
+ var import_path8 = require("path");
3413
+ function isInGitRepo() {
3414
+ try {
3415
+ (0, import_child_process4.execSync)("git rev-parse --git-dir", { stdio: "ignore" });
3416
+ return true;
3417
+ } catch {
3418
+ return false;
3419
+ }
3420
+ }
3421
+ function isGitTracked(filePath) {
3422
+ try {
3423
+ (0, import_child_process4.execFileSync)("git", ["ls-files", "--error-unmatch", "--", filePath], {
3424
+ stdio: "ignore"
3425
+ });
3426
+ return true;
3427
+ } catch {
3428
+ return false;
3429
+ }
3430
+ }
3431
+ function determineMode(gitDiffArgs) {
3432
+ const { positionalIndices } = classifyGitDiffArgs(gitDiffArgs);
3433
+ const firstPositional = gitDiffArgs[positionalIndices[0]];
3434
+ if (firstPositional) {
3435
+ const candidate = (0, import_path8.resolve)(process.cwd(), firstPositional);
3436
+ try {
3437
+ if ((0, import_fs7.existsSync)(candidate) && (0, import_fs7.statSync)(candidate).isFile()) {
3438
+ if (isInGitRepo()) {
3439
+ return isGitTracked(firstPositional) ? "git" : "file";
3440
+ }
3441
+ return "file";
3442
+ }
3443
+ } catch {
3444
+ }
3445
+ }
3446
+ if (isInGitRepo()) {
3447
+ return "git";
3448
+ }
3449
+ if (firstPositional) {
3450
+ const candidate = (0, import_path8.resolve)(process.cwd(), firstPositional);
3451
+ try {
3452
+ if ((0, import_fs7.existsSync)(candidate) && (0, import_fs7.statSync)(candidate).isDirectory()) {
3453
+ return "directory";
3454
+ }
3455
+ } catch {
3456
+ }
3457
+ }
3458
+ return "welcome";
3459
+ }
3460
+
3461
+ // src/guide-loader.ts
3462
+ var import_promises2 = require("fs/promises");
3463
+ var import_path9 = require("path");
3464
+ function deriveGuidePath(outputPath) {
3465
+ const ext = (0, import_path9.extname)(outputPath);
3466
+ const base = ext ? outputPath.slice(0, -ext.length) : outputPath;
3467
+ return `${base}.guide.xml`;
3468
+ }
3469
+ function resolveGuidePath(outputPath, config) {
3470
+ if (config.guideFile) {
3471
+ return (0, import_path9.resolve)(process.cwd(), config.guideFile);
3472
+ }
3473
+ return deriveGuidePath(outputPath);
3474
+ }
3475
+ async function loadGuide(outputPath, config, diffFilePaths) {
3476
+ let guidePath;
3477
+ try {
3478
+ guidePath = resolveGuidePath(outputPath, config);
3479
+ } catch {
3480
+ return null;
3481
+ }
3482
+ try {
3483
+ let content;
3484
+ try {
3485
+ content = await (0, import_promises2.readFile)(guidePath, "utf-8");
3486
+ } catch (error) {
3487
+ const code = error.code;
3488
+ if (code === "ENOENT") {
3489
+ return null;
3490
+ }
3491
+ console.error(
3492
+ `[guide] Ignoring guide at ${guidePath}: unreadable (${code ?? "unknown error"})`
3493
+ );
3494
+ return null;
3495
+ }
3496
+ const result = await parseGuideXml(content);
3497
+ if (result.ok === false) {
3498
+ console.error(`[guide] Ignoring guide at ${guidePath}: invalid (${result.reason})`);
3499
+ return null;
3500
+ }
3501
+ const payload = {
3502
+ groups: reconcileGuide(result.guide, diffFilePaths)
3503
+ };
3504
+ if (result.guide.overview !== void 0) {
3505
+ payload.overview = result.guide.overview;
3506
+ }
3507
+ return payload;
3508
+ } catch (error) {
3509
+ const message = error instanceof Error ? error.message : String(error);
3510
+ console.error(`[guide] Ignoring guide at ${guidePath}: invalid (${message})`);
3511
+ return null;
3512
+ }
3513
+ }
3514
+
3515
+ // src/git-diff-loader.ts
3516
+ init_git();
3517
+ init_diff_parser();
3518
+ async function loadGitDiffWithUntracked(gitDiffArgs, cwd, options = {}) {
3519
+ const { includeUntracked = true } = options;
3520
+ const repository = await getRepoRootAsync(cwd);
3521
+ const rawDiff = await runGitDiffAsync(gitDiffArgs, cwd);
3522
+ const files = parseDiff(rawDiff);
3523
+ if (!includeUntracked) {
3524
+ return { files, repository };
3525
+ }
3526
+ const untrackedPaths = await getUntrackedFilesAsync(repository);
3527
+ let allFiles = files;
3528
+ if (untrackedPaths.length > 0) {
3529
+ const untrackedDiffStr = generateUntrackedDiffs(untrackedPaths, repository);
3530
+ if (untrackedDiffStr.length > 0) {
3531
+ const untrackedFiles = parseDiff(untrackedDiffStr);
3532
+ for (const file of untrackedFiles) {
3533
+ file.isUntracked = true;
3534
+ }
3535
+ allFiles = [...files, ...untrackedFiles];
3536
+ }
3537
+ }
3538
+ return { files: allFiles, repository };
3539
+ }
3540
+
3541
+ // src/staged-untracked.ts
3542
+ function applyStagedUntrackedDefault(config, gitDiffArgs) {
3543
+ const stagedMode = gitDiffArgs.includes("--staged") || gitDiffArgs.includes("--cached");
3544
+ if (!stagedMode) return config;
3545
+ const userExplicitOptIn = config.showUntrackedExplicit && config.showUntracked;
3546
+ if (userExplicitOptIn) return config;
3547
+ return { ...config, showUntracked: false };
3548
+ }
3549
+
3550
+ // src/remote-mode.ts
3551
+ function defaultCreateProvider(forge, runner) {
3552
+ return forge === "github" ? createGitHubProvider(runner) : createGitLabProvider(runner);
3553
+ }
3554
+ var defaultDeps = {
3555
+ createProvider: defaultCreateProvider,
3556
+ detectExistingClone,
3557
+ materialize,
3558
+ resolveRemoteDefaultBranch,
3559
+ runner: defaultGitRunner,
3560
+ loadDiff: (gitDiffArgs, cwd) => (
3561
+ // A base...head diff of a remote PR/MR must never pick up local
3562
+ // untracked files (an existing clone may have unrelated ones).
3563
+ loadGitDiffWithUntracked(gitDiffArgs, cwd, { includeUntracked: false })
3564
+ )
3565
+ };
3566
+ async function startRemoteSession(url, cwd, deps = {}) {
3567
+ const d = { ...defaultDeps, ...deps };
3568
+ const forgeUrl = parseForgeUrl(url);
3569
+ if (!forgeUrl) {
3570
+ throw new Error(`Not a recognized pull-request or merge-request URL: ${url}`);
3571
+ }
3572
+ const provider = d.createProvider(forgeUrl.forge, d.runner);
3573
+ let cliAvailable = true;
3574
+ let baseBranch;
3575
+ let existingClone;
3576
+ try {
3577
+ baseBranch = await provider.fetchBaseBranch(forgeUrl);
3578
+ } catch (error) {
3579
+ if (!(error instanceof ForgeCliUnavailableError)) {
3580
+ throw error;
3581
+ }
3582
+ cliAvailable = false;
3583
+ console.error(
3584
+ `[remote] Forge CLI unavailable (${error.cli}): ${error.message} \u2014 falling back to the remote default branch via git.`
3585
+ );
3586
+ existingClone = await d.detectExistingClone(forgeUrl, cwd, d.runner);
3587
+ baseBranch = await d.resolveRemoteDefaultBranch(forgeUrl, d.runner, existingClone);
3588
+ }
3589
+ const materialized = await d.materialize(forgeUrl, baseBranch, cwd, d.runner, existingClone);
3590
+ let fetchedThreads = [];
3591
+ let threadSyncAvailable = false;
3592
+ if (cliAvailable) {
3593
+ try {
3594
+ fetchedThreads = await provider.fetchThreads(forgeUrl);
3595
+ threadSyncAvailable = true;
3596
+ } catch (error) {
3597
+ const message = error instanceof Error ? error.message : String(error);
3598
+ console.error(
3599
+ `[remote] thread sync unavailable \u2014 continuing without forge threads: ${message}`
3600
+ );
3601
+ }
3602
+ } else {
3603
+ console.error(
3604
+ "[remote] thread sync unavailable \u2014 forge CLI missing, continuing without forge threads."
3605
+ );
3606
+ }
3607
+ return {
3608
+ forgeUrl,
3609
+ repoPath: materialized.repoPath,
3610
+ gitDiffArgs: [`${materialized.baseSha}...${materialized.headSha}`],
3611
+ mode: materialized.mode,
3612
+ cleanup: materialized.cleanup,
3613
+ remote: {
3614
+ remoteUrl: url,
3615
+ remoteBaseSha: materialized.baseSha,
3616
+ remoteHeadSha: materialized.headSha,
3617
+ remoteForge: forgeUrl.forge,
3618
+ threadSyncAvailable,
3619
+ // A temporary clone is deleted on exit, so nothing may be written
3620
+ // into it; the front end needs the fact, not the path.
3621
+ temporaryClone: materialized.mode === "temp-clone"
3622
+ },
3623
+ fetchedComments: mapThreadsToReviewComments(fetchedThreads),
3624
+ fetchedThreads
3625
+ };
3626
+ }
3627
+ async function bootstrapRemoteDiff(url, cwd, ignorePatterns, deps = {}) {
3628
+ const d = { ...defaultDeps, ...deps };
3629
+ const started = await startRemoteSession(url, cwd, d);
3630
+ let files;
3631
+ let repository;
3632
+ try {
3633
+ ({ files, repository } = await d.loadDiff(started.gitDiffArgs, started.repoPath));
3634
+ } catch (error) {
3635
+ started.cleanup();
3636
+ throw error;
3637
+ }
3638
+ const shouldKeep = createIgnoreFilter(ignorePatterns);
3639
+ const filteredFiles = files.filter((f) => shouldKeep(f.newPath || f.oldPath));
3640
+ const session = {
3641
+ ...started,
3642
+ fetchedComments: mapThreadsToReviewComments(started.fetchedThreads, filteredFiles)
3643
+ };
3644
+ return {
3645
+ session,
3646
+ payload: {
3647
+ files: filteredFiles,
3648
+ source: {
3649
+ type: "git",
3650
+ // Same renderer the git-mode path uses, so expand-context can
3651
+ // tokenize this string back into the exact argv.
3652
+ gitDiffArgs: formatGitDiffArgs(session.gitDiffArgs),
3653
+ repository
3654
+ },
3655
+ remote: session.remote
3656
+ }
3657
+ };
3658
+ }
3659
+ function mergeRemoteThreads(resumed, fetched) {
3660
+ const resumedRemoteIds = new Set(
3661
+ resumed.map((c) => c.remoteId).filter((id) => id !== void 0)
3662
+ );
3663
+ return [
3664
+ ...resumed,
3665
+ ...fetched.filter((c) => c.remoteId === void 0 || !resumedRemoteIds.has(c.remoteId))
3666
+ ];
3667
+ }
3668
+ function applyRemoteProvenance(state, remote) {
3669
+ return {
3670
+ ...state,
3671
+ // The three source shapes are mutually exclusive in the document: the
3672
+ // remote-* attributes ARE the source, so the in-session git source
3673
+ // (the materialized clone) must not leak into the saved review. The
3674
+ // welcome source emits no source attributes, mirroring fetch-comments.
3675
+ source: { type: "welcome" },
3676
+ remoteUrl: remote.remoteUrl,
3677
+ remoteBaseSha: remote.remoteBaseSha,
3678
+ remoteHeadSha: remote.remoteHeadSha,
3679
+ remoteForge: remote.remoteForge
3680
+ };
3681
+ }
3682
+ function computeRemoteDrift(recordedHeadSha, liveHeadSha) {
3683
+ if (recordedHeadSha === void 0) {
3684
+ return null;
3685
+ }
3686
+ return {
3687
+ recordedHeadSha,
3688
+ liveHeadSha,
3689
+ drifted: recordedHeadSha !== liveHeadSha
3690
+ };
3691
+ }
3692
+
3693
+ // src/fetch-comments.ts
3694
+ var import_fs8 = require("fs");
3695
+ var import_path10 = require("path");
3696
+ init_diff_parser();
3697
+ init_git();
3698
+ function defaultDeps2() {
3699
+ return {
3700
+ runner: defaultGitRunner,
3701
+ createProvider: (forge, runner) => forge === "github" ? createGitHubProvider(runner) : createGitLabProvider(runner),
3702
+ detectExistingClone,
3703
+ materialize,
3704
+ resolveRemoteDefaultBranch,
3705
+ loadDiffFiles: async (repoPath, baseSha, headSha) => (
3706
+ // Triple-dot: diff from the merge base, matching how forges present a
3707
+ // PR/MR diff. Runs inside the materialized clone.
3708
+ parseDiff(await runGitDiffAsync([`${baseSha}...${headSha}`], repoPath))
3709
+ ),
3710
+ serialize: serializeReview,
3711
+ writeFile: (path4, content) => (0, import_fs8.writeFileSync)(path4, content, "utf-8"),
3712
+ loadConfig,
3713
+ now: () => /* @__PURE__ */ new Date()
3714
+ };
3715
+ }
3716
+ function buildRemoteReviewState(args) {
3717
+ const commentsByPath = /* @__PURE__ */ new Map();
3718
+ for (const comment of args.comments) {
3719
+ const list = commentsByPath.get(comment.filePath);
3720
+ if (list) {
3721
+ list.push(comment);
3722
+ } else {
3723
+ commentsByPath.set(comment.filePath, [comment]);
3724
+ }
3725
+ }
3726
+ const files = [];
3727
+ const diffPaths = /* @__PURE__ */ new Set();
3728
+ for (const diffFile of args.diffFiles) {
3729
+ const path4 = diffFile.changeType === "deleted" ? diffFile.oldPath : diffFile.newPath;
3730
+ diffPaths.add(path4);
3731
+ files.push({
3732
+ path: path4,
3733
+ changeType: diffFile.changeType,
3734
+ viewed: false,
3735
+ comments: commentsByPath.get(path4) ?? []
3736
+ });
3737
+ }
3738
+ for (const [path4, comments] of commentsByPath) {
3739
+ if (path4 === REVIEW_LEVEL_FILE_PATH || diffPaths.has(path4)) continue;
3740
+ files.push({ path: path4, changeType: "modified", viewed: false, comments });
3741
+ }
3742
+ const reviewLevel = commentsByPath.get(REVIEW_LEVEL_FILE_PATH);
3743
+ if (reviewLevel && reviewLevel.length > 0) {
3744
+ files.push({
3745
+ path: REVIEW_LEVEL_FILE_PATH,
3746
+ changeType: "modified",
3747
+ viewed: false,
3748
+ comments: reviewLevel
3749
+ });
3750
+ }
3751
+ return {
3752
+ timestamp: args.timestamp,
3753
+ source: { type: "welcome" },
3754
+ files,
3755
+ remoteUrl: args.remoteUrl,
3756
+ remoteBaseSha: args.baseSha,
3757
+ remoteHeadSha: args.headSha,
3758
+ remoteForge: args.forge
3759
+ };
3760
+ }
3761
+ async function runFetchComments(url, options = {}) {
3762
+ const deps = { ...defaultDeps2(), ...options.deps };
3763
+ const cwd = options.cwd ?? process.cwd();
3764
+ const forgeUrl = parseForgeUrl(url);
3765
+ if (forgeUrl === null) {
3766
+ throw new Error(
3767
+ `Not a recognized pull/merge request URL: ${url}
3768
+ Expected a GitHub PR URL (\u2026/pull/N) or a GitLab MR URL (\u2026/-/merge_requests/N).`
3769
+ );
3770
+ }
3771
+ const provider = deps.createProvider(forgeUrl.forge, deps.runner);
3772
+ let baseBranch;
3773
+ let existingClone;
3774
+ try {
3775
+ baseBranch = await provider.fetchBaseBranch(forgeUrl);
3776
+ } catch (error) {
3777
+ if (!(error instanceof ForgeCliUnavailableError)) throw error;
3778
+ console.error(`[fetch-comments] ${error.message}`);
3779
+ console.error(
3780
+ `[fetch-comments] ${error.cli} unavailable for the base-branch lookup \u2014 falling back to the remote default branch via git ls-remote.`
3781
+ );
3782
+ existingClone = await deps.detectExistingClone(forgeUrl, cwd, deps.runner);
3783
+ baseBranch = await deps.resolveRemoteDefaultBranch(forgeUrl, deps.runner, existingClone);
3784
+ }
3785
+ console.error(`[fetch-comments] Base branch: ${baseBranch}`);
3786
+ const materialized = await deps.materialize(
3787
+ forgeUrl,
3788
+ baseBranch,
3789
+ cwd,
3790
+ deps.runner,
3791
+ existingClone
3792
+ );
3793
+ try {
3794
+ let threads;
3795
+ try {
3796
+ threads = await provider.fetchThreads(forgeUrl, {
3797
+ includeResolved: options.includeResolved ?? false
3798
+ });
3799
+ } catch (error) {
3800
+ if (error instanceof ForgeCliUnavailableError) {
3801
+ throw new Error(
3802
+ `Cannot fetch discussion threads: ${error.message}
3803
+ fetch-comments requires the ${error.cli} CLI to be installed and authenticated.`
3804
+ );
3805
+ }
3806
+ throw error;
3807
+ }
3808
+ console.error(`[fetch-comments] Fetched ${threads.length} threads`);
3809
+ const diffFiles = await deps.loadDiffFiles(
3810
+ materialized.repoPath,
3811
+ materialized.baseSha,
3812
+ materialized.headSha
3813
+ );
3814
+ const comments = mapThreadsToReviewComments(threads, diffFiles);
3815
+ const state = buildRemoteReviewState({
3816
+ remoteUrl: url,
3817
+ forge: forgeUrl.forge,
3818
+ baseSha: materialized.baseSha,
3819
+ headSha: materialized.headSha,
3820
+ diffFiles,
3821
+ comments,
3822
+ timestamp: deps.now().toISOString()
3823
+ });
3824
+ const config = deps.loadConfig();
3825
+ const outputPath = (0, import_path10.resolve)(cwd, config.outputFile);
3826
+ const xml = await deps.serialize(state, outputPath);
3827
+ deps.writeFile(outputPath, xml + "\n");
3828
+ console.error(`[fetch-comments] ${comments.length} threads written to ${outputPath}`);
3829
+ } finally {
3830
+ materialized.cleanup();
3831
+ }
3832
+ }
2714
3833
  // Annotate the CommonJS export names for ESM import in node:
2715
3834
  0 && (module.exports = {
2716
3835
  ForgeCliUnavailableError,
2717
3836
  GUIDE_XSD_SCHEMA,
2718
3837
  IMPLICIT_GUIDE_GROUP_NAME,
2719
3838
  REVIEW_LEVEL_FILE_PATH,
3839
+ applyRemoteProvenance,
3840
+ applyStagedUntrackedDefault,
3841
+ applySuggestion,
3842
+ applySuggestionForSession,
3843
+ bootstrapRemoteDiff,
3844
+ buildRemoteReviewState,
2720
3845
  checkWritability,
3846
+ commitReviewStart,
2721
3847
  computePayloadStats,
3848
+ computeRemoteDrift,
2722
3849
  countTotalLines,
2723
3850
  createGitHubProvider,
2724
3851
  createGitLabProvider,
2725
3852
  createIgnoreFilter,
3853
+ createReviewSession,
2726
3854
  defaultGitRunner,
3855
+ deriveGuidePath,
2727
3856
  detectExistingClone,
3857
+ determineMode,
3858
+ expandContext,
2728
3859
  generateSyntheticDiffs,
2729
3860
  generateUntrackedDiffs,
3861
+ getConfigLoad,
3862
+ getDiffLoad,
3863
+ getFileHunks,
2730
3864
  getGitDiffStats,
2731
3865
  getLanguageFromPath,
2732
3866
  getRenderedTextMode,
2733
3867
  getRepoRoot,
2734
3868
  getRepoRootAsync,
3869
+ getResumeLoad,
2735
3870
  getUntrackedFilesAsync,
2736
3871
  isHtmlFile,
2737
3872
  isMarkdownFile,
@@ -2739,20 +3874,35 @@ async function resolveRemoteDefaultBranch(url, runner = defaultGitRunner, existi
2739
3874
  isPreviewableRenderedText,
2740
3875
  isPreviewableSvg,
2741
3876
  loadConfig,
3877
+ loadGitDiffWithUntracked,
3878
+ loadGuide,
3879
+ loadImage,
2742
3880
  mapThreadsToReviewComments,
2743
3881
  materialize,
3882
+ mergeRemoteThreads,
3883
+ normalizeGitDiffArgs,
2744
3884
  parseDiff,
2745
3885
  parseForgeUrl,
2746
3886
  parseGuideXml,
2747
3887
  parseReviewXml,
2748
3888
  parseReviewXmlString,
3889
+ prepareDirectoryReview,
3890
+ preparePayload,
3891
+ readAttachment,
2749
3892
  reconcileGuide,
3893
+ resolveApplyDestination,
3894
+ resolveGuidePath,
2750
3895
  resolveRemoteDefaultBranch,
3896
+ resolveSourceBaseDir,
3897
+ runFetchComments,
2751
3898
  runGitDiff,
2752
3899
  runGitDiffAsync,
2753
3900
  scanDirectory,
2754
3901
  scanFile,
2755
3902
  serializeReview,
3903
+ startRemoteSession,
3904
+ submitReviewState,
3905
+ takeReviewState,
2756
3906
  validateGitAvailable
2757
3907
  });
2758
3908
  //# sourceMappingURL=index.cjs.map