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

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 (35) hide show
  1. package/README.md +3 -3
  2. package/package.json +2 -2
  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/index.html +4 -0
  7. package/public/js/components/AdvancedConfigTab.js +18 -108
  8. package/public/js/components/VoiceCentricConfigTab.js +18 -108
  9. package/public/js/index.js +47 -5
  10. package/public/js/modules/diff-renderer.js +7 -6
  11. package/public/js/utils/council-timeout.js +203 -0
  12. package/public/local.html +4 -0
  13. package/public/pr.html +4 -0
  14. package/src/ai/antigravity-provider.js +76 -35
  15. package/src/ai/claude-provider.js +115 -39
  16. package/src/ai/codex-provider.js +19 -24
  17. package/src/ai/copilot-provider.js +59 -48
  18. package/src/ai/cursor-agent-provider.js +95 -133
  19. package/src/ai/opencode-provider.js +21 -2
  20. package/src/ai/provider.js +3 -3
  21. package/src/chat/session-manager.js +1 -1
  22. package/src/database.js +240 -59
  23. package/src/git/worktree-pool-lifecycle.js +152 -33
  24. package/src/git/worktree-pool-usage.js +20 -0
  25. package/src/git/worktree.js +14 -5
  26. package/src/main.js +25 -9
  27. package/src/routes/bulk-analysis-configs.js +1 -1
  28. package/src/routes/pr.js +11 -14
  29. package/src/routes/reviews.js +8 -30
  30. package/src/routes/setup.js +22 -9
  31. package/src/setup/pr-setup.js +12 -3
  32. package/src/utils/diff-file-content.js +62 -25
  33. package/src/utils/json-extractor.js +267 -13
  34. package/src/utils/pr-file-blob-cache.js +134 -0
  35. package/src/utils/process-liveness.js +64 -0
@@ -4,10 +4,11 @@
4
4
  const fs = require('fs');
5
5
  const logger = require('../utils/logger');
6
6
  const { WorktreePoolRepository, WorktreeRepository, RepoSettingsRepository, generateWorktreeId } = require('../database');
7
- const { GitWorktreeManager } = require('./worktree');
7
+ const { GitWorktreeManager, getPRHeadBranch } = require('./worktree');
8
8
  const { WorktreePoolUsageTracker } = require('./worktree-pool-usage');
9
9
  const { normalizeRepository } = require('../utils/paths');
10
10
  const { resolvePoolConfig } = require('../config');
11
+ const { isProcessAlive, getBootTimeMs } = require('../utils/process-liveness');
11
12
 
