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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +8 -0
  2. package/package.json +3 -3
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
  5. package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
  6. package/public/css/pr.css +389 -13
  7. package/public/index.html +1 -0
  8. package/public/js/components/AIPanel.js +317 -99
  9. package/public/js/components/AdvancedConfigTab.js +18 -108
  10. package/public/js/components/ReviewHistoryModal.js +294 -0
  11. package/public/js/components/ReviewModal.js +96 -7
  12. package/public/js/components/SplitButton.js +14 -0
  13. package/public/js/components/VoiceCentricConfigTab.js +18 -108
  14. package/public/js/index.js +18 -5
  15. package/public/js/local.js +4 -8
  16. package/public/js/modules/comment-manager.js +2 -1
  17. package/public/js/modules/diff-renderer.js +7 -6
  18. package/public/js/modules/file-comment-manager.js +6 -2
  19. package/public/js/modules/pierre-bridge.js +35 -1
  20. package/public/js/modules/suggestion-manager.js +4 -1
  21. package/public/js/pr.js +174 -66
  22. package/public/js/utils/council-timeout.js +203 -0
  23. package/public/js/utils/posted-comment.js +259 -14
  24. package/public/js/vendor/pierre-diffs-worker.js +41 -13485
  25. package/public/js/vendor/pierre-diffs.js +131 -1364
  26. package/public/local.html +4 -0
  27. package/public/pr.html +5 -0
  28. package/src/ai/copilot-provider.js +21 -2
  29. package/src/ai/cursor-agent-provider.js +21 -2
  30. package/src/ai/opencode-provider.js +21 -2
  31. package/src/chat/api-reference.js +22 -2
  32. package/src/config.js +28 -4
  33. package/src/database.js +416 -114
  34. package/src/git/worktree-pool-lifecycle.js +152 -33
  35. package/src/git/worktree-pool-usage.js +20 -0
  36. package/src/git/worktree.js +14 -5
  37. package/src/github/client.js +70 -15
  38. package/src/github/impl/graphql/pending-review-comments.js +50 -11
  39. package/src/github/impl/graphql/pending-review.js +8 -2
  40. package/src/github/impl/graphql/review-comment-edit.js +89 -0
  41. package/src/github/impl/host/pending-review-comments.js +41 -10
  42. package/src/github/impl/host/review-comment-edit.js +36 -0
  43. package/src/github/impl/rest/pending-review.js +6 -2
  44. package/src/github/impl/rest/review-comment-edit.js +44 -0
  45. package/src/github/impl/review-comment-edit-utils.js +45 -0
  46. package/src/github/operations/pending-review.js +4 -3
  47. package/src/github/operations/review-comment-edit.js +35 -0
  48. package/src/github/record-submission.js +78 -0
  49. package/src/github/update-posted-comment.js +115 -0
  50. package/src/main.js +42 -50
  51. package/src/routes/mcp.js +1 -0
  52. package/src/routes/pr.js +158 -120
  53. package/src/routes/reviews.js +8 -30
  54. package/src/routes/setup.js +22 -9
  55. package/src/setup/pr-setup.js +12 -3
  56. package/src/utils/diff-file-content.js +62 -25
  57. package/src/utils/json-extractor.js +267 -13
  58. package/src/utils/pr-file-blob-cache.js +134 -0
  59. package/src/utils/process-liveness.js +64 -0
package/src/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 = 55;
24
+ const CURRENT_SCHEMA_VERSION = 59;
25
25
 
