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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +8 -0
  2. package/package.json +3 -3
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
  5. package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
  6. package/public/css/pr.css +407 -13
  7. package/public/js/components/AIPanel.js +323 -104
  8. package/public/js/components/ReviewHistoryModal.js +294 -0
  9. package/public/js/components/ReviewModal.js +131 -14
  10. package/public/js/components/SplitButton.js +14 -0
  11. package/public/js/local.js +4 -8
  12. package/public/js/modules/comment-manager.js +6 -12
  13. package/public/js/modules/comment-minimizer.js +4 -1
  14. package/public/js/modules/file-comment-manager.js +38 -74
  15. package/public/js/modules/pierre-bridge.js +36 -0
  16. package/public/js/modules/suggestion-manager.js +4 -1
  17. package/public/js/pr.js +337 -191
  18. package/public/js/utils/posted-comment.js +326 -0
  19. package/public/js/vendor/pierre-diffs-worker.js +41 -13485
  20. package/public/js/vendor/pierre-diffs.js +131 -1364
  21. package/public/local.html +1 -0
  22. package/public/pr.html +2 -0
  23. package/src/chat/api-reference.js +22 -2
  24. package/src/config.js +28 -4
  25. package/src/database.js +177 -35
  26. package/src/github/client.js +95 -16
  27. package/src/github/impl/graphql/pending-review-comments.js +118 -14
  28. package/src/github/impl/graphql/pending-review.js +8 -2
  29. package/src/github/impl/graphql/review-comment-edit.js +89 -0
  30. package/src/github/impl/host/pending-review-comments.js +41 -10
  31. package/src/github/impl/host/review-comment-edit.js +36 -0
  32. package/src/github/impl/rest/pending-review.js +6 -2
  33. package/src/github/impl/rest/review-comment-edit.js +44 -0
  34. package/src/github/impl/review-comment-edit-utils.js +45 -0
  35. package/src/github/operations/pending-review.js +4 -3
  36. package/src/github/operations/review-comment-edit.js +35 -0
  37. package/src/github/record-submission.js +78 -0
  38. package/src/github/update-posted-comment.js +115 -0
  39. package/src/main.js +24 -38
  40. package/src/routes/mcp.js +1 -0
  41. package/src/routes/pr.js +152 -100
@@ -55,7 +55,8 @@ const logger = require('../../../utils/logger');
55
55
  * When set to `false`, each wire comment is sent as the complete request body
56
56
  * in its own POST. This supports hosts whose review-comments extension is
57
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
58
+ * counts as success; optional response ids/URL are captured in `posted`.
59
+ * A 400/422 fails only
59
60
  * that comment; any other failure stops the loop and reports the remaining
60
61
  * comments as skipped.
61
62
  *
