@in-the-loop-labs/pair-review 5.3.4 → 5.3.6

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 (59) hide show
  1. package/README.md +13 -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 +39 -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/chat/acp-bridge.js +26 -1
  34. package/src/chat/claude-code-bridge.js +10 -0
  35. package/src/chat/codex-bridge.js +10 -0
  36. package/src/chat/pi-bridge.js +10 -0
  37. package/src/chat/session-manager.js +333 -19
  38. package/src/config.js +40 -26
  39. package/src/git/diff-flags.js +26 -12
  40. package/src/git/worktree.js +21 -43
  41. package/src/github/client.js +0 -88
  42. package/src/github/impl/graphql/pending-review-comments.js +5 -1
  43. package/src/github/impl/host/pending-review-comments.js +75 -11
  44. package/src/github/submit-pr-context.js +56 -0
  45. package/src/local-review.js +34 -17
  46. package/src/main.js +80 -106
  47. package/src/routes/chat.js +44 -1
  48. package/src/routes/executable-analysis.js +14 -15
  49. package/src/routes/local.js +3 -5
  50. package/src/routes/pr.js +18 -105
  51. package/src/server.js +5 -3
  52. package/src/settings/registry.js +10 -0
  53. package/src/setup/pr-setup.js +1 -1
  54. package/src/setup/stack-setup.js +1 -1
  55. package/src/utils/diff-annotator.js +175 -25
  56. package/src/utils/diff-file-content.js +4 -26
  57. package/src/utils/diff-file-list.js +178 -42
  58. package/src/utils/git-paths.js +77 -0
  59. package/src/utils/paths.js +1 -25
@@ -20,7 +20,8 @@ const { localReviewDiffs } = require('./routes/shared');
20
20
  const summaryGenerator = require('./ai/summary-generator');
21
21
  const tourGenerator = require('./ai/tour-generator');
22
22
  const { getShaAbbrevLength } = require('./git/sha-abbrev');
23
- const { GIT_DIFF_FLAGS, GIT_DIFF_FLAGS_ARRAY } = require('./git/diff-flags');
23
+ const { GIT_DIFF_FLAGS, GIT_DIFF_FLAGS_ARRAY, GIT_PATH_CONFIG, GIT_PATH_CONFIG_ARRAY } = require('./git/diff-flags');
24
+ const { quoteGitPath, splitNulPaths } = require('./utils/git-paths');
24
25
  // Namespace import (not destructured) so detectBaseBranch is resolved off the
25
26
  // module object at call time — this keeps it interceptable by vi.spyOn on the
26
27
  // base-branch module in tests, unlike a destructured binding captured at load.