26
26
  /**
27
27
  * Database schema SQL statements
@@ -52,6 +52,27 @@ const SCHEMA_SQL = {
52
52
  )
53
53
  `,
54
54
 
55
+ comment_postings: `
56
+ CREATE TABLE IF NOT EXISTS comment_postings (
57
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
58
+ comment_id INTEGER NOT NULL REFERENCES comments(id) ON DELETE CASCADE,
59
+ github_review_row_id INTEGER REFERENCES github_reviews(id) ON DELETE SET NULL,
60
+ comment_body TEXT,
61
+ body TEXT NOT NULL,
62
+ file TEXT,
63
+ line_start INTEGER,
64
+ line_end INTEGER,
65
+ side TEXT,
66
+ is_file_level INTEGER NOT NULL DEFAULT 0,
67
+ github_comment_id TEXT,
68
+ github_comment_node_id TEXT,
69
+ github_comment_url TEXT,
70
+ backfilled INTEGER NOT NULL DEFAULT 0,
71
+ kind TEXT NOT NULL DEFAULT 'post' CHECK (kind IN ('post', 'update')),
72
+ posted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
73
+ )
74
+ `,
75
+
55
76
  comments_old: `
56
77
  CREATE TABLE IF NOT EXISTS comments_old (
57
78
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -333,7 +354,9 @@ const SCHEMA_SQL = {
333
354
  last_fetched_at TEXT,
334
355
  last_fetch_attempt_at TEXT,
335
356
  fetch_failure_count INTEGER NOT NULL DEFAULT 0,
336
- created_at TEXT NOT NULL
357
+ created_at TEXT NOT NULL,
358
+ holder_pid INTEGER,
359
+ holder_claimed_at TEXT
337
360
  )
338
361
  `,
339
362
 
@@ -395,6 +418,8 @@ const SCHEMA_SQL = {
395
418
  * Index SQL statements for performance
396
419
  */
