@in-the-loop-labs/pair-review 5.4.0 → 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.
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
- package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
- package/public/index.html +1 -0
- package/public/js/components/AdvancedConfigTab.js +18 -108
- package/public/js/components/VoiceCentricConfigTab.js +18 -108
- package/public/js/index.js +18 -5
- package/public/js/modules/diff-renderer.js +7 -6
- package/public/js/utils/council-timeout.js +203 -0
- package/public/local.html +4 -0
- package/public/pr.html +4 -0
- package/src/ai/copilot-provider.js +21 -2
- package/src/ai/cursor-agent-provider.js +21 -2
- package/src/ai/opencode-provider.js +21 -2
- package/src/database.js +240 -59
- package/src/git/worktree-pool-lifecycle.js +152 -33
- package/src/git/worktree-pool-usage.js +20 -0
- package/src/git/worktree.js +14 -5
- package/src/main.js +18 -6
- package/src/routes/pr.js +11 -14
- package/src/routes/reviews.js +8 -30
- package/src/routes/setup.js +22 -9
- package/src/setup/pr-setup.js +12 -3
- package/src/utils/diff-file-content.js +62 -25
- package/src/utils/json-extractor.js +267 -13
- package/src/utils/pr-file-blob-cache.js +134 -0
- 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
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
|
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
|
|
402
|
-
await this.
|
|
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
|
-
*
|
|
410
|
-
*
|
|
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
|
|
416
|
-
await this._poolRepo.
|
|
417
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
*
|
package/src/git/worktree.js
CHANGED
|
@@ -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
|
|
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:
|
|
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:
|
|
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:
|
|
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
|
@@ -1882,8 +1882,12 @@ Found ${aiSuggestions.length} suggestion${aiSuggestions.length === 1 ? '' : 's'}
|
|
|
1882
1882
|
// so the pool slot must be freed immediately.
|
|
1883
1883
|
if (poolWorktreeId && poolLifecycle) {
|
|
1884
1884
|
try {
|
|
1885
|
-
await poolLifecycle.releaseAfterHeadless(poolWorktreeId);
|
|
1886
|
-
|
|
1885
|
+
const released = await poolLifecycle.releaseAfterHeadless(poolWorktreeId);
|
|
1886
|
+
if (released) {
|
|
1887
|
+
logger.info(`Released pool worktree ${poolWorktreeId} after headless review`);
|
|
1888
|
+
} else {
|
|
1889
|
+
logger.info(`Pool worktree ${poolWorktreeId} not released after headless review: no longer held by this process`);
|
|
1890
|
+
}
|
|
1887
1891
|
} catch (releaseErr) {
|
|
1888
1892
|
logger.error(`Failed to release pool worktree ${poolWorktreeId}: ${releaseErr.message}`);
|
|
1889
1893
|
}
|
|
@@ -2244,8 +2248,12 @@ async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycl
|
|
|
2244
2248
|
// logged, not allowed to mask the original failure.
|
|
2245
2249
|
if (poolWorktreeId && poolLifecycle) {
|
|
2246
2250
|
try {
|
|
2247
|
-
await poolLifecycle.releaseAfterHeadless(poolWorktreeId);
|
|
2248
|
-
|
|
2251
|
+
const released = await poolLifecycle.releaseAfterHeadless(poolWorktreeId);
|
|
2252
|
+
if (released) {
|
|
2253
|
+
logger.info(`Released pool worktree ${poolWorktreeId} after headless prep failure`);
|
|
2254
|
+
} else {
|
|
2255
|
+
logger.info(`Pool worktree ${poolWorktreeId} not released after headless prep failure: no longer held by this process`);
|
|
2256
|
+
}
|
|
2249
2257
|
} catch (releaseErr) {
|
|
2250
2258
|
logger.error(`Failed to release pool worktree ${poolWorktreeId} after prep failure: ${releaseErr.message}`);
|
|
2251
2259
|
}
|
|
@@ -2510,8 +2518,12 @@ async function handleHeadlessAnalysis(prArgs, config, db, flags, poolLifecycle)
|
|
|
2510
2518
|
// pool slot isn't leaked per headless run. Local mode has no pool.
|
|
2511
2519
|
if (prep.poolWorktreeId && prep.poolLifecycle) {
|
|
2512
2520
|
try {
|
|
2513
|
-
await prep.poolLifecycle.releaseAfterHeadless(prep.poolWorktreeId);
|
|
2514
|
-
|
|
2521
|
+
const released = await prep.poolLifecycle.releaseAfterHeadless(prep.poolWorktreeId);
|
|
2522
|
+
if (released) {
|
|
2523
|
+
logger.info(`Released pool worktree ${prep.poolWorktreeId} after headless analysis`);
|
|
2524
|
+
} else {
|
|
2525
|
+
logger.info(`Pool worktree ${prep.poolWorktreeId} not released after headless analysis: no longer held by this process`);
|
|
2526
|
+
}
|
|
2515
2527
|
} catch (releaseErr) {
|
|
2516
2528
|
logger.error(`Failed to release pool worktree ${prep.poolWorktreeId}: ${releaseErr.message}`);
|
|
2517
2529
|
}
|
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 {
|
|
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
|
-
//
|
|
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
|
|
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,
|
package/src/routes/reviews.js
CHANGED
|
@@ -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 {
|
|
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
|
|
34
|
-
* Returns { worktreePath,
|
|
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
|
-
|
|
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
|
|
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,
|
|
1349
|
+
let worktreePath, prNumber, repository;
|
|
1372
1350
|
try {
|
|
1373
|
-
({ worktreePath,
|
|
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 =
|
|
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) {
|