@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
package/src/database.js CHANGED
@@ -21,7 +21,7 @@ function getDbPath() {
21
21
  /**
22
22
  * Current schema version - increment this when adding new migrations
23
23
  */
24
- const CURRENT_SCHEMA_VERSION = 58;
24
+ const CURRENT_SCHEMA_VERSION = 59;
25
25
 
26
26
  /**
27
27
  * Database schema SQL statements
@@ -354,7 +354,9 @@ const SCHEMA_SQL = {
354
354
  last_fetched_at TEXT,
355
355
  last_fetch_attempt_at TEXT,
356
356
  fetch_failure_count INTEGER NOT NULL DEFAULT 0,
357
- created_at TEXT NOT NULL
357
+ created_at TEXT NOT NULL,
358
+ holder_pid INTEGER,
359
+ holder_claimed_at TEXT
358
360
  )
359
361
  `,
360
362
 
@@ -2443,6 +2445,42 @@ const MIGRATIONS = {
2443
2445
  if (!columnExists(db, 'comment_postings', 'kind')) {
2444
2446
  db.exec("ALTER TABLE comment_postings ADD COLUMN kind TEXT NOT NULL DEFAULT 'post' CHECK (kind IN ('post', 'update'))");
2445
2447
  }
2448
+ },
2449
+
2450
+ // Migration to version 59: record which pair-review process holds a pool
2451
+ // worktree. Several processes can share one database (two --headless runs,
2452
+ // or a headless run beside the server); startup cleanup and idle release
2453
+ // now skip or refuse rows a live peer holds. Existing rows get NULL holders,
2454
+ // which startup treats as dead. Each ALTER is guarded by columnExists so a
2455
+ // re-run after a crash between the two finishes the remaining piece.
2456
+ // The checks and ALTERs run in one IMMEDIATE transaction: two processes
2457
+ // starting together against a v58 database would otherwise both see the
2458
+ // column missing, and the second ALTER would fail with a duplicate-column
2459
+ // error. Under the write lock the second process waits (busy timeout),
2460
+ // then sees the columns and skips. runVersionedMigrations does not wrap
2461
+ // migrations in a transaction; if a caller ever does, better-sqlite3 turns
2462
+ // this into a SAVEPOINT inside the caller's transaction.
2463
+ 59: (db) => {
2464
+ console.log('Running migration to schema version 59: add holder process to worktree_pool...');
2465
+ db.transaction(() => {
2466
+ if (!tableExists(db, 'worktree_pool')) {
2467
+ console.log(' worktree_pool table does not exist, skipping');
2468
+ return;
2469
+ }
2470
+ if (!columnExists(db, 'worktree_pool', 'holder_pid')) {
2471
+ db.exec('ALTER TABLE worktree_pool ADD COLUMN holder_pid INTEGER');
2472
+ console.log(' Added holder_pid column to worktree_pool');
2473
+ } else {
2474
+ console.log(' holder_pid column already present; nothing to do');
2475
+ }
2476
+ if (!columnExists(db, 'worktree_pool', 'holder_claimed_at')) {
2477
+ db.exec('ALTER TABLE worktree_pool ADD COLUMN holder_claimed_at TEXT');
2478
+ console.log(' Added holder_claimed_at column to worktree_pool');
2479
+ } else {
2480
+ console.log(' holder_claimed_at column already present; nothing to do');
2481
+ }
2482
+ }).immediate();
2483
+ console.log('Migration to schema version 59 complete');
2446
2484
  }
2447
2485
  };
2448
2486
 
@@ -3033,7 +3071,34 @@ class WorktreeRepository {
3033
3071
  }
3034
3072
 
3035
3073
  /**
3036
- * WorktreePoolRepository class for managing pool worktree database records
3074
+ * Validate the process ID a pool claim is stamped with. Every holder-taking
3075
+ * WorktreePoolRepository method requires one; the repository never reads
3076
+ * process.pid itself, so the caller (WorktreePoolLifecycle) owns identity.
3077
+ * @param {*} holderPid
3078
+ * @param {string} method - Method name for the error message
3079
+ */
3080
+ function assertHolderPid(holderPid, method) {
3081
+ if (!Number.isInteger(holderPid) || holderPid <= 0) {
3082
+ throw new TypeError(`WorktreePoolRepository.${method}: holderPid must be a positive integer, got ${holderPid}`);
3083
+ }
3084
+ }
3085
+
3086
+ /**
3087
+ * Pool worktree rows record the pair-review process that holds them
3088
+ * (`holder_pid`, `holder_claimed_at`). Several processes can share one
3089
+ * database, so every claim stamps the claimant, and the normal releases
3090
+ * (`markAvailable`, `abandonSwitch`) are gated on still being the holder: in
3091
+ * normal operation a process only frees a row it holds.
3092
+ *
3093
+ * Deliberate exceptions, which do not check the holder:
3094
+ * - `forceMarkAvailable` serves user-initiated deletes (releaseForDeletion)
3095
+ * and frees the row whoever holds it;
3096
+ * - `delete` serves user-initiated destroys (destroyPoolWorktree) and the
3097
+ * removal of stale or orphaned rows the caller has just claimed;
3098
+ * - `deleteReservation` removes a failed `creating` placeholder, gated on
3099
+ * status only;
3100
+ * - `resetStaleAndPreserve` (startup) checks holder liveness instead of
3101
+ * holding: it reclaims or resets only rows whose holder is dead.
3037
3102
  */
3038
3103
  class WorktreePoolRepository {
3039
3104
  constructor(db) {
@@ -3047,11 +3112,13 @@ class WorktreePoolRepository {
3047
3112
  * @param {string} params.repository - owner/repo
3048
3113
  * @param {string} params.path - Absolute filesystem path
3049
3114
  * @param {number} [params.prNumber] - If provided, insert as 'in_use' for this PR (avoids race with claimAvailable)
3115
+ * @param {number} [params.holderPid] - Required with prNumber: the process that holds the in_use row
3050
3116
  */
3051
- async create({ id, repository, path, prNumber }) {
3117
+ async create({ id, repository, path, prNumber, holderPid }) {
3052
3118
  const now = new Date().toISOString();
3053
3119
  if (prNumber != null) {
3054
- await run(this.db, `INSERT INTO worktree_pool (id, repository, path, status, current_pr_number, last_switched_at, created_at) VALUES (?, ?, ?, 'in_use', ?, ?, ?)`, [id, repository, path, prNumber, now, now]);
3120
+ assertHolderPid(holderPid, 'create');
3121
+ await run(this.db, `INSERT INTO worktree_pool (id, repository, path, status, current_pr_number, last_switched_at, created_at, holder_pid, holder_claimed_at) VALUES (?, ?, ?, 'in_use', ?, ?, ?, ?, ?)`, [id, repository, path, prNumber, now, now, holderPid, now]);
3055
3122
  } else {
3056
3123
  await run(this.db, `INSERT INTO worktree_pool (id, repository, path, status, created_at) VALUES (?, ?, ?, 'available', ?)`, [id, repository, path, now]);
3057
3124
  }
@@ -3109,26 +3176,92 @@ class WorktreePoolRepository {
3109
3176
  }
3110
3177
 
3111
3178
  /**
3112
- * Mark a pool worktree as in_use.
3179
+ * Conditionally mark a pool worktree in_use for a PR, completing a claim
3180
+ * this process already holds. Clears current_review_id (the caller sets
3181
+ * the review owner afterwards).
3182
+ *
3183
+ * - fromStatus 'switching' (end of a PR switch): requires the row to still be
3184
+ * `switching` and held by holderPid.
3185
+ * - fromStatus 'in_use' (end of a refresh): requires the row to still be
3186
+ * `in_use` for this PR and held by holderPid.
3187
+ *
3188
+ * A false return means the row was freed or taken over while the caller was
3189
+ * working on it; nothing is written.
3190
+ *
3191
+ * @param {string} id - Pool worktree ID
3192
+ * @param {number} prNumber - PR number the row is being marked for
3193
+ * @param {number} holderPid - Process that must hold the row
3194
+ * @param {'switching'|'in_use'} fromStatus - Status the row must still be in
3195
+ * @returns {Promise<boolean>} true if the row was updated
3196
+ */
3197
+ async markInUse(id, prNumber, holderPid, fromStatus) {
3198
+ assertHolderPid(holderPid, 'markInUse');
3199
+ const now = new Date().toISOString();
3200
+ let result;
3201
+ if (fromStatus === 'switching') {
3202
+ result = await run(this.db, `UPDATE worktree_pool SET status = 'in_use', current_pr_number = ?, last_switched_at = ?, current_review_id = NULL WHERE id = ? AND status = 'switching' AND holder_pid = ?`, [prNumber, now, id, holderPid]);
3203
+ } else if (fromStatus === 'in_use') {
3204
+ result = await run(this.db, `UPDATE worktree_pool SET status = 'in_use', current_pr_number = ?, last_switched_at = ?, current_review_id = NULL WHERE id = ? AND status = 'in_use' AND current_pr_number = ? AND holder_pid = ?`, [prNumber, now, id, prNumber, holderPid]);
3205
+ } else {
3206
+ throw new TypeError(`WorktreePoolRepository.markInUse: fromStatus must be 'switching' or 'in_use', got ${fromStatus}`);
3207
+ }
3208
+ return result.changes > 0;
3209
+ }
3210
+
3211
+ /**
3212
+ * Atomically take an `available` pool worktree that still carries this PR
3213
+ * back into use (the setup route's reclaim fast path). Conditional on the
3214
+ * row still being available for the same PR, so a peer that claimed it
3215
+ * first is never overwritten.
3216
+ *
3217
+ * @param {string} id - Pool worktree ID
3218
+ * @param {number} prNumber - PR number the row must still carry
3219
+ * @param {number} holderPid - Process taking the row
3220
+ * @returns {Promise<boolean>} true if the row was reclaimed
3113
3221
  */
3114
- async markInUse(id, prNumber) {
3222
+ async reclaimAvailableForPR(id, prNumber, holderPid) {
3223
+ assertHolderPid(holderPid, 'reclaimAvailableForPR');
3115
3224
  const now = new Date().toISOString();
3116
- await run(this.db, `UPDATE worktree_pool SET status = 'in_use', current_pr_number = ?, last_switched_at = ?, current_review_id = NULL WHERE id = ?`, [prNumber, now, id]);
3225
+ const result = await run(this.db, `UPDATE worktree_pool SET status = 'in_use', last_switched_at = ?, current_review_id = NULL, holder_pid = ?, holder_claimed_at = ? WHERE id = ? AND status = 'available' AND current_pr_number = ?`, [now, holderPid, now, id, prNumber]);
3226
+ return result.changes > 0;
3227
+ }
3228
+
3229
+ /**
3230
+ * Mark a pool worktree available (evictable), but only if it is `in_use`
3231
+ * and held by holderPid. Clears review ownership and the holder.
3232
+ *
3233
+ * @param {string} id - Pool worktree ID
3234
+ * @param {number} holderPid - Process that must hold the row
3235
+ * @returns {Promise<boolean>} true if the row was released
3236
+ */
3237
+ async markAvailable(id, holderPid) {
3238
+ assertHolderPid(holderPid, 'markAvailable');
3239
+ const result = await run(this.db, `UPDATE worktree_pool SET status = 'available', current_review_id = NULL, holder_pid = NULL, holder_claimed_at = NULL WHERE id = ? AND status = 'in_use' AND holder_pid = ?`, [id, holderPid]);
3240
+ return result.changes > 0;
3117
3241
  }
3118
3242
 
3119
3243
  /**
3120
- * Mark a pool worktree as available (evictable).
3121
- * Clears current_review_id to release ownership.
3244
+ * Roll back a failed PR switch: return a `switching` row held by holderPid
3245
+ * to `available`. Clears review ownership and the holder.
3246
+ *
3247
+ * @param {string} id - Pool worktree ID
3248
+ * @param {number} holderPid - Process that must hold the row
3249
+ * @returns {Promise<boolean>} true if the row was rolled back
3122
3250
  */
3123
- async markAvailable(id) {
3124
- await run(this.db, `UPDATE worktree_pool SET status = 'available', current_review_id = NULL WHERE id = ?`, [id]);
3251
+ async abandonSwitch(id, holderPid) {
3252
+ assertHolderPid(holderPid, 'abandonSwitch');
3253
+ const result = await run(this.db, `UPDATE worktree_pool SET status = 'available', current_review_id = NULL, holder_pid = NULL, holder_claimed_at = NULL WHERE id = ? AND status = 'switching' AND holder_pid = ?`, [id, holderPid]);
3254
+ return result.changes > 0;
3125
3255
  }
3126
3256
 
3127
3257
  /**
3128
- * Mark a pool worktree as switching (transitional state during PR switch).
3258
+ * Unconditionally mark a pool worktree available, clearing review ownership
3259
+ * and the holder. Only for user-initiated deletes (releaseForDeletion).
3260
+ *
3261
+ * @param {string} id - Pool worktree ID
3129
3262
  */
3130
- async markSwitching(id) {
3131
- await run(this.db, `UPDATE worktree_pool SET status = 'switching' WHERE id = ?`, [id]);
3263
+ async forceMarkAvailable(id) {
3264
+ await run(this.db, `UPDATE worktree_pool SET status = 'available', current_review_id = NULL, holder_pid = NULL, holder_claimed_at = NULL WHERE id = ?`, [id]);
3132
3265
  }
3133
3266
 
3134
3267
  /**
@@ -3246,16 +3379,19 @@ class WorktreePoolRepository {
3246
3379
  * Uses BEGIN IMMEDIATE to serialize against concurrent callers, preventing
3247
3380
  * two requests from both observing spare capacity and both creating slots.
3248
3381
  *
3249
- * Inserts a placeholder row with status 'creating'. The caller must:
3250
- * - On success: call markInUse() to transition to 'in_use'
3382
+ * Inserts a placeholder row with status 'creating', held by holderPid.
3383
+ * The caller must:
3384
+ * - On success: call finalizeReservation() to transition to 'in_use'
3251
3385
  * - On failure: call deleteReservation() to remove the placeholder
3252
3386
  *
3253
3387
  * @param {string} id - Pool worktree ID (e.g., 'pool-abc')
3254
3388
  * @param {string} repository - Repository in "owner/repo" format
3255
3389
  * @param {number} poolSize - Maximum pool slots for this repository
3390
+ * @param {number} holderPid - Process reserving the slot
3256
3391
  * @returns {Promise<boolean>} true if the slot was reserved, false if at capacity
3257
3392
  */
3258
- async reserveSlot(id, repository, poolSize) {
3393
+ async reserveSlot(id, repository, poolSize, holderPid) {
3394
+ assertHolderPid(holderPid, 'reserveSlot');
3259
3395
  const reserveTx = this.db.transaction(() => {
3260
3396
  const row = this.db.prepare(
3261
3397
  `SELECT COUNT(*) as count FROM worktree_pool WHERE repository = ? COLLATE NOCASE`
@@ -3269,8 +3405,8 @@ class WorktreePoolRepository {
3269
3405
  // finalizeReservation will replace it with the real path.
3270
3406
  const placeholderPath = `__creating__${id}`;
3271
3407
  this.db.prepare(
3272
- `INSERT INTO worktree_pool (id, repository, path, status, created_at) VALUES (?, ?, ?, 'creating', ?)`
3273
- ).run(id, repository, placeholderPath, now);
3408
+ `INSERT INTO worktree_pool (id, repository, path, status, created_at, holder_pid, holder_claimed_at) VALUES (?, ?, ?, 'creating', ?, ?, ?)`
3409
+ ).run(id, repository, placeholderPath, now, holderPid, now);
3274
3410
  return true;
3275
3411
  });
3276
3412
  return reserveTx.immediate();
@@ -3279,14 +3415,19 @@ class WorktreePoolRepository {
3279
3415
  /**
3280
3416
  * Finalize a reserved pool slot after successful worktree creation.
3281
3417
  * Updates the placeholder row with the actual path and marks it in_use.
3418
+ * Requires the row to still be `creating` and held by holderPid.
3282
3419
  *
3283
3420
  * @param {string} id - Pool worktree ID
3284
3421
  * @param {string} path - Absolute filesystem path to the created worktree
3285
3422
  * @param {number} prNumber - PR number to assign
3423
+ * @param {number} holderPid - Process that must hold the reservation
3424
+ * @returns {Promise<boolean>} true if the reservation was finalized
3286
3425
  */
3287
- async finalizeReservation(id, path, prNumber) {
3426
+ async finalizeReservation(id, path, prNumber, holderPid) {
3427
+ assertHolderPid(holderPid, 'finalizeReservation');
3288
3428
  const now = new Date().toISOString();
3289
- await run(this.db, `UPDATE worktree_pool SET path = ?, status = 'in_use', current_pr_number = ?, last_switched_at = ? WHERE id = ? AND status = 'creating'`, [path, prNumber, now, id]);
3429
+ const result = await run(this.db, `UPDATE worktree_pool SET path = ?, status = 'in_use', current_pr_number = ?, last_switched_at = ? WHERE id = ? AND status = 'creating' AND holder_pid = ?`, [path, prNumber, now, id, holderPid]);
3430
+ return result.changes > 0;
3290
3431
  }
3291
3432
 
3292
3433
  /**
@@ -3301,26 +3442,35 @@ class WorktreePoolRepository {
3301
3442
  /**
3302
3443
  * Atomically find and claim a pool worktree already assigned to a PR.
3303
3444
  * Uses BEGIN IMMEDIATE to serialize against concurrent callers.
3445
+ * The holder moves to holderPid. Same-PR sharing is intentional: a row
3446
+ * held by another process for the same PR is still taken, and that
3447
+ * process's pid is returned as `previousHolderPid` so the caller can log it.
3304
3448
  *
3305
3449
  * @param {number} prNumber - PR number to find
3306
3450
  * @param {string} repository - Repository in "owner/repo" format
3307
- * @returns {Promise<Object|null>} Claimed pool entry or null if not found
3451
+ * @param {number} holderPid - Process claiming the row
3452
+ * @returns {Promise<Object|null>} Claimed pool entry (with `previousHolderPid`,
3453
+ * null unless a different process held it) or null if not found
3308
3454
  */
3309
- async claimByPR(prNumber, repository) {
3455
+ async claimByPR(prNumber, repository, holderPid) {
3456
+ assertHolderPid(holderPid, 'claimByPR');
3310
3457
  const claimTx = this.db.transaction(() => {
3311
3458
  const entry = this.db.prepare(`
3312
- SELECT id, repository, path, status, current_pr_number, last_switched_at, last_fetched_at, created_at
3459
+ SELECT id, repository, path, status, current_pr_number, last_switched_at, last_fetched_at, created_at, holder_pid
3313
3460
  FROM worktree_pool
3314
3461
  WHERE current_pr_number = ? AND repository = ? COLLATE NOCASE
3315
3462
  AND status IN ('in_use', 'available')
3316
3463
  `).get(prNumber, repository);
3317
- if (entry) {
3318
- const now = new Date().toISOString();
3319
- this.db.prepare(
3320
- `UPDATE worktree_pool SET status = 'in_use', current_pr_number = ?, last_switched_at = ?, current_review_id = NULL WHERE id = ?`
3321
- ).run(prNumber, now, entry.id);
3322
- }
3323
- return entry || null;
3464
+ if (!entry) return null;
3465
+ const now = new Date().toISOString();
3466
+ this.db.prepare(
3467
+ `UPDATE worktree_pool SET status = 'in_use', current_pr_number = ?, last_switched_at = ?, current_review_id = NULL, holder_pid = ?, holder_claimed_at = ? WHERE id = ?`
3468
+ ).run(prNumber, now, holderPid, now, entry.id);
3469
+ const { holder_pid: priorHolder, ...claimed } = entry;
3470
+ return {
3471
+ ...claimed,
3472
+ previousHolderPid: priorHolder != null && priorHolder !== holderPid ? priorHolder : null,
3473
+ };
3324
3474
  });
3325
3475
  return claimTx.immediate();
3326
3476
  }
@@ -3328,12 +3478,15 @@ class WorktreePoolRepository {
3328
3478
  /**
3329
3479
  * Atomically find and claim the LRU available pool worktree for a repository.
3330
3480
  * Uses BEGIN IMMEDIATE to serialize against concurrent callers.
3331
- * Marks the claimed entry as 'switching' so no other caller can grab it.
3481
+ * Marks the claimed entry as 'switching', held by holderPid, so no other
3482
+ * caller can grab it.
3332
3483
  *
3333
3484
  * @param {string} repository - Repository in "owner/repo" format
3485
+ * @param {number} holderPid - Process claiming the row
3334
3486
  * @returns {Promise<Object|null>} Claimed pool entry or null if none available
3335
3487
  */
3336
- async claimAvailable(repository) {
3488
+ async claimAvailable(repository, holderPid) {
3489
+ assertHolderPid(holderPid, 'claimAvailable');
3337
3490
  const claimTx = this.db.transaction(() => {
3338
3491
  const entry = this.db.prepare(`
3339
3492
  SELECT id, repository, path, status, current_pr_number, last_switched_at, last_fetched_at, created_at
@@ -3343,9 +3496,10 @@ class WorktreePoolRepository {
3343
3496
  LIMIT 1
3344
3497
  `).get(repository);
3345
3498
  if (entry) {
3499
+ const now = new Date().toISOString();
3346
3500
  this.db.prepare(
3347
- `UPDATE worktree_pool SET status = 'switching' WHERE id = ?`
3348
- ).run(entry.id);
3501
+ `UPDATE worktree_pool SET status = 'switching', holder_pid = ?, holder_claimed_at = ? WHERE id = ?`
3502
+ ).run(holderPid, now, entry.id);
3349
3503
  }
3350
3504
  return entry || null;
3351
3505
  });
@@ -3354,29 +3508,56 @@ class WorktreePoolRepository {
3354
3508
 
3355
3509
  /**
3356
3510
  * Reset stale pool entries on startup while preserving valid ownership.
3357
- * Entries are considered stale if: no review owner, interrupted switching,
3358
- * or the owning review has been deleted.
3359
- * @returns {Array<{id: string, current_review_id: number}>} Preserved entries for in-memory rehydration
3360
- */
3361
- async resetStaleAndPreserve() {
3362
- // Delete placeholder entries that were mid-creation when the server stopped.
3363
- // These have no valid path or worktree on disk — they cannot be recovered.
3364
- await run(this.db, `DELETE FROM worktree_pool WHERE status = 'creating'`);
3365
-
3366
- // Reset entries that are stale: no review owner, interrupted switching, or review deleted
3367
- await run(this.db, `
3368
- UPDATE worktree_pool SET status = 'available', current_review_id = NULL
3369
- WHERE status != 'available' AND (
3370
- current_review_id IS NULL
3371
- OR status = 'switching'
3372
- OR current_review_id NOT IN (SELECT id FROM reviews)
3373
- )
3374
- `);
3375
- // Return preserved entries for in-memory rehydration
3376
- return await query(this.db, `
3377
- SELECT id, current_review_id FROM worktree_pool
3378
- WHERE status = 'in_use' AND current_review_id IS NOT NULL
3379
- `);
3511
+ * Runs in one IMMEDIATE transaction.
3512
+ *
3513
+ * Rows held by a live process (`isHolderDead(row)` false) are skipped: not
3514
+ * written and not returned — another pair-review process sharing this
3515
+ * database is preparing or using them. For rows whose holder is dead:
3516
+ * - `creating` placeholders are deleted (no worktree on disk to recover);
3517
+ * - `in_use` rows whose review still exists are taken over (holder =
3518
+ * selfPid) and returned for in-memory rehydration;
3519
+ * - everything else (`switching`, `in_use` with no or a deleted review) is
3520
+ * reset to `available` with review ownership and holder cleared.
3521
+ *
3522
+ * @param {number} selfPid - The starting process, which takes over preserved rows
3523
+ * @param {(row: {id: string, status: string, current_review_id: number|null,
3524
+ * holder_pid: number|null, holder_claimed_at: string|null}) => boolean} isHolderDead
3525
+ * Synchronous predicate deciding whether a row's holder is gone
3526
+ * @returns {Promise<Array<{id: string, current_review_id: number}>>} Preserved entries for in-memory rehydration
3527
+ */
3528
+ async resetStaleAndPreserve(selfPid, isHolderDead) {
3529
+ assertHolderPid(selfPid, 'resetStaleAndPreserve');
3530
+ if (typeof isHolderDead !== 'function') {
3531
+ throw new TypeError('WorktreePoolRepository.resetStaleAndPreserve: isHolderDead must be a function');
3532
+ }
3533
+ const resetTx = this.db.transaction(() => {
3534
+ const rows = this.db.prepare(`
3535
+ SELECT wp.id, wp.status, wp.current_review_id, wp.holder_pid, wp.holder_claimed_at,
3536
+ (r.id IS NOT NULL) AS review_exists
3537
+ FROM worktree_pool wp
3538
+ LEFT JOIN reviews r ON r.id = wp.current_review_id
3539
+ WHERE wp.status != 'available'
3540
+ ORDER BY wp.id
3541
+ `).all();
3542
+ const deleteCreating = this.db.prepare(`DELETE FROM worktree_pool WHERE id = ? AND status = 'creating'`);
3543
+ const takeOver = this.db.prepare(`UPDATE worktree_pool SET holder_pid = ?, holder_claimed_at = ? WHERE id = ?`);
3544
+ const reset = this.db.prepare(`UPDATE worktree_pool SET status = 'available', current_review_id = NULL, holder_pid = NULL, holder_claimed_at = NULL WHERE id = ?`);
3545
+ const now = new Date().toISOString();
3546
+ const preserved = [];
3547
+ for (const { review_exists: reviewExists, ...row } of rows) {
3548
+ if (!isHolderDead(row)) continue;
3549
+ if (row.status === 'creating') {
3550
+ deleteCreating.run(row.id);
3551
+ } else if (row.status === 'in_use' && reviewExists) {
3552
+ takeOver.run(selfPid, now, row.id);
3553
+ preserved.push({ id: row.id, current_review_id: row.current_review_id });
3554
+ } else {
3555
+ reset.run(row.id);
3556
+ }
3557
+ }
3558
+ return preserved;
3559
+ });
3560
+ return resetTx.immediate();
3380
3561
  }
3381
3562
  }
3382
3563