@@ -292,13 +293,13 @@ function isBinaryFile(buffer) {
292
293
  async function getUntrackedFiles(repoPath) {
293
294
  try {
294
295
  // Get list of untracked files (excluding ignored files)
295
- const output = execSync('git ls-files --others --exclude-standard', {
296
+ const output = execSync(`git ${GIT_PATH_CONFIG} ls-files -z --others --exclude-standard`, {
296
297
  cwd: repoPath,
297
298
  encoding: 'utf8',
298
299
  stdio: ['pipe', 'pipe', 'pipe']
299
300
  });
300
301
 
301
- const files = output.trim().split('\n').filter(f => f.length > 0);
302
+ const files = splitNulPaths(output);
302
303
 
303
304
  // Process files in parallel for better performance
304
305
  // Use Promise.allSettled to process all files even if some fail
@@ -398,6 +399,24 @@ async function findMergeBase(repoPath, baseBranch) {
398
399
  }
399
400
  }
400
401
 
402
+ /**
403
+ * Rewrite the file headers of a `git diff --no-index /dev/null <abs path>`
404
+ * patch to name the repo-relative path, spelled the way git spells a header
405
+ * (C-quoted only when the name contains a control character, `"` or `\`).
406
+ * The `+++` path gets git's trailing tab when it contains a space.
407
+ * @param {string} fileDiff - Patch for one untracked file
408
+ * @param {string} file - Repo-relative path
409
+ * @returns {string} Patch with repo-relative headers
410
+ */
411
+ function respellUntrackedDiffHeaders(fileDiff, file) {
412
+ const newPath = quoteGitPath(`b/${file}`);
413
+ const header = `diff --git ${quoteGitPath(`a/${file}`)} ${newPath}`;
414
+ const plusLine = `+++ ${newPath}${file.includes(' ') ? '\t' : ''}`;
415
+ return fileDiff
416
+ .replace(/^diff --git .*$/m, () => header)
417
+ .replace(/^\+\+\+ .*$/m, () => plusLine);
418
+ }
419
+
401
420
  /**
402
421
  * Generate diff output for untracked files using git diff --no-index.
403
422
  * @param {string} repoPath - Path to the git repository
@@ -426,7 +445,7 @@ function generateUntrackedDiffs(repoPath, untrackedFiles, options = {}) {
426
445
  const filePath = path.join(repoPath, untracked.file);
427
446
  let fileDiff;
428
447
  try {
429
- fileDiff = execFileSync('git', [...diffArgs, filePath], {
448
+ fileDiff = execFileSync('git', [...GIT_PATH_CONFIG_ARRAY, ...diffArgs, filePath], {
430
449
  cwd: repoPath,
431
450
  encoding: 'utf8',
432
451
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -447,9 +466,7 @@ function generateUntrackedDiffs(repoPath, untrackedFiles, options = {}) {
447
466
  }
448
467
 
449
468
  if (fileDiff && fileDiff.trim()) {
450
- const normalizedDiff = fileDiff
451
- .replace(/^diff --git a\/.+? b\/.+$/m, `diff --git a/${untracked.file} b/${untracked.file}`)
452
- .replace(/^\+\+\+ b\/.+$/m, `+++ b/${untracked.file}`);
469
+ const normalizedDiff = respellUntrackedDiffHeaders(fileDiff, untracked.file);
453
470
 
454
471
  if (diff) {
455
472
  diff += '\n';
@@ -522,19 +539,19 @@ async function generateScopedDiff(repoPath, scopeStart, scopeEnd, baseBranch, op
522
539
  try {
523
540
  if (hasBranch) {
524
541
  // Branch scope → working tree vs merge-base (includes committed + staged + unstaged)
525
- diff = execSync(`git diff ${mergeBaseSha} ${GIT_DIFF_FLAGS}${contextFlag}${extraArgsStr}${wFlag}`, {
542
+ diff = execSync(`git ${GIT_PATH_CONFIG} diff ${mergeBaseSha} ${GIT_DIFF_FLAGS}${contextFlag}${extraArgsStr}${wFlag}`, {
526
543
  cwd: repoPath, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],
527
544
  maxBuffer: 50 * 1024 * 1024
528
545
  });
529
546
  } else if (hasStaged) {
530
547
  // Staged + Unstaged scope → all changes vs HEAD
531
- diff = execSync(`git diff HEAD ${GIT_DIFF_FLAGS}${contextFlag}${extraArgsStr}${wFlag}`, {
548
+ diff = execSync(`git ${GIT_PATH_CONFIG} diff HEAD ${GIT_DIFF_FLAGS}${contextFlag}${extraArgsStr}${wFlag}`, {
532
549
  cwd: repoPath, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],
533
550
  maxBuffer: 50 * 1024 * 1024
534
551
  });
535
552
  } else {
536
553
  // Unstaged only (or Unstaged–Untracked) → working tree changes
537
- diff = execSync(`git diff ${GIT_DIFF_FLAGS}${contextFlag}${extraArgsStr}${wFlag}`, {
554
+ diff = execSync(`git ${GIT_PATH_CONFIG} diff ${GIT_DIFF_FLAGS}${contextFlag}${extraArgsStr}${wFlag}`, {
538
555
  cwd: repoPath, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],
539
556
  maxBuffer: 50 * 1024 * 1024
540
557
  });
@@ -553,7 +570,7 @@ async function generateScopedDiff(repoPath, scopeStart, scopeEnd, baseBranch, op
553
570
  // Count staged/unstaged for stats when relevant
554
571
  if (hasStaged) {
555
572
  try {
556
- const stagedDiff = execSync(`git diff --cached --stat ${GIT_DIFF_FLAGS}`, {
573
+ const stagedDiff = execSync(`git ${GIT_PATH_CONFIG} diff --cached --stat ${GIT_DIFF_FLAGS}`, {
557
574
  cwd: repoPath, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe']
558
575
  });
559
576
  if (stagedDiff.trim()) {
@@ -563,7 +580,7 @@ async function generateScopedDiff(repoPath, scopeStart, scopeEnd, baseBranch, op
563
580
  }
564
581
  if (hasUnstaged) {
565
582
  try {
566
- const unstagedDiff = execSync(`git diff --stat ${GIT_DIFF_FLAGS}`, {
583
+ const unstagedDiff = execSync(`git ${GIT_PATH_CONFIG} diff --stat ${GIT_DIFF_FLAGS}`, {
567
584
  cwd: repoPath, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe']
568
585
  });
569
586
  if (unstagedDiff.trim()) {
@@ -615,7 +632,7 @@ async function computeScopedDigest(repoPath, scopeStart, scopeEnd) {
615
632
  // Staged in scope → cached diff content
616
633
  if (scopeIncludes(scopeStart, scopeEnd, 'staged')) {
617
634
  try {
618
- const result = await execAsync(`git diff --cached ${GIT_DIFF_FLAGS}`, {
635
+ const result = await execAsync(`git ${GIT_PATH_CONFIG} diff --cached ${GIT_DIFF_FLAGS}`, {
619
636
  cwd: repoPath, encoding: 'utf8', maxBuffer: 50 * 1024 * 1024
620
637
  });
621
638
  parts.push('STAGED:' + result.stdout);
@@ -627,7 +644,7 @@ async function computeScopedDigest(repoPath, scopeStart, scopeEnd) {
627
644
  // Unstaged in scope → working tree diff
628
645
  if (scopeIncludes(scopeStart, scopeEnd, 'unstaged')) {
629
646
  try {
630
- const result = await execAsync(`git diff ${GIT_DIFF_FLAGS}`, {
647
+ const result = await execAsync(`git ${GIT_PATH_CONFIG} diff ${GIT_DIFF_FLAGS}`, {
631
648
  cwd: repoPath, encoding: 'utf8', maxBuffer: 50 * 1024 * 1024
632
649
  });
633
650
  parts.push('UNSTAGED:' + result.stdout);
@@ -639,10 +656,10 @@ async function computeScopedDigest(repoPath, scopeStart, scopeEnd) {
639
656
  // Untracked in scope → file list with sizes/mtimes
640
657
  if (scopeIncludes(scopeStart, scopeEnd, 'untracked')) {
641
658
  try {
642
- const result = await execAsync('git ls-files --others --exclude-standard', {
659
+ const result = await execAsync(`git ${GIT_PATH_CONFIG} ls-files -z --others --exclude-standard`, {
643
660
  cwd: repoPath, encoding: 'utf8'
644
661
  });
645
- const files = result.stdout.trim().split('\n').filter(f => f.length > 0);
662
+ const files = splitNulPaths(result.stdout);
646
663
  let untrackedInfo = '';
647
664
  for (const file of files) {
648
665
  try {
@@ -682,7 +699,7 @@ async function generateLocalDiff(repoPath, options = {}) {
682
699
  // Always count staged changes for CLI info message, even when staged is out of scope
683
700
  if (!result.stats.stagedChanges) {
684
701
  try {
685
- const stagedStat = execSync(`git diff --cached --stat ${GIT_DIFF_FLAGS}`, {
702
+ const stagedStat = execSync(`git ${GIT_PATH_CONFIG} diff --cached --stat ${GIT_DIFF_FLAGS}`, {
686
703
  cwd: repoPath, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe']
687
704
  });
688
705
  if (stagedStat.trim()) {
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 };
@@ -23,7 +23,8 @@ const { buildChatStartedPayload, buildChatResumedPayload, buildChatHookContext,
23
23
  const { resolveFormat } = require('../utils/comment-formatter');
24
24
  const { getAllChatProviders, getAllCachedChatAvailability } = require('../chat/chat-providers');
25
25
  const { getChatModelCatalog, canonicalChatModel } = require('../chat/chat-models');
26
- const { SESSION_BUSY } = require('../chat/session-manager');
26
+ const ChatSessionManager = require('../chat/session-manager');
27
+ const { SESSION_BUSY } = ChatSessionManager;
27
28
  const { resolveLoadSkills } = require('../config');
28
29
 
29
30
  /**
@@ -218,6 +219,46 @@ function unregisterChatBroadcast(sessionId) {
218
219
  }
219
220
  }
220
221
 
222
+ /**
223
+ * React to the session manager closing an idle session: drop the session's
224
+ * broadcast listeners (they belong to the closed bridge) and tell connected
225
+ * clients, so the next send shows the resume indicator. The session resumes
226
+ * transparently on its next message.
227
+ * The listener for ChatSessionManager's 'session-idle-closed' event (see
228
+ * createChatSessionManager).
229
+ * @param {{sessionId: number}} event
230
+ */
231
+ function handleSessionIdleClosed({ sessionId }) {
232
+ unregisterChatBroadcast(sessionId);
233
+ broadcastChat(sessionId, { type: 'session_closed', reason: 'idle' });
234
+ }
235
+
236
+ /**
237
+ * Build the server's ChatSessionManager: provider overrides from
238
+ * `config.chat_providers`, the idle timeout from `config.chat.idle_timeout_minutes`
239
+ * (the manager decides what counts as disabled), the idle-close listener that
240
+ * keeps this module's broadcast registry and clients in sync, and a running
241
+ * idle reaper. Lives here because it needs both the manager class and this
242
+ * module's broadcast state; session-manager.js must not require a route module.
243
+ * @param {Database} db
244
+ * @param {Object} config - Effective config (post global-settings overlay)
245
+ * @param {Object} [options]
246
+ * @param {Object} [options._deps] - Clock/timer overrides passed to the manager
247
+ * @returns {ChatSessionManager}
248
+ */
249
+ function createChatSessionManager(db, config = {}, { _deps } = {}) {
250
+ const idleTimeoutMs = Number(config.chat?.idle_timeout_minutes) * 60 * 1000;
251
+ const manager = new ChatSessionManager(db, config.chat_providers || {}, { idleTimeoutMs, _deps });
252
+ manager.on('session-idle-closed', handleSessionIdleClosed);
253
+ manager.startIdleReaper();
254
+ if (manager.idleTimeoutMs) {
255
+ logger.info(`Chat sessions idle for ${manager.idleTimeoutMs / 60000} minute(s) will be closed (resumable on next message)`);
256
+ } else {
257
+ logger.info('Idle chat session shutdown is disabled (chat.idle_timeout_minutes is not a positive number)');
258
+ }
259
+ return manager;
260
+ }
261
+
221
262
  /**
222
263
  * Fetch chat instructions from repo settings for a review.
223
264
  * @param {Database} db - Database instance
@@ -791,6 +832,8 @@ router.get('/api.md', (req, res) => {
791
832
  });
792
833
 
793
834
  module.exports = router;
835
+ module.exports.handleSessionIdleClosed = handleSessionIdleClosed;
836
+ module.exports.createChatSessionManager = createChatSessionManager;
794
837
 
795
838
  // Expose internals for testing
796
839
  module.exports._broadcastUnsubscribers = broadcastUnsubscribers;
@@ -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
  }