397
420
  const INDEX_SQL = [
421
+ 'CREATE INDEX IF NOT EXISTS idx_comment_postings_comment ON comment_postings(comment_id, id)',
422
+ 'CREATE INDEX IF NOT EXISTS idx_comment_postings_github_review ON comment_postings(github_review_row_id)',
398
423
  'CREATE INDEX IF NOT EXISTS idx_reviews_pr ON reviews(pr_number, repository)',
399
424
  'CREATE INDEX IF NOT EXISTS idx_comments_review_file ON comments(review_id, file, line_start)',
400
425
  'CREATE INDEX IF NOT EXISTS idx_comments_ai_run ON comments(ai_run_id)',
@@ -490,6 +515,27 @@ function tableExists(db, tableName) {
490
515
  return !!row;
491
516
  }
492
517
 
518
+ // Bind each legacy comment's values rather than referencing outer columns in
519
+ // ORDER BY (unsupported by SQLite). Guarding by posting makes crash retry safe.
520
+ function backfillLegacyPostings(db) {
521
+ const comments = db.prepare(`SELECT * FROM comments c
522
+ WHERE status IN ('submitted', 'draft')
523
+ AND NOT EXISTS (SELECT 1 FROM comment_postings p WHERE p.comment_id = c.id)`).all();
524
+ const findReview = db.prepare(`SELECT id FROM github_reviews WHERE review_id = ?
525
+ ORDER BY (state = 'pending') = ? DESC,
526
+ julianday(created_at) <= julianday(?) + 5.0/86400 DESC,
527
+ created_at DESC, id DESC LIMIT 1`);
528
+ const insert = db.prepare(`INSERT INTO comment_postings
529
+ (comment_id, github_review_row_id, comment_body, body, file, line_start, line_end,
530
+ side, is_file_level, backfilled, posted_at)
531
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, COALESCE(?, CURRENT_TIMESTAMP))`);
532
+ for (const c of comments) {
533
+ const review = findReview.get(c.review_id, c.status === 'draft' ? 1 : 0, c.updated_at);
534
+ insert.run(c.id, review?.id ?? null, c.body, c.body ?? '', c.file,
535
+ c.line_start, c.line_end, c.side, c.is_file_level || 0, c.updated_at);
536
+ }
537
+ }
538
+
493
539
  const MIGRATIONS = {
494
540
  // Migration to version 1: handles all legacy column additions
495
541
  1: (db) => {
@@ -2363,6 +2409,78 @@ const MIGRATIONS = {
2363
2409
  console.log(' pool_fetch_owner column already present; nothing to do');
2364
2410
  }
2365
2411
  console.log('Migration to schema version 55 complete');
2412
+ },
2413
+
2414
+ 56: (db) => {
2415
+ db.transaction(() => {
2416
+ db.exec(SCHEMA_SQL.comment_postings);
2417
+ db.exec('CREATE INDEX IF NOT EXISTS idx_comment_postings_comment ON comment_postings(comment_id, id)');
2418
+ db.exec('CREATE INDEX IF NOT EXISTS idx_comment_postings_github_review ON comment_postings(github_review_row_id)');
2419
+ backfillLegacyPostings(db);
2420
+ })();
2421
+ },
2422
+
2423
+ 57: (db) => {
2424
+ db.transaction(() => {
2425
+ backfillLegacyPostings(db);
2426
+ // Fix obsolete pending duplicates without deleting history. Subsequent
2427
+ // upserts propagate state to all rows of the same GitHub identity.
2428
+ const pending = db.prepare("SELECT * FROM github_reviews WHERE state = 'pending'").all();
2429
+ const newer = db.prepare(`SELECT * FROM github_reviews WHERE review_id = ? AND id > ?
2430
+ AND state != 'pending' AND
2431
+ ((? IS NOT NULL AND github_node_id = ?) OR (? IS NOT NULL AND github_review_id = ?))
2432
+ ORDER BY id DESC LIMIT 1`);
2433
+ for (const row of pending) {
2434
+ const match = newer.get(row.review_id, row.id, row.github_node_id, row.github_node_id,
2435
+ row.github_review_id, row.github_review_id);
2436
+ if (match) db.prepare('UPDATE github_reviews SET state = ?, submitted_at = ?, event = ? WHERE id = ?')
2437
+ .run(match.state, match.submitted_at, match.event, row.id);
2438
+ }
2439
+ db.exec("UPDATE comments SET status = 'active' WHERE source = 'user' AND status IN ('submitted', 'draft')");
2440
+ db.exec("UPDATE comments SET status = 'submitted' WHERE source = 'ai' AND status = 'draft'");
2441
+ })();
2442
+ },
2443
+
2444
+ 58: (db) => {
2445
+ if (!columnExists(db, 'comment_postings', 'kind')) {
2446
+ db.exec("ALTER TABLE comment_postings ADD COLUMN kind TEXT NOT NULL DEFAULT 'post' CHECK (kind IN ('post', 'update'))");
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');
2366
2484
  }
2367
2485
  };
2368
2486
 
@@ -2953,7 +3071,34 @@ class WorktreeRepository {
2953
3071
  }
2954
3072
 
2955
3073
  /**
2956
- * 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.
2957
3102
  */
2958
3103
  class WorktreePoolRepository {
2959
3104
  constructor(db) {
@@ -2967,11 +3112,13 @@ class WorktreePoolRepository {
2967
3112
  * @param {string} params.repository - owner/repo
2968
3113
  * @param {string} params.path - Absolute filesystem path
2969
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
2970
3116
  */
2971
- async create({ id, repository, path, prNumber }) {
3117
+ async create({ id, repository, path, prNumber, holderPid }) {
2972
3118
  const now = new Date().toISOString();
2973
3119
  if (prNumber != null) {
2974
- 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]);
2975
3122
  } else {
2976
3123
  await run(this.db, `INSERT INTO worktree_pool (id, repository, path, status, created_at) VALUES (?, ?, ?, 'available', ?)`, [id, repository, path, now]);
2977
3124
  }
@@ -3029,26 +3176,92 @@ class WorktreePoolRepository {
3029
3176
  }
3030
3177
 
3031
3178
  /**
3032
- * 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
3033
3221
  */
3034
- async markInUse(id, prNumber) {
3222
+ async reclaimAvailableForPR(id, prNumber, holderPid) {
3223
+ assertHolderPid(holderPid, 'reclaimAvailableForPR');
3035
3224
  const now = new Date().toISOString();
3036
- 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;
3037
3227
  }
3038
3228
 
3039
3229
  /**
3040
- * Mark a pool worktree as available (evictable).
3041
- * Clears current_review_id to release ownership.
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
3042
3236
  */
3043
- async markAvailable(id) {
3044
- await run(this.db, `UPDATE worktree_pool SET status = 'available', current_review_id = NULL WHERE id = ?`, [id]);
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;
3045
3241
  }
3046
3242
 
3047
3243
  /**
3048
- * Mark a pool worktree as switching (transitional state during PR switch).
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
3049
3250
  */
3050
- async markSwitching(id) {
3051
- await run(this.db, `UPDATE worktree_pool SET status = 'switching' 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;
3255
+ }
3256
+
3257
+ /**
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
3262
+ */
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]);
3052
3265
  }
3053
3266
 
3054
3267
  /**
@@ -3166,16 +3379,19 @@ class WorktreePoolRepository {
3166
3379
  * Uses BEGIN IMMEDIATE to serialize against concurrent callers, preventing
3167
3380
  * two requests from both observing spare capacity and both creating slots.
3168
3381
  *
3169
- * Inserts a placeholder row with status 'creating'. The caller must:
3170
- * - 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'
3171
3385
  * - On failure: call deleteReservation() to remove the placeholder
3172
3386
  *
3173
3387
  * @param {string} id - Pool worktree ID (e.g., 'pool-abc')
3174
3388
  * @param {string} repository - Repository in "owner/repo" format
3175
3389
  * @param {number} poolSize - Maximum pool slots for this repository
3390
+ * @param {number} holderPid - Process reserving the slot
3176
3391
  * @returns {Promise<boolean>} true if the slot was reserved, false if at capacity
3177
3392
  */
3178
- async reserveSlot(id, repository, poolSize) {
3393
+ async reserveSlot(id, repository, poolSize, holderPid) {
3394
+ assertHolderPid(holderPid, 'reserveSlot');
3179
3395
  const reserveTx = this.db.transaction(() => {
3180
3396
  const row = this.db.prepare(
3181
3397
  `SELECT COUNT(*) as count FROM worktree_pool WHERE repository = ? COLLATE NOCASE`
@@ -3189,8 +3405,8 @@ class WorktreePoolRepository {
3189
3405
  // finalizeReservation will replace it with the real path.
3190
3406
  const placeholderPath = `__creating__${id}`;
3191
3407
  this.db.prepare(
3192
- `INSERT INTO worktree_pool (id, repository, path, status, created_at) VALUES (?, ?, ?, 'creating', ?)`
3193
- ).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);
3194
3410
  return true;
3195
3411
  });
3196
3412
  return reserveTx.immediate();
@@ -3199,14 +3415,19 @@ class WorktreePoolRepository {
3199
3415
  /**
3200
3416
  * Finalize a reserved pool slot after successful worktree creation.
3201
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.
3202
3419
  *
3203
3420
  * @param {string} id - Pool worktree ID
3204
3421
  * @param {string} path - Absolute filesystem path to the created worktree
3205
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
3206
3425
  */
3207
- async finalizeReservation(id, path, prNumber) {
3426
+ async finalizeReservation(id, path, prNumber, holderPid) {
3427
+ assertHolderPid(holderPid, 'finalizeReservation');
3208
3428
  const now = new Date().toISOString();
3209
- 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;
3210
3431
  }
3211
3432
 
3212
3433
  /**
@@ -3221,26 +3442,35 @@ class WorktreePoolRepository {
3221
3442
  /**
3222
3443
  * Atomically find and claim a pool worktree already assigned to a PR.
3223
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.
3224
3448
  *
3225
3449
  * @param {number} prNumber - PR number to find
3226
3450
  * @param {string} repository - Repository in "owner/repo" format
3227
- * @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
3228
3454
  */
3229
- async claimByPR(prNumber, repository) {
3455
+ async claimByPR(prNumber, repository, holderPid) {
3456
+ assertHolderPid(holderPid, 'claimByPR');
3230
3457
  const claimTx = this.db.transaction(() => {
3231
3458
  const entry = this.db.prepare(`
3232
- 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
3233
3460
  FROM worktree_pool
3234
3461
  WHERE current_pr_number = ? AND repository = ? COLLATE NOCASE
3235
3462
  AND status IN ('in_use', 'available')
3236
3463
  `).get(prNumber, repository);
3237
- if (entry) {
3238
- const now = new Date().toISOString();
3239
- this.db.prepare(
3240
- `UPDATE worktree_pool SET status = 'in_use', current_pr_number = ?, last_switched_at = ?, current_review_id = NULL WHERE id = ?`
3241
- ).run(prNumber, now, entry.id);
3242
- }
3243
- 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
+ };
3244
3474
  });
3245
3475
  return claimTx.immediate();
3246
3476
  }
@@ -3248,12 +3478,15 @@ class WorktreePoolRepository {
3248
3478
  /**
3249
3479
  * Atomically find and claim the LRU available pool worktree for a repository.
3250
3480
  * Uses BEGIN IMMEDIATE to serialize against concurrent callers.
3251
- * 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.
3252
3483
  *
3253
3484
  * @param {string} repository - Repository in "owner/repo" format
3485
+ * @param {number} holderPid - Process claiming the row
3254
3486
  * @returns {Promise<Object|null>} Claimed pool entry or null if none available
3255
3487
  */
3256
- async claimAvailable(repository) {
3488
+ async claimAvailable(repository, holderPid) {
3489
+ assertHolderPid(holderPid, 'claimAvailable');
3257
3490
  const claimTx = this.db.transaction(() => {
3258
3491
  const entry = this.db.prepare(`
3259
3492
  SELECT id, repository, path, status, current_pr_number, last_switched_at, last_fetched_at, created_at
@@ -3263,9 +3496,10 @@ class WorktreePoolRepository {
3263
3496
  LIMIT 1
3264
3497
  `).get(repository);
3265
3498
  if (entry) {
3499
+ const now = new Date().toISOString();
3266
3500
  this.db.prepare(
3267
- `UPDATE worktree_pool SET status = 'switching' WHERE id = ?`
3268
- ).run(entry.id);
3501
+ `UPDATE worktree_pool SET status = 'switching', holder_pid = ?, holder_claimed_at = ? WHERE id = ?`
3502
+ ).run(holderPid, now, entry.id);
3269
3503
  }
3270
3504
  return entry || null;
3271
3505
  });
@@ -3274,29 +3508,56 @@ class WorktreePoolRepository {
3274
3508
 
3275
3509
  /**
3276
3510
  * Reset stale pool entries on startup while preserving valid ownership.
3277
- * Entries are considered stale if: no review owner, interrupted switching,
3278
- * or the owning review has been deleted.
3279
- * @returns {Array<{id: string, current_review_id: number}>} Preserved entries for in-memory rehydration
3280
- */
3281
- async resetStaleAndPreserve() {
3282
- // Delete placeholder entries that were mid-creation when the server stopped.
3283
- // These have no valid path or worktree on disk — they cannot be recovered.
3284
- await run(this.db, `DELETE FROM worktree_pool WHERE status = 'creating'`);
3285
-
3286
- // Reset entries that are stale: no review owner, interrupted switching, or review deleted
3287
- await run(this.db, `
3288
- UPDATE worktree_pool SET status = 'available', current_review_id = NULL
3289
- WHERE status != 'available' AND (
3290
- current_review_id IS NULL
3291
- OR status = 'switching'
3292
- OR current_review_id NOT IN (SELECT id FROM reviews)
3293
- )
3294
- `);
3295
- // Return preserved entries for in-memory rehydration
3296
- return await query(this.db, `
3297
- SELECT id, current_review_id FROM worktree_pool
3298
- WHERE status = 'in_use' AND current_review_id IS NOT NULL
3299
- `);
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();
3300
3561
  }
3301
3562
  }
3302
3563
 
@@ -3623,7 +3884,32 @@ class RepoSettingsRepository {
3623
3884
  /**
3624
3885
  * CommentRepository class for managing comment database records
3625
3886
  */
3887
+ // Shared joins for list/single/restore responses. Publication is independent
3888
+ // of lifecycle: dismissed comments retain their posting history.
3889
+ const PUBLICATION_JOIN = `LEFT JOIN comment_postings lp ON lp.id =
3890
+ (SELECT MAX(id) FROM comment_postings WHERE comment_id = c.id)
3891
+ LEFT JOIN github_reviews lgr ON lgr.id = lp.github_review_row_id`;
3892
+ const PUBLICATION_COLUMNS = `lp.id AS posting_id, lp.posted_at AS publication_posted_at,
3893
+ lp.github_review_row_id, lp.github_comment_url, lgr.github_url AS review_url,
3894
+ lgr.state AS publication_review_state, lp.comment_body IS NOT c.body AS publication_changed,
3895
+ (SELECT COUNT(*) FROM comment_postings WHERE comment_id = c.id) AS posting_count`;
3896
+
3897
+ function shapePublication(row) {
3898
+ if (!row) return row;
3899
+ const { posting_id, publication_posted_at, github_review_row_id,
3900
+ github_comment_url, review_url, publication_review_state, publication_changed, posting_count, ...comment } = row;
3901
+ return { ...comment, publication: posting_id == null ? null : {
3902
+ state: publication_review_state === 'pending' ? 'draft' : 'posted',
3903
+ posted_at: publication_posted_at, review_url, comment_url: github_comment_url,
3904
+ github_review_row_id, posting_count, changed: Boolean(publication_changed)
3905
+ } };
3906
+ }
3907
+
3626
3908
  class CommentRepository {
3909
+ // Mirrored by isPendingComment in posted-comment.js; pinned by parity tests.
3910
+ static pendingCommentSql(alias = 'c') {
3911
+ return `${alias}.status = 'active' AND NOT EXISTS (SELECT 1 FROM comment_postings p WHERE p.comment_id = ${alias}.id)`;
3912
+ }
3627
3913
  /**
3628
3914
  * Create a new CommentRepository instance
3629
3915
  * @param {Database} db - Database instance
@@ -3855,7 +4141,7 @@ class CommentRepository {
3855
4141
  * @returns {Promise<Object|null>} Comment record or null if not found
3856
4142
  */
3857
4143
  async getComment(id, source = null) {
3858
- let sql = 'SELECT * FROM comments WHERE id = ?';
4144
+ let sql = `SELECT c.*, ${PUBLICATION_COLUMNS} FROM comments c ${PUBLICATION_JOIN} WHERE c.id = ?`;
3859
4145
  const params = [id];
3860
4146
 
3861
4147
  if (source) {
@@ -3863,7 +4149,7 @@ class CommentRepository {
3863
4149
  params.push(source);
3864
4150
  }
3865
4151
 
3866
- return await queryOne(this.db, sql, params);
4152
+ return shapePublication(await queryOne(this.db, sql, params));
3867
4153
  }
3868
4154
 
3869
4155
  /**
@@ -3925,7 +4211,7 @@ class CommentRepository {
3925
4211
  }
3926
4212
 
3927
4213
  /**
3928
- * Bulk delete all user comments for a review
4214
+ * Bulk dismiss only user comments not yet posted for a review
3929
4215
  * Also dismisses any AI suggestions that were parents of the deleted comments.
3930
4216
  * @param {number} reviewId - Review ID (from reviews table)
3931
4217
  * @returns {Promise<{deletedCount: number, dismissedSuggestionIds: number[]}>} Number of comments deleted and list of dismissed suggestion IDs
@@ -3943,16 +4229,16 @@ class CommentRepository {
3943
4229
 
3944
4230
  // First, find all user comments with parent_id (adopted from AI suggestions)
3945
4231
  const adoptedComments = await query(this.db, `
3946
- SELECT parent_id FROM comments
4232
+ SELECT parent_id FROM comments c
3947
4233
  WHERE review_id = ? AND source = 'user' AND parent_id IS NOT NULL
3948
- AND status IN ('active', 'submitted', 'draft')
4234
+ AND ${CommentRepository.pendingCommentSql()}
3949
4235
  `, [reviewId]);
3950
4236
 
3951
4237
  // Soft delete all user comments
3952
4238
  const result = await run(this.db, `
3953
- UPDATE comments
4239
+ UPDATE comments AS c
3954
4240
  SET status = 'inactive', updated_at = CURRENT_TIMESTAMP
3955
- WHERE review_id = ? AND source = 'user' AND status IN ('active', 'submitted', 'draft')
4241
+ WHERE review_id = ? AND source = 'user' AND ${CommentRepository.pendingCommentSql()}
3956
4242
  `, [reviewId]);
3957
4243
 
3958
4244
  // Dismiss all parent AI suggestions with a single UPDATE statement
@@ -3975,27 +4261,6 @@ class CommentRepository {
3975
4261
  return { deletedCount: result.changes, dismissedSuggestionIds };
3976
4262
  }
3977
4263
 
3978
- /**
3979
- * Mark every comment held in the review's pending GitHub draft as submitted.
3980
- *
3981
- * A comment gets status 'draft' only when it is added to a pending review on
3982
- * GitHub (Save as Draft, or headless --ai-draft). Submitting that pending
3983
- * review publishes all of its comments, so callers run this after a non-draft
3984
- * submit that reused an existing pending review, inside the same transaction
3985
- * as the rest of the submission bookkeeping.
3986
- * @param {number} reviewId - Review ID (from reviews table)
3987
- * @param {string} [updatedAt] - Timestamp to record (default: now)
3988
- * @returns {Promise<number>} Number of comments marked submitted
3989
- */
3990
- async markDraftCommentsSubmitted(reviewId, updatedAt = new Date().toISOString()) {
3991
- const result = await run(this.db, `
3992
- UPDATE comments
3993
- SET status = 'submitted', updated_at = ?
3994
- WHERE review_id = ? AND status = 'draft'
3995
- `, [updatedAt, reviewId]);
3996
- return result.changes;
3997
- }
3998
-
3999
4264
  /**
4000
4265
  * Get all user comments for a review
4001
4266
  * @param {number} reviewId - Review ID (from reviews table)
@@ -4005,33 +4270,14 @@ class CommentRepository {
4005
4270
  */
4006
4271
  async getUserComments(reviewId, options = {}) {
4007
4272
  const { includeDismissed = false } = options;
4008
- const statusFilter = includeDismissed
4009
- ? "status IN ('active', 'submitted', 'draft', 'inactive')"
4010
- : "status IN ('active', 'submitted', 'draft')";
4011
-
4012
- return await query(this.db, `
4013
- SELECT
4014
- id,
4015
- source,
4016
- author,
4017
- file,
4018
- line_start,
4019
- line_end,
4020
- side,
4021
- diff_position,
4022
- type,
4023
- title,
4024
- body,
4025
- status,
4026
- parent_id,
4027
- is_file_level,
4028
- severity,
4029
- created_at,
4030
- updated_at
4031
- FROM comments
4032
- WHERE review_id = ? AND source = 'user' AND ${statusFilter}
4033
- ORDER BY file, line_start, created_at
4273
+ const statusFilter = includeDismissed ? "c.status IN ('active', 'inactive')" : "c.status = 'active'";
4274
+ const rows = await query(this.db, `
4275
+ SELECT c.*, ${PUBLICATION_COLUMNS}
4276
+ FROM comments c ${PUBLICATION_JOIN}
4277
+ WHERE c.review_id = ? AND c.source = 'user' AND ${statusFilter}
4278
+ ORDER BY c.file, c.line_start, c.created_at
4034
4279
  `, [reviewId]);
4280
+ return rows.map(shapePublication);
4035
4281
  }
4036
4282
 
4037
4283
  /**
@@ -4087,7 +4333,8 @@ class CommentRepository {
4087
4333
  }
4088
4334
 
4089
4335
  /**
4090
- * Restore a soft-deleted user comment (set status from 'inactive' back to 'active')
4336
+ * Restore a soft-deleted user comment. Postings survive dismissal, so
4337
+ * restoring a posted comment does not queue it for another submission.
4091
4338
  * @param {number} id - Comment ID
4092
4339
  * @returns {Promise<boolean>} True if restored successfully
4093
4340
  */
@@ -5675,6 +5922,33 @@ class AnalysisRunRepository {
5675
5922
  /**
5676
5923
  * GitHubReviewRepository class for managing GitHub review submission records
5677
5924
  */
5925
+ class CommentPostingRepository {
5926
+ constructor(db) { this.db = db; }
5927
+
5928
+ async insertMany(postings) {
5929
+ for (const p of postings) {
5930
+ await run(this.db, `INSERT INTO comment_postings
5931
+ (comment_id, github_review_row_id, comment_body, body, file, line_start,
5932
+ line_end, side, is_file_level, github_comment_id, github_comment_node_id,
5933
+ github_comment_url, backfilled, kind, posted_at)
5934
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(?, CURRENT_TIMESTAMP))`,
5935
+ [p.comment_id, p.github_review_row_id ?? null, p.comment_body ?? null, p.body,
5936
+ p.file ?? null, p.line_start ?? null, p.line_end ?? null, p.side ?? null,
5937
+ p.is_file_level ? 1 : 0, p.github_comment_id == null ? null : String(p.github_comment_id),
5938
+ p.github_comment_node_id ?? null, p.github_comment_url ?? null,
5939
+ p.backfilled ? 1 : 0, p.kind ?? 'post', p.posted_at ?? null]);
5940
+ }
5941
+ }
5942
+
5943
+ async listByComment(commentId) {
5944
+ return query(this.db, 'SELECT * FROM comment_postings WHERE comment_id = ? ORDER BY id', [commentId]);
5945
+ }
5946
+
5947
+ async listByGitHubReviewRow(rowId) {
5948
+ return query(this.db, 'SELECT * FROM comment_postings WHERE github_review_row_id = ? ORDER BY id', [rowId]);
5949
+ }
5950
+ }
5951
+
5678
5952
  class GitHubReviewRepository {
5679
5953
  /**
5680
5954
  * Create a new GitHubReviewRepository instance
@@ -5697,6 +5971,30 @@ class GitHubReviewRepository {
5697
5971
  * @param {string} [data.github_url] - GitHub URL for the review
5698
5972
  * @returns {Promise<Object>} Created github_review record
5699
5973
  */
5974
+ async findByGitHubIdentity(reviewId, { nodeId = null, databaseId = null } = {}) {
5975
+ return queryOne(this.db, `SELECT * FROM github_reviews WHERE review_id = ?
5976
+ AND ((? IS NOT NULL AND github_node_id = ?) OR (? IS NOT NULL AND github_review_id = ?))
5977
+ ORDER BY id DESC LIMIT 1`, [reviewId, nodeId, nodeId, databaseId, databaseId]);
5978
+ }
5979
+
5980
+ async upsertForSubmission(reviewId, data) {
5981
+ const identity = { nodeId: data.github_node_id, databaseId: data.github_review_id };
5982
+ const existing = await this.findByGitHubIdentity(reviewId, identity);
5983
+ if (!existing) return this.create(reviewId, data);
5984
+ const update = { ...data };
5985
+ if (!update.github_url) delete update.github_url;
5986
+ if (data.state === 'pending') delete update.body; // GitHub ignores a replacement draft body.
5987
+ await this.update(existing.id, update);
5988
+ // Preserve legacy duplicate rows, but never leave their linked postings in
5989
+ // an obsolete pending state after the identity has been submitted.
5990
+ await run(this.db, `UPDATE github_reviews SET state = ?, submitted_at = ?, event = ?
5991
+ WHERE review_id = ? AND id != ? AND
5992
+ ((? IS NOT NULL AND github_node_id = ?) OR (? IS NOT NULL AND github_review_id = ?))`,
5993
+ [data.state, data.submitted_at ?? null, data.event ?? null, reviewId, existing.id,
5994
+ identity.nodeId ?? null, identity.nodeId ?? null, identity.databaseId ?? null, identity.databaseId ?? null]);
5995
+ return this.getById(existing.id);
5996
+ }
5997
+
5700
5998
  async create(reviewId, data = {}) {
5701
5999
  const {
5702
6000
  github_review_id = null,
@@ -6430,6 +6728,7 @@ module.exports = {
6430
6728
  getDatabaseStatus,
6431
6729
  getSchemaVersion,
6432
6730
  CURRENT_SCHEMA_VERSION,
6731
+ runVersionedMigrations,
6433
6732
  getDbPath,
6434
6733
  WorktreeRepository,
6435
6734
  WorktreePoolRepository,
@@ -6448,7 +6747,10 @@ module.exports = {
6448
6747
  TourRepository,
6449
6748
  generateWorktreeId,
6450
6749
  migrateExistingWorktrees,
6750
+ shapePublication,
6751
+ CommentPostingRepository,
6451
6752
  // Exported for testing only
6753
+ _setupSchema: setupSchema,
6452
6754
  _MIGRATIONS: MIGRATIONS,
6453
6755
  MIGRATIONS
6454
6756
  };