12
13
  /**
13
14
  * Consolidates the worktree pool state machine: absorbs WorktreePoolManager
@@ -30,6 +31,9 @@ class WorktreePoolLifecycle {
30
31
  fs: fs,
31
32
  simpleGit: require('simple-git'),
32
33
  GitWorktreeManager: GitWorktreeManager,
34
+ pid: process.pid,
35
+ isProcessAlive: isProcessAlive,
36
+ getBootTimeMs: getBootTimeMs,
33
37
  };
34
38
  const deps = { ...defaults, ..._deps };
35
39
 
@@ -42,6 +46,15 @@ class WorktreePoolLifecycle {
42
46
  this._fs = deps.fs;
43
47
  this._simpleGit = deps.simpleGit;
44
48
  this._GitWorktreeManager = deps.GitWorktreeManager;
49
+ // The process this lifecycle claims pool rows as. Several pair-review
50
+ // processes can share one database; every claim is stamped with this pid
51
+ // and normal releases are gated on still holding the row. The exceptions
52
+ // are user-initiated deletes (releaseForDeletion, destroyPoolWorktree),
53
+ // removal of stale rows just claimed, and failed-reservation cleanup; see
54
+ // WorktreePoolRepository.
55
+ this._pid = deps.pid;
56
+ this._isProcessAlive = deps.isProcessAlive;
57
+ this._getBootTimeMs = deps.getBootTimeMs;
45
58
  }
46
59
 
47
60
  /**
@@ -78,8 +91,14 @@ class WorktreePoolLifecycle {
78
91
  const { poolSize } = options;
79
92
 
80
93
  // 1. Already assigned to this PR? Atomically claim via DB transaction.
81
- const existingPool = await this._poolRepo.claimByPR(prInfo.prNumber, repository);
94
+ const existingPool = await this._poolRepo.claimByPR(prInfo.prNumber, repository, this._pid);
82
95
  if (existingPool) {
96
+ // A grace timer armed for this row's previous use must not fire during
97
+ // the refresh fetch and free the row under this claim.
98
+ this._usageTracker.cancelGrace(existingPool.id);
99
+ if (existingPool.previousHolderPid) {
100
+ logger.info(`Taking over pool worktree ${existingPool.id} from pid ${existingPool.previousHolderPid} (same PR)`);
101
+ }
83
102
  const worktreeRecord = await this._worktreeRepo.findById(existingPool.id);
84
103
  if (worktreeRecord) {
85
104
  if (!this._fs.existsSync(worktreeRecord.path)) {
@@ -88,7 +107,29 @@ class WorktreePoolLifecycle {
88
107
  await this._worktreeRepo.delete(existingPool.id);
89
108
  } else {
90
109
  logger.info(`Pool worktree ${existingPool.id} already assigned to PR #${prInfo.prNumber}, refreshing`);
91
- return this._refreshPoolWorktree(existingPool, worktreeRecord, prInfo, prData);
110
+ try {
111
+ return await this._refreshPoolWorktree(existingPool, worktreeRecord, prInfo, prData);
112
+ } catch (err) {
113
+ // The claim left the row in_use under this process. Free it unless
114
+ // this process is still using it (a session or analysis from an
115
+ // earlier acquisition); the release is gated on still holding it.
116
+ // Never free a row this claim took from another process: that
117
+ // process may still be serving the PR, and this tracker cannot
118
+ // see it. If it is actually dead, startup reclaims the row.
119
+ if (!existingPool.previousHolderPid && !this._usageTracker.isInUse(existingPool.id)) {
120
+ try {
121
+ const released = await this._poolRepo.markAvailable(existingPool.id, this._pid);
122
+ if (released) {
123
+ logger.info(`Released pool worktree ${existingPool.id} after refresh failure`);
124
+ } else {
125
+ logger.info(`Pool worktree ${existingPool.id} not released after refresh failure: no longer held by this process`);
126
+ }
127
+ } catch (releaseErr) {
128
+ logger.error(`Failed to release pool worktree ${existingPool.id} after refresh failure: ${releaseErr.message}`);
129
+ }
130
+ }
131
+ throw err;
132
+ }
92
133
  }
93
134
  } else {
94
135
  logger.warn(`Orphaned pool entry ${existingPool.id} -- removing`);
@@ -97,8 +138,9 @@ class WorktreePoolLifecycle {
97
138
  }
98
139
 
99
140
  // 2. Available slot (LRU eviction)? Atomically claim via DB transaction.
100
- const available = await this._poolRepo.claimAvailable(repository);
141
+ const available = await this._poolRepo.claimAvailable(repository, this._pid);
101
142
  if (available) {
143
+ this._usageTracker.cancelGrace(available.id);
102
144
  const worktreeRecord = await this._worktreeRepo.findById(available.id);
103
145
  if (worktreeRecord) {
104
146
  if (!this._fs.existsSync(worktreeRecord.path)) {
@@ -117,7 +159,7 @@ class WorktreePoolLifecycle {
117
159
 
118
160
  // 3. Pool not full -- atomically reserve a slot, then create
119
161
  const poolId = generateWorktreeId();
120
- const reserved = await this._poolRepo.reserveSlot(poolId, repository, poolSize);
162
+ const reserved = await this._poolRepo.reserveSlot(poolId, repository, poolSize, this._pid);
121
163
  if (reserved) {
122
164
  logger.info(`Reserved pool slot ${poolId} for PR #${prInfo.prNumber}, creating worktree`);
123
165
  return this._createPoolWorktree(prInfo, prData, repositoryPath, options, poolId);
@@ -129,7 +171,7 @@ class WorktreePoolLifecycle {
129
171
 
130
172
  const normalizedPrData = {
131
173
  head_sha: prData.head?.sha || prData.head_sha,
132
- head_branch: prData.head?.ref || prData.head_branch,
174
+ head_branch: getPRHeadBranch(prData),
133
175
  base_sha: prData.base?.sha || prData.base_sha,
134
176
  base_branch: prData.base?.ref || prData.base_branch,
135
177
  repository: prData.repository,
@@ -182,7 +224,7 @@ class WorktreePoolLifecycle {
182
224
  // Normalize prData into the shape createWorktreeForPR expects
183
225
  const normalizedPrData = {
184
226
  head_sha: prData.head?.sha || prData.head_sha,
185
- head_branch: prData.head?.ref || prData.head_branch,
227
+ head_branch: getPRHeadBranch(prData),
186
228
  base_sha: prData.base?.sha || prData.base_sha,
187
229
  base_branch: prData.base?.ref || prData.base_branch,
188
230
  repository: prData.repository,
@@ -204,7 +246,10 @@ class WorktreePoolLifecycle {
204
246
 
205
247
  // Finalize the reservation: set path and mark in_use.
206
248
  // Use poolId (the reserved pool slot ID), NOT worktreeId (the worktrees-table ID).
207
- await this._poolRepo.finalizeReservation(poolId, worktreePath, prInfo.prNumber);
249
+ const finalized = await this._poolRepo.finalizeReservation(poolId, worktreePath, prInfo.prNumber, this._pid);
250
+ if (!finalized) {
251
+ logger.warn(`Pool reservation ${poolId} was no longer creating and held by this process when finalizing; pool row not updated`);
252
+ }
208
253
 
209
254
  logger.info(`Created pool worktree ${poolId} at ${worktreePath}`);
210
255
  return { worktreePath, worktreeId: poolId };
@@ -271,7 +316,7 @@ class WorktreePoolLifecycle {
271
316
  // Run reset_script if configured
272
317
  if (options.resetScript) {
273
318
  logger.info(`Executing reset script: ${options.resetScript}`);
274
- const headRef = prData.head?.ref || prData.head_branch || '';
319
+ const headRef = getPRHeadBranch(prData);
275
320
  const baseRef = prData.base?.ref || prData.base_branch || '';
276
321
  const headSha = worktreeManager.getPRHeadSha(prData);
277
322
  const baseSha = worktreeManager.getPRBaseSha(prData);
@@ -290,7 +335,7 @@ class WorktreePoolLifecycle {
290
335
  }
291
336
 
292
337
  // Update worktrees table (returns paths of deleted non-pool worktree records)
293
- const branch = prData.head?.ref || prData.head_branch || '';
338
+ const branch = getPRHeadBranch(prData);
294
339
  const deletedPaths = await this._worktreeRepo.switchPR(poolEntry.id, prInfo.prNumber, branch);
295
340
 
296
341
  // Best-effort disk cleanup for deleted non-pool worktree directories
@@ -311,15 +356,20 @@ class WorktreePoolLifecycle {
311
356
  // that marks the worktree available while the new PR is using it.
312
357
  this._usageTracker.clearWorktree(poolEntry.id);
313
358
 
314
- // Mark in_use in pool table
315
- await this._poolRepo.markInUse(poolEntry.id, prInfo.prNumber);
359
+ // Mark in_use in pool table -- only if the row is still switching under
360
+ // this process. False means it was taken over mid-switch.
361
+ const marked = await this._poolRepo.markInUse(poolEntry.id, prInfo.prNumber, this._pid, 'switching');
362
+ if (!marked) {
363
+ throw new Error(`pool worktree ${poolEntry.id} was taken over during switch`);
364
+ }
316
365
 
317
366
  logger.info(`Switched pool worktree ${poolEntry.id} to PR #${prInfo.prNumber}`);
318
367
  return { worktreePath: poolEntry.path, worktreeId: poolEntry.id };
319
368
  } catch (err) {
320
- // Roll back to available on failure
369
+ // Roll back to available on failure (only while still switching under
370
+ // this process -- never frees a row someone else now holds)
321
371
  try {
322
- await this._poolRepo.markAvailable(poolEntry.id);
372
+ await this._poolRepo.abandonSwitch(poolEntry.id, this._pid);
323
373
  } catch (rollbackErr) {
324
374
  logger.error(`Failed to roll back pool worktree ${poolEntry.id} status: ${rollbackErr.message}`);
325
375
  }
@@ -340,6 +390,7 @@ class WorktreePoolLifecycle {
340
390
  */
