@in-the-loop-labs/pair-review 5.3.3 → 5.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +8 -2
  2. package/bin/git-diff-lines +2 -1
  3. package/package.json +1 -1
  4. package/plugin/.claude-plugin/plugin.json +1 -1
  5. package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
  6. package/plugin-code-critic/skills/analyze/scripts/git-diff-lines +104 -25
  7. package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
  8. package/public/css/pr.css +162 -46
  9. package/public/css/styles.css +0 -12
  10. package/public/js/components/AIPanel.js +3 -2
  11. package/public/js/components/AnalysisConfigModal.js +4 -1
  12. package/public/js/components/ChatPanel.js +15 -8
  13. package/public/js/components/PanelGroup.js +115 -21
  14. package/public/js/components/SuggestionNavigator.js +16 -3
  15. package/public/js/local.js +7 -12
  16. package/public/js/modules/diff-renderer.js +13 -0
  17. package/public/js/modules/file-comment-manager.js +19 -10
  18. package/public/js/modules/hunk-parser.js +39 -2
  19. package/public/js/modules/panel-resizer.js +41 -3
  20. package/public/js/modules/pierre-bridge.js +11 -2
  21. package/public/js/modules/suggestion-manager.js +128 -33
  22. package/public/js/pr.js +132 -29
  23. package/public/js/repo-settings.js +35 -19
  24. package/public/js/utils/git-paths.js +140 -0
  25. package/public/js/utils/smart-truncate.js +88 -0
  26. package/public/local.html +6 -0
  27. package/public/pr.html +6 -0
  28. package/src/ai/analyzer.js +15 -13
  29. package/src/ai/antigravity-provider.js +44 -24
  30. package/src/ai/codex-provider.js +67 -64
  31. package/src/ai/cursor-agent-provider.js +4 -4
  32. package/src/ai/muse-provider.js +68 -3
  33. package/src/ai/summary-generator.js +8 -5
  34. package/src/git/diff-flags.js +26 -12
  35. package/src/git/worktree.js +21 -43
  36. package/src/github/client.js +0 -88
  37. package/src/github/impl/graphql/pending-review-comments.js +5 -1
  38. package/src/github/submit-pr-context.js +56 -0
  39. package/src/local-review.js +34 -17
  40. package/src/main.js +80 -106
  41. package/src/routes/executable-analysis.js +14 -15
  42. package/src/routes/local.js +3 -5
  43. package/src/routes/pr.js +18 -105
  44. package/src/setup/pr-setup.js +1 -1
  45. package/src/setup/stack-setup.js +1 -1
  46. package/src/utils/diff-annotator.js +175 -25
  47. package/src/utils/diff-file-content.js +4 -26
  48. package/src/utils/diff-file-list.js +178 -42
  49. package/src/utils/git-paths.js +77 -0
  50. package/src/utils/paths.js +1 -25
package/src/routes/pr.js CHANGED
@@ -20,7 +20,7 @@ const { GitHubClient } = require('../github/client');
20
20
  const { PRArgumentParser } = require('../github/parser');
21
21
  const { getGeneratedFilePatterns } = require('../git/gitattributes');
22
22
  const { getShaAbbrevLength, DEFAULT_SHA_ABBREV_LENGTH } = require('../git/sha-abbrev');
23
- const { normalizeRepository, resolveRenamedFile, resolveRenamedFileOld } = require('../utils/paths');
23
+ const { normalizeRepository } = require('../utils/paths');
24
24
  const { mergeInstructions } = require('../utils/instructions');
25
25
  const Analyzer = require('../ai/analyzer');
26
26
  const { v4: uuidv4 } = require('uuid');
@@ -32,13 +32,14 @@ const { resolveHostName } = require('../links/repo-links');
32
32
  const { resolveHostListText } = require('../links/host-names');
33
33
  const { backgroundQueue } = require('../ai/background-queue');
34
34
  const logger = require('../utils/logger');
35
- const { buildDiffLineSet } = require('../utils/diff-annotator');
35
+ const { buildReviewComments } = require('../utils/diff-annotator');
36
36
  const { broadcastReviewEvent } = require('../events/review-events');
