@in-the-loop-labs/pair-review 5.0.2 → 5.1.0

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/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 = 54;
24
+ const CURRENT_SCHEMA_VERSION = 55;
25
25
 
26
26
  /**
27
27
  * Database schema SQL statements
@@ -158,6 +158,7 @@ const SCHEMA_SQL = {
158
158
  pool_fetch_interval_minutes INTEGER,
159
159
  pool_fetch_started_at TEXT,
160
160
  pool_fetch_finished_at TEXT,
161
+ pool_fetch_owner TEXT,
161
162
  load_skills INTEGER,
162
163
  created_at TEXT DEFAULT CURRENT_TIMESTAMP,
163
164
  updated_at TEXT DEFAULT CURRENT_TIMESTAMP
@@ -330,6 +331,8 @@ const SCHEMA_SQL = {
330
331
  current_review_id INTEGER,
331
332
  last_switched_at TEXT,
332
333
  last_fetched_at TEXT,
334
+ last_fetch_attempt_at TEXT,
335
+ fetch_failure_count INTEGER NOT NULL DEFAULT 0,
333
336
  created_at TEXT NOT NULL
334
337
  )
335
338
  `,
@@ -2320,6 +2323,46 @@ const MIGRATIONS = {
2320
2323
  }
2321
2324
  db.exec('CREATE INDEX IF NOT EXISTS idx_chat_snippets_last_used ON chat_snippets(last_used_at DESC)');
2322
2325
  console.log('Migration to schema version 54 complete');
2326
+ },
2327
+
2328
+ // Migration to version 55: track background fetch attempts (not just
2329
+ // successes) on pool worktrees. `last_fetched_at` only advances on success,
2330
+ // so a repeatedly failing fetch stayed permanently "due" and re-ran every
2331
+ // tick — on a large monorepo that re-downloaded the same pack forever.
2332
+ // `last_fetch_attempt_at` + `fetch_failure_count` drive an exponential
2333
+ // backoff instead. Also records which instance holds the repo fetch lease
2334
+ // (`pool_fetch_owner`) so a stale heartbeat cannot refresh — or a late
2335
+ // release cannot clear — a lease another instance has since claimed.
2336
+ // Each ALTER is guarded by columnExists so re-running the migration after a
2337
+ // crash is safe, and each table is guarded independently so a partial apply
2338
+ // finishes the remaining pieces.
2339
+ 55: (db) => {
2340
+ console.log('Running migration to schema version 55: add fetch attempt tracking to worktree_pool...');
2341
+ if (!tableExists(db, 'worktree_pool')) {
2342
+ console.log(' worktree_pool table does not exist, skipping');
2343
+ } else {
2344
+ if (!columnExists(db, 'worktree_pool', 'last_fetch_attempt_at')) {
2345
+ db.exec('ALTER TABLE worktree_pool ADD COLUMN last_fetch_attempt_at TEXT');
2346
+ console.log(' Added last_fetch_attempt_at column to worktree_pool');
2347
+ } else {
2348
+ console.log(' last_fetch_attempt_at column already present; nothing to do');
2349
+ }
2350
+ if (!columnExists(db, 'worktree_pool', 'fetch_failure_count')) {
2351
+ db.exec('ALTER TABLE worktree_pool ADD COLUMN fetch_failure_count INTEGER NOT NULL DEFAULT 0');
2352
+ console.log(' Added fetch_failure_count column to worktree_pool');
2353
+ } else {
2354
+ console.log(' fetch_failure_count column already present; nothing to do');
2355
+ }
2356
+ }
2357
+ if (!tableExists(db, 'repo_settings')) {
2358
+ console.log(' repo_settings table does not exist, skipping fetch lease owner');
2359
+ } else if (!columnExists(db, 'repo_settings', 'pool_fetch_owner')) {
2360
+ db.exec('ALTER TABLE repo_settings ADD COLUMN pool_fetch_owner TEXT');
2361
+ console.log(' Added pool_fetch_owner column to repo_settings');
2362
+ } else {
2363
+ console.log(' pool_fetch_owner column already present; nothing to do');
2364
+ }
2365
+ console.log('Migration to schema version 55 complete');
2323
2366
  }
2324
2367
  };
2325
2368
 
@@ -3009,11 +3052,32 @@ class WorktreePoolRepository {
3009
3052
  }
3010
3053
 
3011
3054
  /**
3012
- * Update last_fetched_at timestamp.
3055
+ * Record a successful fetch: stamp both the success and attempt timestamps
3056
+ * and clear the failure streak that drives the backoff.
3013
3057
  */