341
391
  async _refreshPoolWorktree(poolEntry, worktreeRecord, prInfo, prData) {
342
392
  const targetSha = prData.head?.sha || prData.head_sha;
393
+ let alreadyAtTarget = false;
343
394
  if (targetSha) {
344
395
  try {
345
396
  const git = this._simpleGit(poolEntry.path);
@@ -352,18 +403,23 @@ class WorktreePoolLifecycle {
352
403
  number: prInfo.prNumber,
353
404
  });
354
405
  await worktreeManager.ensureBaseShaAvailable(git, prData, remote);
355
- logger.info(`Pool worktree ${poolEntry.id} already at target SHA ${targetSha.slice(0, 8)}, skipping refresh`);
356
- await this._poolRepo.markInUse(poolEntry.id, prInfo.prNumber);
357
- return { worktreePath: poolEntry.path, worktreeId: poolEntry.id };
406
+ alreadyAtTarget = true;
358
407
  }
359
408
  } catch (err) {
360
409
  logger.warn(`Could not check HEAD of pool worktree ${poolEntry.id}: ${err.message}`);
361
410
  }
362
411
  }
412
+ // Outside the try above: a takeover detected here must propagate, not
413
+ // fall through to a full refresh (reset/clean) of a row someone else holds.
414
+ if (alreadyAtTarget) {
415
+ logger.info(`Pool worktree ${poolEntry.id} already at target SHA ${targetSha.slice(0, 8)}, skipping refresh`);
416
+ await this._markRefreshedInUse(poolEntry.id, prInfo.prNumber);
417
+ return { worktreePath: poolEntry.path, worktreeId: poolEntry.id };
418
+ }
363
419
 
