@in-the-loop-labs/pair-review 5.3.7 → 5.4.1

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 +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/index.html +1 -0
  8. package/public/js/components/AIPanel.js +317 -99
  9. package/public/js/components/AdvancedConfigTab.js +18 -108
  10. package/public/js/components/ReviewHistoryModal.js +294 -0
  11. package/public/js/components/ReviewModal.js +96 -7
  12. package/public/js/components/SplitButton.js +14 -0
  13. package/public/js/components/VoiceCentricConfigTab.js +18 -108
  14. package/public/js/index.js +18 -5
  15. package/public/js/local.js +4 -8
  16. package/public/js/modules/comment-manager.js +2 -1
  17. package/public/js/modules/diff-renderer.js +7 -6
  18. package/public/js/modules/file-comment-manager.js +6 -2
  19. package/public/js/modules/pierre-bridge.js +35 -1
  20. package/public/js/modules/suggestion-manager.js +4 -1
  21. package/public/js/pr.js +174 -66
  22. package/public/js/utils/council-timeout.js +203 -0
  23. package/public/js/utils/posted-comment.js +259 -14
  24. package/public/js/vendor/pierre-diffs-worker.js +41 -13485
  25. package/public/js/vendor/pierre-diffs.js +131 -1364
  26. package/public/local.html +4 -0
  27. package/public/pr.html +5 -0
  28. package/src/ai/copilot-provider.js +21 -2
  29. package/src/ai/cursor-agent-provider.js +21 -2
  30. package/src/ai/opencode-provider.js +21 -2
  31. package/src/chat/api-reference.js +22 -2
  32. package/src/config.js +28 -4
  33. package/src/database.js +416 -114
  34. package/src/git/worktree-pool-lifecycle.js +152 -33
  35. package/src/git/worktree-pool-usage.js +20 -0
  36. package/src/git/worktree.js +14 -5
  37. package/src/github/client.js +70 -15
  38. package/src/github/impl/graphql/pending-review-comments.js +50 -11
  39. package/src/github/impl/graphql/pending-review.js +8 -2
  40. package/src/github/impl/graphql/review-comment-edit.js +89 -0
  41. package/src/github/impl/host/pending-review-comments.js +41 -10
  42. package/src/github/impl/host/review-comment-edit.js +36 -0
  43. package/src/github/impl/rest/pending-review.js +6 -2
  44. package/src/github/impl/rest/review-comment-edit.js +44 -0
  45. package/src/github/impl/review-comment-edit-utils.js +45 -0
  46. package/src/github/operations/pending-review.js +4 -3
  47. package/src/github/operations/review-comment-edit.js +35 -0
  48. package/src/github/record-submission.js +78 -0
  49. package/src/github/update-posted-comment.js +115 -0
  50. package/src/main.js +42 -50
  51. package/src/routes/mcp.js +1 -0
  52. package/src/routes/pr.js +158 -120
  53. package/src/routes/reviews.js +8 -30
  54. package/src/routes/setup.js +22 -9
  55. package/src/setup/pr-setup.js +12 -3
  56. package/src/utils/diff-file-content.js +62 -25
  57. package/src/utils/json-extractor.js +267 -13
  58. package/src/utils/pr-file-blob-cache.js +134 -0
  59. package/src/utils/process-liveness.js +64 -0
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 {
@@ -57,7 +59,7 @@ const { safeParseJson } = require('../utils/safe-parse-json');
57
59
  const { mergeChangedFilesWithDiff, parseUnifiedDiffPatches, buildChangedFileEntries } = require('../utils/diff-file-list');
58
60
  const { parseHunks } = require('../utils/diff-hunks');
59
61
  const { hashHunk } = require('../ai/hunk-hashing');
60
- const { resolveOriginalFileContentSpecs } = require('../utils/diff-file-content');
62
+ const { getPRFileContentSpecs, invalidatePRFileBlobCache } = require('../utils/pr-file-blob-cache');
61
63
  const { validateCouncilConfig, normalizeCouncilConfig } = require('./councils');
62
64
  const { resolveReviewConfig } = require('../review-config');
63
65
  const { TIERS, TIER_ALIASES, VALID_TIERS, resolveTier } = require('../ai/prompts/config');
@@ -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
@@ -567,7 +584,7 @@ router.post('/api/pr/:owner/:repo/:number/refresh', async (req, res) => {
567
584
 
568
585
  // Check if PR exists in database
569
586
  const existingPR = await queryOne(db, `
570
- SELECT id FROM pr_metadata
587
+ SELECT id, pr_data FROM pr_metadata
571
588
  WHERE pr_number = ? AND repository = ? COLLATE NOCASE
572
589
  `, [prNumber, repository]);
573
590
 
@@ -622,8 +639,11 @@ router.post('/api/pr/:owner/:repo/:number/refresh', async (req, res) => {
622
639
  const diff = await worktreeManager.generateUnifiedDiff(worktreePath, diffPrData);
623
640
  const changedFiles = await worktreeManager.getChangedFiles(worktreePath, diff);
624
641
 
625
- // Prepare extended data
642
+ // Preserve review state and cached repository metadata, then overlay the
643
+ // fresh PR payload. Diff fields below use the locally generated results.
626
644
  const extendedData = {
645
+ ...safeParseJson(existingPR.pr_data, {}),
646
+ ...prData,
627
647
  state: prData.state,
628
648
  diff: diff,
629
649
  changed_files: changedFiles,
@@ -642,6 +662,7 @@ router.post('/api/pr/:owner/:repo/:number/refresh', async (req, res) => {
642
662
  SET
643
663
  title = ?,
644
664
  description = ?,
665
+ author = ?,
645
666
  base_branch = ?,
646
667
  head_branch = ?,
647
668
  updated_at = CURRENT_TIMESTAMP,
@@ -650,12 +671,14 @@ router.post('/api/pr/:owner/:repo/:number/refresh', async (req, res) => {
650
671
  `, [
651
672
  prData.title,
652
673
  prData.body || '',
674
+ prData.author,
653
675
  prData.base_branch,
654
676
  prData.head_branch,
655
677
  JSON.stringify(extendedData),
656
678
  prNumber,
657
679
  repository
658
680
  ]);
681
+ invalidatePRFileBlobCache(db, repository, prNumber);
659
682
 
660
683
  logger.info(`Successfully refreshed PR #${prNumber} for ${repository}`);
661
684
 
@@ -1051,6 +1074,10 @@ router.get('/api/pr/:owner/:repo/:number/github-drafts', async (req, res) => {
1051
1074
  githubClient,
1052
1075
  { owner, repo, prNumber }
1053
1076
  );
1077
+ } else {
1078
+ await reconcileStalePendingRecords(githubReviewRepo,
1079
+ await githubReviewRepo.findPendingByReviewId(review.id), githubClient,
1080
+ { owner, repo, prNumber });
1054
1081
  }
1055
1082
  } catch (githubError) {
1056
1083
  // Log the error but don't fail the request - return local data only
@@ -1380,17 +1407,7 @@ router.get('/api/file-content-original/:fileName(*)', async (req, res) => {
1380
1407
  // Prefer the exact blob from the cached diff snapshot. If that is unavailable,
1381
1408
  // fall back to repo-wide base_sha and finally the worktree filesystem.
1382
1409
  const repository = normalizeRepository(owner, repo);
1383
- const prRecord = await queryOne(db, `
1384
- SELECT pr_data FROM pr_metadata
1385
- WHERE pr_number = ? AND repository = ? COLLATE NOCASE
1386
- `, [prNumber, repository]);
1387
-
1388
- const prData = safeParseJson(prRecord?.pr_data, null);
1389
- if (prRecord?.pr_data && !prData) {
1390
- logger.warn('Could not parse pr_data for file-content route');
1391
- }
1392
-
1393
- const contentSpecs = resolveOriginalFileContentSpecs(prData, fileName);
1410
+ const contentSpecs = getPRFileContentSpecs(db, repository, prNumber, fileName);
1394
1411
 
1395
1412
  if (contentSpecs.length > 0) {
1396
1413
  try {
@@ -1460,6 +1477,48 @@ router.get('/api/file-content-original/:fileName(*)', async (req, res) => {
1460
1477
  }
1461
1478
  });
1462
1479
 
1480
+ // Publication actions are PR-only. Local reviews have no host identity.
1481
+ router.get('/api/reviews/:id/submissions', async (req, res) => {
1482
+ try {
1483
+ const db = req.app.get('db');
1484
+ const review = await new ReviewRepository(db).getReview(Number(req.params.id));
1485
+ if (!review) return res.status(404).json({ error: 'Review not found' });
1486
+ if (!review.pr_number || !review.repository) return res.status(400).json({ error: 'Review history is only available in PR mode' });
1487
+ res.json({ submissions: await listSubmissions(db, review.id) });
1488
+ } catch (error) {
1489
+ logger.error('Error loading review history:', error);
1490
+ res.status(500).json({ error: 'Failed to load review history' });
1491
+ }
1492
+ });
1493
+
1494
+ router.post('/api/reviews/:id/comments/:commentId/update-on-github', async (req, res) => {
1495
+ try {
1496
+ const db = req.app.get('db');
1497
+ const comment = await new CommentRepository(db).getComment(Number(req.params.commentId), 'user');
1498
+ if (!comment || comment.review_id !== Number(req.params.id)) return res.status(404).json({ error: 'Comment not found' });
1499
+ const review = await new ReviewRepository(db).getReview(comment.review_id);
1500
+ if (!review?.pr_number || !review.repository) return res.status(400).json({ error: 'Updating on GitHub is only available in PR mode' });
1501
+ const [owner, repo] = review.repository.split('/');
1502
+ // Reuse the PR-aware resolver, including recorded alt-host evidence.
1503
+ const resolved = await resolveBindingForRequest({ app: req.app, params: { number: String(review.pr_number) } }, review.repository);
1504
+ if (!resolved) return res.status(401).json({ error: 'GitHub token not configured' });
1505
+ const updated = await updatePostedComment(db, { commentId: comment.id, owner, repo,
1506
+ pull_number: review.pr_number, githubClient: new GitHubClient(resolved.binding) },
1507
+ reviewId => broadcastReviewEvent(reviewId, { type: 'review:comments_changed' }, { sourceClientId: req.get('X-Client-Id') }));
1508
+ res.json({ success: true, comment: updated });
1509
+ } catch (error) {
1510
+ logger.error('Error updating posted comment:', error);
1511
+ const code = error.code === 'unresolved_identity' ? 'unresolved_identity'
1512
+ : error.status === 404 || error.code === 'not_found' ? 'not_found_on_github'
1513
+ : [403, 422].includes(error.status) || error.code === 'forbidden' ? 'forbidden' : 'update_failed';
1514
+ const status = error.status || (code === 'unresolved_identity' ? 409 : code === 'not_found_on_github' ? 404 : code === 'forbidden' ? 403 : 500);
1515
+ const message = code === 'not_found_on_github' ? 'The host could not find this comment. Nothing was posted.'
1516
+ : code === 'forbidden' ? 'The host refused this update. Check your permissions or whether the conversation is locked. Nothing was posted.'
1517
+ : error.message;
1518
+ res.status(status).json({ error: message, code, review_url: error.review_url });
1519
+ }
1520
+ });
1521
+
1463
1522
  /**
1464
1523
  * Submit review to GitHub
1465
1524
  */
@@ -1533,7 +1592,7 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1533
1592
  commit_sha,
1534
1593
  is_file_level
1535
1594
  FROM comments
1536
- WHERE review_id = ? AND source = 'user' AND status = 'active'
1595
+ WHERE review_id = ? AND source = 'user' AND ${CommentRepository.pendingCommentSql('comments')}
1537
1596
  ORDER BY file, line_start
1538
1597
  `, [review.id]);
1539
1598
 
@@ -1606,21 +1665,28 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1606
1665
  prMetadata
1607
1666
  });
1608
1667
 
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;
1668
+ try {
1669
+ if (event === 'DRAFT') {
1670
+ // Delegate to createDraftReviewGraphQL (handles both new and existing drafts)
1671
+ githubReview = await githubClient.createDraftReviewGraphQL(
1672
+ prNodeId, body || '', graphqlComments, existingDraft?.id, submitPrContext
1673
+ );
1674
+ // When adding to an existing draft, use the existing URL and include prior comments in total count
1675
+ if (existingDraft) {
1676
+ githubReview.html_url = githubReview.html_url || existingDraft.url;
1677
+ githubReview.comments_count = existingDraft.comments.totalCount + githubReview.comments_count;
1678
+ }
1679
+ } else {
1680
+ // For non-drafts, create/use review, add comments, and submit
1681
+ githubReview = await githubClient.createReviewGraphQL(
1682
+ prNodeId, event, body || '', graphqlComments, existingDraft?.id, submitPrContext
1683
+ );
1618
1684
  }
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
- );
1685
+ } catch (error) {
1686
+ await recordRetainedSubmission(db, error, {
1687
+ reviewId: review.id, body, existingDraft, sourceRows: comments, sentComments: graphqlComments
1688
+ }, () => broadcastReviewEvent(review.id, { type: 'review:comments_changed' }));
1689
+ throw error;
1624
1690
  }
1625
1691
 
1626
1692
  // ID storage strategy:
@@ -1629,11 +1695,6 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1629
1695
  // - reviewData JSON -> uses 'github_node_id' key for the GraphQL node ID
1630
1696
  // - reviews.review_id -> legacy column, no longer written (github_reviews table has taken over)
1631
1697
  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
1698
  // Build review metadata for database storage
1638
1699
  const reviewData = {
1639
1700
  github_node_id: githubNodeId,
@@ -1665,37 +1726,12 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1665
1726
  reviewData: reviewData
1666
1727
  });
1667
1728
 
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
1729
+ await recordReviewSubmission(db, {
1730
+ reviewId: review.id, event, body, githubReview, existingDraft,
1731
+ sourceRows: comments, sentComments: graphqlComments,
1732
+ postedComments: githubReview.postedComments
1678
1733
  });
1679
1734
 
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
1735
  // Commit transaction
1700
1736
  await run(db, 'COMMIT');
1701
1737
 
@@ -1867,6 +1903,7 @@ router.post('/api/pr/:owner/:repo/:number/files/viewed', async (req, res) => {
1867
1903
  SET pr_data = ?, updated_at = CURRENT_TIMESTAMP
1868
1904
  WHERE pr_number = ? AND repository = ? COLLATE NOCASE
1869
1905
  `, [JSON.stringify(prData), prNumber, repository]);
1906
+ invalidatePRFileBlobCache(db, repository, prNumber);
1870
1907
 
1871
1908
  res.json({
1872
1909
  success: true,
@@ -2897,5 +2934,6 @@ module.exports = router;
2897
2934
  // absent) can be exercised directly without spinning up the route.
2898
2935
  module.exports._internals = {
2899
2936
  syncPendingDraftFromGitHub,
2937
+ reconcileStalePendingRecords,
2900
2938
  resolveBindingForRequest
2901
2939
  };
@@ -22,7 +22,7 @@ const { GitWorktreeManager } = require('../git/worktree');
22
22
  const { normalizeRepository } = require('../utils/paths');
23
23
  const { resolveFormat, formatAdoptedComment: formatComment } = require('../utils/comment-formatter');
24
24
  const { safeParseJson } = require('../utils/safe-parse-json');
25
- const { resolveOriginalFileContentSpecs } = require('../utils/diff-file-content');
25
+ const { getPRFileContentSpecs } = require('../utils/pr-file-blob-cache');
26
26
  const validateReviewId = require('./middleware/validate-review-id');
27
27
  const { reviewScope, scopeIncludes, includesBranch } = require('../local-scope');
28
28
  const { findMergeBase } = require('../local-review');
@@ -30,8 +30,8 @@ const { findMergeBase } = require('../local-review');
30
30
  const router = express.Router();
31
31
 
32
32
  /**
33
- * Resolve the worktree path and base_sha for a PR-mode review.
34
- * Returns { worktreePath, baseSha } or throws with { status, error } on failure.
33
+ * Resolve the worktree path and normalized repository for a PR-mode review.
34
+ * Returns { worktreePath, prNumber, repository } or throws with { statusCode } on failure.
35
35
  */
36
36
  async function resolveWorktreeForReview(review, db) {
37
37
  const prNumber = review.pr_number;
@@ -54,19 +54,7 @@ async function resolveWorktreeForReview(review, db) {
54
54
 
55
55
  const worktreePath = await worktreeManager.getWorktreePath({ owner, repo, number: prNumber });
56
56
 
57
- // Load cached PR metadata so callers can resolve exact diff blobs.
58
- const normalizedRepo = normalizeRepository(owner, repo);
59
- const prRecord = await queryOne(db, `
60
- SELECT pr_data FROM pr_metadata
61
- WHERE pr_number = ? AND repository = ? COLLATE NOCASE
62
- `, [prNumber, normalizedRepo]);
63
-
64
- const prData = safeParseJson(prRecord?.pr_data, null);
65
- if (prRecord?.pr_data && !prData) {
66
- logger.warn('Could not parse pr_data for review');
67
- }
68
-
69
- return { worktreePath, prData };
57
+ return { worktreePath, prNumber, repository: normalizeRepository(owner, repo) };
70
58
  }
71
59
 
72
60
  /**
@@ -1059,17 +1047,7 @@ router.get('/api/reviews/:reviewId/file-content/:fileName(*)', validateReviewId,
1059
1047
  // Prefer the exact blob from the cached diff snapshot. If that is unavailable,
1060
1048
  // fall back to repo-wide base_sha and finally the worktree filesystem.
1061
1049
  const normalizedRepo = normalizeRepository(owner, repo);
1062
- const prRecord = await queryOne(db, `
1063
- SELECT pr_data FROM pr_metadata
1064
- WHERE pr_number = ? AND repository = ? COLLATE NOCASE
1065
- `, [prNumber, normalizedRepo]);
1066
-
1067
- const prData = safeParseJson(prRecord?.pr_data, null);
1068
- if (prRecord?.pr_data && !prData) {
1069
- logger.warn('Could not parse pr_data for file-content route');
1070
- }
1071
-
1072
- const contentSpecs = resolveOriginalFileContentSpecs(prData, fileName);
1050
+ const contentSpecs = getPRFileContentSpecs(db, normalizedRepo, prNumber, fileName);
1073
1051
 
1074
1052
  if (contentSpecs.length > 0) {
1075
1053
  try {
@@ -1368,9 +1346,9 @@ router.get('/api/reviews/:reviewId/file-contents/:fileName(*)', validateReviewId
1368
1346
  }
1369
1347
 
1370
1348
  // --- PR mode ---
1371
- let worktreePath, prData;
1349
+ let worktreePath, prNumber, repository;
1372
1350
  try {
1373
- ({ worktreePath, prData } = await resolveWorktreeForReview(review, db));
1351
+ ({ worktreePath, prNumber, repository } = await resolveWorktreeForReview(review, db));
1374
1352
  } catch (resolveErr) {
1375
1353
  return res.status(resolveErr.statusCode || 500).json({ error: resolveErr.message });
1376
1354
  }
@@ -1378,7 +1356,7 @@ router.get('/api/reviews/:reviewId/file-contents/:fileName(*)', validateReviewId
1378
1356
  if (status !== 'added') {
1379
1357
  // Prefer the exact blob from the cached diff snapshot; fall back to base_sha.
1380
1358
  // Matches the /file-content endpoint so both stay consistent with stale PR metadata.
1381
- const contentSpecs = resolveOriginalFileContentSpecs(prData, oldFilePath);
1359
+ const contentSpecs = getPRFileContentSpecs(db, repository, prNumber, oldFilePath);
1382
1360
  for (const contentSpec of contentSpecs) {
1383
1361
  const content = await gitShow(worktreePath, contentSpec.gitSpec);
1384
1362
  if (content != null) {
@@ -167,7 +167,7 @@ router.post('/api/setup/pr/:owner/:repo/:number', async (req, res) => {
167
167
  const repository = normalizeRepository(owner, repo);
168
168
  const existingPR = await queryOne(
169
169
  db,
170
- 'SELECT id, pr_data FROM pr_metadata WHERE pr_number = ? AND repository = ? COLLATE NOCASE',
170
+ 'SELECT id, title, description, author, base_branch, head_branch, pr_data FROM pr_metadata WHERE pr_number = ? AND repository = ? COLLATE NOCASE',
171
171
  [prNumber, repository]
172
172
  );
173
173
  if (existingPR) {
@@ -186,15 +186,21 @@ router.post('/api/setup/pr/:owner/:repo/:number', async (req, res) => {
186
186
  const poolEntry = poolLifecycle ? await poolLifecycle.poolRepo.getPoolEntry(worktree.id) : null;
187
187
  if (poolEntry && poolEntry.status !== 'in_use') {
188
188
  if (poolEntry.status === 'available' && poolEntry.current_pr_number === prNumber) {
189
- // Still associated with this PR — reclaim without re-setup
189
+ // Still associated with this PR — reclaim without re-setup. The
190
+ // reclaim is atomic and conditional: another process sharing this
191
+ // database may have claimed the row since the read above.
190
192
  logger.info(`Reclaiming pool worktree ${worktree.id} for ${repository} #${prNumber} (was ${poolEntry.status})`);
191
- await poolLifecycle.poolRepo.markInUse(poolEntry.id, prNumber);
192
- const reviewRepo = new ReviewRepository(db);
193
- const { review } = await reviewRepo.getOrCreate({ prNumber, repository });
194
- await poolLifecycle.poolRepo.setCurrentReviewId(poolEntry.id, review.id);
195
- return res.json({ existing: true, reviewUrl: `/pr/${owner}/${repo}/${prNumber}` });
193
+ const reclaimed = await poolLifecycle.reclaimForPR(poolEntry.id, prNumber);
194
+ if (reclaimed) {
195
+ const reviewRepo = new ReviewRepository(db);
196
+ const { review } = await reviewRepo.getOrCreate({ prNumber, repository });
197
+ await poolLifecycle.poolRepo.setCurrentReviewId(poolEntry.id, review.id);
198
+ return res.json({ existing: true, reviewUrl: `/pr/${owner}/${repo}/${prNumber}` });
199
+ }
200
+ logger.info(`Pool worktree ${worktree.id} was claimed by another process before it could be reclaimed for ${repository} #${prNumber}, re-running setup to reacquire`);
201
+ } else {
202
+ logger.info(`Pool worktree ${worktree.id} for ${repository} #${prNumber} is ${poolEntry.status}, re-running setup to reacquire`);
196
203
  }
197
- logger.info(`Pool worktree ${worktree.id} for ${repository} #${prNumber} is ${poolEntry.status}, re-running setup to reacquire`);
198
204
  } else {
199
205
  return res.json({ existing: true, reviewUrl: `/pr/${owner}/${repo}/${prNumber}` });
200
206
  }
@@ -210,7 +216,14 @@ router.post('/api/setup/pr/:owner/:repo/:number', async (req, res) => {
210
216
  try {
211
217
  const parsed = JSON.parse(existingPR.pr_data);
212
218
  if (parsed.head_sha) {
213
- restoreMetadata = parsed;
219
+ restoreMetadata = {
220
+ ...parsed,
221
+ title: parsed.title ?? existingPR.title,
222
+ body: parsed.body ?? existingPR.description,
223
+ author: parsed.author ?? existingPR.author,
224
+ base_branch: parsed.base_branch ?? existingPR.base_branch,
225
+ head_branch: parsed.head_branch ?? existingPR.head_branch
226
+ };
214
227
  }
215
228
  } catch (e) {
216
229
  logger.warn(`Could not parse stored pr_data for ${repository} #${prNumber}`);
@@ -20,6 +20,7 @@ const { findMainGitRoot } = require('../local-review');
20
20
  const { getConfigDir, getRepoPath, resolveRepoOptions, resolvePoolConfig, getRepoResetScript, resolveHostBinding, resolveBindingRepositoryFromPR, getRepoConfig, getRepoCloneUrlForHost, DEFAULT_CHECKOUT_TIMEOUT_MS } = require('../config');
21
21
  const { storedHostToOption, isDualHostRepoConfig, resolveRecordedHost, bindingRepositoryForHost } = require('../utils/host-resolution');
22
22
  const logger = require('../utils/logger');
23
+ const { invalidatePRFileBlobCache } = require('../utils/pr-file-blob-cache');
23
24
  const { fireReviewStartedHook } = require('../hooks/payloads');
24
25
  const simpleGit = require('simple-git');
25
26
  const fs = require('fs').promises;
@@ -231,6 +232,10 @@ async function storePRData(db, prInfo, prData, diff, changedFiles, worktreePath,
231
232
  await run(db, 'ROLLBACK');
232
233
  logger.error('Error storing PR data:', error);
233
234
  throw new Error(`Failed to store PR data: ${error.message}`);
235
+ } finally {
236
+ // pr_data may have changed (or a lookup may have cached uncommitted rows
237
+ // mid-transaction), so drop the file-content blob cache once it settles.
238
+ invalidatePRFileBlobCache(db, repository, prInfo.number);
234
239
  }
235
240
  }
236
241
 
@@ -810,7 +815,7 @@ async function setupPRReview({ db, owner, repo, prNumber, githubToken, bindingRe
810
815
  await worktreeRepo.getOrCreate({
811
816
  prNumber,
812
817
  repository,
813
- branch: prData.head_branch || prData.head?.ref || '',
818
+ branch: worktreeManager.getPRHeadBranch(prData),
814
819
  path: worktreePath
815
820
  });
816
821
  }
@@ -948,8 +953,12 @@ async function setupPRReview({ db, owner, repo, prNumber, githubToken, bindingRe
948
953
  // mechanism can never fire to reclaim it.
949
954
  if (poolWorktreeId && poolLifecycle) {
950
955
  try {
951
- await poolLifecycle.releaseAfterHeadless(poolWorktreeId);
952
- logger.info(`Released pool worktree ${poolWorktreeId} after setup failure`);
956
+ const released = await poolLifecycle.releaseAfterHeadless(poolWorktreeId);
957
+ if (released) {
958
+ logger.info(`Released pool worktree ${poolWorktreeId} after setup failure`);
959
+ } else {
960
+ logger.info(`Pool worktree ${poolWorktreeId} not released after setup failure: no longer held by this process`);
961
+ }
953
962
  } catch (releaseErr) {
954
963
  logger.error(`Failed to release pool worktree ${poolWorktreeId} after setup failure: ${releaseErr.message}`);
955
964
  }