3014
3058
  async updateLastFetched(id) {
3015
3059
  const now = new Date().toISOString();
3016
- await run(this.db, `UPDATE worktree_pool SET last_fetched_at = ? WHERE id = ?`, [now, id]);
3060
+ await run(this.db, `UPDATE worktree_pool SET last_fetched_at = ?, last_fetch_attempt_at = ?, fetch_failure_count = 0 WHERE id = ?`, [now, now, id]);
3061
+ }
3062
+
3063
+ /**
3064
+ * Stamp last_fetch_attempt_at before a fetch starts, so a fetch that is
3065
+ * killed (or that dies with the whole process) still backs off on restart.
3066
+ */
3067
+ async recordFetchAttempt(id) {
3068
+ const now = new Date().toISOString();
3069
+ await run(this.db, `UPDATE worktree_pool SET last_fetch_attempt_at = ? WHERE id = ?`, [now, id]);
3070
+ }
3071
+
3072
+ /**
3073
+ * Increment the consecutive failure count for a pool worktree's fetch and
3074
+ * re-stamp the attempt time. The backoff is measured from when the failure
3075
+ * landed, not when the fetch started — otherwise a fetch that grinds for most
3076
+ * of its timeout consumes its own cooldown and retries almost immediately.
3077
+ */
3078
+ async recordFetchFailure(id) {
3079
+ const now = new Date().toISOString();
3080
+ await run(this.db, `UPDATE worktree_pool SET fetch_failure_count = fetch_failure_count + 1, last_fetch_attempt_at = ? WHERE id = ?`, [now, id]);
3017
3081
  }
3018
3082
 
3019
3083
  /**
@@ -3045,7 +3109,7 @@ class WorktreePoolRepository {
3045
3109
  */
3046
3110
  async findAllForFetch(repository) {
3047
3111
  return await query(this.db, `
3048
- SELECT id, path, last_fetched_at, status
3112
+ SELECT id, path, last_fetched_at, last_fetch_attempt_at, fetch_failure_count, status
3049
3113
  FROM worktree_pool
3050
3114
  WHERE repository = ? COLLATE NOCASE AND status NOT IN ('switching', 'creating')
3051
3115
  ORDER BY last_fetched_at ASC NULLS FIRST
@@ -3471,45 +3535,61 @@ class RepoSettingsRepository {
3471
3535
  * Uses SQLite UPSERT with a conditional WHERE clause to avoid TOCTOU races
3472
3536
  * between instances sharing the same database. Creates a repo_settings row
3473
3537
  * if one doesn't exist yet (config-only repos).
3538
+ *
3539
+ * The claim stamps `pool_fetch_owner` with the caller's instance id. Refresh
3540
+ * and release are gated on that token, so an instance whose lease already
3541
+ * expired and was taken over cannot extend or clear the new holder's lease.
3542
+ *
3474
3543
  * @param {string} repository - Repository in owner/repo format
3544
+ * @param {string} ownerId - Opaque id identifying the claiming instance
3475
3545
  * @param {number} [staleGuardMs=600000] - Consider a fetch stale after this many ms (default 10 min)
3476
3546
  * @returns {Promise<boolean>} true if the lease was successfully claimed
3477
3547
  */
3478
- async tryClaimFetch(repository, staleGuardMs = 600000) {
3548
+ async tryClaimFetch(repository, ownerId, staleGuardMs = 600000) {
3479
3549
  const now = new Date().toISOString();
3480
3550
  const staleThreshold = new Date(Date.now() - staleGuardMs).toISOString();
3481
3551
  const result = await run(this.db,
3482
- `INSERT INTO repo_settings (repository, pool_fetch_started_at, created_at, updated_at)
3483
- VALUES (?, ?, ?, ?)
3552
+ `INSERT INTO repo_settings (repository, pool_fetch_started_at, pool_fetch_owner, created_at, updated_at)
3553
+ VALUES (?, ?, ?, ?, ?)
3484
3554
  ON CONFLICT(repository) DO UPDATE SET pool_fetch_started_at = excluded.pool_fetch_started_at,
3555
+ pool_fetch_owner = excluded.pool_fetch_owner,
3485
3556
  pool_fetch_finished_at = NULL
3486
3557
  WHERE pool_fetch_started_at IS NULL
3487
3558
  OR pool_fetch_finished_at >= pool_fetch_started_at
3488
3559
  OR pool_fetch_started_at < ?`,
3489
- [repository, now, now, now, staleThreshold]
3560
+ [repository, now, ownerId ?? null, now, now, staleThreshold]
3490
3561
  );
3491
3562
  return result.changes > 0;
3492
3563
  }