364
420
  const normalizedPrData = {
365
421
  head_sha: prData.head?.sha || prData.head_sha,
366
- head_branch: prData.head?.ref || prData.head_branch,
422
+ head_branch: getPRHeadBranch(prData),
367
423
  base_sha: prData.base?.sha || prData.base_sha,
368
424
  base_branch: prData.base?.ref || prData.base_branch,
369
425
  repository: prData.repository,
@@ -398,23 +454,39 @@ class WorktreePoolLifecycle {
398
454
  }
399
455
  }
400
456
 
401
- // Ensure pool entry is marked in_use
402
- await this._poolRepo.markInUse(poolEntry.id, prInfo.prNumber);
457
+ // Ensure pool entry is still in_use for this PR under this process
458
+ await this._markRefreshedInUse(poolEntry.id, prInfo.prNumber);
403
459
 
404
460
  logger.info(`Refreshed pool worktree ${poolEntry.id} for PR #${prInfo.prNumber}`);
405
461
  return { worktreePath: poolEntry.path, worktreeId: poolEntry.id };
406
462
  }
407
463
 
408
464
  /**
409
- * Release a pool worktree, marking it as available for reuse.
410
- * Kept for backward compatibility -- callers that only need to mark
411
- * a worktree available without touching usage tracking can use this.
465
+ * Conditionally confirm a refreshed pool row is still in_use for the PR
466
+ * under this process. Throws if it was taken over while refreshing.
412
467
  *
413
468
  * @param {string} worktreeId - Pool worktree ID
469
+ * @param {number} prNumber - PR number
470
+ * @private
414
471
  */