37
37
  const { fireHooks, hasHooks } = require('../hooks/hook-runner');
38
38
  const { buildReviewStartedPayload, buildReviewLoadedPayload, buildAnalysisStartedPayload, buildAnalysisCompletedPayload, getCachedUser } = require('../hooks/payloads');
39
39
  const simpleGit = require('simple-git');
40
- const { GIT_DIFF_FLAGS_ARRAY, GIT_DIFF_SUMMARY_FLAGS_ARRAY } = require('../git/diff-flags');
40
+ const { GIT_DIFF_FLAGS_ARRAY, SIMPLE_GIT_PATH_OPTIONS } = require('../git/diff-flags');
41
41
  const { walkPRStack, DEFAULT_TRUNK_BRANCHES } = require('../github/stack-walker');
42
+ const { buildSubmitPrContext } = require('../github/submit-pr-context');
42
43
  const summaryGenerator = require('../ai/summary-generator');
43
44
  const tourGenerator = require('../ai/tour-generator');
44
45
  const {
@@ -53,7 +54,7 @@ const {
53
54
  registerProcess: registerProcessForCancellation
54
55
  } = require('./shared');
55
56
  const { safeParseJson } = require('../utils/safe-parse-json');
56
- const { mergeChangedFilesWithDiff, parseUnifiedDiffPatches } = require('../utils/diff-file-list');
57
+ const { mergeChangedFilesWithDiff, parseUnifiedDiffPatches, buildChangedFileEntries } = require('../utils/diff-file-list');
57
58
  const { parseHunks } = require('../utils/diff-hunks');
58
59
  const { hashHunk } = require('../ai/hunk-hashing');
59
60
  const { resolveOriginalFileContentSpecs } = require('../utils/diff-file-content');
@@ -619,7 +620,7 @@ router.post('/api/pr/:owner/:repo/:number/refresh', async (req, res) => {
619
620
  head_sha: prData.head_sha
620
621
  };
621
622
  const diff = await worktreeManager.generateUnifiedDiff(worktreePath, diffPrData);
622
- const changedFiles = await worktreeManager.getChangedFiles(worktreePath, diffPrData);
623
+ const changedFiles = await worktreeManager.getChangedFiles(worktreePath, diff);
623
624
 
624
625
  // Prepare extended data
625
626
  const extendedData = {
@@ -1174,7 +1175,7 @@ router.get('/api/pr/:owner/:repo/:number/diff', async (req, res) => {
1174
1175
  try {
1175
1176
  const worktreePath = worktreeRecord.path;
1176
1177
  await fs.access(worktreePath);
1177
- const git = simpleGit(worktreePath);
1178
+ const git = simpleGit(worktreePath, SIMPLE_GIT_PATH_OPTIONS);
1178
1179
 
1179
1180
  const baseSha = prData.base_sha;
1180
1181
  const headSha = prData.head_sha;
@@ -1183,25 +1184,8 @@ router.get('/api/pr/:owner/:repo/:number/diff', async (req, res) => {
1183
1184
  const diffArgs = [`${baseSha}...${headSha}`, '--unified=3', ...GIT_DIFF_FLAGS_ARRAY, '-w'];
1184
1185
  diffContent = await git.diff(diffArgs);
1185
1186
 
1186
- const summaryArgs = [`${baseSha}...${headSha}`, ...GIT_DIFF_SUMMARY_FLAGS_ARRAY, '-w'];
1187
- const diffSummary = await git.diffSummary(summaryArgs);
1188
1187
  gitattributes = await getGeneratedFilePatterns(worktreePath);
1189
- changedFiles = diffSummary.files.map(file => {
1190
- const resolvedFile = resolveRenamedFile(file.file);
1191
- const isRenamed = resolvedFile !== file.file;
1192
- const result = {
1193
- file: resolvedFile,
1194
- insertions: file.insertions,
1195
- deletions: file.deletions,
1196
- changes: file.changes,
1197
- generated: gitattributes.isGenerated(resolvedFile)
1198
- };
1199
- if (isRenamed) {
1200
- result.renamed = true;
1201
- result.renamedFrom = resolveRenamedFileOld(file.file);
1202
- }
1203
- return result;
1204
- });
1188
+ changedFiles = buildChangedFileEntries(diffContent, gitattributes);
1205
1189
  }
1206
1190
  } catch (wsError) {
1207
1191
  logger.warn(`Could not generate diff for PR #${prNumber}: ${wsError.message}`);
@@ -1571,65 +1555,8 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1571
1555
  //
1572
1556
  // We check whether the comment's target line actually appears in a diff hunk
1573
1557
  // rather than relying on diff_position (which may not be set by all sources).
1574
- const diffLineSet = buildDiffLineSet(diffContent);
1575
-
1576
- const graphqlComments = comments.map(comment => {
1577
- const side = comment.side || 'RIGHT';
1578
- const isRange = comment.line_end && comment.line_end !== comment.line_start;
1579
-
1580
- // Check if this is an explicit file-level comment (is_file_level=1)
1581
- // These are comments about the entire file, not tied to specific lines
1582
- if (comment.is_file_level === 1) {
1583
- console.log(`Formatting file-level comment: ${comment.file}`);
1584
-
1585
- return {
1586
- path: comment.file,
1587
- body: comment.body,
1588
- isFileLevel: true
1589
- };
1590
- }
1591
-
1592
- // Detect expanded context comments by checking whether the target line
1593
- // actually appears in a diff hunk. This is more reliable than checking
1594
- // diff_position, which may be absent for comments created by the chat agent.
1595
- // For range comments, both endpoints must be inside the diff; if the start
1596
- // line falls outside a hunk but the end is inside, submitting with start_line
1597
- // would produce a position GitHub cannot render.
1598
- const isExpandedContext = isRange
1599
- ? !diffLineSet.isLineInDiff(comment.file, comment.line_start, side) || !diffLineSet.isLineInDiff(comment.file, comment.line_end, side)
1600
- : !diffLineSet.isLineInDiff(comment.file, comment.line_start, side);
1601
-
1602
- if (isExpandedContext) {
1603
- // File-level comment with line reference prefix
1604
- const lineRef = isRange
1605
- ? `(Ref Lines ${comment.line_start}-${comment.line_end})`
1606
- : `(Ref Line ${comment.line_start})`;
1607
-
1608
- console.log(`Formatting file-level comment (expanded context): ${comment.file} ${lineRef}`);
1609
-
1610
- return {
1611
- path: comment.file,
1612
- body: `${lineRef} ${comment.body}`,
1613
- isFileLevel: true
1614
- };
1615
- }
1616
-
1617
- console.log(`Formatting line comment: ${comment.file}:${comment.line_start}${isRange ? `-${comment.line_end}` : ''} side=${side}`);
1618
-
1619
- const commentObj = {
1620
- path: comment.file,
1621
- line: isRange ? comment.line_end : comment.line_start,
1622
- body: comment.body,
1623
- side: side,
1624
- isFileLevel: false
1625
- };
1626
-
1627
- if (isRange) {
1628
- commentObj.start_line = comment.line_start;
1629
- }
1630
-
1631
- return commentObj;
1632
- });
1558
+ // Headless --ai-draft / --ai-review submits through the same mapping.
1559
+ const graphqlComments = buildReviewComments(comments, diffContent);
1633
1560
 
1634
1561
  // Submit review using GraphQL API (supports file-level comments)
1635
1562
  console.log(`${event === 'DRAFT' ? 'Creating draft review' : 'Submitting review'} for PR #${prNumber} with ${comments.length} comments`);
@@ -1667,31 +1594,17 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1667
1594
 
1668
1595
  const prNodeId = prData.node_id ?? null;
1669
1596
 
1670
- // The PR head SHA is required by the host pending-review-comments path
1671
- // (GitHub-compatible alt-hosts validate each inline comment like
1672
- // `pulls.createReviewComment`, which mandates `commit_id`). The GraphQL
1673
- // path on github.com ignores it (the pending review pins the commit
1674
- // implicitly), so threading it through is harmless there.
1675
- // `prData.head_sha` is the canonical source (merged from the cached PR
1676
- // JSON); `prMetadata.head_sha` is a defensive fallback for callers whose
1677
- // record exposes it as a column. If neither is present, proceed without
1678
- // it but warn loudly so the resulting 422 is diagnosable.
1679
- const headSha = prData.head_sha || prMetadata.head_sha || null;
1680
- if (!headSha) {
1681
- logger.warn(
1682
- `Submit review for ${repository}#${prNumber}: PR head SHA is missing ` +
1683
- `(prData.head_sha and prMetadata.head_sha both absent). Host inline-comment ` +
1684
- `posting will likely fail with a 422 missing commit_id error.`
1685
- );
1686
- }
1687
-
1688
- const submitPrContext = {
1597
+ // Shared with headless --ai-draft / --ai-review (src/main.js): carries the
1598
+ // draft's numeric review id and the PR head SHA that alt-hosts require as
1599
+ // each inline comment's commit_id.
1600
+ const submitPrContext = buildSubmitPrContext({
1689
1601
  owner,
1690
1602
  repo,
1691
1603
  prNumber,
1692
- reviewId: existingDraft?.databaseId,
1693
- headSha
1694
- };
1604
+ existingDraft,
1605
+ prData,
1606
+ prMetadata
1607
+ });
1695
1608
 
1696
1609
  if (event === 'DRAFT') {
1697
1610
  // Delegate to createDraftReviewGraphQL (handles both new and existing drafts)
@@ -882,7 +882,7 @@ async function setupPRReview({ db, owner, repo, prNumber, githubToken, bindingRe
882
882
  // ------------------------------------------------------------------
883
883
  progress({ step: 'diff', status: 'running', message: 'Generating unified diff...' });
884
884
  const diff = await worktreeManager.generateUnifiedDiff(worktreePath, prData);
885
- const changedFiles = await worktreeManager.getChangedFiles(worktreePath, prData);
885
+ const changedFiles = await worktreeManager.getChangedFiles(worktreePath, diff);
886
886
  progress({ step: 'diff', status: 'completed', message: 'Diff generated.' });
887
887
 
888
888
  // ------------------------------------------------------------------
@@ -88,7 +88,7 @@ async function setupStackPR({ db, owner, repo, prNumber, githubToken, binding, b
88
88
  const diff = await worktreeManager.generateUnifiedDiff(worktreePath, prData);
89
89
 
90
90
  // 5. Get changed files with stats
91
- const changedFiles = await worktreeManager.getChangedFiles(worktreePath, prData);
91
+ const changedFiles = await worktreeManager.getChangedFiles(worktreePath, diff);
92
92
 
93
93
  // 6. Store via storePRData (creates/updates pr_metadata, reviews, worktrees records).
94
94
  // Stamp the host of the binding used to fetch this stack PR (null for
@@ -3,6 +3,9 @@
3
3
  * Diff annotation utility for adding explicit line numbers to unified diffs
4
4
  * Provides two-column format showing both OLD (base) and NEW (head) line numbers
5
5
  */
6
+ const { parseDiffGitPaths, decodeDiffLinePath } = require('./git-paths');
7
+
8
+ const logger = require('./logger');
6
9
 
7
10
  /**
8
11
  * Parse a hunk header to extract line number information
@@ -12,8 +15,12 @@
12
15
  */
13
16
  function parseHunkHeader(header) {
14
17
  // Match: @@ -oldStart,oldCount +newStart,newCount @@ optional context
15
- // Count can be omitted, defaulting to 1
16
- const match = header.match(/^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@(.*)$/);
18
+ // Count can be omitted, defaulting to 1. The `s` (dotAll) flag lets the
19
+ // trailing context span a carriage return: git trims trailing whitespace
20
+ // from the function-context line but keeps a lone `\r` inside it, and
21
+ // without dotAll `.` stops at that `\r`, `$` cannot match, and the whole
22
+ // header is rejected, so its hunk body goes uncounted.
23
+ const match = header.match(/^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@(.*)$/s);
17
24
 
18
25
  if (!match) {
19
26
  return null;
@@ -73,6 +80,13 @@ function getLineContent(line) {
73
80
 
74
81
  /**
75
82
  * Parse file header lines to extract old and new file paths
83
+ *
84
+ * CALLER CONTRACT: only call this on lines that are OUTSIDE a hunk body. It
85
+ * returns `true` for anything merely starting with `---`, `+++`, `index ` or
86
+ * `diff --git`, and those prefixes are ordinary CONTENT inside a hunk (a
87
+ * deleted `-- x` is emitted as `--- x`, an added `++ x` as `+++ x`). Both
88
+ * loops in this file enforce that with an `!inHunk` guard.
89
+ *
76
90
  * @param {string} line - A diff line that might be a file header
77
91
  * @param {Object} currentFile - Current file info to update
78
92
  * @returns {boolean} Whether this was a file header line
@@ -80,28 +94,30 @@ function getLineContent(line) {
80
94
  function parseFileHeader(line, currentFile) {
81
95
  // Handle diff --git header
82
96
  if (line.startsWith('diff --git')) {
83
- const match = line.match(/^diff --git a\/(.+) b\/(.+)$/);
84
- if (match) {
85
- currentFile.oldPath = match[1];
86
- currentFile.newPath = match[2];
97
+ const paths = parseDiffGitPaths(line);
98
+ if (paths) {
99
+ currentFile.oldPath = paths.oldPath;
100
+ currentFile.newPath = paths.newPath;
87
101
  }
88
102
  return true;
89
103
  }
90
104
 
91
105
  // Handle --- header
92
106
  if (line.startsWith('---')) {
93
- const match = line.match(/^---\s+(?:a\/)?(.+)$/);
94
- if (match && match[1] !== '/dev/null') {
95
- currentFile.oldPath = match[1];
107
+ const match = line.match(/^---\s+(.+)$/);
108
+ const oldPath = match ? decodeDiffLinePath(match[1], 'a/') : null;
109
+ if (oldPath !== null) {
110
+ currentFile.oldPath = oldPath;
96
111
  }
97
112
  return true;
98
113
  }
99
114
 
100
115
  // Handle +++ header
101
116
  if (line.startsWith('+++')) {
102
- const match = line.match(/^\+\+\+\s+(?:b\/)?(.+)$/);
103
- if (match && match[1] !== '/dev/null') {
104
- currentFile.newPath = match[1];
117
+ const match = line.match(/^\+\+\+\s+(.+)$/);
118
+ const newPath = match ? decodeDiffLinePath(match[1], 'b/') : null;
119
+ if (newPath !== null) {
120
+ currentFile.newPath = newPath;
105
121
  }
106
122
  return true;
107
123
  }
@@ -137,7 +153,7 @@ function parseFileHeader(line, currentFile) {
137
153
  if (line.startsWith('rename from')) {
138
154
  const match = line.match(/^rename from (.+)$/);
139
155
  if (match) {
140
- currentFile.renamedFrom = match[1];
156
+ currentFile.renamedFrom = decodeDiffLinePath(match[1]);
141
157
  }
142
158
  return true;
143
159
  }
@@ -145,7 +161,7 @@ function parseFileHeader(line, currentFile) {
145
161
  if (line.startsWith('rename to')) {
146
162
  const match = line.match(/^rename to (.+)$/);
147
163
  if (match) {
148
- currentFile.renamedTo = match[1];
164
+ currentFile.renamedTo = decodeDiffLinePath(match[1]);
149
165
  }
150
166
  return true;
151
167
  }
@@ -218,8 +234,13 @@ function annotateDiff(rawDiff) {
218
234
  continue;
219
235
  }
220
236
 
221
- // Parse file header lines
222
- if (parseFileHeader(line, currentFile)) {
237
+ // Parse file header lines. Guarded on `!inHunk`: inside a hunk body these
238
+ // prefixes are content, and letting `parseFileHeader` claim them both
239
+ // corrupts the file path (an added `++ x` line arrives as `+++ x`) and
240
+ // skips the counter-advancing branches below, shifting every later anchor
241
+ // in the file. `git diff` opens every file with `diff --git`, which resets
242
+ // `inHunk` above before that file's real headers arrive.
243
+ if (!inHunk && parseFileHeader(line, currentFile)) {
223
244
  // Check if we just detected a binary file that needs output
224
245
  if (currentFile.isBinary && fileStarted && !fileHeaderOutput) {
225
246
  let filePath = currentFile.newPath || currentFile.oldPath || 'unknown';
@@ -410,15 +431,35 @@ function parseAnnotatedDiff(annotatedDiff) {
410
431
  * Used to determine whether a comment targets a line GitHub can render inline
411
432
  * (inside a hunk) vs. one that must be submitted as file-level.
412
433
  *
434
+ * File headers are only headers OUTSIDE a hunk body. `parseFileHeader`
435
+ * returns `true` for anything starting with `---`, `+++`, `index ` or
436
+ * `diff --git`, and inside a hunk those are content: a deleted `-- x` line is
437
+ * emitted as `--- x`, an added `++ x` as `+++ x`, and an unindented `++i;` as
438
+ * `+++i;`. Letting the header parser claim them overwrote the section's path
439
+ * with a fragment of source code AND skipped the counter-advancing branch,
440
+ * shifting every later RIGHT anchor in the file by one. The `!inHunk` guard is
441
+ * what makes those lines fall through to the ordinary `+`/`-` accounting where
442
+ * they belong.
443
+ *
444
+ * Each line also records the hunk it belongs to, so a caller can tell
445
+ * whether two lines share a hunk: GitHub only accepts a multi-line comment
446
+ * whose two ends are in the same hunk.
447
+ *
413
448
  * @param {string} rawDiff - Raw unified diff from git
414
- * @returns {{ isLineInDiff: (file: string, line: number, side?: string) => boolean }}
449
+ * @returns {{
450
+ * isLineInDiff: (file: string, line: number, side?: string) => boolean,
451
+ * hunkOf: (file: string, line: number, side?: string) => number|null
452
+ * }} `hunkOf` returns an index that is unique per hunk across the whole
453
+ * diff, or null for a line outside every hunk.
415
454
  */
416
455
  function buildDiffLineSet(rawDiff) {
417
456
  if (!rawDiff || rawDiff.trim() === '') {
418
- return { isLineInDiff: () => false };
457
+ return { isLineInDiff: () => false, hunkOf: () => null };
419
458
  }
420
459
 
421
- const entries = new Set();
460
+ // `${file}:${side}:${line}` -> index of the hunk that contains the line
461
+ const entries = new Map();
462
+ let hunkIndex = -1;
422
463
  const diffLines = rawDiff.split('\n');
423
464
  // Trim trailing empty element produced by split('\n') on newline-terminated input.
424
465
  // Without this, the empty string matches the context-line branch and adds phantom
@@ -437,7 +478,9 @@ function buildDiffLineSet(rawDiff) {
437
478
  continue;
438
479
  }
439
480
 
440
- if (parseFileHeader(line, currentFile)) {
481
+ // Header lines are headers only outside a hunk body — see the docblock.
482
+ // Inside one they fall through to the +/- accounting below.
483
+ if (!inHunk && parseFileHeader(line, currentFile)) {
441
484
  continue;
442
485
  }
443
486
 
@@ -446,6 +489,7 @@ function buildDiffLineSet(rawDiff) {
446
489
  oldLineNum = hunkInfo.oldStart;
447
490
  newLineNum = hunkInfo.newStart;
448
491
  inHunk = true;
492
+ hunkIndex++;
449
493
  continue;
450
494
  }
451
495
 
@@ -457,14 +501,14 @@ function buildDiffLineSet(rawDiff) {
457
501
  if (!filePath) continue;
458
502
 
459
503
  if (line.startsWith('+')) {
460
- entries.add(`${filePath}:RIGHT:${newLineNum}`);
504
+ entries.set(`${filePath}:RIGHT:${newLineNum}`, hunkIndex);
461
505
  newLineNum++;
462
506
  } else if (line.startsWith('-')) {
463
- entries.add(`${filePath}:LEFT:${oldLineNum}`);
507
+ entries.set(`${filePath}:LEFT:${oldLineNum}`, hunkIndex);
464
508
  oldLineNum++;
465
509
  } else if (line.startsWith(' ') || line === '') {
466
- entries.add(`${filePath}:LEFT:${oldLineNum}`);
467
- entries.add(`${filePath}:RIGHT:${newLineNum}`);
510
+ entries.set(`${filePath}:LEFT:${oldLineNum}`, hunkIndex);
511
+ entries.set(`${filePath}:RIGHT:${newLineNum}`, hunkIndex);
468
512
  oldLineNum++;
469
513
  newLineNum++;
470
514
  }
@@ -473,10 +517,115 @@ function buildDiffLineSet(rawDiff) {
473
517
  return {
474
518
  isLineInDiff(file, lineNum, side = 'RIGHT') {
475
519
  return entries.has(`${file}:${side}:${lineNum}`);
520
+ },
521
+ hunkOf(file, lineNum, side = 'RIGHT') {
522
+ const hunk = entries.get(`${file}:${side}:${lineNum}`);
523
+ return hunk === undefined ? null : hunk;
476
524
  }
477
525
  };
478
526
  }
479
527
 
528
+ /**
529
+ * Map stored comment rows to the GitHub review comments that a review
530
+ * submission sends. The one mapping for both submit paths: the web submit
531
+ * route (src/routes/pr.js) and headless --ai-draft / --ai-review
532
+ * (src/main.js). Both GitHub transports (GraphQL and the host REST
533
+ * extension) accept the result.
534
+ *
535
+ * - `is_file_level = 1` rows become file-level comments.
536
+ * - A range written backwards (`line_end < line_start`) is the same span,
537
+ * so its ends are put in ascending order first.
538
+ * - A range becomes a multi-line comment (`start_line`, `start_side`, `line`)
539
+ * only when both ends are inside the diff, on the comment side, in the
540
+ * SAME hunk. GitHub rejects a range that crosses hunks, and one rejected
541
+ * comment discards the whole pending review.
542
+ * - Otherwise, a single line or a range whose `line_start` is inside a hunk
543
+ * becomes a single-line comment on `line_start` (the line the finding is
544
+ * anchored on).
545
+ * - Anything else (e.g. expanded context) cannot be inline, so it becomes a
546
+ * file-level comment whose body starts with `(Ref Line N)` or
547
+ * `(Ref Lines N-M)`.
548
+ *
549
+ * @param {Array<Object>|null} rows - Comment rows: file, line_start,
550
+ * line_end, side, body, is_file_level
551
+ * @param {string} diffContent - Raw unified diff used for the hunk check
552
+ * @param {Object} [options]
553
+ * @param {(row: Object) => string} [options.formatBody] - Comment text for a
554
+ * row, before any line reference prefix. Defaults to `row.body`.
555
+ * @returns {Array<{path: string, body: string, isFileLevel: boolean,
556
+ * line?: number, side?: string, start_line?: number, start_side?: string}>}
557
+ */
558
+ function buildReviewComments(rows, diffContent, { formatBody = row => row.body } = {}) {
559
+ const diffLineSet = buildDiffLineSet(diffContent);
560
+
561
+ return (rows || []).map(comment => {
562
+ const side = comment.side || 'RIGHT';
563
+ const body = formatBody(comment);
564
+
565
+ // Explicit file-level comment: about the whole file, not tied to lines
566
+ if (comment.is_file_level === 1) {
567
+ logger.debug(`Formatting file-level comment: ${comment.file}`);
568
+ return {
569
+ path: comment.file,
570
+ body,
571
+ isFileLevel: true
572
+ };
573
+ }
574
+
575
+ // A backwards range is the same span; order it so start < end.
576
+ const isRange = comment.line_start != null && Boolean(comment.line_end) && comment.line_end !== comment.line_start;
577
+ const rangeStart = isRange ? Math.min(comment.line_start, comment.line_end) : comment.line_start;
578
+ const rangeEnd = isRange ? Math.max(comment.line_start, comment.line_end) : comment.line_start;
579
+
580
+ // Check whether the target lines actually appear in a diff hunk rather
581
+ // than relying on diff_position, which may be absent (e.g. comments
582
+ // created by the chat agent or headless AI findings).
583
+ if (isRange) {
584
+ const startHunk = diffLineSet.hunkOf(comment.file, rangeStart, side);
585
+ const endHunk = diffLineSet.hunkOf(comment.file, rangeEnd, side);
586
+ if (startHunk !== null && startHunk === endHunk) {
587
+ logger.debug(`Formatting range comment: ${comment.file}:${rangeStart}-${rangeEnd} side=${side}`);
588
+ return {
589
+ path: comment.file,
590
+ line: rangeEnd,
591
+ body,
592
+ side,
593
+ isFileLevel: false,
594
+ start_line: rangeStart,
595
+ start_side: side
596
+ };
597
+ }
598
+ }
599
+
600
+ // A single line, or a range GitHub cannot render as one thread: anchor
601
+ // on line_start when it is inside a hunk.
602
+ if (diffLineSet.isLineInDiff(comment.file, comment.line_start, side)) {
603
+ if (isRange) {
604
+ logger.debug(`Range ${comment.file}:${rangeStart}-${rangeEnd} side=${side} does not fit one hunk; anchoring on line ${comment.line_start}`);
605
+ } else {
606
+ logger.debug(`Formatting line comment: ${comment.file}:${comment.line_start} side=${side}`);
607
+ }
608
+ return {
609
+ path: comment.file,
610
+ line: comment.line_start,
611
+ body,
612
+ side,
613
+ isFileLevel: false
614
+ };
615
+ }
616
+
617
+ const lineRef = isRange
618
+ ? `(Ref Lines ${rangeStart}-${rangeEnd})`
619
+ : `(Ref Line ${comment.line_start})`;
620
+ logger.debug(`Formatting file-level comment (expanded context): ${comment.file} ${lineRef}`);
621
+ return {
622
+ path: comment.file,
623
+ body: `${lineRef} ${body}`,
624
+ isFileLevel: true
625
+ };
626
+ });
627
+ }
628
+
480
629
  module.exports = {
481
630
  annotateDiff,
482
631
  parseAnnotatedDiff,
@@ -484,5 +633,6 @@ module.exports = {
484
633
  formatLineNum,
485
634
  getLineMarker,
486
635
  getLineContent,
487
- buildDiffLineSet
636
+ buildDiffLineSet,
637
+ buildReviewComments
488
638
  };
@@ -7,30 +7,7 @@
7
7
  * rendered patch, even if cached PR metadata drifts.
8
8
  */
9
9
 
10
- function parseDiffGitPaths(headerLine) {
11
- if (!headerLine.startsWith('diff --git ')) {
12
- return null;
13
- }
14
-
15
- const rest = headerLine.slice('diff --git '.length);
16
- const quotedMatch = rest.match(/^"a\/(.+)" "b\/(.+)"$/);
17
- if (quotedMatch) {
18
- return {
19
- oldPath: quotedMatch[1].replace(/\\"/g, '"'),
20
- newPath: quotedMatch[2].replace(/\\"/g, '"')
21
- };
22
- }
23
-
24
- const plainMatch = rest.match(/^a\/(.+?) b\/(.+)$/);
25
- if (!plainMatch) {
26
- return null;
27
- }
28
-
29
- return {
30
- oldPath: plainMatch[1],
31
- newPath: plainMatch[2]
32
- };
33
- }
10
+ const { parseDiffGitPaths, parsePatchPaths } = require('./git-paths');
34
11
 
35
12
  function findFileBlobInfoInDiff(diffText, fileName) {
36
13
  if (!diffText || !fileName) {
@@ -40,9 +17,10 @@ function findFileBlobInfoInDiff(diffText, fileName) {
40
17
  const lines = diffText.split('\n');
41
18
  let matchedPaths = null;
42
19
 
43
- for (const line of lines) {
20
+ for (let i = 0; i < lines.length; i++) {
21
+ const line = lines[i];
44
22
  if (line.startsWith('diff --git ')) {
45
- const paths = parseDiffGitPaths(line);
23
+ const paths = parsePatchPaths(lines, i);
46
24
  matchedPaths = paths && (paths.oldPath === fileName || paths.newPath === fileName)
47
25
  ? paths
48
26
  : null;