@in-the-loop-labs/pair-review 5.3.7 → 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 (39) 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 +389 -13
  7. package/public/js/components/AIPanel.js +317 -99
  8. package/public/js/components/ReviewHistoryModal.js +294 -0
  9. package/public/js/components/ReviewModal.js +96 -7
  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 +2 -1
  13. package/public/js/modules/file-comment-manager.js +6 -2
  14. package/public/js/modules/pierre-bridge.js +35 -1
  15. package/public/js/modules/suggestion-manager.js +4 -1
  16. package/public/js/pr.js +174 -66
  17. package/public/js/utils/posted-comment.js +259 -14
  18. package/public/js/vendor/pierre-diffs-worker.js +41 -13485
  19. package/public/js/vendor/pierre-diffs.js +131 -1364
  20. package/public/pr.html +1 -0
  21. package/src/chat/api-reference.js +22 -2
  22. package/src/config.js +28 -4
  23. package/src/database.js +177 -56
  24. package/src/github/client.js +70 -15
  25. package/src/github/impl/graphql/pending-review-comments.js +50 -11
  26. package/src/github/impl/graphql/pending-review.js +8 -2
  27. package/src/github/impl/graphql/review-comment-edit.js +89 -0
  28. package/src/github/impl/host/pending-review-comments.js +41 -10
  29. package/src/github/impl/host/review-comment-edit.js +36 -0
  30. package/src/github/impl/rest/pending-review.js +6 -2
  31. package/src/github/impl/rest/review-comment-edit.js +44 -0
  32. package/src/github/impl/review-comment-edit-utils.js +45 -0
  33. package/src/github/operations/pending-review.js +4 -3
  34. package/src/github/operations/review-comment-edit.js +35 -0
  35. package/src/github/record-submission.js +78 -0
  36. package/src/github/update-posted-comment.js +115 -0
  37. package/src/main.js +24 -44
  38. package/src/routes/mcp.js +1 -0
  39. package/src/routes/pr.js +147 -106
package/src/routes/pr.js CHANGED
@@ -40,6 +40,8 @@ const simpleGit = require('simple-git');
40
40
  const { GIT_DIFF_FLAGS_ARRAY, SIMPLE_GIT_PATH_OPTIONS } = require('../git/diff-flags');
41
41
  const { walkPRStack, DEFAULT_TRUNK_BRANCHES } = require('../github/stack-walker');
42
42
  const { buildSubmitPrContext } = require('../github/submit-pr-context');
43
+ const { recordReviewSubmission, recordRetainedSubmission } = require('../github/record-submission');
44
+ const { updatePostedComment, listSubmissions } = require('../github/update-posted-comment');
43
45
  const summaryGenerator = require('../ai/summary-generator');
44
46
  const tourGenerator = require('../ai/tour-generator');