415
- async release(worktreeId) {
416
- await this._poolRepo.markAvailable(worktreeId);
417
- logger.info(`Pool worktree ${worktreeId} released`);
472
+ async _markRefreshedInUse(worktreeId, prNumber) {
473
+ const marked = await this._poolRepo.markInUse(worktreeId, prNumber, this._pid, 'in_use');
474
+ if (!marked) {
475
+ throw new Error(`pool worktree ${worktreeId} was taken over during refresh`);
476
+ }
477
+ }
478
+
479
+ /**
480
+ * Take an `available` pool worktree that still carries this PR back into
481
+ * use under this process (the setup route's reclaim fast path). Atomic and
482
+ * conditional: false when a peer claimed or reassigned the row first.
483
+ *
484
+ * @param {string} worktreeId - Pool worktree ID
485
+ * @param {number} prNumber - PR number the row must still carry
486
+ * @returns {Promise<boolean>} true if the row was reclaimed
487
+ */
488
+ async reclaimForPR(worktreeId, prNumber) {
489
+ return this._poolRepo.reclaimAvailableForPR(worktreeId, prNumber, this._pid);
418
490
  }
419
491
 
420
492
  // ── New lifecycle methods ────────────────────────────────────────────────
@@ -476,13 +548,14 @@ class WorktreePoolLifecycle {
476
548
 
477
549
  /**
478
550
  * Release a worktree for deletion: clear usage state first, then
479
- * mark available in the database.
551
+ * mark available in the database. User-initiated, so unconditional
552
+ * (whoever holds the row).
480
553
  *
481
554
  * @param {string} worktreeId - Pool worktree ID
482
555
  */
483
556
  async releaseForDeletion(worktreeId) {
484
557
  this._usageTracker.clearWorktree(worktreeId);
485
- await this._poolRepo.markAvailable(worktreeId);
558
+ await this._poolRepo.forceMarkAvailable(worktreeId);
486
559
  }
487
560
 
488
561
  /**
@@ -491,11 +564,16 @@ class WorktreePoolLifecycle {
491
564
  * before the DB write prevents a race where another request claims the slot
492
565
  * (after the DB write) and then has its tracking state wiped by clearWorktree.
493
566
  *
567
+ * The DB write only frees a row this process still holds; a row another
568
+ * process has since taken over is left alone.
569
+ *
494
570
  * @param {string} worktreeId - Pool worktree ID
571
+ * @returns {Promise<boolean>} true if the row was released, false if this
572
+ * process no longer held it
495
573
  */
496
574
  async releaseAfterHeadless(worktreeId) {
497
575
  this._usageTracker.clearWorktree(worktreeId);
498
- await this._poolRepo.markAvailable(worktreeId);
576
+ return this._poolRepo.markAvailable(worktreeId, this._pid);
499
577
  }
500
578
 
501
579
  /**
@@ -558,12 +636,42 @@ class WorktreePoolLifecycle {
558
636
  return this._usageTracker.getActiveAnalyses(worktreeId);
559
637
  }
560
638
 
639
+ /**
640
+ * Decide at startup whether the process recorded as holding a pool row is
641
+ * gone. Used only by resetAndRehydrate; there is no runtime liveness check.
642
+ *
643
+ * Dead when: no holder recorded (legacy rows); the holder is this pid (a
644
+ * process that has just started holds nothing, so its own pid on a row
645
+ * means the pid was reused); the claim time is missing, unparseable or
646
+ * before the OS booted; or the holder process no longer exists. Uncertain
647
+ * liveness answers count as alive.
648
+ *
649
+ * @param {{holder_pid: number|null, holder_claimed_at: string|null}} row
650
+ * @param {number} bootTimeMs - OS boot time (ms since epoch)
651
+ * @returns {boolean}
652
+ * @private
653
+ */
654
+ _isHolderDeadAtStartup(row, bootTimeMs) {
655
+ if (row.holder_pid == null) return true;
656
+ if (row.holder_pid === this._pid) return true;
657
+ const claimedAtMs = row.holder_claimed_at ? Date.parse(row.holder_claimed_at) : NaN;
658
+ if (Number.isNaN(claimedAtMs) || claimedAtMs < bootTimeMs) return true;
659
+ return !this._isProcessAlive(row.holder_pid);
660
+ }
661
+
561
662
  /**
562
663
  * Reset stale pool entries and rehydrate preserved ones on startup.
563
664
  *
665
+ * MUST run before this process acquires any pool worktree (true for both
666
+ * callers, src/main.js and src/server.js): the startup liveness check
667
+ * treats rows stamped with this process's own pid as left over by a dead
668
+ * process that had the same pid.
669
+ *
564
670
  * This method:
565
671
  * 1. Calls resetStaleAndPreserve() to clean up stale DB entries and
566
- * identify entries with valid review ownership
672
+ * identify entries with valid review ownership. Rows held by another
673
+ * live pair-review process are skipped; preserved rows are taken over
674
+ * by this process
567
675
  * 2. Wires the onIdle callback with retry logic (2 attempts, 1s delay)
568
676
  * so that idle worktrees are automatically marked available
569
677
  * 3. Rehydrates preserved entries by triggering a synthetic
@@ -575,7 +683,11 @@ class WorktreePoolLifecycle {
575
683
  */
576
684
  async resetAndRehydrate() {
577
685
  // 1. Reset stale entries and get preserved ones
578
- const preserved = await this._poolRepo.resetStaleAndPreserve();
686
+ const bootTimeMs = this._getBootTimeMs();
687
+ const preserved = await this._poolRepo.resetStaleAndPreserve(
688
+ this._pid,
689
+ (row) => this._isHolderDeadAtStartup(row, bootTimeMs)
690
+ );
579
691
  if (preserved.length > 0) {
580
692
  logger.info(`Pool startup: preserved ${preserved.length} active worktree(s)`);
581
693
  }
@@ -590,8 +702,14 @@ class WorktreePoolLifecycle {
590
702
  this._usageTracker.onIdle = async (worktreeId) => {
591
703
  for (let attempt = 1; attempt <= 2; attempt++) {
592
704
  try {
593
- await this._poolRepo.markAvailable(worktreeId);
594
- logger.info(`Pool worktree ${worktreeId} is now available`);
705
+ const released = await this._poolRepo.markAvailable(worktreeId, this._pid);
706
+ if (released) {
707
+ logger.info(`Pool worktree ${worktreeId} is now available`);
708
+ } else {
709
+ // Not an error: the row is no longer in_use under this process
710
+ // (freed, switched, or taken over). Retrying cannot change that.
711
+ logger.info(`Pool worktree ${worktreeId} idle but not released: no longer held by this process`);
712
+ }
595
713
  return;
596
714
  } catch (err) {
597
715
  if (attempt < 2) {
@@ -670,6 +788,7 @@ class WorktreePoolLifecycle {
670
788
  repository: orphan.repository,
671
789
  path: orphan.path,
672
790
  prNumber: orphan.pr_number,
791
+ holderPid: this._pid,
673
792
  });
674
793
  await this._poolRepo.setCurrentReviewId(orphan.id, orphan.reviewId);
675
794
  adoptedInUse.push({ id: orphan.id, current_review_id: orphan.reviewId });
@@ -140,6 +140,26 @@ class WorktreePoolUsageTracker {
140
140
  return new Set(this._analyses.get(worktreeId) || []);
141
141
  }
142
142
 
143
+ /**
144
+ * Cancel a pending grace-period timer for a worktree, if one is armed.
145
+ * Sessions and analyses are untouched, and onIdle does not fire.
146
+ *
147
+ * Used when this process claims a pool row: a timer armed for the row's
148
+ * previous use must not fire mid-acquire and free the row under the new
149
+ * claim.
150
+ *
151
+ * @param {string} worktreeId - Pool worktree ID
152
+ * @returns {boolean} true if a pending timer was cancelled
153
+ */
154
+ cancelGrace(worktreeId) {
155
+ const timer = this._graceTimers.get(worktreeId);
156
+ if (!timer) return false;
157
+ clearTimeout(timer);
158
+ this._graceTimers.delete(worktreeId);
159
+ logger.debug(`Grace period cancelled for pool worktree ${worktreeId} — claimed by this process`);
160
+ return true;
161
+ }
162
+
143
163
  /**
144
164
  * Forcefully clear all tracking state for a single worktree.
145
165
  *
@@ -15,6 +15,15 @@ const { spawn, execSync } = require('child_process');
15
15
 
16
16
  const MISSING_COMMIT_ERROR_CODE = 'PAIR_REVIEW_MISSING_COMMIT';
17
17
 
18
+ /**
19
+ * Resolve the PR head branch consistently for stored and REST metadata.
20
+ * @param {Object|null} prData
21
+ * @returns {string}
22
+ */
23
+ function getPRHeadBranch(prData) {
24
+ return prData?.head_branch || prData?.head?.ref || '';
25
+ }
26
+
18
27
  /**
19
28
  * Git worktree manager for handling PR branch checkouts and diffs
20
29
  */
@@ -213,7 +222,7 @@ class GitWorktreeManager {
213
222
  * @returns {string}
214
223
  */
215
224
  getPRHeadBranch(prData) {
216
- return prData?.head?.ref || prData?.head_branch || '';
225
+ return getPRHeadBranch(prData);
217
226
  }
218
227
 
219
228
  /**
@@ -533,7 +542,7 @@ class GitWorktreeManager {
533
542
  const migrated = await this.worktreeRepo.getOrCreate({
534
543
  prNumber: prInfo.number,
535
544
  repository,
536
- branch: prData.head_branch || prData.base_branch,
545
+ branch: this.getPRHeadBranch(prData),
537
546
  path: refreshedPath,
538
547
  explicitId,
539
548
  });
@@ -571,7 +580,7 @@ class GitWorktreeManager {
571
580
  worktreeRecord = await this.worktreeRepo.getOrCreate({
572
581
  prNumber: prInfo.number,
573
582
  repository,
574
- branch: prData.head_branch || prData.base_branch,
583
+ branch: this.getPRHeadBranch(prData),
575
584
  path: legacyPath,
576
585
  explicitId,
577
586
  });
@@ -744,7 +753,7 @@ class GitWorktreeManager {
744
753
  const record = await this.worktreeRepo.getOrCreate({
745
754
  prNumber: prInfo.number,
746
755
  repository,
747
- branch: prData.head_branch || prData.base_branch,
756
+ branch: this.getPRHeadBranch(prData),
748
757
  path: worktreePath,
749
758
  explicitId,
750
759
  });
@@ -1498,4 +1507,4 @@ class GitWorktreeManager {
1498
1507
  }
1499
1508
  }
1500
1509
 
1501
- module.exports = { GitWorktreeManager, MISSING_COMMIT_ERROR_CODE };
1510
+ module.exports = { GitWorktreeManager, MISSING_COMMIT_ERROR_CODE, getPRHeadBranch };
package/src/main.js CHANGED
@@ -234,12 +234,16 @@ OPTIONS:
234
234
  The web UI also starts for the human reviewer.
235
235
  --model <name> Override the AI model. Claude Code is the default provider.
236
236
  Available models: opus, sonnet, haiku (Claude Code);
237
- also: fable-5.1-xhigh, fable-5.1-high,
237
+ also: fable-5.2-xhigh, fable-5.2-high,
238
+ fable-5.1-xhigh, fable-5.1-high,
238
239
  fable-5-xhigh, fable-5-high, opus-5.5-xhigh,
239
240
  opus-5.5-high, opus-5.5-medium, opus-5.5-low,
240
241
  opus-5-xhigh, opus-5-high,
241
- sonnet-5-xhigh, sonnet-5-high, sonnet-4.6
242
- (default is opus-5.5-high; opus is Opus 5.5 XHigh;
242
+ sonnet-5.5-xhigh, sonnet-5.5-high,
243
+ sonnet-5-xhigh, sonnet-5-high, sonnet-4.6,
244
+ haiku-5.5-medium
245
+ (default is opus-5.5-high; opus is Opus 5.5 High;
246
+ fable is Fable 5.2 High;
243
247
  a saved default_model wins over the default)
244
248
  or use provider-specific models with Antigravity/Codex
245
249
  --provider <name> Override the AI provider for headless modes
@@ -1882,8 +1886,12 @@ Found ${aiSuggestions.length} suggestion${aiSuggestions.length === 1 ? '' : 's'}
1882
1886
  // so the pool slot must be freed immediately.
1883
1887
  if (poolWorktreeId && poolLifecycle) {
1884
1888
  try {
1885
- await poolLifecycle.releaseAfterHeadless(poolWorktreeId);
1886
- logger.info(`Released pool worktree ${poolWorktreeId} after headless review`);
1889
+ const released = await poolLifecycle.releaseAfterHeadless(poolWorktreeId);
1890
+ if (released) {
1891
+ logger.info(`Released pool worktree ${poolWorktreeId} after headless review`);
1892
+ } else {
1893
+ logger.info(`Pool worktree ${poolWorktreeId} not released after headless review: no longer held by this process`);
1894
+ }
1887
1895
  } catch (releaseErr) {
1888
1896
  logger.error(`Failed to release pool worktree ${poolWorktreeId}: ${releaseErr.message}`);
1889
1897
  }
@@ -2244,8 +2252,12 @@ async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycl
2244
2252
  // logged, not allowed to mask the original failure.
2245
2253
  if (poolWorktreeId && poolLifecycle) {
2246
2254
  try {
2247
- await poolLifecycle.releaseAfterHeadless(poolWorktreeId);
2248
- logger.info(`Released pool worktree ${poolWorktreeId} after headless prep failure`);
2255
+ const released = await poolLifecycle.releaseAfterHeadless(poolWorktreeId);
2256
+ if (released) {
2257
+ logger.info(`Released pool worktree ${poolWorktreeId} after headless prep failure`);
2258
+ } else {
2259
+ logger.info(`Pool worktree ${poolWorktreeId} not released after headless prep failure: no longer held by this process`);
2260
+ }
2249
2261
  } catch (releaseErr) {
2250
2262
  logger.error(`Failed to release pool worktree ${poolWorktreeId} after prep failure: ${releaseErr.message}`);
2251
2263
  }
@@ -2510,8 +2522,12 @@ async function handleHeadlessAnalysis(prArgs, config, db, flags, poolLifecycle)
2510
2522
  // pool slot isn't leaked per headless run. Local mode has no pool.
2511
2523
  if (prep.poolWorktreeId && prep.poolLifecycle) {
2512
2524
  try {
2513
- await prep.poolLifecycle.releaseAfterHeadless(prep.poolWorktreeId);
2514
- logger.info(`Released pool worktree ${prep.poolWorktreeId} after headless analysis`);
2525
+ const released = await prep.poolLifecycle.releaseAfterHeadless(prep.poolWorktreeId);
2526
+ if (released) {
2527
+ logger.info(`Released pool worktree ${prep.poolWorktreeId} after headless analysis`);
2528
+ } else {
2529
+ logger.info(`Pool worktree ${prep.poolWorktreeId} not released after headless analysis: no longer held by this process`);
2530
+ }
2515
2531
  } catch (releaseErr) {
2516
2532
  logger.error(`Failed to release pool worktree ${prep.poolWorktreeId}: ${releaseErr.message}`);
2517
2533
  }
@@ -152,7 +152,7 @@ function sanitizeSingleConfig(config) {
152
152
  // to the provider's own default rather than forwarding an invalid pair. Unknown
153
153
  // providers (custom/unavailable, not in the registry) pass through unchanged.
154
154
  // A model "belongs" to the provider if config.model matches a model id OR one of
155
- // its aliases (e.g. 'opus' is an alias of the canonical 'opus-5.5-xhigh'). Matching
155
+ // its aliases (e.g. 'opus' is an alias of the canonical 'opus-5.5-high'). Matching
156
156
  // id-only would wrongly treat a valid alias as a mismatched pair and silently coerce
157
157
  // it to the provider default.
158
158
  let normalizedModel = config.model;
package/src/routes/pr.js CHANGED
@@ -59,7 +59,7 @@ const { safeParseJson } = require('../utils/safe-parse-json');
59
59
  const { mergeChangedFilesWithDiff, parseUnifiedDiffPatches, buildChangedFileEntries } = require('../utils/diff-file-list');
60
60
  const { parseHunks } = require('../utils/diff-hunks');
61
61
  const { hashHunk } = require('../ai/hunk-hashing');
62
- const { resolveOriginalFileContentSpecs } = require('../utils/diff-file-content');
62
+ const { getPRFileContentSpecs, invalidatePRFileBlobCache } = require('../utils/pr-file-blob-cache');
63
63
  const { validateCouncilConfig, normalizeCouncilConfig } = require('./councils');
64
64
  const { resolveReviewConfig } = require('../review-config');
65
65
  const { TIERS, TIER_ALIASES, VALID_TIERS, resolveTier } = require('../ai/prompts/config');
@@ -584,7 +584,7 @@ router.post('/api/pr/:owner/:repo/:number/refresh', async (req, res) => {
584
584
 
585
585
  // Check if PR exists in database
586
586
  const existingPR = await queryOne(db, `
587
- SELECT id FROM pr_metadata
587
+ SELECT id, pr_data FROM pr_metadata
588
588
  WHERE pr_number = ? AND repository = ? COLLATE NOCASE
589
589
  `, [prNumber, repository]);
590
590
 
@@ -639,8 +639,11 @@ router.post('/api/pr/:owner/:repo/:number/refresh', async (req, res) => {
639
639
  const diff = await worktreeManager.generateUnifiedDiff(worktreePath, diffPrData);
640
640
  const changedFiles = await worktreeManager.getChangedFiles(worktreePath, diff);
641
641
 
642
- // 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.
643
644
  const extendedData = {
645
+ ...safeParseJson(existingPR.pr_data, {}),
646
+ ...prData,
644
647
  state: prData.state,
645
648
  diff: diff,
646
649
  changed_files: changedFiles,
@@ -659,6 +662,7 @@ router.post('/api/pr/:owner/:repo/:number/refresh', async (req, res) => {
659
662
  SET
660
663
  title = ?,
661
664
  description = ?,
665
+ author = ?,
662
666
  base_branch = ?,
663
667
  head_branch = ?,
664
668
  updated_at = CURRENT_TIMESTAMP,
@@ -667,12 +671,14 @@ router.post('/api/pr/:owner/:repo/:number/refresh', async (req, res) => {
667
671
  `, [
668
672
  prData.title,
669
673
  prData.body || '',
674
+ prData.author,
670
675
  prData.base_branch,
671
676
  prData.head_branch,
672
677
  JSON.stringify(extendedData),
673
678
  prNumber,
674
679
  repository
675
680
  ]);
681
+ invalidatePRFileBlobCache(db, repository, prNumber);
676
682
 
677
683
  logger.info(`Successfully refreshed PR #${prNumber} for ${repository}`);
678
684
 
@@ -1401,17 +1407,7 @@ router.get('/api/file-content-original/:fileName(*)', async (req, res) => {
1401
1407
  // Prefer the exact blob from the cached diff snapshot. If that is unavailable,
1402
1408
  // fall back to repo-wide base_sha and finally the worktree filesystem.
1403
1409
  const repository = normalizeRepository(owner, repo);
1404
- const prRecord = await queryOne(db, `
1405
- SELECT pr_data FROM pr_metadata
1406
- WHERE pr_number = ? AND repository = ? COLLATE NOCASE
1407
- `, [prNumber, repository]);
1408
-
1409
- const prData = safeParseJson(prRecord?.pr_data, null);
1410
- if (prRecord?.pr_data && !prData) {
1411
- logger.warn('Could not parse pr_data for file-content route');
1412
- }
1413
-
1414
- const contentSpecs = resolveOriginalFileContentSpecs(prData, fileName);
1410
+ const contentSpecs = getPRFileContentSpecs(db, repository, prNumber, fileName);
1415
1411
 
1416
1412
  if (contentSpecs.length > 0) {
1417
1413
  try {
@@ -1907,6 +1903,7 @@ router.post('/api/pr/:owner/:repo/:number/files/viewed', async (req, res) => {
1907
1903
  SET pr_data = ?, updated_at = CURRENT_TIMESTAMP
1908
1904
  WHERE pr_number = ? AND repository = ? COLLATE NOCASE
1909
1905
  `, [JSON.stringify(prData), prNumber, repository]);
1906
+ invalidatePRFileBlobCache(db, repository, prNumber);
1910
1907
 
1911
1908
  res.json({
1912
1909
  success: true,