@@ -182,11 +183,11 @@ function toWireComment(comment, commitId) {
182
183
  * @param {Array} comments - Comments with `{ path, line?, start_line?,
183
184
  * side?, body, isFileLevel? }`. Same shape the GraphQL impl accepts.
184
185
  * @param {number} [_batchSize] - Ignored; kept for signature parity.
185
- * @returns {Promise<{successCount: number, failed: boolean, failedDetails: string[]}>}
186
+ * @returns {Promise<{successCount: number, failed: boolean, failedDetails: string[], posted: Array|null}>}
186
187
  */
187
188
  async function addCommentsInBatches(octokit, features, prContext, reviewId, comments, _batchSize) {
188
189
  if (!comments || comments.length === 0) {
189
- return { successCount: 0, failed: false, failedDetails: [] };
190
+ return { successCount: 0, failed: false, failedDetails: [], posted: [] };
190
191
  }
191
192
 
192
193
  if (!prContext || typeof prContext !== 'object') {
@@ -261,15 +262,23 @@ async function addCommentsInBatches(octokit, features, prContext, reviewId, comm
261
262
  if (!useBatchRequest) {
262
263
  let successCount = 0;
263
264
  const failedDetails = [];
265
+ let posted = [];
264
266
  const locationOf = (c) => (c.line ? `${c.path}:${c.line}` : `${c.path}:file-level`);
265
267
 
266
268
  for (let index = 0; index < wireComments.length; index++) {
267
269
  try {
268
- await octokit.request(`POST ${endpoint}`, {
270
+ const response = await octokit.request(`POST ${endpoint}`, {
269
271
  headers,
270
272
  data: wireComments[index]
271
273
  });
272
274
  successCount++;
275
+ const data = response?.data;
276
+ posted.push({
277
+ index,
278
+ github_comment_id: data?.id != null ? String(data.id) : null,
279
+ github_comment_node_id: data?.node_id ?? null,
280
+ github_comment_url: data?.html_url ?? null
281
+ });
273
282
  } catch (error) {
274
283
  const status = error && (error.status || error.statusCode);
275
284
  const message = (error && error.message) || 'Unknown error';
@@ -282,6 +291,9 @@ async function addCommentsInBatches(octokit, features, prContext, reviewId, comm
282
291
  // shares the endpoint, review and credentials with the remaining
283
292
  // comments and would fail them all, so stop here.
284
293
  if (status !== 400 && status !== 422) {
294
+ // A lost response/server error may have attached this comment.
295
+ // The subset is unknown, unlike an explicit validation rejection.
296
+ posted = null;
285
297
  for (const skipped of comments.slice(index + 1)) {
286
298
  failedDetails.push(
287
299
  `${locationOf(skipped)} - skipped after ${status || 'network error'}`
@@ -304,7 +316,8 @@ async function addCommentsInBatches(octokit, features, prContext, reviewId, comm
304
316
  return {
305
317
  successCount,
306
318
  failed: failedDetails.length > 0,
307
- failedDetails
319
+ failedDetails,
320
+ posted
308
321
  };
309
322
  }
310
323
 
@@ -333,7 +346,8 @@ async function addCommentsInBatches(octokit, features, prContext, reviewId, comm
333
346
  return {
334
347
  successCount: 0,
335
348
  failed: true,
336
- failedDetails
349
+ failedDetails,
350
+ posted: null
337
351
  };
338
352
  }
339
353
 
@@ -348,7 +362,7 @@ async function addCommentsInBatches(octokit, features, prContext, reviewId, comm
348
362
 
349
363
  const failedDetails = [];
350
364
  for (const entry of failedList) {
351
- const idx = typeof entry.index === 'number' ? entry.index : null;
365
+ const idx = typeof entry?.index === 'number' ? entry.index : null;
352
366
  const errMsg = (entry && (entry.error_message || entry.message)) || 'Unknown error';
353
367
  const source = idx !== null && idx >= 0 && idx < comments.length ? comments[idx] : null;
354
368
  const location = source
@@ -358,10 +372,25 @@ async function addCommentsInBatches(octokit, features, prContext, reviewId, comm
358
372
  logger.warn(`Host comment failed: ${location} - ${errMsg}`);
359
373
  }
360
374
 
375
+ // Only infer the complement when every failure has a unique valid index
376
+ // and the host explicitly accounts for every submitted comment. No ids
377
+ // are inferred from an undocumented batch response shape.
378
+ const failedIndexes = new Set(failedList.map(entry => entry?.index));
379
+ const knownSubset = hasExplicitAdded && Number.isInteger(added) && added >= 0 &&
380
+ added + failedList.length === comments.length &&
381
+ failedIndexes.size === failedList.length &&
382
+ [...failedIndexes].every(index => Number.isInteger(index) && index >= 0 && index < comments.length);
383
+ const posted = knownSubset
384
+ ? comments.flatMap((_, index) => failedIndexes.has(index) ? [] : [{
385
+ index, github_comment_id: null, github_comment_node_id: null, github_comment_url: null
386
+ }])
387
+ : null;
388
+
361
389
  // Sanity check: if the host reported an explicit count, the accounted-
362
390
  // for items (added + failed) should equal the total submitted. If they
363
391
  // don't, the host response is internally inconsistent — log a warning
364
- // but still trust the explicit counts.
392
+ // but preserve the legacy explicit counts. `posted` remains null: callers
393
+ // must not use these counts to guess which comments were attached.
365
394
  if (hasExplicitAdded && added + failedList.length !== comments.length) {
366
395
  logger.warn(
367
396
  `Host pending_review_comments inconsistent counts: added=${added}, ` +
@@ -376,7 +405,8 @@ async function addCommentsInBatches(octokit, features, prContext, reviewId, comm
376
405
  return {
377
406
  successCount: added,
378
407
  failed: true,
379
- failedDetails
408
+ failedDetails,
409
+ posted
380
410
  };
381
411
  }
382
412
 
@@ -388,7 +418,8 @@ async function addCommentsInBatches(octokit, features, prContext, reviewId, comm
388
418
  return {
389
419
  successCount,
390
420
  failed: false,
391
- failedDetails: []
421
+ failedDetails: [],
422
+ posted
392
423
  };
393
424
  }
394
425
 
@@ -0,0 +1,36 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const { requireFields, normalizeComment, updateResult } = require('../review-comment-edit-utils');
3
+ const { commentId, reviewId } = require('../rest/review-comment-edit');
4
+
5
+ const UPDATE_ENDPOINT = '/repos/{owner}/{repo}/pulls/comments/{comment_id}';
6
+ const LIST_ENDPOINT = '/repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments';
7
+
8
+ function endpoint(template, values) {
9
+ // Defense in depth: never allow endpoint configuration to send credentials
10
+ // outside the bound host, even when constructed without config validation.
11
+ if (typeof template !== 'string' || !template.startsWith('/') || template.startsWith('//') || /[\\\r\n]/.test(template)) {
12
+ throw new Error('review_comment_edit endpoint must be a relative path');
13
+ }
14
+ return template.replace(/\{(owner|repo|pull_number|comment_id|review_id)\}/g, (_match, key) => {
15
+ requireFields(values, [key]);
16
+ return encodeURIComponent(String(values[key]));
17
+ });
18
+ }
19
+
20
+ async function updateReviewComment(octokit, features, ref, body) {
21
+ requireFields(ref, ['owner', 'repo']);
22
+ const id = await commentId(octokit, ref);
23
+ const path = endpoint(features.review_comment_edit_endpoint || UPDATE_ENDPOINT, { ...ref, comment_id: id });
24
+ const { data } = await octokit.request(`PATCH ${path}`, { body });
25
+ return updateResult(data);
26
+ }
27
+
28
+ async function listCommentsForReview(octokit, features, ref) {
29
+ requireFields(ref, ['owner', 'repo', 'pull_number']);
30
+ const id = await reviewId(octokit, ref);
31
+ const path = endpoint(features.review_comment_edit_list_endpoint || LIST_ENDPOINT, { ...ref, review_id: id });
32
+ const rows = await octokit.paginate(`GET ${path}`, { per_page: 100 });
33
+ return rows.map(normalizeComment);
34
+ }
35
+
36
+ module.exports = { updateReviewComment, listCommentsForReview };
@@ -187,9 +187,10 @@ async function getPendingReviewForUser(octokit, owner, repo, prNumber) {
187
187
  * @param {Object} octokit
188
188
  * @param {string|number} nodeId - GraphQL node id OR numeric review id
189
189
  * @param {Object} prContext - { owner, repo, prNumber, reviewId? }
190
+ * @param {Object} [options] - { strict?: boolean }, propagate non-404 failures
190
191
  * @returns {Promise<Object|null>}
191
192
  */
192
- async function getReviewById(octokit, nodeId, prContext) {
193
+ async function getReviewById(octokit, nodeId, prContext, { strict = false } = {}) {
193
194
  if (!prContext || !prContext.owner || !prContext.repo || !prContext.prNumber) {
194
195
  throw new Error(
195
196
  'REST getReviewById requires prContext={owner, repo, prNumber}. ' +
@@ -210,7 +211,9 @@ async function getReviewById(octokit, nodeId, prContext) {
210
211
  } else {
211
212
  // No usable numeric id — surface a clear error rather than calling
212
213
  // the REST API with a GraphQL node id (which would 404).
213
- logger.warn(`REST getReviewById called with non-numeric id "${nodeId}" and no prContext.reviewId`);
214
+ const message = `REST getReviewById called with non-numeric id "${nodeId}" and no prContext.reviewId`;
215
+ logger.warn(message);
216
+ if (strict) throw new Error(message);
214
217
  return null;
215
218
  }
216
219
  }
@@ -237,6 +240,7 @@ async function getReviewById(octokit, nodeId, prContext) {
237
240
  return null;
238
241
  }
239
242
  logger.warn(`Error fetching review ${reviewId} via REST: ${error.message}`);
243
+ if (strict) throw error;
240
244
  return null;
241
245
  }
242
246
  }
@@ -0,0 +1,44 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const { failure, requireFields, normalizeComment, updateResult } = require('../review-comment-edit-utils');
3
+
4
+ // A node-only ref is resolved with a read, never by posting a replacement.
5
+ async function commentId(octokit, ref) {
6
+ if (ref?.github_comment_id) return String(ref.github_comment_id);
7
+ requireFields(ref, ['github_comment_node_id']);
8
+ const result = await octokit.graphql(`query($id: ID!) {
9
+ node(id: $id) { ... on PullRequestReviewComment { fullDatabaseId } }
10
+ }`, { id: ref.github_comment_node_id });
11
+ if (!result.node?.fullDatabaseId) throw failure('not_found', 'Review comment not found');
12
+ return String(result.node.fullDatabaseId);
13
+ }
14
+
15
+ async function reviewId(octokit, ref) {
16
+ if (ref?.github_review_id) return String(ref.github_review_id);
17
+ requireFields(ref, ['github_node_id']);
18
+ const result = await octokit.graphql(`query($id: ID!) {
19
+ node(id: $id) { ... on PullRequestReview { fullDatabaseId } }
20
+ }`, { id: ref.github_node_id });
21
+ if (!result.node?.fullDatabaseId) throw failure('not_found', 'Review not found');
22
+ return String(result.node.fullDatabaseId);
23
+ }
24
+
25
+ async function updateReviewComment(octokit, ref, body) {
26
+ requireFields(ref, ['owner', 'repo']);
27
+ const id = await commentId(octokit, ref);
28
+ const { data } = await octokit.rest.pulls.updateReviewComment({
29
+ owner: ref.owner, repo: ref.repo, comment_id: id, body
30
+ });
31
+ return updateResult(data);
32
+ }
33
+
34
+ async function listCommentsForReview(octokit, ref) {
35
+ requireFields(ref, ['owner', 'repo', 'pull_number']);
36
+ const id = await reviewId(octokit, ref);
37
+ const rows = await octokit.paginate(octokit.rest.pulls.listCommentsForReview, {
38
+ owner: ref.owner, repo: ref.repo, pull_number: ref.pull_number,
39
+ review_id: id, per_page: 100
40
+ });
41
+ return rows.map(normalizeComment);
42
+ }
43
+
44
+ module.exports = { updateReviewComment, listCommentsForReview, commentId, reviewId };
@@ -0,0 +1,45 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const stringId = value => value == null ? null : String(value);
3
+
4
+ function failure(code, message) {
5
+ return Object.assign(new Error(message), { code });
6
+ }
7
+
8
+ function requireFields(ref, fields) {
9
+ for (const field of fields) {
10
+ if (ref?.[field] == null || ref[field] === '') {
11
+ throw failure('invalid_ref', `Review comment reference requires ${field}`);
12
+ }
13
+ }
14
+ }
15
+
16
+ function normalizeComment(row) {
17
+ const id = stringId(row.id ?? row.github_comment_id);
18
+ const nodeId = row.node_id ?? row.github_comment_node_id ?? null;
19
+ const url = row.html_url ?? row.github_comment_url ?? null;
20
+ const login = row.user?.login ?? row.author_login ?? null;
21
+ return {
22
+ id, node_id: nodeId, html_url: url, user: { login },
23
+ github_comment_id: id, github_comment_node_id: nodeId,
24
+ github_comment_url: url, author_login: login,
25
+ in_reply_to_id: stringId(row.in_reply_to_id),
26
+ path: row.path, line: row.line ?? null, start_line: row.start_line ?? null,
27
+ side: row.side ?? null, start_side: row.start_side ?? null,
28
+ original_line: row.original_line ?? null,
29
+ original_start_line: row.original_start_line ?? null,
30
+ subject_type: row.subject_type ?? null,
31
+ body: row.body, created_at: row.created_at ?? null
32
+ };
33
+ }
34
+
35
+ function updateResult(row) {
36
+ const normalized = normalizeComment(row);
37
+ return {
38
+ github_comment_id: normalized.github_comment_id,
39
+ github_comment_node_id: normalized.github_comment_node_id,
40
+ github_comment_url: normalized.github_comment_url,
41
+ body: normalized.body
42
+ };
43
+ }
44
+
45
+ module.exports = { stringId, failure, requireFields, normalizeComment, updateResult };
@@ -65,15 +65,16 @@ async function getPendingReviewForUser(octokit, features, owner, repo, prNumber)
65
65
  * REQUIRED when `features.pending_review_check === "rest"` because the
66
66
  * REST endpoint identifies a review by (owner, repo, pull_number,
67
67
  * review_id) rather than by node id. Optional for the GraphQL path.
68
+ * @param {Object} [options] - { strict?: boolean }, propagate non-not-found failures
68
69
  * @returns {Promise<Object|null>}
69
70
  */
70
- async function getReviewById(octokit, features, nodeId, prContext) {
71
+ async function getReviewById(octokit, features, nodeId, prContext, options) {
71
72
  const mode = selectFeature(features);
72
73
  if (mode === 'graphql') {
73
- return graphqlImpl.getReviewById(octokit, nodeId);
74
+ return graphqlImpl.getReviewById(octokit, nodeId, options);
74
75
  }
75
76
  if (mode === 'rest') {
76
- return restImpl.getReviewById(octokit, nodeId, prContext);
77
+ return restImpl.getReviewById(octokit, nodeId, prContext, options);
77
78
  }
78
79
  if (mode === 'host') {
79
80
  throw new Error('Host implementation for pending_review_check not yet available (Phase 5)');
@@ -0,0 +1,35 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const graphqlImpl = require('../impl/graphql/review-comment-edit');
3
+ const restImpl = require('../impl/rest/review-comment-edit');
4
+ const hostImpl = require('../impl/host/review-comment-edit');
5
+
6
+ const AREA = 'review_comment_edit';
7
+ const IMPLEMENTED_MODES = new Set(['graphql', 'rest', 'host']);
8
+
9
+ async function dispatch(method, octokit, features, ref, body) {
10
+ const mode = features?.[AREA] || 'graphql';
11
+ try {
12
+ if (mode === 'graphql') return await graphqlImpl[method](octokit, ref, body);
13
+ if (mode === 'rest') return await restImpl[method](octokit, ref, body);
14
+ if (mode === 'host') return await hostImpl[method](octokit, features, ref, body);
15
+ throw new Error(`Unknown features.${AREA} value: "${mode}"`);
16
+ } catch (error) {
17
+ const types = (error.errors || []).map(item => item.type ?? item.extensions?.code);
18
+ const status = error.status ?? error.response?.status;
19
+ // Octokit's legacy `code` can be the numeric HTTP status; never let it
20
+ // override the stable operation codes (and avoid that deprecated getter).
21
+ const code = status === 404 || types.includes('NOT_FOUND') ? 'not_found' :
22
+ status === 403 || status === 422 || types.some(type => ['FORBIDDEN', 'UNPROCESSABLE', 'UNPROCESSABLE_ENTITY'].includes(type)) ? 'forbidden' :
23
+ status ? undefined : error.code;
24
+ const wrapped = new Error(`${method} (${mode}): ${error.message}`, { cause: error });
25
+ if (code) wrapped.code = code;
26
+ if (status) wrapped.status = status;
27
+ throw wrapped;
28
+ }
29
+ }
30
+
31
+ module.exports = {
32
+ AREA, IMPLEMENTED_MODES,
33
+ updateReviewComment: (octokit, features, ref, body) => dispatch('updateReviewComment', octokit, features, ref, body),
34
+ listCommentsForReview: (octokit, features, ref) => dispatch('listCommentsForReview', octokit, features, ref)
35
+ };
@@ -0,0 +1,78 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const { GitHubReviewRepository, CommentPostingRepository, run } = require('../database');
3
+ const logger = require('../utils/logger');
4
+
5
+ /** Record the exact attached subset, inside the caller's short transaction. */
6
+ async function recordReviewSubmission(db, {
7
+ reviewId, event, body, githubReview, existingDraft = null,
8
+ sourceRows, sentComments, postedComments, postedAt = new Date().toISOString()
9
+ }) {
10
+ const review = await new GitHubReviewRepository(db).upsertForSubmission(reviewId, {
11
+ github_node_id: githubReview.id == null ? null : String(githubReview.id),
12
+ github_review_id: githubReview.databaseId == null
13
+ ? (existingDraft?.databaseId == null ? null : String(existingDraft.databaseId))
14
+ : String(githubReview.databaseId),
15
+ state: event === 'DRAFT' ? 'pending' : 'submitted',
16
+ event: event === 'DRAFT' ? null : event,
17
+ body: body || '', submitted_at: event === 'DRAFT' ? null : postedAt,
18
+ github_url: githubReview.html_url || existingDraft?.url || null
19
+ });
20
+ // A successful submission with unknown per-comment accounting keeps the
21
+ // historical all-sent contract, preventing silent reposts on the next submit.
22
+ // Failure callers only invoke this helper with an explicit known subset.
23
+ const posted = postedComments == null
24
+ ? sentComments.map((_, index) => ({ index })) : postedComments;
25
+ const postings = posted.map(p => {
26
+ const sent = sentComments[p.index];
27
+ const source = sourceRows[p.index];
28
+ if (!sent || !source) throw new Error(`Invalid posted comment index: ${p.index}`);
29
+ return {
30
+ comment_id: source.id, github_review_row_id: review.id,
31
+ comment_body: source.body, body: sent.body, file: sent.path,
32
+ line_start: sent.start_line ?? sent.line, line_end: sent.line,
33
+ side: sent.side, is_file_level: sent.isFileLevel,
34
+ github_comment_id: p.github_comment_id,
35
+ github_comment_node_id: p.github_comment_node_id,
36
+ github_comment_url: p.github_comment_url, posted_at: postedAt
37
+ };
38
+ });
39
+ await new CommentPostingRepository(db).insertMany(postings);
40
+ // Headless suggestions have a terminal disposition, not user lifecycle.
41
+ for (const p of postings) {
42
+ await run(db, "UPDATE comments SET status = 'submitted', updated_at = ? WHERE id = ? AND source = 'ai'",
43
+ [postedAt, p.comment_id]);
44
+ }
45
+ return review.id;
46
+ }
47
+
48
+ /** The API call has already failed; persist only its known, retained subset. */
49
+ async function recordRetainedSubmission(db, error, args, afterCommit = () => {}) {
50
+ if (!error.reviewRetained) return;
51
+ if (Array.isArray(error.postedComments) && error.postedComments.length) {
52
+ let began = false;
53
+ try {
54
+ await run(db, 'BEGIN TRANSACTION');
55
+ began = true;
56
+ await recordReviewSubmission(db, {
57
+ ...args, event: 'DRAFT', githubReview: error.pendingReview,
58
+ postedComments: error.postedComments
59
+ });
60
+ await run(db, 'COMMIT');
61
+ began = false;
62
+ } catch (dbError) {
63
+ if (began) {
64
+ try { await run(db, 'ROLLBACK'); }
65
+ catch (rollbackError) { logger.error('Failed to roll back retained-posting bookkeeping:', rollbackError); }
66
+ }
67
+ logger.error('Failed to record retained GitHub comment postings:', dbError);
68
+ error.message += ' Recording the retained comments locally failed; check the pending review on GitHub before resubmitting.';
69
+ throw error;
70
+ }
71
+ afterCommit();
72
+ error.message += ` ${error.postedComments.length} of ${args.sentComments.length} comments were added to your pending review on GitHub and are marked as such.`;
73
+ } else if (error.postedComments === null) {
74
+ error.message += ' The added subset is unknown; check the pending review on GitHub before resubmitting.';
75
+ }
76
+ }
77
+
78
+ module.exports = { recordReviewSubmission, recordRetainedSubmission };
@@ -0,0 +1,115 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const { query, queryOne, run, withTransaction, CommentRepository, CommentPostingRepository } = require('../database');
3
+ const { buildReviewComments } = require('../utils/diff-annotator');
4
+
5
+ /** Exact wire identity, never a fuzzy body/line search. Replies cannot match roots. */
6
+ function matchesPosting(candidate, posting, login) {
7
+ if (!login || !candidate.user?.login || candidate.user.login.toLowerCase() !== login.toLowerCase() ||
8
+ candidate.in_reply_to_id != null || candidate.path !== posting.file || candidate.body !== posting.body) return false;
9
+ if (posting.is_file_level) return candidate.subject_type === 'file';
10
+ if (candidate.subject_type === 'file') return false;
11
+ // GitHub shifts current coordinates as commits land, even before a comment
12
+ // becomes outdated. Original coordinates identify the anchor we sent.
13
+ const line = candidate.original_line;
14
+ const start = candidate.original_start_line;
15
+ const expectedEnd = posting.line_end ?? posting.line_start;
16
+ if (expectedEnd == null || line == null) return false;
17
+ const expectedStart = posting.line_start === expectedEnd ? null : posting.line_start;
18
+ return line === expectedEnd && (start ?? null) === (expectedStart ?? null) &&
19
+ candidate.side === (posting.side || 'RIGHT') &&
20
+ (candidate.start_side ?? null) === (expectedStart == null ? null : (posting.side || 'RIGHT'));
21
+ }
22
+
23
+ function identityError(posting) {
24
+ return Object.assign(new Error("Couldn't find this comment on GitHub. Nothing was posted."), {
25
+ status: 409, code: 'unresolved_identity', review_url: posting.review_url
26
+ });
27
+ }
28
+
29
+ /** Network work precedes the short bookkeeping transaction; there is NO create fallback. */
30
+ async function updatePostedComment(db, { commentId, githubClient, owner, repo, pull_number }, afterCommit = () => {}) {
31
+ const comments = new CommentRepository(db);
32
+ const comment = await comments.getComment(commentId, 'user');
33
+ if (!comment?.publication) throw Object.assign(new Error('Comment has not been posted'), { status: 400 });
34
+ const posting = await queryOne(db, `SELECT p.*, gr.github_review_id, gr.github_node_id,
35
+ gr.github_url AS review_url, gr.state AS review_state FROM comment_postings p
36
+ LEFT JOIN github_reviews gr ON gr.id = p.github_review_row_id
37
+ WHERE p.comment_id = ? ORDER BY p.id DESC LIMIT 1`, [commentId]);
38
+ const ref = { owner, repo, pull_number, github_comment_id: posting.github_comment_id,
39
+ github_comment_node_id: posting.github_comment_node_id, github_review_id: posting.github_review_id,
40
+ github_node_id: posting.github_node_id };
41
+ // Each adapter can resolve the other ID form through a read-only lookup.
42
+ const hasUsableId = ref.github_comment_node_id || ref.github_comment_id;
43
+ let recovered = null;
44
+ if (!hasUsableId) {
45
+ const user = await githubClient.getAuthenticatedUser();
46
+ const trustedReview = !posting.backfilled && (ref.github_review_id || ref.github_node_id);
47
+ // PR-wide lists omit unpublished comments. Never search them for a draft.
48
+ if (!trustedReview && posting.review_state === 'pending') throw identityError(posting);
49
+ const candidates = trustedReview
50
+ ? await githubClient.listCommentsForReview(ref)
51
+ : await githubClient.listReviewComments({ owner, repo, pull_number });
52
+ const matches = [];
53
+ for (const candidate of candidates.filter(c => matchesPosting(c, posting, user.login))) {
54
+ // A legacy PR-wide search can otherwise mistake another locally known
55
+ // comment for this one when the original copy was deleted on the host.
56
+ const claimed = await queryOne(db, `SELECT 1 FROM comment_postings WHERE comment_id != ? AND
57
+ ((? IS NOT NULL AND github_comment_id = ?) OR (? IS NOT NULL AND github_comment_node_id = ?)) LIMIT 1`,
58
+ [commentId, candidate.id == null ? null : String(candidate.id), candidate.id == null ? null : String(candidate.id),
59
+ candidate.node_id ?? null, candidate.node_id ?? null]);
60
+ if (!claimed) matches.push(candidate);
61
+ }
62
+ if (matches.length !== 1) throw identityError(posting);
63
+ const match = matches[0];
64
+ recovered = { id: match.id == null ? null : String(match.id), node: match.node_id || null,
65
+ url: match.html_url || null };
66
+ ref.github_comment_id = recovered.id;
67
+ ref.github_comment_node_id = recovered.node;
68
+ if (!recovered.node && !recovered.id) throw identityError(posting);
69
+ // Repair survives even an update rejection, so the next attempt targets the same comment.
70
+ await run(db, `UPDATE comment_postings SET github_comment_id = ?, github_comment_node_id = ?,
71
+ github_comment_url = COALESCE(?, github_comment_url) WHERE comment_id = ?`,
72
+ [recovered.id, recovered.node, recovered.url, commentId]);
73
+ }
74
+ // An edit cannot move the host anchor. Preserve the posted shape rather
75
+ // than recalculating inline vs file fallback against today's diff. User
76
+ // bodies already include any configured adoption formatting.
77
+ const sent = posting.is_file_level
78
+ ? buildReviewComments([comment], '')[0] : { body: comment.body };
79
+ const result = await githubClient.updateReviewComment(ref, sent.body);
80
+ const ids = { id: result?.github_comment_id || ref.github_comment_id,
81
+ node: result?.github_comment_node_id || ref.github_comment_node_id,
82
+ url: result?.github_comment_url || recovered?.url || posting.github_comment_url };
83
+ await withTransaction(db, async () => {
84
+ await run(db, `UPDATE comment_postings SET github_comment_id = ?, github_comment_node_id = ?,
85
+ github_comment_url = COALESCE(?, github_comment_url) WHERE comment_id = ?`,
86
+ [ids.id, ids.node, ids.url, commentId]);
87
+ await new CommentPostingRepository(db).insertMany([{ ...posting, id: undefined,
88
+ github_comment_id: ids.id, github_comment_node_id: ids.node,
89
+ github_comment_url: ids.url,
90
+ comment_body: comment.body, body: sent.body, kind: 'update',
91
+ posted_at: new Date().toISOString() }]);
92
+ });
93
+ afterCommit(comment.review_id);
94
+ return comments.getComment(commentId, 'user');
95
+ }
96
+
97
+ /** Group old duplicate review identities while retaining every posting and lifecycle. */
98
+ async function listSubmissions(db, reviewId) {
99
+ const reviews = await query(db, 'SELECT * FROM github_reviews WHERE review_id = ? ORDER BY id DESC', [reviewId]);
100
+ const postings = await query(db, `SELECT p.*, c.status, c.status AS comment_status FROM comment_postings p
101
+ JOIN comments c ON c.id = p.comment_id WHERE c.review_id = ? ORDER BY p.id`, [reviewId]);
102
+ const groups = [];
103
+ for (const review of reviews) {
104
+ let group = groups.find(g => (review.github_node_id && g.github_node_id === review.github_node_id) ||
105
+ (review.github_review_id && g.github_review_id === review.github_review_id));
106
+ if (!group) { group = { ...review, postings: [] }; groups.push(group); }
107
+ group.postings.push(...postings.filter(p => p.github_review_row_id === review.id));
108
+ }
109
+ for (const group of groups) group.postings.sort((a, b) => a.id - b.id);
110
+ const unknown = postings.filter(p => p.github_review_row_id == null);
111
+ if (unknown.length) groups.push({ id: null, state: 'submitted', event: null, body: '', postings: unknown });
112
+ return groups;
113
+ }
114
+
115
+ module.exports = { matchesPosting, updatePostedComment, listSubmissions };