@in-the-loop-labs/pair-review 5.3.4 → 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 (49) hide show
  1. package/README.md +7 -1
  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/cursor-agent-provider.js +4 -4
  31. package/src/ai/muse-provider.js +68 -3
  32. package/src/ai/summary-generator.js +8 -5
  33. package/src/git/diff-flags.js +26 -12
  34. package/src/git/worktree.js +21 -43
  35. package/src/github/client.js +0 -88
  36. package/src/github/impl/graphql/pending-review-comments.js +5 -1
  37. package/src/github/submit-pr-context.js +56 -0
  38. package/src/local-review.js +34 -17
  39. package/src/main.js +80 -106
  40. package/src/routes/executable-analysis.js +14 -15
  41. package/src/routes/local.js +3 -5
  42. package/src/routes/pr.js +18 -105
  43. package/src/setup/pr-setup.js +1 -1
  44. package/src/setup/stack-setup.js +1 -1
  45. package/src/utils/diff-annotator.js +175 -25
  46. package/src/utils/diff-file-content.js +4 -26
  47. package/src/utils/diff-file-list.js +178 -42
  48. package/src/utils/git-paths.js +77 -0
  49. package/src/utils/paths.js +1 -25
package/src/main.js CHANGED
@@ -7,6 +7,7 @@ const { loadConfig, getConfigDir, showWelcomeMessage, resolveDbName, resolveRepo
7
7
  const { initializeDatabase, run, queryOne, query, migrateExistingWorktrees, WorktreeRepository, ReviewRepository, RepoSettingsRepository, GitHubReviewRepository, WorktreePoolRepository, CouncilRepository, CommentRepository, AnalysisRunRepository, PRMetadataRepository } = require('./database');
8
8
  const { PRArgumentParser } = require('./github/parser');
9
9
  const { GitHubClient } = require('./github/client');
10
+ const { buildSubmitPrContext } = require('./github/submit-pr-context');
10
11
  const { GitWorktreeManager } = require('./git/worktree');
11
12
  const { fetchNoTags } = require('./git/fetch-helpers');
12
13
  const { cleanupOrphanedKeepFiles } = require('./git/pack-cleanup');
@@ -28,12 +29,14 @@ const { includesBranch, parseScopeArg, VALID_SCOPE_RANGES, EMPTY_SCOPE_MESSAGE }
28
29
  const { storePRData, resolvePrHostBinding, registerRepositoryLocation, findRepositoryPath } = require('./setup/pr-setup');
29
30
  const { resolvePreflightBinding, setupHostParam, bindingRepositoryForHost } = require('./utils/host-resolution');
30
31
  const { fireReviewStartedHook } = require('./hooks/payloads');
31
- const { normalizeRepository, resolveRenamedFile, resolveRenamedFileOld } = require('./utils/paths');
32
+ const { normalizeRepository } = require('./utils/paths');
32
33
  const { rejectUrlLikeLocalReviewPath } = require('./utils/local-path-input');
34
+ const { buildReviewComments } = require('./utils/diff-annotator');
33
35
  const logger = require('./utils/logger');
34
36
  const simpleGit = require('simple-git');
35
37
  const { getGeneratedFilePatterns } = require('./git/gitattributes');
36
- const { GIT_DIFF_FLAGS_ARRAY, GIT_DIFF_SUMMARY_FLAGS_ARRAY } = require('./git/diff-flags');
38
+ const { GIT_DIFF_FLAGS_ARRAY, SIMPLE_GIT_PATH_OPTIONS } = require('./git/diff-flags');
39
+ const { buildChangedFileEntries } = require('./utils/diff-file-list');
37
40
  const { getEmoji: getCategoryEmoji } = require('./utils/category-emoji');
38
41
  const open = (...args) => process.env.PAIR_REVIEW_NO_OPEN ? Promise.resolve() : import('open').then(({default: open}) => open(...args));
39
42
  const { registerProtocolHandler, unregisterProtocolHandler } = require('./protocol-handler');
@@ -1342,6 +1345,50 @@ function formatAISuggestion(text, category) {
1342
1345
  return `${emoji} **${capitalizedCategory}**: ${text}`;
1343
1346
  }
1344
1347
 
1348
+ /**
1349
+ * Load the final AI suggestions a headless (--ai-draft / --ai-review) review
1350
+ * submits: the review's active, orchestrated (not per-level), non-raw AI
1351
+ * findings. The rows carry everything buildReviewComments needs to map them
1352
+ * to GitHub comments: side (LEFT for a deleted line), the range end and the
1353
+ * file-level flag.
1354
+ *
1355
+ * Rows GitHub cannot take are skipped and reported: those without a file
1356
+ * path, and line findings without a positive line number. File-level
1357
+ * findings (is_file_level = 1) need no line.
1358
+ *
1359
+ * @param {Object} db - Database instance
1360
+ * @param {number} reviewId - reviews.id the findings belong to
1361
+ * @returns {Promise<Array<Object>>} Submittable suggestion rows, ordered by file and line
1362
+ */
1363
+ async function loadHeadlessSuggestions(db, reviewId) {
1364
+ const rows = await query(db, `
1365
+ SELECT
1366
+ id,
1367
+ file,
1368
+ line_start,
1369
+ line_end,
1370
+ body,
1371
+ diff_position,
1372
+ side,
1373
+ title,
1374
+ type,
1375
+ is_file_level
1376
+ FROM comments
1377
+ WHERE review_id = ? AND source = 'ai' AND ai_level IS NULL AND (is_raw = 0 OR is_raw IS NULL) AND status = 'active'
1378
+ ORDER BY file, line_start
1379
+ `, [reviewId]);
1380
+
1381
+ return rows.filter(suggestion => {
1382
+ const hasValidPath = typeof suggestion.file === 'string' && suggestion.file.trim() !== '';
1383
+ const hasValidLine = suggestion.is_file_level === 1 || suggestion.line_start > 0;
1384
+ if (!hasValidPath || !hasValidLine) {
1385
+ logger.warn(`Skipping suggestion for ${suggestion.file || 'unknown file'}:${suggestion.line_start || 'unknown line'} - missing valid line or path information`);
1386
+ return false;
1387
+ }
1388
+ return true;
1389
+ });
1390
+ }
1391
+
1345
1392
  /**
1346
1393
  * Shared implementation for headless (non-interactive) review modes.
1347
1394
  * Used by both --ai-draft and --ai-review.
@@ -1440,7 +1487,7 @@ async function performHeadlessReview(args, config, db, flags, options, externalP
1440
1487
 
1441
1488
  // Generate diff directly from current checkout
1442
1489
  console.log('Generating unified diff from checkout...');
1443
- const git = simpleGit(worktreePath);
1490
+ const git = simpleGit(worktreePath, SIMPLE_GIT_PATH_OPTIONS);
1444
1491
 
1445
1492
  // Ensure we have the base SHA available (fetch if needed)
1446
1493
  try {
@@ -1460,30 +1507,9 @@ async function performHeadlessReview(args, config, db, flags, options, externalP
1460
1507
  ...GIT_DIFF_FLAGS_ARRAY
1461
1508
  ]);
1462
1509
 
1463
- // Get changed files
1464
- const diffSummary = await git.diffSummary([
1465
- `${prData.base_sha}...${prData.head_sha}`,
1466
- ...GIT_DIFF_SUMMARY_FLAGS_ARRAY
1467
- ]);
1510
+ // Build changed files from the diff (one source of path spelling)
1468
1511
  const gitattributes = await getGeneratedFilePatterns(worktreePath);
1469
-
1470
- changedFiles = diffSummary.files.map(file => {
1471
- const resolvedFile = resolveRenamedFile(file.file);
1472
- const isRenamed = resolvedFile !== file.file;
1473
- const result = {
1474
- file: resolvedFile,
1475
- insertions: file.insertions,
1476
- deletions: file.deletions,
1477
- changes: file.changes,
1478
- binary: file.binary || false,
1479
- generated: gitattributes.isGenerated(resolvedFile)
1480
- };
1481
- if (isRenamed) {
1482
- result.renamed = true;
1483
- result.renamedFrom = resolveRenamedFileOld(file.file);
1484
- }
1485
- return result;
1486
- });
1512
+ changedFiles = buildChangedFileEntries(diff, gitattributes);
1487
1513
  } else {
1488
1514
  // Use worktree approach - only use cwd if it matches the target repo
1489
1515
  const currentDir = parser.getCurrentDirectory();
@@ -1570,7 +1596,7 @@ async function performHeadlessReview(args, config, db, flags, options, externalP
1570
1596
 
1571
1597
  console.log('Generating unified diff...');
1572
1598
  diff = await worktreeManager.generateUnifiedDiff(worktreePath, prData);
1573
- changedFiles = await worktreeManager.getChangedFiles(worktreePath, prData);
1599
+ changedFiles = await worktreeManager.getChangedFiles(worktreePath, diff);
1574
1600
  }
1575
1601
 
1576
1602
  // Store PR data in database
@@ -1678,21 +1704,9 @@ async function performHeadlessReview(args, config, db, flags, options, externalP
1678
1704
  throw new Error(`AI analysis failed: ${analysisError.message}`);
1679
1705
  }
1680
1706
 
1681
- // Query for final AI suggestions (orchestrated, not per-level)
1682
- // Use review.id (not prMetadata.id) to match how comments are stored
1683
- const aiSuggestions = await query(db, `
1684
- SELECT
1685
- id,
1686
- file,
1687
- line_start,
1688
- body,
1689
- diff_position,
1690
- title,
1691
- type
1692
- FROM comments
1693
- WHERE review_id = ? AND source = 'ai' AND ai_level IS NULL AND (is_raw = 0 OR is_raw IS NULL) AND status = 'active'
1694
- ORDER BY file, line_start
1695
- `, [review.id]);
1707
+ // Final AI suggestions (orchestrated, not per-level). Use review.id (not
1708
+ // prMetadata.id) to match how comments are stored.
1709
+ const aiSuggestions = await loadHeadlessSuggestions(db, review.id);
1696
1710
 
1697
1711
  console.log(`Found ${aiSuggestions.length} AI suggestions to submit`);
1698
1712
 
@@ -1701,39 +1715,14 @@ async function performHeadlessReview(args, config, db, flags, options, externalP
1701
1715
  return; // Exit gracefully without creating a review
1702
1716
  }
1703
1717
 
1704
- // Filter out suggestions without valid line information
1705
- // Note: diff positions will be recalculated fresh by GitHub client
1706
- const validSuggestions = aiSuggestions.filter(suggestion => {
1707
- const hasValidLine = suggestion.line_start && suggestion.line_start > 0;
1708
- const hasValidPath = suggestion.file && suggestion.file.trim() !== '';
1709
-
1710
- if (!hasValidLine || !hasValidPath) {
1711
- console.warn(`Skipping suggestion for ${suggestion.file || 'unknown file'}:${suggestion.line_start || 'unknown line'} - missing valid line or path information`);
1712
- return false;
1713
- }
1714
-
1715
- return true;
1716
- });
1717
-
1718
- console.log(`Filtered to ${validSuggestions.length} suggestions with valid line information`);
1719
-
1720
- if (validSuggestions.length === 0) {
1721
- console.log('No suggestions with valid line information. Exiting without creating review.');
1722
- return; // Exit gracefully without creating a review
1723
- }
1724
-
1725
- // Format AI suggestions for GitHub
1726
- const githubComments = validSuggestions.map(suggestion => {
1727
- // Format with emoji and category prefix, same as adopted suggestions
1728
- const formattedBody = formatAISuggestion(suggestion.body, suggestion.type);
1729
-
1730
- return {
1731
- path: suggestion.file,
1732
- line: suggestion.line_start,
1733
- body: formattedBody,
1734
- side: 'RIGHT', // AI suggestions always target added/modified code
1735
- isFileLevel: false // AI suggestions always target specific lines
1736
- };
1718
+ // Same mapping as the web submit route: each comment keeps its side,
1719
+ // ranges keep start_line, file-level findings stay file-level, and a line
1720
+ // outside every diff hunk becomes a file-level comment with a
1721
+ // "(Ref Line N)" prefix. Only the body formatting is headless-specific.
1722
+ // Diff positions are recalculated fresh by the GitHub client.
1723
+ const githubComments = buildReviewComments(aiSuggestions, diff, {
1724
+ // Same emoji + category prefix as adopted suggestions
1725
+ formatBody: suggestion => formatAISuggestion(suggestion.body, suggestion.type)
1737
1726
  });
1738
1727
 
1739
1728
  // Build review body with AI-generated summary
@@ -1746,7 +1735,7 @@ ${analysisSummary}
1746
1735
  > Generated by [pair-review](https://github.com/in-the-loop-labs/pair-review) with \`${footerFlag}\` mode`
1747
1736
  : `## AI Analysis Summary
1748
1737
 
1749
- Found ${validSuggestions.length} suggestion${validSuggestions.length === 1 ? '' : 's'} from automated analysis.
1738
+ Found ${aiSuggestions.length} suggestion${aiSuggestions.length === 1 ? '' : 's'} from automated analysis.
1750
1739
 
1751
1740
  > Generated by [pair-review](https://github.com/in-the-loop-labs/pair-review) with \`${footerFlag}\` mode`;
1752
1741
 
@@ -1781,12 +1770,17 @@ Found ${validSuggestions.length} suggestion${validSuggestions.length === 1 ? ''
1781
1770
 
1782
1771
  const prNodeId = storedPRData.node_id ?? null;
1783
1772
 
1784
- const submitPrContext = {
1773
+ // Same builder as the web submit route: carries the draft's numeric review
1774
+ // id and the PR head SHA that alt-hosts require as each inline comment's
1775
+ // commit_id (without it they reject the comments with a 422).
1776
+ const submitPrContext = buildSubmitPrContext({
1785
1777
  owner: prInfo.owner,
1786
1778
  repo: prInfo.repo,
1787
1779
  prNumber: prInfo.number,
1788
- reviewId: existingDraft?.databaseId
1789
- };
1780
+ existingDraft,
1781
+ prData: storedPRData,
1782
+ prMetadata
1783
+ });
1790
1784
 
1791
1785
  let githubReview;
1792
1786
  if (options.reviewEvent === 'DRAFT') {
@@ -1848,9 +1842,9 @@ Found ${validSuggestions.length} suggestion${validSuggestions.length === 1 ? ''
1848
1842
  });
1849
1843
 
1850
1844
  // Update AI suggestions to appropriate status (batch update for performance)
1851
- // Use validSuggestions (not aiSuggestions) to only update those that were actually submitted
1852
- if (validSuggestions.length > 0) {
1853
- const suggestionIds = validSuggestions.map(s => s.id);
1845
+ // Only the submitted suggestions (loadHeadlessSuggestions skipped the rest)
1846
+ if (aiSuggestions.length > 0) {
1847
+ const suggestionIds = aiSuggestions.map(s => s.id);
1854
1848
  const placeholders = suggestionIds.map(() => '?').join(',');
1855
1849
  await run(db, `
1856
1850
  UPDATE comments
@@ -2096,7 +2090,7 @@ async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycl
2096
2090
  console.log(`Using current checkout at ${worktreePath}`);
2097
2091
 
2098
2092
  console.log('Generating unified diff from checkout...');
2099
- const git = simpleGit(worktreePath);
2093
+ const git = simpleGit(worktreePath, SIMPLE_GIT_PATH_OPTIONS);
2100
2094
  try {
2101
2095
  await fetchNoTags(git, ['origin', prData.base_sha]);
2102
2096
  } catch (fetchError) {
@@ -2111,28 +2105,8 @@ async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycl
2111
2105
  '--unified=3',
2112
2106
  ...GIT_DIFF_FLAGS_ARRAY
2113
2107
  ]);
2114
- const diffSummary = await git.diffSummary([
2115
- `${prData.base_sha}...${prData.head_sha}`,
2116
- ...GIT_DIFF_SUMMARY_FLAGS_ARRAY
2117
- ]);
2118
2108
  const gitattributes = await getGeneratedFilePatterns(worktreePath);
2119
- changedFiles = diffSummary.files.map(file => {
2120
- const resolvedFile = resolveRenamedFile(file.file);
2121
- const isRenamed = resolvedFile !== file.file;
2122
- const result = {
2123
- file: resolvedFile,
2124
- insertions: file.insertions,
2125
- deletions: file.deletions,
2126
- changes: file.changes,
2127
- binary: file.binary || false,
2128
- generated: gitattributes.isGenerated(resolvedFile)
2129
- };
2130
- if (isRenamed) {
2131
- result.renamed = true;
2132
- result.renamedFrom = resolveRenamedFileOld(file.file);
2133
- }
2134
- return result;
2135
- });
2109
+ changedFiles = buildChangedFileEntries(diff, gitattributes);
2136
2110
  } else {
2137
2111
  const currentDir = parser.getCurrentDirectory();
2138
2112
  const isMatchingRepo = await parser.isMatchingRepository(currentDir, prInfo.owner, prInfo.repo);
@@ -2208,7 +2182,7 @@ async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycl
2208
2182
 
2209
2183
  console.log('Generating unified diff...');
2210
2184
  diff = await worktreeManager.generateUnifiedDiff(worktreePath, prData);
2211
- changedFiles = await worktreeManager.getChangedFiles(worktreePath, prData);
2185
+ changedFiles = await worktreeManager.getChangedFiles(worktreePath, diff);
2212
2186
  }
2213
2187
 
2214
2188
  console.log('Storing pull request data...');
@@ -3035,4 +3009,4 @@ if (require.main === module) {
3035
3009
  main();
3036
3010
  }
3037
3011
 
3038
- module.exports = { main, parseArgs, detectPRFromGitHubEnvironment, printCouncilList, handleHeadlessAnalysis, handleHeadlessDelegated, runHeadlessAnalysis, buildHeadlessJson, buildHeadlessErrorJson, emitHeadlessResult, resolveCliInstructions, resolveCliBindingRepository, startPoolBackgroundFetches, isPoolEntryDueForFetch, POOL_FETCH_TICK_MS, MAX_POOL_FETCH_BACKOFF_MS };
3012
+ module.exports = { main, parseArgs, detectPRFromGitHubEnvironment, printCouncilList, handleHeadlessAnalysis, handleHeadlessDelegated, runHeadlessAnalysis, buildHeadlessJson, buildHeadlessErrorJson, emitHeadlessResult, loadHeadlessSuggestions, resolveCliInstructions, resolveCliBindingRepository, startPoolBackgroundFetches, isPoolEntryDueForFetch, POOL_FETCH_TICK_MS, MAX_POOL_FETCH_BACKOFF_MS };
@@ -27,7 +27,8 @@ const { fireHooks, hasHooks } = require('../hooks/hook-runner');
27
27
  const { buildAnalysisStartedPayload, buildAnalysisCompletedPayload, getCachedUser } = require('../hooks/payloads');
28
28
  const { normalizePath, resolveRenamedFile } = require('../utils/paths');
29
29
  const { buildFileLineCountMap, validateSuggestionLineNumbers } = require('../utils/line-validation');
30
- const { GIT_DIFF_FLAGS } = require('../git/diff-flags');
30
+ const { GIT_DIFF_FLAGS, GIT_PATH_CONFIG } = require('../git/diff-flags');
31
+ const { splitNulPaths } = require('../utils/git-paths');
31
32
  const { generateScopedDiff, findMergeBase } = require('../local-review');
32
33
  const { scopeIncludes } = require('../local-scope');
33
34
 
@@ -72,14 +73,14 @@ async function generateDiffForExecutable(cwd, context, diffArgs, outputPath) {
72
73
  } else if (context.baseSha && context.headSha) {
73
74
  // PR mode: straightforward base...head diff
74
75
  const { stdout } = await execPromise(
75
- `git diff ${GIT_DIFF_FLAGS}${extraFlags} ${context.baseSha}...${context.headSha}`,
76
+ `git ${GIT_PATH_CONFIG} diff ${GIT_DIFF_FLAGS}${extraFlags} ${context.baseSha}...${context.headSha}`,
76
77
  { cwd, maxBuffer: 50 * 1024 * 1024 }
77
78
  );
78
79
  diff = stdout;
79
80
  } else {
80
81
  // Fallback: simple working-tree diff
81
82
  const { stdout } = await execPromise(
82
- `git diff ${GIT_DIFF_FLAGS}${extraFlags}`,
83
+ `git ${GIT_PATH_CONFIG} diff ${GIT_DIFF_FLAGS}${extraFlags}`,
83
84
  { cwd, maxBuffer: 50 * 1024 * 1024 }
84
85
  );
85
86
  diff = stdout;
@@ -108,10 +109,10 @@ async function getChangedFiles(cwd, context, { throwOnError = false } = {}) {
108
109
  try {
109
110
  if (context.baseSha && context.headSha) {
110
111
  const { stdout } = await execPromise(
111
- `git diff ${GIT_DIFF_FLAGS} ${context.baseSha}...${context.headSha} --name-only`,
112
+ `git ${GIT_PATH_CONFIG} diff ${GIT_DIFF_FLAGS} ${context.baseSha}...${context.headSha} --name-only -z`,
112
113
  { cwd }
113
114
  );
114
- return stdout.trim().split('\n').filter(f => f.length > 0);
115
+ return splitNulPaths(stdout);
115
116
  }
116
117
 
117
118
  // Local mode: scope-aware file list
@@ -127,37 +128,35 @@ async function getChangedFiles(cwd, context, { throwOnError = false } = {}) {
127
128
  if (hasBranch && baseBranch) {
128
129
  const mergeBase = await findMergeBase(cwd, baseBranch);
129
130
  commands.push(
130
- execPromise(`git diff ${GIT_DIFF_FLAGS} ${mergeBase}..HEAD --name-only`, { cwd }).then(r => r.stdout)
131
+ execPromise(`git ${GIT_PATH_CONFIG} diff ${GIT_DIFF_FLAGS} ${mergeBase}..HEAD --name-only -z`, { cwd }).then(r => r.stdout)
131
132
  );
132
133
  }
133
134
  if (hasStaged) {
134
135
  commands.push(
135
- execPromise(`git diff ${GIT_DIFF_FLAGS} --cached --name-only`, { cwd }).then(r => r.stdout)
136
+ execPromise(`git ${GIT_PATH_CONFIG} diff ${GIT_DIFF_FLAGS} --cached --name-only -z`, { cwd }).then(r => r.stdout)
136
137
  );
137
138
  }
138
139
  if (hasUnstaged) {
139
140
  commands.push(
140
- execPromise(`git diff ${GIT_DIFF_FLAGS} --name-only`, { cwd }).then(r => r.stdout)
141
+ execPromise(`git ${GIT_PATH_CONFIG} diff ${GIT_DIFF_FLAGS} --name-only -z`, { cwd }).then(r => r.stdout)
141
142
  );
142
143
  }
143
144
  if (hasUntracked) {
144
145
  commands.push(
145
- execPromise('git ls-files --others --exclude-standard', { cwd }).then(r => r.stdout)
146
+ execPromise(`git ${GIT_PATH_CONFIG} ls-files -z --others --exclude-standard`, { cwd }).then(r => r.stdout)
146
147
  );
147
148
  }
148
149
  } else {
149
150
  // Fallback: no scope info — include unstaged + untracked + staged
150
151
  commands.push(
151
- execPromise(`git diff ${GIT_DIFF_FLAGS} --name-only`, { cwd }).then(r => r.stdout),
152
- execPromise('git ls-files --others --exclude-standard', { cwd }).then(r => r.stdout),
153
- execPromise(`git diff ${GIT_DIFF_FLAGS} --cached --name-only`, { cwd }).then(r => r.stdout)
152
+ execPromise(`git ${GIT_PATH_CONFIG} diff ${GIT_DIFF_FLAGS} --name-only -z`, { cwd }).then(r => r.stdout),
153
+ execPromise(`git ${GIT_PATH_CONFIG} ls-files -z --others --exclude-standard`, { cwd }).then(r => r.stdout),
154
+ execPromise(`git ${GIT_PATH_CONFIG} diff ${GIT_DIFF_FLAGS} --cached --name-only -z`, { cwd }).then(r => r.stdout)
154
155
  );
155
156
  }
156
157
 
157
158
  const results = await Promise.all(commands);
158
- const all = results
159
- .flatMap(output => output.trim().split('\n'))
160
- .filter(f => f.length > 0);
159
+ const all = results.flatMap(output => splitNulPaths(output));
161
160
  return [...new Set(all)];
162
161
  } catch (error) {
163
162
  if (throwOnError) {
@@ -925,11 +925,9 @@ router.get('/api/local/:reviewId/diff', async (req, res) => {
925
925
  try {
926
926
  const gitattributes = await getGeneratedFilePatterns(review.local_path);
927
927
  if (gitattributes.getPatterns().length > 0) {
928
- // Extract file paths from the diff header lines (--- a/path and +++ b/path)
929
- const filePathRegex = /^diff --git a\/.+? b\/(.+)$/gm;
930
- let match;
931
- while ((match = filePathRegex.exec(diffContent)) !== null) {
932
- const filePath = match[1];
928
+ // Decoded new paths from the diff --git headers, spelled the way
929
+ // the browser keys files (see public/js/utils/git-paths.js)
930
+ for (const filePath of parseUnifiedDiffPatches(diffContent).keys()) {
933
931
  if (gitattributes.isGenerated(filePath)) {
934
932
  generatedFiles.push(filePath);
935
933
  }
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