@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
package/src/config.js CHANGED
@@ -19,13 +19,12 @@ const IMPLEMENTATION_MATRIX = {
19
19
  pending_review_comments: _pendingReviewCommentsOps.IMPLEMENTED_MODES
20
20
  };
21
21
 
22
- // Recognised `_endpoint` sub-keys. These ride alongside the area key in
23
- // `features` (e.g. `pending_review_comments_endpoint`) and are validated
24
- // separately from area modes. Listed explicitly so a typo like
25
- // `pending_review_commentes_endpoint` is rejected at startup rather than
26
- // silently ignored.
27
- const KNOWN_ENDPOINT_SUBKEYS = new Set([
28
- 'pending_review_comments_endpoint'
22
+ // Recognised sub-keys that configure an implementation without selecting a
23
+ // feature area. They are validated separately from area modes. Listing them
24
+ // explicitly keeps typos from being silently ignored.
25
+ const KNOWN_FEATURE_SUBKEYS = new Set([
26
+ 'pending_review_comments_endpoint',
27
+ 'pending_review_comments_batch'
29
28
  ]);
30
29
 
31
30
  let _cachedCommandToken = null;
@@ -92,7 +91,7 @@ const DEFAULT_CONFIG = {
92
91
  enable_chat: true, // When true, enables the chat panel feature (uses chat_provider)
93
92
  chat_provider: "pi", // Chat provider: 'pi', 'copilot-acp', 'opencode-acp', 'cursor-acp', 'codex'
94
93
  comment_format: "legacy", // Comment format preset or custom template for adopted suggestions
95
- chat: { enable_shortcuts: true, enter_to_send: true }, // Chat panel settings (enable_shortcuts: show action shortcut buttons, enter_to_send: Enter sends message instead of newline)
94
+ chat: { enable_shortcuts: true, enter_to_send: true, idle_timeout_minutes: 10 }, // Chat panel settings (enable_shortcuts: show action shortcut buttons, enter_to_send: Enter sends message instead of newline, idle_timeout_minutes: shut down a chat agent process after this many idle minutes — resumed transparently on the next message; 0 disables)
96
95
  providers: {}, // Custom AI analysis provider configurations (overrides built-in defaults)
97
96
  chat_providers: {}, // Custom chat provider configurations (overrides built-in defaults)
98
97
  repos: {}, // Repository configurations: { "owner/repo": { path: "~/path/to/clone" } }
@@ -582,11 +581,10 @@ function _resolveFeatures(apiHost, explicit) {
582
581
  out[area] = 'rest';
583
582
  }
584
583
  }
585
- // Preserve endpoint-override sub-keys (e.g. `pending_review_comments_endpoint`)
586
- // so the operations layer can read them at dispatch time. Validation of
587
- // these keys happens in `validateRepoConfig()` at startup.
584
+ // Preserve implementation sub-keys so the operations layer can read them
585
+ // at dispatch time. Validation happens in `validateRepoConfig()` at startup.
588
586
  for (const [key, value] of Object.entries(overrides)) {
589
- if (key.endsWith('_endpoint') && typeof value === 'string') {
587
+ if (KNOWN_FEATURE_SUBKEYS.has(key)) {
590
588
  out[key] = value;
591
589
  }
592
590
  }
@@ -965,17 +963,15 @@ function validateRepoConfig(config) {
965
963
  }
966
964
 
967
965
  for (const [area, value] of Object.entries(features)) {
968
- // Endpoint-override sub-keys (e.g. `pending_review_comments_endpoint`)
969
- // are validated separately below. Reject anything that ends in
970
- // `_endpoint` but isn't a recognised override so typos surface here.
966
+ // Implementation sub-keys are validated separately below.
967
+ if (KNOWN_FEATURE_SUBKEYS.has(area)) continue;
968
+ // Reject unknown endpoint overrides with a specific error before the
969
+ // general unknown-feature check.
971
970
  if (area.endsWith('_endpoint')) {
972
- if (!KNOWN_ENDPOINT_SUBKEYS.has(area)) {
973
- throw new Error(
974
- `Invalid pair-review config: repos["${repoKey}"].features.${area} is not a recognised endpoint override. ` +
975
- `Valid endpoint overrides: ${Array.from(KNOWN_ENDPOINT_SUBKEYS).join(', ')}.`
976
- );
977
- }
978
- continue;
971
+ throw new Error(
972
+ `Invalid pair-review config: repos["${repoKey}"].features.${area} is not a recognised endpoint override. ` +
973
+ `Valid endpoint overrides: ${Array.from(KNOWN_FEATURE_SUBKEYS).filter((key) => key.endsWith('_endpoint')).join(', ')}.`
974
+ );
979
975
  }
980
976
  // Reject unknown feature keys (e.g. `pendin_review_check` typo).
981
977
  // Without this, the key is silently ignored by _resolveFeatures.
@@ -1020,7 +1016,7 @@ function validateRepoConfig(config) {
1020
1016
  // would resolve to a mode lacking a runtime implementation).
1021
1017
  const resolvedFeatures = _resolveFeatures(apiHost, features);
1022
1018
  for (const [area, value] of Object.entries(resolvedFeatures)) {
1023
- if (area.endsWith('_endpoint')) continue;
1019
+ if (KNOWN_FEATURE_SUBKEYS.has(area)) continue;
1024
1020
  if (Object.prototype.hasOwnProperty.call(features, area)) continue; // already checked above
1025
1021
  const implemented = IMPLEMENTATION_MATRIX[area];
1026
1022
  if (implemented && !implemented.has(value)) {
@@ -1033,8 +1029,9 @@ function validateRepoConfig(config) {
1033
1029
  }
1034
1030
 
1035
1031
  // Validate the optional endpoint override for the host-extension
1036
- // `pending_review_comments` area. Only meaningful when that area is
1037
- // set to "host" — applying it otherwise is a config error.
1032
+ // `pending_review_comments` area. Only meaningful when that area
1033
+ // resolves to "host" (explicitly, or by default on an alt-host) —
1034
+ // applying it otherwise is a config error.
1038
1035
  const endpointOverride = features.pending_review_comments_endpoint;
1039
1036
  if (endpointOverride !== undefined && endpointOverride !== null) {
1040
1037
  if (typeof endpointOverride !== 'string' || !endpointOverride) {
@@ -1042,7 +1039,7 @@ function validateRepoConfig(config) {
1042
1039
  `Invalid pair-review config: repos["${repoKey}"].features.pending_review_comments_endpoint must be a non-empty string.`
1043
1040
  );
1044
1041
  }
1045
- if (features.pending_review_comments !== 'host') {
1042
+ if (resolvedFeatures.pending_review_comments !== 'host') {
1046
1043
  throw new Error(
1047
1044
  `Invalid pair-review config: repos["${repoKey}"].features.pending_review_comments_endpoint is only valid when pending_review_comments = "host".`
1048
1045
  );
@@ -1065,6 +1062,23 @@ function validateRepoConfig(config) {
1065
1062
  }
1066
1063
  }
1067
1064
 
1065
+ // Some hosts expose the pending-review endpoint but accept one comment
1066
+ // per POST instead of the generic batch envelope. Batch mode remains the
1067
+ // default to preserve the documented host-extension contract.
1068
+ const batchComments = features.pending_review_comments_batch;
1069
+ if (batchComments !== undefined && batchComments !== null) {
1070
+ if (typeof batchComments !== 'boolean') {
1071
+ throw new Error(
1072
+ `Invalid pair-review config: repos["${repoKey}"].features.pending_review_comments_batch must be a boolean.`
1073
+ );
1074
+ }
1075
+ if (resolvedFeatures.pending_review_comments !== 'host') {
1076
+ throw new Error(
1077
+ `Invalid pair-review config: repos["${repoKey}"].features.pending_review_comments_batch is only valid when pending_review_comments = "host".`
1078
+ );
1079
+ }
1080
+ }
1081
+
1068
1082
  if (repoEntry.url_pattern !== undefined && repoEntry.url_pattern !== null) {
1069
1083
  if (typeof repoEntry.url_pattern !== 'string') {
1070
1084
  throw new Error(
@@ -29,21 +29,35 @@ const GIT_DIFF_FLAGS_ARRAY = [
29
29
  ];
30
30
 
31
31
  /**
32
- * Array form for simple-git .diffSummary() calls.
33
- * Use --numstat so simple-git parses machine-readable output with exact file paths.
34
- * The default --stat output is display-oriented and may abbreviate long paths,
35
- * which breaks downstream matching for generated route files and similar cases.
36
- * Omits --src-prefix/--dst-prefix since diffSummary doesn't output file content with prefixes.
32
+ * Git config that makes path-producing commands print names verbatim.
33
+ *
34
+ * With git's default core.quotePath=true, any path with a byte >= 0x80 is
35
+ * C-quoted with octal escapes (`"caf\303\251.js"`) in diff headers,
36
+ * --name-only, --numstat and ls-files output. Pinning it off keeps non-ASCII
37
+ * names readable everywhere. `-c` must precede the subcommand, so exec calls
38
+ * spell commands as `git ${GIT_PATH_CONFIG} diff ...`.
39
+ *
40
+ * Git still quotes paths containing control characters, `"` or `\` in diff
41
+ * headers; src/utils/git-paths.js decodes those. Path LISTS are read with -z,
42
+ * which is never quoted.
37
43
  */
38
- const GIT_DIFF_SUMMARY_FLAGS_ARRAY = [
39
- '--no-color',
40
- '--no-ext-diff',
41
- '--no-relative',
42
- '--numstat'
43
- ];
44
+ const GIT_PATH_CONFIG = '-c core.quotePath=false';
45
+
46
+ /**
47
+ * Array form of GIT_PATH_CONFIG for execFile / spawn argument lists.
48
+ */
49
+ const GIT_PATH_CONFIG_ARRAY = ['-c', 'core.quotePath=false'];
50
+
51
+ /**
52
+ * simple-git constructor options carrying the same config, for every
53
+ * simple-git instance that runs diff: `simpleGit(dir, SIMPLE_GIT_PATH_OPTIONS)`.
54
+ */
55
+ const SIMPLE_GIT_PATH_OPTIONS = Object.freeze({ config: ['core.quotePath=false'] });
44
56
 
45
57
  module.exports = {
46
58
  GIT_DIFF_FLAGS,
47
59
  GIT_DIFF_FLAGS_ARRAY,
48
- GIT_DIFF_SUMMARY_FLAGS_ARRAY
60
+ GIT_PATH_CONFIG,
61
+ GIT_PATH_CONFIG_ARRAY,
62
+ SIMPLE_GIT_PATH_OPTIONS
49
63
  };
@@ -6,8 +6,10 @@ const os = require('os');
6
6
  const { getConfigDir, DEFAULT_CHECKOUT_TIMEOUT_MS } = require('../config');
7
7
  const { WorktreeRepository, generateWorktreeId } = require('../database');
8
8
  const { getGeneratedFilePatterns } = require('./gitattributes');
9
- const { normalizeRepository, resolveRenamedFile, resolveRenamedFileOld } = require('../utils/paths');
10
- const { GIT_DIFF_FLAGS_ARRAY, GIT_DIFF_SUMMARY_FLAGS_ARRAY } = require('./diff-flags');
9
+ const { normalizeRepository } = require('../utils/paths');
10
+ const { buildChangedFileEntries } = require('../utils/diff-file-list');
11
+ const { decodeGitPath } = require('../utils/git-paths');
12
+ const { GIT_DIFF_FLAGS_ARRAY, SIMPLE_GIT_PATH_OPTIONS } = require('./diff-flags');
11
13
  const { rawFetchNoTags, fetchWithPruneRecovery } = require('./fetch-helpers');
12
14
  const { spawn, execSync } = require('child_process');
13
15
 
@@ -39,7 +41,7 @@ class GitWorktreeManager {
39
41
  * @returns {import('simple-git').SimpleGit}
40
42
  */
41
43
  _gitFor(dirPath) {
42
- return simpleGit(dirPath);
44
+ return simpleGit(dirPath, SIMPLE_GIT_PATH_OPTIONS);
43
45
  }
44
46
 
45
47
  /**
@@ -873,48 +875,21 @@ class GitWorktreeManager {
873
875
  }
874
876
 
875
877
  /**
876
- * Get list of changed files in the PR
877
- * @param {string} worktreePath - Path to worktree
878
- * @param {Object} prData - PR data from GitHub API
878
+ * Get list of changed files in the PR, built from its unified diff.
879
+ *
880
+ * The diff is the one source of PR paths: renames come from its explicit
881
+ * `rename from` / `rename to` lines and counts from its hunks, so
882
+ * changed_files spells every file exactly like the diff headers the
883
+ * browser keys on (see buildChangedFileEntries).
884
+ *
885
+ * @param {string} worktreePath - Path to worktree (for .gitattributes)
886
+ * @param {string} diff - Unified diff from generateUnifiedDiff
879
887
  * @returns {Promise<Array>} Array of changed file information
880
888
  */
881
- async getChangedFiles(worktreePath, prData) {
889
+ async getChangedFiles(worktreePath, diff) {
882
890
  try {
883
- const git = this._gitFor(worktreePath);
884
- const baseSha = this.getPRBaseSha(prData);
885
- const headSha = this.getPRHeadSha(prData);
886
-
887
- await this.assertCommitAvailableLocally(git, baseSha, 'Base SHA');
888
- await this.assertCommitAvailableLocally(git, headSha, 'Head SHA');
889
-
890
- // Get file changes with stats using base SHA and head SHA
891
- // This ensures we get the exact files changed in the PR, even if the base branch has moved
892
- const diffSummary = await git.diffSummary([
893
- `${baseSha}...${headSha}`,
894
- ...GIT_DIFF_SUMMARY_FLAGS_ARRAY
895
- ]);
896
-
897
- // Parse .gitattributes to identify generated files
898
891
  const gitattributes = await getGeneratedFilePatterns(worktreePath);
899
-
900
- return diffSummary.files.map(file => {
901
- const resolvedFile = resolveRenamedFile(file.file);
902
- const isRenamed = resolvedFile !== file.file;
903
- const result = {
904
- file: resolvedFile,
905
- insertions: file.insertions,
906
- deletions: file.deletions,
907
- changes: file.changes,
908
- binary: file.binary || false,
909
- generated: gitattributes.isGenerated(resolvedFile)
910
- };
911
- if (isRenamed) {
912
- result.renamed = true;
913
- result.renamedFrom = resolveRenamedFileOld(file.file);
914
- }
915
- return result;
916
- });
917
-
892
+ return buildChangedFileEntries(diff, gitattributes);
918
893
  } catch (error) {
919
894
  console.error('Error getting changed files:', error);
920
895
  throw this.wrapError('Failed to get changed files', error);
@@ -1449,9 +1424,12 @@ class GitWorktreeManager {
1449
1424
  */
1450
1425
  async getSparseCheckoutPatterns(repoPath) {
1451
1426
  try {
1452
- const git = simpleGit(repoPath);
1427
+ // `sparse-checkout list` C-quotes names like a diff header does:
1428
+ // core.quotePath=false keeps non-ASCII verbatim, and decodeGitPath
1429
+ // undoes the quoting git still applies to `"`, `\` and control chars.
1430
+ const git = this._gitFor(repoPath);
1453
1431
  const output = await git.raw(['sparse-checkout', 'list']);
1454
- return output.trim().split('\n').filter(Boolean);
1432
+ return output.split('\n').filter(Boolean).map(decodeGitPath);
1455
1433
  } catch {
1456
1434
  return [];
1457
1435
  }
@@ -986,94 +986,6 @@ class GitHubClient {
986
986
  }
987
987
  }
988
988
 
989
- /**
990
- * Calculate diff position for a given file path and line number
991
- * Position is counted from the first @@ hunk header, where position 1 = first line after @@
992
- * @param {string} diffContent - The unified diff content
993
- * @param {string} filePath - File path to find in diff
994
- * @param {number} lineNumber - Line number in the new file
995
- * @returns {number} Diff position or -1 if not found
996
- */
997
- calculateDiffPosition(diffContent, filePath, lineNumber) {
998
- if (!diffContent || !filePath || lineNumber === undefined) {
999
- console.warn('calculateDiffPosition: Missing required parameters', {
1000
- filePath,
1001
- lineNumber,
1002
- hasDiffContent: !!diffContent
1003
- });
1004
- return -1;
1005
- }
1006
-
1007
- const lines = diffContent.split('\n');
1008
- let inFile = false;
1009
- let currentFile = '';
1010
- let position = 0;
1011
- let newLineNumber = 0;
1012
- let foundHunk = false;
1013
-
1014
- for (let i = 0; i < lines.length; i++) {
1015
- const line = lines[i];
1016
-
1017
- if (line.startsWith('diff --git')) {
1018
- const match = line.match(/diff --git a\/(.+) b\/(.+)/);
1019
- if (match) {
1020
- currentFile = match[2];
1021
- inFile = currentFile === filePath;
1022
- position = 0;
1023
- newLineNumber = 0;
1024
- foundHunk = false;
1025
- }
1026
- continue;
1027
- }
1028
-
1029
- if (!inFile) continue;
1030
-
1031
- if (line.startsWith('@@')) {
1032
- const match = line.match(/@@ -\d+,?\d* \+(\d+),?\d* @@/);
1033
- if (match) {
1034
- newLineNumber = parseInt(match[1]) - 1;
1035
-
1036
- if (!foundHunk) {
1037
- position = 0;
1038
- foundHunk = true;
1039
- } else {
1040
- position++;
1041
- }
1042
- }
1043
- continue;
1044
- }
1045
-
1046
- if (!foundHunk) continue;
1047
-
1048
- const isDiffContentLine = line.startsWith('+') || line.startsWith('-') || line.startsWith(' ') || (line === '' && foundHunk);
1049
-
1050
- if (!isDiffContentLine) continue;
1051
-
1052
- position++;
1053
-
1054
- if (line.startsWith('+')) {
1055
- newLineNumber++;
1056
- if (newLineNumber === lineNumber) {
1057
- return position;
1058
- }
1059
- } else if (line.startsWith(' ') || (line === '' && foundHunk)) {
1060
- newLineNumber++;
1061
- if (newLineNumber === lineNumber) {
1062
- return position;
1063
- }
1064
- }
1065
- }
1066
-
1067
- console.warn('calculateDiffPosition: Position not found', {
1068
- filePath,
1069
- lineNumber,
1070
- inFile,
1071
- foundHunk,
1072
- finalNewLineNumber: newLineNumber
1073
- });
1074
- return -1;
1075
- }
1076
-
1077
989
  /**
1078
990
  * Handle errors specific to review submission
1079
991
  * @param {Error} error - The API error
@@ -45,7 +45,11 @@ function buildBatchMutation(batch) {
45
45
  }
46
46
 
47
47
  const side = comment.side || 'RIGHT';
48
- const startLineField = comment.start_line ? `startLine: ${comment.start_line}\n ` : '';
48
+ // A range sends its start side too: GitHub defaults startSide to RIGHT,
49
+ // which breaks a LEFT-side (deleted lines) range.
50
+ const startLineField = comment.start_line
51
+ ? `startLine: ${comment.start_line}\n startSide: ${comment.start_side || side}\n `
52
+ : '';
49
53
  return `
50
54
  comment${index}: addPullRequestReviewThread(input: {
51
55
  pullRequestId: $prId
@@ -7,7 +7,9 @@ const logger = require('../../../utils/logger');
7
7
  * GitHub's REST API does not support adding inline comments to a *pending*
8
8
  * draft review (the `addPullRequestReviewThread` GraphQL mutation has no
9
9
  * REST equivalent). Alt-hosts that advertise a compatible extension expose
10
- * this via a single HTTP POST that accepts a batch of comments.
10
+ * this through a review-comments endpoint. The generic contract accepts a
11
+ * batch of comments in one POST. Hosts that accept one comment per POST can
12
+ * set `features.pending_review_comments_batch` to `false`.
11
13
  *
12
14
  * Documented generic contract:
13
15
  *
@@ -49,16 +51,23 @@ const logger = require('../../../utils/logger');
49
51
  * placeholders. The template must be a relative path (starting with
50
52
  * `/repos/` or similar) — absolute URLs are rejected at config validation.
51
53
  *
54
+ * Request shape: `features.pending_review_comments_batch` defaults to `true`.
55
+ * When set to `false`, each wire comment is sent as the complete request body
56
+ * in its own POST. This supports hosts whose review-comments extension is
57
+ * singular while preserving the generic batch contract by default. Any 2xx
58
+ * counts as success and the response body is ignored. A 400/422 fails only
59
+ * that comment; any other failure stops the loop and reports the remaining
60
+ * comments as skipped.
61
+ *
52
62
  * Note on `reviewId`: this argument is the *host's* review identifier
53
63
  * (e.g. a numeric REST id), not a GraphQL node id. The REST/host
54
64
  * `review_lifecycle` impl (Phase 4) returns this id when it creates the
55
65
  * pending review; the caller passes it through unchanged.
56
66
  *
57
67
  * Note on `batchSize`: the original parameter is kept in the signature
58
- * for API compatibility with the GraphQL impl, but the host endpoint
59
- * accepts arbitrary batch sizes in a single call. We send all comments
60
- * in one POST and let the server enforce its own limits. The argument
61
- * is otherwise ignored.
68
+ * for API compatibility with the GraphQL impl. It is ignored. Batch hosts
69
+ * receive all comments in one request. Singular hosts receive one request
70
+ * per comment.
62
71
  */
63
72
 
64
73
  const DEFAULT_ENDPOINT_TEMPLATE =
@@ -161,7 +170,8 @@ function toWireComment(comment, commitId) {
161
170
  * the binding token automatically.
162
171
  * @param {Object} features - Feature-flag object from the host binding.
163
172
  * May include `pending_review_comments_endpoint` to override the
164
- * default endpoint path.
173
+ * default endpoint path and `pending_review_comments_batch: false` for
174
+ * hosts that accept one comment per request.
165
175
  * @param {Object} prContext - `{ owner, repo, prNumber, headSha? }`.
166
176
  * Required — the host endpoint is path-shaped, so the GraphQL node IDs
167
177
  * are not sufficient on their own. `headSha` (the PR head SHA) is
@@ -237,17 +247,71 @@ async function addCommentsInBatches(octokit, features, prContext, reviewId, comm
237
247
  // field and let the host surface its own validation error.
238
248
  const commitId = prContext.headSha;
239
249
  const wireComments = comments.map((c) => toWireComment(c, commitId));
250
+ const useBatchRequest = !features || features.pending_review_comments_batch !== false;
240
251
  logger.info(
241
- `Posting ${wireComments.length} comment(s) to host endpoint ${endpoint}`
252
+ `Posting ${wireComments.length} comment(s) to host endpoint ${endpoint} ` +
253
+ `using ${useBatchRequest ? 'one batch request' : 'individual requests'}`
242
254
  );
243
255
 
256
+ const headers = {
257
+ 'content-type': 'application/json',
258
+ accept: 'application/json'
259
+ };
260
+
261
+ if (!useBatchRequest) {
262
+ let successCount = 0;
263
+ const failedDetails = [];
264
+ const locationOf = (c) => (c.line ? `${c.path}:${c.line}` : `${c.path}:file-level`);
265
+
266
+ for (let index = 0; index < wireComments.length; index++) {
267
+ try {
268
+ await octokit.request(`POST ${endpoint}`, {
269
+ headers,
270
+ data: wireComments[index]
271
+ });
272
+ successCount++;
273
+ } catch (error) {
274
+ const status = error && (error.status || error.statusCode);
275
+ const message = (error && error.message) || 'Unknown error';
276
+ const detail = `${locationOf(comments[index])} - ${status || 'network error'}: ${message}`;
277
+ failedDetails.push(detail);
278
+ logger.warn(`Host comment failed: ${detail}`);
279
+ // 400/422 reject this comment alone (e.g. a line outside the diff),
280
+ // so keep going and report every bad comment at once. Anything else
281
+ // (auth, a bad endpoint, rate limiting, server or network errors)
282
+ // shares the endpoint, review and credentials with the remaining
283
+ // comments and would fail them all, so stop here.
284
+ if (status !== 400 && status !== 422) {
285
+ for (const skipped of comments.slice(index + 1)) {
286
+ failedDetails.push(
287
+ `${locationOf(skipped)} - skipped after ${status || 'network error'}`
288
+ );
289
+ }
290
+ break;
291
+ }
292
+ }
293
+ }
294
+
295
+ if (failedDetails.length > 0) {
296
+ logger.error(
297
+ `Host pending_review_comments partial failure: ${successCount} added, ` +
298
+ `${failedDetails.length} failed`
299
+ );
300
+ } else {
301
+ logger.info(`Host pending_review_comments complete: ${successCount} comment(s) added`);
302
+ }
303
+
304
+ return {
305
+ successCount,
306
+ failed: failedDetails.length > 0,
307
+ failedDetails
308
+ };
309
+ }
310
+
244
311
  let response;
245
312
  try {
246
313
  response = await octokit.request(`POST ${endpoint}`, {
247
- headers: {
248
- 'content-type': 'application/json',
249
- accept: 'application/json'
250
- },
314
+ headers,
251
315
  data: { comments: wireComments }
252
316
  });
253
317
  } catch (error) {
@@ -0,0 +1,56 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const logger = require('../utils/logger');
3
+
4
+ /**
5
+ * Build the `prContext` handed to `createReviewGraphQL` /
6
+ * `createDraftReviewGraphQL` when a review is submitted to GitHub or an
7
+ * alt-host.
8
+ *
9
+ * Shared by both submit entry points so they cannot drift apart:
10
+ * - the web submit route (`POST /api/pr/:owner/:repo/:number/submit-review`
11
+ * in src/routes/pr.js)
12
+ * - headless `--ai-draft` / `--ai-review` (`performHeadlessReview` in
13
+ * src/main.js)
14
+ *
15
+ * `headSha` (the PR head SHA) is required by the host pending-review-comments
16
+ * path: GitHub-compatible alt-hosts validate each inline comment like
17
+ * `pulls.createReviewComment`, which rejects a missing `commit_id` with a 422.
18
+ * The GraphQL path on github.com ignores it (the pending review pins the
19
+ * commit implicitly), so threading it through is harmless there.
20
+ *
21
+ * `prData.head_sha` (the parsed `pr_metadata.pr_data` JSON) is the canonical
22
+ * source; `prMetadata.head_sha` is a fallback for records that expose it at
23
+ * the top level (as `PRMetadataRepository.getByPR` does). When neither is
24
+ * present the context carries `headSha: null` and a warning is logged so the
25
+ * resulting 422 is diagnosable.
26
+ *
27
+ * @param {Object} params
28
+ * @param {string} params.owner - Repository owner
29
+ * @param {string} params.repo - Repository name
30
+ * @param {number} params.prNumber - Pull request number
31
+ * @param {Object|null} [params.existingDraft] - The user's pending review, if
32
+ * any; its numeric `databaseId` becomes `reviewId` for REST/host paths
33
+ * @param {Object|null} [params.prData] - Parsed `pr_data` JSON
34
+ * @param {Object|null} [params.prMetadata] - The `pr_metadata` record
35
+ * @returns {{ owner: string, repo: string, prNumber: number, reviewId: (number|undefined), headSha: (string|null) }}
36
+ */
37
+ function buildSubmitPrContext({ owner, repo, prNumber, existingDraft = null, prData = null, prMetadata = null }) {
38
+ const headSha = prData?.head_sha || prMetadata?.head_sha || null;
39
+ if (!headSha) {
40
+ logger.warn(
41
+ `Submit review for ${owner}/${repo}#${prNumber}: PR head SHA is missing ` +
42
+ `(prData.head_sha and prMetadata.head_sha both absent). Host inline-comment ` +
43
+ `posting will likely fail with a 422 missing commit_id error.`
44
+ );
45
+ }
46
+
47
+ return {
48
+ owner,
49
+ repo,
50
+ prNumber,
51
+ reviewId: existingDraft?.databaseId,
52
+ headSha
53
+ };
54
+ }
55
+
56
+ module.exports = { buildSubmitPrContext };