3493
3564
 
3494
3565
  /**
3495
- * Refresh the fetch lease timestamp for a repository.
3496
- * Called after each successful worktree fetch to extend the stale guard window
3497
- * so the 10-minute default only needs to outlive a single stalled fetch rather
3498
- * than the entire serial loop across all worktrees.
3566
+ * Extend the fetch lease for a repository (heartbeat).
3567
+ *
3568
+ * A single healthy fetch on a large monorepo can outlive the 10-minute stale
3569
+ * guard, so the holder re-stamps `pool_fetch_started_at` periodically while
3570
+ * its fetches run; without that, another instance would deem the lease stale
3571
+ * mid-fetch and start a concurrent fetch into the same object store.
3572
+ * The update is a no-op unless `ownerId` still matches the recorded owner, so
3573
+ * a heartbeat from an instance that already lost the lease cannot revive it.
3574
+ *
3499
3575
  * @param {string} repository - Repository in owner/repo format
3576
+ * @param {string} ownerId - Instance id that claimed the lease
3500
3577
  */
3501
- async refreshFetchLease(repository) {
3578
+ async refreshFetchLease(repository, ownerId) {
3502
3579
  const now = new Date().toISOString();
3503
- await run(this.db, `UPDATE repo_settings SET pool_fetch_started_at = ? WHERE repository = ?`, [now, repository]);
3580
+ await run(this.db, `UPDATE repo_settings SET pool_fetch_started_at = ? WHERE repository = ? AND pool_fetch_owner = ?`, [now, repository, ownerId ?? null]);
3504
3581
  }
3505
3582
 
3506
3583
  /**
3507
3584
  * Mark a repo-level background fetch as finished.
3585
+ * Only the instance that still owns the lease may release it — a late release
3586
+ * from a previous holder must not clear a lease someone else has claimed.
3508
3587
  * @param {string} repository - Repository in owner/repo format
3588
+ * @param {string} ownerId - Instance id that claimed the lease
3509
3589
  */
3510
- async markFetchFinished(repository) {
3590
+ async markFetchFinished(repository, ownerId) {
3511
3591
  const now = new Date().toISOString();
3512
- await run(this.db, `UPDATE repo_settings SET pool_fetch_finished_at = ? WHERE repository = ?`, [now, repository]);
3592
+ await run(this.db, `UPDATE repo_settings SET pool_fetch_finished_at = ? WHERE repository = ? AND pool_fetch_owner = ?`, [now, repository, ownerId ?? null]);
3513
3593
  }
3514
3594
 
3515
3595
  /**
@@ -1,4 +1,5 @@
1
1
  // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const logger = require('../utils/logger');
2
3
 
3
4
  /**
4
5
  * Fetch from a remote without auto-following tags reachable from the fetched
@@ -23,7 +24,54 @@ async function rawFetchNoTags(git, args) {
23
24
  return git.raw(['fetch', '--no-tags', ...args]);
24
25
  }
25
26
 
27
+ /**
28
+ * Detect whether a fetch failed because a remote-tracking ref collides with the
29
+ * ref hierarchy (a directory/file conflict, e.g. `refs/remotes/origin/foo`
30
+ * exists as a ref while `refs/remotes/origin/foo/bar` needs to be created).
31
+ *
32
+ * `cannot lock ref` on its own is too broad: git emits it for transient
33
+ * lock-file races too ("cannot lock ref 'X': Unable to create '….lock': File
34
+ * exists"), which pruning cannot fix and which would waste a full prune + refetch.
35
+ * A genuine D/F conflict names the colliding ref in quotes — "'refs/remotes/
36
+ * origin/foo' exists" — so require that quoted-ref " exists" clause alongside it.
37
+ *
38
+ * @param {Error} error
39
+ * @returns {boolean}
40
+ */
41
+ function isRefHierarchyConflict(error) {
42
+ const message = String(error?.message || '').toLowerCase();
43
+ if (message.includes('exists; cannot create')) return true;
44
+ if (message.includes('would clobber existing tag')) return true;
45
+ return message.includes('cannot lock ref') && message.includes("' exists");
46
+ }
47
+
48
+ /**
49
+ * Fetch a single refspec from a remote, recovering once from ref hierarchy
50
+ * conflicts by pruning stale remote-tracking refs and retrying.
51
+ *
52
+ * `git remote prune` is used rather than `git fetch --prune` on purpose: it
53
+ * deletes stale remote-tracking refs without downloading anything, so the
54
+ * recovery path stays cheap on large monorepos.
55
+ *
56
+ * @param {Object} git - simple-git instance
57
+ * @param {string} remote - Remote name
58
+ * @param {string} refspec - Refspec to fetch
59
+ * @returns {Promise<*>}
60
+ */
61
+ async function fetchWithPruneRecovery(git, remote, refspec) {
62
+ try {
63
+ return await fetchNoTags(git, [remote, refspec]);
64
+ } catch (error) {
65
+ if (!isRefHierarchyConflict(error)) throw error;
66
+ logger.info(`Ref hierarchy conflict fetching ${refspec} from ${remote}, pruning stale remote-tracking refs and retrying: ${error.message}`);
67
+ await git.raw(['remote', 'prune', remote]);
68
+ return fetchNoTags(git, [remote, refspec]);
69
+ }
70
+ }
71
+
26
72
  module.exports = {
27
73
  fetchNoTags,
28
74
  rawFetchNoTags,
75
+ isRefHierarchyConflict,
76
+ fetchWithPruneRecovery,
29
77
  };
@@ -0,0 +1,120 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ const fs = require('fs');
3
+ const os = require('os');
4
+ const path = require('path');
5
+ const logger = require('../utils/logger');
6
+
7
+ // Default dependencies (overridable for testing)
8
+ const defaults = {
9
+ fs,
10
+ os,
11
+ logger,
12
+ process,
13
+ };
14
+
15
+ // `.keep` bodies are written by git as "<program> <pid> on <hostname>",
16
+ // e.g. "fetch-pack 20739 on Hostname.local".
17
+ const KEEP_CONTENT_RE = /^(\S+)\s+(\d+)\s+on\s+(.+?)\s*$/;
18
+
19
+ /**
20
+ * Check whether a process id is still running on this machine.
21
+ * Signal 0 performs the permission/existence check without delivering a signal.
22
+ * EPERM means the process exists but belongs to another user — still alive.
23
+ *
24
+ * @param {number} pid
25
+ * @param {object} [_deps] - Internal: dependency overrides for testing
26
+ * @returns {boolean}
27
+ */
28
+ function isPidAlive(pid, _deps) {
29
+ const deps = { ...defaults, ..._deps };
30
+ try {
31
+ deps.process.kill(pid, 0);
32
+ return true;
33
+ } catch (err) {
34
+ return err?.code === 'EPERM';
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Remove `pack-*.keep` markers left behind by git processes that no longer
40
+ * exist.
41
+ *
42
+ * A `.keep` file tells git "a process is actively depending on this pack, do
43
+ * not touch it". `git repack`/`git gc` silently skip kept packs and still exit
44
+ * 0, so a marker orphaned by a killed `git fetch` permanently prevents the
45
+ * pack's disk space from ever being reclaimed.
46
+ *
47
+ * Only the marker is removed, never the pack or its index: git can be killed
48
+ * between updating refs and removing the `.keep`, so an orphan-kept pack may
49
+ * hold objects that live refs point at. Dropping the marker makes the pack a
50
+ * normal candidate for `git repack`/`gc`, which will keep whatever is still
51
+ * reachable and discard the rest — deleting the pack ourselves would corrupt
52
+ * the repository.
53
+ *
54
+ * A marker is removed only when its contents parse, name this host, and name a
55
+ * pid that is no longer alive. Anything else is left alone.
56
+ *
57
+ * @param {string} packDir - Path to the repository's objects/pack directory
58
+ * @param {object} [_deps] - Internal: dependency overrides for testing
59
+ * @returns {Promise<{scanned: number, removed: number, skipped: number, errors: number}>}
60
+ */
61
+ async function cleanupOrphanedKeepFiles(packDir, _deps) {
62
+ const deps = { ...defaults, ..._deps };
63
+ const summary = { scanned: 0, removed: 0, skipped: 0, errors: 0 };
64
+
65
+ let entries;
66
+ try {
67
+ entries = deps.fs.readdirSync(packDir);
68
+ } catch (err) {
69
+ // A missing pack directory is normal (fresh/empty object store).
70
+ if (err?.code !== 'ENOENT') {
71
+ summary.errors++;
72
+ deps.logger.warn(`Could not scan pack directory ${packDir}: ${err.message}`);
73
+ }
74
+ return summary;
75
+ }
76
+
77
+ const hostname = deps.os.hostname();
78
+ const removedNames = [];
79
+
80
+ for (const name of entries) {
81
+ if (!name.endsWith('.keep')) continue;
82
+ summary.scanned++;
83
+
84
+ const keepPath = path.join(packDir, name);
85
+ try {
86
+ const content = deps.fs.readFileSync(keepPath, 'utf-8').trim();
87
+ const match = KEEP_CONTENT_RE.exec(content);
88
+ if (!match) {
89
+ summary.skipped++;
90
+ continue;
91
+ }
92
+
93
+ const pid = Number(match[2]);
94
+ const keepHost = match[3];
95
+ // A pid from another machine says nothing about our process table.
96
+ if (keepHost !== hostname || isPidAlive(pid, _deps)) {
97
+ summary.skipped++;
98
+ continue;
99
+ }
100
+
101
+ deps.fs.unlinkSync(keepPath);
102
+ summary.removed++;
103
+ removedNames.push(name);
104
+ } catch (err) {
105
+ summary.errors++;
106
+ deps.logger.warn(`Could not process keep file ${keepPath}: ${err.message}`);
107
+ }
108
+ }
109
+
110
+ if (summary.removed > 0) {
111
+ deps.logger.info(`Removed ${summary.removed} orphaned pack .keep file(s) in ${packDir}: ${removedNames.join(', ')}`);
112
+ }
113
+
114
+ return summary;
115
+ }
116
+
117
+ module.exports = {
118
+ isPidAlive,
119
+ cleanupOrphanedKeepFiles,
120
+ };
@@ -8,7 +8,7 @@ const { WorktreeRepository, generateWorktreeId } = require('../database');
8
8
  const { getGeneratedFilePatterns } = require('./gitattributes');
9
9
  const { normalizeRepository, resolveRenamedFile, resolveRenamedFileOld } = require('../utils/paths');
10
10
  const { GIT_DIFF_FLAGS_ARRAY, GIT_DIFF_SUMMARY_FLAGS_ARRAY } = require('./diff-flags');
11
- const { fetchNoTags, rawFetchNoTags } = require('./fetch-helpers');
11
+ const { rawFetchNoTags, fetchWithPruneRecovery } = require('./fetch-helpers');
12
12
  const { spawn, execSync } = require('child_process');
13
13
 
14
14
  const MISSING_COMMIT_ERROR_CODE = 'PAIR_REVIEW_MISSING_COMMIT';
@@ -371,7 +371,9 @@ class GitWorktreeManager {
371
371
  const prTrackingRef = `refs/remotes/${baseRemote}/pr-${prNumber}`;
372
372
 
373
373
  try {
374
- await fetchNoTags(git, [baseRemote, `+refs/pull/${prNumber}/head:${prTrackingRef}`]);
374
+ // Through fetchWithPruneRecovery so a stale `pr-N/*` remote-tracking
375
+ // hierarchy self-heals instead of failing every fetch for this PR.
376
+ await fetchWithPruneRecovery(git, baseRemote, `+refs/pull/${prNumber}/head:${prTrackingRef}`);
375
377
  return {
376
378
  remote: baseRemote,
377
379
  trackingRef: prTrackingRef,
@@ -595,33 +597,45 @@ class GitWorktreeManager {
595
597
  // Resolve which remote points to the PR's base repository (handles forks)
596
598
  const remote = await this.resolveRemoteForPR(git, prData, prInfo);
597
599
 
598
- // Fetch only the specific base branch we need, with error handling for ref conflicts
599
- console.log(`Fetching base branch ${prData.base_branch} from ${remote}...`);
600
- try {
601
- await fetchNoTags(git, [remote, `+refs/heads/${prData.base_branch}:refs/remotes/${remote}/${prData.base_branch}`]);
602
- } catch (fetchError) {
603
- // If fetch fails due to ref conflicts, try alternative approaches
604
- console.log(`Standard fetch failed, trying alternative: ${fetchError.message}`);
600
+ // Fetch only the specific base branch we need, recovering from ref hierarchy
601
+ // conflicts. Nested REST payloads carry the ref under base.ref rather than
602
+ // base_branch, so accept either form.
603
+ const baseBranch = prData?.base_branch || prData?.base?.ref || null;
604
+ // Start point for `git worktree add`. Normally the remote-tracking base
605
+ // branch; PR payloads carrying only a base SHA fall back to the bare SHA,
606
+ // which must already exist in the source repo's object store — the worktree
607
+ // add happens before ensureBaseShaAvailable could fetch it.
608
+ let startPoint;
609
+ if (baseBranch) {
610
+ startPoint = `${remote}/${baseBranch}`;
611
+ console.log(`Fetching base branch ${baseBranch} from ${remote}...`);
605
612
  try {
606
- // Try fetching with force flag to overwrite conflicting refs
607
- await rawFetchNoTags(git, ['--force', remote, `+refs/heads/${prData.base_branch}:refs/remotes/${remote}/${prData.base_branch}`]);
608
- } catch (altFetchError) {
609
- console.warn(`Could not fetch base branch ${prData.base_branch}, will try to use existing ref`);
613
+ await fetchWithPruneRecovery(git, remote, `+refs/heads/${baseBranch}:refs/remotes/${remote}/${baseBranch}`);
614
+ } catch (fetchError) {
610
615
  // Continue anyway - the branch might already be available locally
616
+ console.warn(`Could not fetch base branch ${baseBranch} (${fetchError.message}), will try to use existing ref`);
617
+ }
618
+ } else {
619
+ const baseSha = this.getPRBaseSha(prData);
620
+ if (!baseSha) {
621
+ throw new Error(`Cannot create worktree for PR #${prInfo.number} (${prInfo.owner}/${prInfo.repo}): PR data has neither a base branch nor a base SHA to start from`);
611
622
  }
623
+ console.warn(`No base branch recorded for PR #${prInfo.number}; creating the worktree from base SHA ${baseSha} instead`);
624
+ await this.ensureCommitAvailable(git, baseSha, remote, 'Base SHA');
625
+ startPoint = baseSha;
612
626
  }
613
627
 
614
628
  // Create worktree — strategy depends on whether a checkout script is configured
615
629
  if (checkoutScript) {
616
630
  // With checkout_script: create worktree with --no-checkout from main git root.
617
631
  // The script will configure sparse-checkout before files are populated.
618
- console.log(`Creating worktree at ${worktreePath} from ${prData.base_branch} (--no-checkout, script will configure sparse-checkout)...`);
632
+ console.log(`Creating worktree at ${worktreePath} from ${startPoint} (--no-checkout, script will configure sparse-checkout)...`);
619
633
  try {
620
- await git.raw(['worktree', 'add', '--no-checkout', worktreePath, `${remote}/${prData.base_branch}`]);
634
+ await git.raw(['worktree', 'add', '--no-checkout', worktreePath, startPoint]);
621
635
  } catch (worktreeError) {
622
636
  if (worktreeError.message.includes('already registered')) {
623
637
  console.log('Worktree already registered, trying with --force...');
624
- await git.raw(['worktree', 'add', '--force', '--no-checkout', worktreePath, `${remote}/${prData.base_branch}`]);
638
+ await git.raw(['worktree', 'add', '--force', '--no-checkout', worktreePath, startPoint]);
625
639
  } else {
626
640
  throw worktreeError;
627
641
  }
@@ -631,16 +645,16 @@ class GitWorktreeManager {
631
645
  // (to inherit sparse-checkout from existing worktree)
632
646
  const worktreeAddGit = worktreeSourcePath ? this._gitFor(worktreeSourcePath) : git;
633
647
  if (worktreeSourcePath) {
634
- console.log(`Creating worktree at ${worktreePath} from ${prData.base_branch} (inheriting sparse-checkout from ${worktreeSourcePath})...`);
648
+ console.log(`Creating worktree at ${worktreePath} from ${startPoint} (inheriting sparse-checkout from ${worktreeSourcePath})...`);
635
649
  } else {
636
- console.log(`Creating worktree at ${worktreePath} from ${prData.base_branch}...`);
650
+ console.log(`Creating worktree at ${worktreePath} from ${startPoint}...`);
637
651
  }
638
652
  try {
639
- await worktreeAddGit.raw(['worktree', 'add', worktreePath, `${remote}/${prData.base_branch}`]);
653
+ await worktreeAddGit.raw(['worktree', 'add', worktreePath, startPoint]);
640
654
  } catch (worktreeError) {
641
655
  if (worktreeError.message.includes('already registered')) {
642
656
  console.log('Worktree already registered, trying with --force...');
643
- await worktreeAddGit.raw(['worktree', 'add', '--force', worktreePath, `${remote}/${prData.base_branch}`]);
657
+ await worktreeAddGit.raw(['worktree', 'add', '--force', worktreePath, startPoint]);
644
658
  } else {
645
659
  throw worktreeError;
646
660
  }
@@ -665,7 +679,7 @@ class GitWorktreeManager {
665
679
  if (headBranch) {
666
680
  try {
667
681
  console.log(`Fetching head branch ${headBranch}...`);
668
- await fetchNoTags(worktreeGit, [remote, `+refs/heads/${headBranch}:refs/remotes/${remote}/${headBranch}`]);
682
+ await fetchWithPruneRecovery(worktreeGit, remote, `+refs/heads/${headBranch}:refs/remotes/${remote}/${headBranch}`);
669
683
  // Create/update a local branch pointing to the fetched ref so tooling can reference it by name
670
684
  await worktreeGit.branch(['-f', headBranch, `${remote}/${headBranch}`]);
671
685
  } catch (branchFetchError) {
@@ -676,7 +690,7 @@ class GitWorktreeManager {
676
690
 
677
691
  console.log(`Executing checkout script: ${checkoutScript}`);
678
692
  const scriptEnv = {
679
- BASE_BRANCH: prData.base_branch,
693
+ BASE_BRANCH: baseBranch,
680
694
  HEAD_BRANCH: headBranch,
681
695
  BASE_SHA: this.getPRBaseSha(prData),
682
696
  HEAD_SHA: this.getPRHeadSha(prData),
@@ -740,11 +754,9 @@ class GitWorktreeManager {
740
754
  * @param {string} repo - Repository name
741
755
  * @param {number} number - PR number
742
756
  * @param {Object} prData - PR data from GitHub API (for remote resolution)
743
- * @param {Object} [options]
744
- * @param {boolean} [options.skipBulkFetch=false] - Skip the bulk `git fetch <remote> --prune`; targeted base-SHA and PR-head fetches still run
745
757
  * @returns {Promise<string>} Path to updated worktree
746
758
  */
747
- async updateWorktree(owner, repo, number, prData, options = {}) {
759
+ async updateWorktree(owner, repo, number, prData) {
748
760
  const prInfo = { owner, repo, number };
749
761
  const headSha = this.getPRHeadSha(prData);
750
762
  const worktreePath = await this.getWorktreePath(prInfo);
@@ -764,26 +776,21 @@ class GitWorktreeManager {
764
776
  // Resolve which remote points to the PR's base repository (handles forks)
765
777
  const remote = await this.resolveRemoteForPR(worktreeGit, prData, prInfo);
766
778
 
767
- // Fetch the latest from the resolved remote (--prune removes stale
768
- // tracking refs that would otherwise block fetch on ref hierarchy conflicts).
769
- // Opt out via skip_bulk_fetch on very large monorepos where this is too slow;
770
- // the targeted base-SHA and PR-head ref fetches below still run.
771
- if (options.skipBulkFetch) {
772
- console.log(`Skipping bulk fetch from ${remote} (skip_bulk_fetch enabled)`);
773
- // Still fetch only the PR's base branch so ensureBaseShaAvailable does not
774
- // have to fall back to `git fetch <remote> <sha>`, which some Git servers
775
- // and mirrors reject (they require uploadpack.allowReachableSHA1InWant).
776
- // This mirrors the targeted fetch used in createWorktreeForPR.
777
- if (prData?.base_branch) {
778
- try {
779
- await fetchNoTags(worktreeGit, [remote, `+refs/heads/${prData.base_branch}:refs/remotes/${remote}/${prData.base_branch}`]);
780
- } catch (fetchError) {
781
- console.warn(`Targeted base-branch fetch failed, will rely on existing refs: ${fetchError.message}`);
782
- }
779
+ // Fetch only the PR's base branch so ensureBaseShaAvailable does not have to
780
+ // fall back to `git fetch <remote> <sha>`, which some Git servers and mirrors
781
+ // reject (they require uploadpack.allowReachableSHA1InWant). This mirrors the
782
+ // targeted fetch used in createWorktreeForPR; ensureBaseShaAvailable below is
783
+ // the correctness backstop if the ref cannot be updated.
784
+ const baseBranch = prData?.base_branch || prData?.base?.ref || null;
785
+ if (baseBranch) {
786
+ console.log(`Fetching base branch ${baseBranch} from ${remote}...`);
787
+ try {
788
+ await fetchWithPruneRecovery(worktreeGit, remote, `+refs/heads/${baseBranch}:refs/remotes/${remote}/${baseBranch}`);
789
+ } catch (fetchError) {
790
+ console.warn(`Targeted base-branch fetch failed, will rely on existing refs: ${fetchError.message}`);
783
791
  }
784
792
  } else {
785
- console.log(`Fetching latest changes from ${remote}...`);
786
- await fetchNoTags(worktreeGit, ['--prune', remote]);
793
+ console.warn(`No base branch recorded for PR #${number}; skipping targeted base fetch (ensureBaseShaAvailable may fall back to a direct SHA fetch)`);
787
794
  }
788
795
 
789
796
  await this.ensureBaseShaAvailable(worktreeGit, prData, remote);
@@ -1175,6 +1182,21 @@ class GitWorktreeManager {
1175
1182
  // Resolve which remote points to the PR's base repository (handles forks)
1176
1183
  const remote = await this.resolveRemoteForPR(git, prData, prInfo);
1177
1184
 
1185
+ // Fetch the PR's base branch first, exactly as createWorktreeForPR and
1186
+ // updateWorktree do, so ensureBaseShaAvailable does not have to fall back
1187
+ // to `git fetch <remote> <sha>` — a form some servers and mirrors reject.
1188
+ const baseBranch = prData?.base_branch || prData?.base?.ref || null;
1189
+ if (baseBranch) {
1190
+ console.log(`Fetching base branch ${baseBranch} from ${remote}...`);
1191
+ try {
1192
+ await fetchWithPruneRecovery(git, remote, `+refs/heads/${baseBranch}:refs/remotes/${remote}/${baseBranch}`);
1193
+ } catch (fetchError) {
1194
+ console.warn(`Targeted base-branch fetch failed, will rely on existing refs: ${fetchError.message}`);
1195
+ }
1196
+ } else {
1197
+ console.warn(`No base branch recorded for PR #${prNumber}; skipping targeted base fetch (ensureBaseShaAvailable may fall back to a direct SHA fetch)`);
1198
+ }
1199
+
1178
1200
  await this.ensureBaseShaAvailable(git, prData, remote);
1179
1201
 
1180
1202
  // Fetch the latest PR head from remote