45
47
  const {
@@ -204,6 +206,66 @@ async function resolveBindingForRequest(req, repository) {
204
206
  return null;
205
207
  }
206
208
 
209
+ /**
210
+ * Resolve stale drafts before opening a short local transaction. Errors are
211
+ * retried on the next load; a confirmed missing review is treated as dismissed,
212
+ * never requeued. Postings stay intact and derive their state from these rows.
213
+ * @returns {Promise<boolean>} Whether any pending record changed state
214
+ */
215
+ async function reconcileStalePendingRecords(githubReviewRepo, records, githubClient, prContext,
216
+ { keepPendingOnError = true } = {}) {
217
+ const updates = [];
218
+ const lookups = new Map();
219
+ for (const record of records) {
220
+ let actualState = 'dismissed';
221
+ let data = null;
222
+ const lookupId = record.github_node_id || record.github_review_id;
223
+ if (githubClient && lookupId) {
224
+ const key = record.github_review_id || lookupId;
225
+ try {
226
+ if (!lookups.has(key)) {
227
+ const context = prContext ? { ...prContext, reviewId: record.github_review_id } : null;
228
+ lookups.set(key, githubClient.getReviewById(lookupId, context, { strict: true }));
229
+ }
230
+ data = await lookups.get(key);
231
+ if (data) {
232
+ actualState = data.state === 'PENDING' ? 'pending'
233
+ : data.state === 'DISMISSED' ? 'dismissed' : 'submitted';
234
+ }
235
+ } catch (error) {
236
+ logger.warn(`Error querying GitHub for old review ${lookupId}: ${error.message}`);
237
+ if (keepPendingOnError) continue;
238
+ }
239
+ } else if (keepPendingOnError) {
240
+ // Without a usable client/identity absence cannot be confirmed.
241
+ continue;
242
+ }
243
+ if (actualState === 'pending') continue;
244
+ const update = { state: actualState };
245
+ if (actualState === 'submitted' && data?.submittedAt) update.submitted_at = data.submittedAt;
246
+ updates.push({ record, update });
247
+ }
248
+ if (!updates.length) return false;
249
+
250
+ const changedReviews = new Set();
251
+ let changed = false;
252
+ await withTransaction(githubReviewRepo.db, async () => {
253
+ for (const { record, update } of updates) {
254
+ // A submit may have completed while the network lookups were in flight.
255
+ const current = await githubReviewRepo.getById(record.id);
256
+ if (current?.state !== 'pending') continue;
257
+ await githubReviewRepo.update(record.id, update);
258
+ changed = true;
259
+ if (record.review_id != null) changedReviews.add(record.review_id);
260
+ }
261
+ });
262
+ // Include the requesting tab: its initial comments fetch may have raced us.
263
+ for (const reviewId of changedReviews) {
264
+ broadcastReviewEvent(reviewId, { type: 'review:comments_changed' });
265
+ }
266
+ return changed;
267
+ }
268
+
207
269
  /**
208
270
  * Sync pending draft review from GitHub with local database
209
271
  *
@@ -234,10 +296,15 @@ async function syncPendingDraftFromGitHub(githubReviewRepo, reviewId, githubPend
234
296
  const githubDbIdStr = (githubPendingReview.databaseId !== undefined && githubPendingReview.databaseId !== null)
235
297
  ? String(githubPendingReview.databaseId)
236
298
  : null;
237
- const matchingRecord = existingPendingRecords.find(r =>
299
+ const matchesCurrentDraft = r =>
238
300
  (r.github_node_id && r.github_node_id === githubPendingReview.id) ||
239
- (githubDbIdStr !== null && r.github_review_id === githubDbIdStr)
240
- );
301
+ (githubDbIdStr !== null && r.github_review_id === githubDbIdStr);
302
+ const matchingRecord = existingPendingRecords.find(matchesCurrentDraft);
303
+ // Older drafts can remain stale even when we already know the current one.
304
+ // Exclude every duplicate of the current identity, not just the chosen row.
305
+ await reconcileStalePendingRecords(githubReviewRepo,
306
+ existingPendingRecords.filter(r => !matchesCurrentDraft(r)), githubClient, prContext,
307
+ { keepPendingOnError: false });
241
308
 
242
309
  let pendingDraft;
243
310
  if (matchingRecord) {
@@ -251,60 +318,6 @@ async function syncPendingDraftFromGitHub(githubReviewRepo, reviewId, githubPend
251
318
  pendingDraft = await githubReviewRepo.getById(matchingRecord.id);
252
319
  } else {
253
320
  // New draft from GitHub - create new record
254
- // Query GitHub for the actual state of old pending records
255
- for (const oldRecord of existingPendingRecords) {
256
- let actualState = 'dismissed'; // Default if we can't determine
257
- let githubReviewData = null;
258
-
259
- // On the GraphQL path the node id is the canonical identifier; on
260
- // the REST path the numeric id (`github_review_id`) is the only
261
- // value we may have. Run the lookup whenever we have either —
262
- // otherwise mark the record as dismissed without querying.
263
- const oldLookupId = oldRecord.github_node_id || oldRecord.github_review_id;
264
- if (githubClient && (oldRecord.github_node_id || oldRecord.github_review_id)) {
265
- try {
266
- // prContext carries the REST review id when available. The
267
- // GraphQL path ignores it. The github_review_id column holds
268
- // the numeric REST id we received when the draft was created.
269
- const reviewPrContext = prContext
270
- ? { ...prContext, reviewId: oldRecord.github_review_id }
271
- : null;
272
- githubReviewData = await githubClient.getReviewById(oldLookupId, reviewPrContext);
273
-
274
- if (githubReviewData) {
275
- // Map GitHub state to our local state
276
- // GitHub states: PENDING, APPROVED, CHANGES_REQUESTED, COMMENTED, DISMISSED
277
- // Our states: local, pending, submitted, dismissed
278
- if (githubReviewData.state === 'PENDING') {
279
- // This shouldn't happen (we have a different pending review now), but handle it
280
- actualState = 'pending';
281
- } else if (githubReviewData.state === 'DISMISSED') {
282
- actualState = 'dismissed';
283
- } else {
284
- // APPROVED, CHANGES_REQUESTED, COMMENTED all mean it was submitted
285
- actualState = 'submitted';
286
- }
287
- logger.debug(`Old review ${oldLookupId} actual state from GitHub: ${githubReviewData.state} -> ${actualState}`);
288
- } else {
289
- // Review not found on GitHub - treat as dismissed
290
- logger.debug(`Old review ${oldLookupId} not found on GitHub, marking as dismissed`);
291
- actualState = 'dismissed';
292
- }
293
- } catch (error) {
294
- // On error, default to dismissed (most likely scenario)
295
- logger.warn(`Error querying GitHub for old review ${oldLookupId}: ${error.message}, marking as dismissed`);
296
- actualState = 'dismissed';
297
- }
298
- }
299
-
300
- // Update the old record with the actual state and submitted_at if available
301
- const updateData = { state: actualState };
302
- if (actualState === 'submitted' && githubReviewData?.submittedAt) {
303
- updateData.submitted_at = githubReviewData.submittedAt;
304
- }
305
- await githubReviewRepo.update(oldRecord.id, updateData);
306
- }
307
-
308
321
  pendingDraft = await githubReviewRepo.create(reviewId, {
309
322
  github_review_id: String(githubPendingReview.databaseId),
310
323
  github_node_id: githubPendingReview.id,
@@ -403,6 +416,10 @@ router.get('/api/pr/:owner/:repo/:number', async (req, res) => {
403
416
  githubClient,
404
417
  { owner: repoOwner, repo: repoName, prNumber }
405
418
  );
419
+ } else {
420
+ await reconcileStalePendingRecords(githubReviewRepo,
421
+ await githubReviewRepo.findPendingByReviewId(review.id), githubClient,
422
+ { owner: repoOwner, repo: repoName, prNumber });
406
423
  }
407
424
  } catch (githubError) {
408
425
  // Log the error but don't fail the request - draft info is supplementary
@@ -1051,6 +1068,10 @@ router.get('/api/pr/:owner/:repo/:number/github-drafts', async (req, res) => {
1051
1068
  githubClient,
1052
1069
  { owner, repo, prNumber }
1053
1070
  );
1071
+ } else {
1072
+ await reconcileStalePendingRecords(githubReviewRepo,
1073
+ await githubReviewRepo.findPendingByReviewId(review.id), githubClient,
1074
+ { owner, repo, prNumber });
1054
1075
  }
1055
1076
  } catch (githubError) {
1056
1077
  // Log the error but don't fail the request - return local data only
@@ -1460,6 +1481,48 @@ router.get('/api/file-content-original/:fileName(*)', async (req, res) => {
1460
1481
  }
1461
1482
  });
1462
1483
 
1484
+ // Publication actions are PR-only. Local reviews have no host identity.
1485
+ router.get('/api/reviews/:id/submissions', async (req, res) => {
1486
+ try {
1487
+ const db = req.app.get('db');
1488
+ const review = await new ReviewRepository(db).getReview(Number(req.params.id));
1489
+ if (!review) return res.status(404).json({ error: 'Review not found' });
1490
+ if (!review.pr_number || !review.repository) return res.status(400).json({ error: 'Review history is only available in PR mode' });
1491
+ res.json({ submissions: await listSubmissions(db, review.id) });
1492
+ } catch (error) {
1493
+ logger.error('Error loading review history:', error);
1494
+ res.status(500).json({ error: 'Failed to load review history' });
1495
+ }
1496
+ });
1497
+
1498
+ router.post('/api/reviews/:id/comments/:commentId/update-on-github', async (req, res) => {
1499
+ try {
1500
+ const db = req.app.get('db');
1501
+ const comment = await new CommentRepository(db).getComment(Number(req.params.commentId), 'user');
1502
+ if (!comment || comment.review_id !== Number(req.params.id)) return res.status(404).json({ error: 'Comment not found' });
1503
+ const review = await new ReviewRepository(db).getReview(comment.review_id);
1504
+ if (!review?.pr_number || !review.repository) return res.status(400).json({ error: 'Updating on GitHub is only available in PR mode' });
1505
+ const [owner, repo] = review.repository.split('/');
1506
+ // Reuse the PR-aware resolver, including recorded alt-host evidence.
1507
+ const resolved = await resolveBindingForRequest({ app: req.app, params: { number: String(review.pr_number) } }, review.repository);
1508
+ if (!resolved) return res.status(401).json({ error: 'GitHub token not configured' });
1509
+ const updated = await updatePostedComment(db, { commentId: comment.id, owner, repo,
1510
+ pull_number: review.pr_number, githubClient: new GitHubClient(resolved.binding) },
1511
+ reviewId => broadcastReviewEvent(reviewId, { type: 'review:comments_changed' }, { sourceClientId: req.get('X-Client-Id') }));
1512
+ res.json({ success: true, comment: updated });
1513
+ } catch (error) {
1514
+ logger.error('Error updating posted comment:', error);
1515
+ const code = error.code === 'unresolved_identity' ? 'unresolved_identity'
1516
+ : error.status === 404 || error.code === 'not_found' ? 'not_found_on_github'
1517
+ : [403, 422].includes(error.status) || error.code === 'forbidden' ? 'forbidden' : 'update_failed';
1518
+ const status = error.status || (code === 'unresolved_identity' ? 409 : code === 'not_found_on_github' ? 404 : code === 'forbidden' ? 403 : 500);
1519
+ const message = code === 'not_found_on_github' ? 'The host could not find this comment. Nothing was posted.'
1520
+ : code === 'forbidden' ? 'The host refused this update. Check your permissions or whether the conversation is locked. Nothing was posted.'
1521
+ : error.message;
1522
+ res.status(status).json({ error: message, code, review_url: error.review_url });
1523
+ }
1524
+ });
1525
+
1463
1526
  /**
1464
1527
  * Submit review to GitHub
1465
1528
  */
@@ -1533,7 +1596,7 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1533
1596
  commit_sha,
1534
1597
  is_file_level
1535
1598
  FROM comments
1536
- WHERE review_id = ? AND source = 'user' AND status = 'active'
1599
+ WHERE review_id = ? AND source = 'user' AND ${CommentRepository.pendingCommentSql('comments')}
1537
1600
  ORDER BY file, line_start
1538
1601
  `, [review.id]);
1539
1602
 
@@ -1606,21 +1669,28 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1606
1669
  prMetadata
1607
1670
  });
1608
1671
 
1609
- if (event === 'DRAFT') {
1610
- // Delegate to createDraftReviewGraphQL (handles both new and existing drafts)
1611
- githubReview = await githubClient.createDraftReviewGraphQL(
1612
- prNodeId, body || '', graphqlComments, existingDraft?.id, submitPrContext
1613
- );
1614
- // When adding to an existing draft, use the existing URL and include prior comments in total count
1615
- if (existingDraft) {
1616
- githubReview.html_url = githubReview.html_url || existingDraft.url;
1617
- githubReview.comments_count = existingDraft.comments.totalCount + githubReview.comments_count;
1672
+ try {
1673
+ if (event === 'DRAFT') {
1674
+ // Delegate to createDraftReviewGraphQL (handles both new and existing drafts)
1675
+ githubReview = await githubClient.createDraftReviewGraphQL(
1676
+ prNodeId, body || '', graphqlComments, existingDraft?.id, submitPrContext
1677
+ );
1678
+ // When adding to an existing draft, use the existing URL and include prior comments in total count
1679
+ if (existingDraft) {
1680
+ githubReview.html_url = githubReview.html_url || existingDraft.url;
1681
+ githubReview.comments_count = existingDraft.comments.totalCount + githubReview.comments_count;
1682
+ }
1683
+ } else {
1684
+ // For non-drafts, create/use review, add comments, and submit
1685
+ githubReview = await githubClient.createReviewGraphQL(
1686
+ prNodeId, event, body || '', graphqlComments, existingDraft?.id, submitPrContext
1687
+ );
1618
1688
  }
1619
- } else {
1620
- // For non-drafts, create/use review, add comments, and submit
1621
- githubReview = await githubClient.createReviewGraphQL(
1622
- prNodeId, event, body || '', graphqlComments, existingDraft?.id, submitPrContext
1623
- );
1689
+ } catch (error) {
1690
+ await recordRetainedSubmission(db, error, {
1691
+ reviewId: review.id, body, existingDraft, sourceRows: comments, sentComments: graphqlComments
1692
+ }, () => broadcastReviewEvent(review.id, { type: 'review:comments_changed' }));
1693
+ throw error;
1624
1694
  }
1625
1695
 
1626
1696
  // ID storage strategy:
@@ -1629,11 +1699,6 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1629
1699
  // - reviewData JSON -> uses 'github_node_id' key for the GraphQL node ID
1630
1700
  // - reviews.review_id -> legacy column, no longer written (github_reviews table has taken over)
1631
1701
  const githubNodeId = String(githubReview.id); // GraphQL methods return node IDs
1632
- // Use databaseId from the mutation response, or fall back to existingDraft's databaseId
1633
- const githubDatabaseId = githubReview.databaseId
1634
- ? String(githubReview.databaseId)
1635
- : existingDraft ? String(existingDraft.databaseId) : null;
1636
-
1637
1702
  // Build review metadata for database storage
1638
1703
  const reviewData = {
1639
1704
  github_node_id: githubNodeId,
@@ -1665,37 +1730,12 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1665
1730
  reviewData: reviewData
1666
1731
  });
1667
1732
 
1668
- // Create a github_reviews record to track this submission
1669
- const githubReviewRepo = new GitHubReviewRepository(db);
1670
- await githubReviewRepo.create(review.id, {
1671
- github_review_id: githubDatabaseId,
1672
- github_node_id: githubNodeId,
1673
- state: event === 'DRAFT' ? 'pending' : 'submitted',
1674
- event: event === 'DRAFT' ? null : event,
1675
- body: body || '',
1676
- submitted_at: event === 'DRAFT' ? null : new Date().toISOString(),
1677
- github_url: githubReview.html_url
1733
+ await recordReviewSubmission(db, {
1734
+ reviewId: review.id, event, body, githubReview, existingDraft,
1735
+ sourceRows: comments, sentComments: graphqlComments,
1736
+ postedComments: githubReview.postedComments
1678
1737
  });
1679
1738
 
1680
- console.log(`${event === 'DRAFT' ? 'Draft review created' : 'Review submitted'} successfully: ${githubReview.html_url}${event === 'DRAFT' ? ' (Review ID: ' + githubReview.id + ')' : ''}`);
1681
-
1682
- // Update comments table to mark submitted comments
1683
- const commentStatus = event === 'DRAFT' ? 'draft' : 'submitted';
1684
- const commentUpdateTime = new Date().toISOString();
1685
- for (const comment of comments) {
1686
- await run(db, `
1687
- UPDATE comments
1688
- SET status = ?, updated_at = ?
1689
- WHERE id = ?
1690
- `, [commentStatus, commentUpdateTime, comment.id]);
1691
- }
1692
-
1693
- // Submitting a pending review publishes the comments saved to it
1694
- // earlier, which are still 'draft' locally.
1695
- if (event !== 'DRAFT' && existingDraft) {
1696
- await new CommentRepository(db).markDraftCommentsSubmitted(review.id, commentUpdateTime);
1697
- }
1698
-
1699
1739
  // Commit transaction
1700
1740
  await run(db, 'COMMIT');
1701
1741
 
@@ -2897,5 +2937,6 @@ module.exports = router;
2897
2937
  // absent) can be exercised directly without spinning up the route.
2898
2938
  module.exports._internals = {
2899
2939
  syncPendingDraftFromGitHub,
2940
+ reconcileStalePendingRecords,
2900
2941
  resolveBindingForRequest
2901
2942
  };