@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/main.js CHANGED
@@ -1,12 +1,15 @@
1
1
  // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
2
  const fs = require('fs');
3
+ const path = require('path');
4
+ const crypto = require('crypto');
3
5
  const { v4: uuidv4 } = require('uuid');
4
- const { loadConfig, getConfigDir, showWelcomeMessage, resolveDbName, resolveRepoOptions, resolvePoolConfig, getRepoResetScript, resolveLoadSkills, buildCouncilProviderOverrides } = require('./config');
5
- const { initializeDatabase, run, queryOne, query, migrateExistingWorktrees, WorktreeRepository, ReviewRepository, RepoSettingsRepository, GitHubReviewRepository, WorktreePoolRepository, CouncilRepository, CommentRepository, AnalysisRunRepository } = require('./database');
6
+ const { loadConfig, getConfigDir, showWelcomeMessage, resolveDbName, resolveRepoOptions, resolvePoolConfig, getRepoResetScript, getRepoSkipBulkFetch, getRepoFetchTimeout, resolveLoadSkills, buildCouncilProviderOverrides } = require('./config');
7
+ const { initializeDatabase, run, queryOne, query, migrateExistingWorktrees, WorktreeRepository, ReviewRepository, RepoSettingsRepository, GitHubReviewRepository, WorktreePoolRepository, CouncilRepository, CommentRepository, AnalysisRunRepository, PRMetadataRepository } = require('./database');
6
8
  const { PRArgumentParser } = require('./github/parser');
7
9
  const { GitHubClient } = require('./github/client');
8
10
  const { GitWorktreeManager } = require('./git/worktree');
9
11
  const { fetchNoTags } = require('./git/fetch-helpers');
12
+ const { cleanupOrphanedKeepFiles } = require('./git/pack-cleanup');
10
13
  const { WorktreePoolLifecycle } = require('./git/worktree-pool-lifecycle');
11
14
  const { startServer } = require('./server');
12
15
  const Analyzer = require('./ai/analyzer');
@@ -131,7 +134,6 @@ function detectPRFromGitHubEnvironment() {
131
134
  * Get the version from package.json
132
135
  */
133
136
  function getVersion() {
134
- const path = require('path');
135
137
  const packageJson = require(path.join(__dirname, '..', 'package.json'));
136
138
  return packageJson.version;
137
139
  }
@@ -240,7 +242,7 @@ OPTIONS:
240
242
  --model when the model belongs to a non-default
241
243
  provider (e.g. --provider codex --model gpt-5.5).
242
244
  Available: claude, antigravity, codex, copilot,
243
- opencode, cursor-agent, pi
245
+ opencode, cursor-agent, pi, muse
244
246
  --council <handle> Run analysis with a saved council (multi-voice). Handle is a
245
247
  council name, name-slug, or id (prefix). See --list-councils.
246
248
  --list-councils List saved councils (handles to use with --council) and exit
@@ -275,6 +277,7 @@ ENVIRONMENT VARIABLES:
275
277
  PAIR_REVIEW_CLAUDE_CMD Custom command to invoke Claude CLI (default: claude)
276
278
  PAIR_REVIEW_ANTIGRAVITY_CMD Custom command to invoke Antigravity CLI (default: agy)
277
279
  PAIR_REVIEW_CODEX_CMD Custom command to invoke Codex CLI (default: codex)
280
+ PAIR_REVIEW_MUSE_CMD Custom command to invoke Muse Code CLI (default: muse)
278
281
 
279
282
  CONFIGURATION:
280
283
  Config file: ~/.pair-review/config.json
@@ -664,6 +667,7 @@ ENVIRONMENT VARIABLES:
664
667
  PAIR_REVIEW_CLAUDE_CMD Custom Claude CLI command (default: claude)
665
668
  PAIR_REVIEW_ANTIGRAVITY_CMD Custom Antigravity CLI command (default: agy)
666
669
  PAIR_REVIEW_CODEX_CMD Custom Codex CLI command (default: codex)
670
+ PAIR_REVIEW_MUSE_CMD Custom Muse Code CLI command (default: muse)
667
671
  PAIR_REVIEW_DB_NAME Custom database filename (overrides config)
668
672
 
669
673
  LOCAL CONFIG:
@@ -674,6 +678,7 @@ AI PROVIDERS:
674
678
  Claude (default): Requires 'claude' CLI installed
675
679
  Antigravity: Requires 'agy' CLI installed
676
680
  Codex: Requires 'codex' CLI installed
681
+ Muse: Requires 'muse' CLI installed
677
682
 
678
683
  Select provider per-repository in the web UI settings.
679
684
  `);
@@ -901,7 +906,7 @@ AI PROVIDERS:
901
906
  }
902
907
  let localRepository = null;
903
908
  if (wantsInstructionHandoff && flags.local) {
904
- const localTarget = require('path').resolve(flags.localPath || process.cwd());
909
+ const localTarget = path.resolve(flags.localPath || process.cwd());
905
910
  const localRoot = await findGitRoot(localTarget);
906
911
  localRepository = await getRepositoryName(localRoot);
907
912
  }
@@ -1011,7 +1016,6 @@ AI PROVIDERS:
1011
1016
  }
1012
1017
 
1013
1018
  // Migrate existing worktrees to database (if any)
1014
- const path = require('path');
1015
1019
  const worktreeBaseDir = path.join(getConfigDir(), 'worktrees');
1016
1020
  const migrationResult = await migrateExistingWorktrees(db, worktreeBaseDir);
1017
1021
  if (migrationResult.migrated > 0) {
@@ -1541,17 +1545,25 @@ async function performHeadlessReview(args, config, db, flags, options, externalP
1541
1545
  }).catch(err => { logger.warn(`Review hook failed: ${err.message}`); });
1542
1546
  }
1543
1547
 
1544
- // Get PR metadata ID for AI analysis
1545
- const prMetadata = await queryOne(db, `
1546
- SELECT id, pr_data FROM pr_metadata
1547
- WHERE pr_number = ? AND repository = ? COLLATE NOCASE
1548
- `, [prInfo.number, repository]);
1548
+ // Get PR metadata for AI analysis.
1549
+ //
1550
+ // Read it through PRMetadataRepository.getByPR — the SAME accessor the web
1551
+ // routes use (src/routes/pr.js) — so the analyzer receives the normalized
1552
+ // row shape it expects: `repository` as the "owner/repo" string, `pr_number`
1553
+ // as the number, plus `description`/`author` from their columns. Passing the
1554
+ // raw `pr_data` blob here (the previous behavior) handed the analyzer the
1555
+ // GitHub API shape, where `repository` is an object and the number lives
1556
+ // under `number`, which made buildDedupContext throw and silently drop every
1557
+ // consolidation stage into its store-everything fallback (#557).
1558
+ const prMetadataRepo = new PRMetadataRepository(db);
1559
+ const prMetadata = await prMetadataRepo.getByPR(prInfo.number, repository);
1549
1560
 
1550
1561
  if (!prMetadata) {
1551
1562
  throw new Error('Failed to retrieve stored PR metadata');
1552
1563
  }
1553
1564
 
1554
- const storedPRData = JSON.parse(prMetadata.pr_data);
1565
+ // The raw blob is still needed for fields that live only in pr_data (node_id).
1566
+ const storedPRData = prMetadata.pr_data_parsed;
1555
1567
 
1556
1568
  // Get or create a review record for this PR
1557
1569
  // The review.id is passed to the analyzer so comments use review.id, not prMetadata.id
@@ -1600,7 +1612,7 @@ async function performHeadlessReview(args, config, db, flags, options, externalP
1600
1612
  const { result: analysisResult } = await runHeadlessAnalysis(db, config, {
1601
1613
  reviewId: review.id,
1602
1614
  worktreePath,
1603
- prMetadata: storedPRData,
1615
+ prMetadata,
1604
1616
  changedFiles: null,
1605
1617
  repository,
1606
1618
  repoSettings,
@@ -1868,7 +1880,11 @@ Found ${validSuggestions.length} suggestion${validSuggestions.length === 1 ? ''
1868
1880
  * @param {Object} params
1869
1881
  * @param {number} params.reviewId - Review id comments are stored under
1870
1882
  * @param {string} params.worktreePath - Checked-out worktree / local repo path
1871
- * @param {Object} params.prMetadata - PR/local metadata (head_sha, base_sha, etc.)
1883
+ * @param {Object} params.prMetadata - PR/local metadata (head_sha, base_sha, etc.).
1884
+ * PR mode MUST pass the normalized `pr_metadata` row (`repository` as the
1885
+ * "owner/repo" string, `pr_number` as the number) — the raw `pr_data` blob has
1886
+ * `repository` as an object and the number under `number`, which breaks dedup
1887
+ * context construction and, with it, consolidation (#557).
1872
1888
  * @param {Array|null} params.changedFiles - Changed-file list (local mode) or null (PR mode computes it)
1873
1889
  * @param {string} params.repository - owner/repo
1874
1890
  * @param {Object|null} params.repoSettings - Repo settings row
@@ -1953,9 +1969,11 @@ async function runHeadlessAnalysis(db, config, {
1953
1969
  * convention) so the in-memory usage tracker populated by
1954
1970
  * `resetAndRehydrate()` is the one acquisitions go through. Falls back to a
1955
1971
  * fresh instance only when not supplied.
1956
- * @returns {Promise<Object>} { githubClient, worktreePath, storedPRData, review,
1972
+ * @returns {Promise<Object>} { githubClient, worktreePath, prMetadata, review,
1957
1973
  * repository, repoSettings, poolWorktreeId, poolLifecycle, reviewConfig,
1958
- * providerOverrides }
1974
+ * providerOverrides }. `prMetadata` is the normalized `pr_metadata` row from
1975
+ * `PRMetadataRepository.getByPR` — the shape the analyzer expects — NOT the
1976
+ * raw `pr_data` blob (#557).
1959
1977
  */
1960
1978
  async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycle = null) {
1961
1979
  const parser = new PRArgumentParser(config);
@@ -2160,17 +2178,16 @@ async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycl
2160
2178
  }).catch(err => { logger.warn(`Review hook failed: ${err.message}`); });
2161
2179
  }
2162
2180
 
2163
- const prMetadata = await queryOne(db, `
2164
- SELECT id, pr_data FROM pr_metadata
2165
- WHERE pr_number = ? AND repository = ? COLLATE NOCASE
2166
- `, [prInfo.number, repository]);
2181
+ // Read through PRMetadataRepository.getByPR so the analyzer gets the same
2182
+ // normalized row the web routes pass (see the matching comment in
2183
+ // performHeadlessReview and issue #557).
2184
+ const prMetadataRepo = new PRMetadataRepository(db);
2185
+ const prMetadata = await prMetadataRepo.getByPR(prInfo.number, repository);
2167
2186
 
2168
2187
  if (!prMetadata) {
2169
2188
  throw new Error('Failed to retrieve stored PR metadata');
2170
2189
  }
2171
2190
 
2172
- const storedPRData = JSON.parse(prMetadata.pr_data);
2173
-
2174
2191
  const reviewRepo = new ReviewRepository(db);
2175
2192
  const { review } = await reviewRepo.getOrCreate({ prNumber: prInfo.number, repository });
2176
2193
 
@@ -2199,7 +2216,7 @@ async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycl
2199
2216
  return {
2200
2217
  githubClient,
2201
2218
  worktreePath,
2202
- storedPRData,
2219
+ prMetadata,
2203
2220
  review,
2204
2221
  repository,
2205
2222
  repoSettings,
@@ -2272,7 +2289,7 @@ async function handleHeadlessDelegated(prArgs, config, db, flags, probe) {
2272
2289
  let localPath = null;
2273
2290
  let host;
2274
2291
  if (flags.local) {
2275
- localPath = require('path').resolve(flags.localPath || process.cwd());
2292
+ localPath = path.resolve(flags.localPath || process.cwd());
2276
2293
  const repoRoot = await findGitRoot(localPath);
2277
2294
  repository = await getRepositoryName(repoRoot);
2278
2295
  } else {
@@ -2352,7 +2369,7 @@ async function handleHeadlessAnalysis(prArgs, config, db, flags, poolLifecycle)
2352
2369
  }
2353
2370
  }
2354
2371
 
2355
- const resolvedPath = require('path').resolve(flags.localPath || process.cwd());
2372
+ const resolvedPath = path.resolve(flags.localPath || process.cwd());
2356
2373
  console.log(`Finding git repository root from ${resolvedPath}...`);
2357
2374
  const repoPath = await findGitRoot(resolvedPath);
2358
2375
  console.log(`Found git repository at: ${repoPath}`);
@@ -2467,7 +2484,7 @@ async function handleHeadlessAnalysis(prArgs, config, db, flags, poolLifecycle)
2467
2484
  ({ runId } = await runHeadlessAnalysis(db, config, {
2468
2485
  reviewId: prep.review.id,
2469
2486
  worktreePath: prep.worktreePath,
2470
- prMetadata: prep.storedPRData,
2487
+ prMetadata: prep.prMetadata,
2471
2488
  changedFiles: null,
2472
2489
  repository: prep.repository,
2473
2490
  repoSettings: prep.repoSettings,
@@ -2503,7 +2520,9 @@ async function handleHeadlessAnalysis(prArgs, config, db, flags, poolLifecycle)
2503
2520
  * @param {Object} db - Database instance
2504
2521
  * @param {string} runId - Analysis run id
2505
2522
  * @param {'pr'|'local'} mode - Review mode (passthrough)
2506
- * @returns {Promise<Object>} { ok, mode, run, suggestions, count }
2523
+ * @returns {Promise<Object>} { ok, mode, consolidation, run, suggestions, count }
2524
+ * where `consolidation` is 'success' | 'failed' | 'skipped' | null — see the
2525
+ * inline comment on the field for what each value means for `suggestions`.
2507
2526
  */
2508
2527
  async function buildHeadlessJson(db, runId, mode) {
2509
2528
  const run = await new AnalysisRunRepository(db).getById(runId, { includeDiff: false });
@@ -2523,6 +2542,26 @@ async function buildHeadlessJson(db, runId, mode) {
2523
2542
  // see buildHeadlessErrorJson for the failure shape.
2524
2543
  ok: true,
2525
2544
  mode,
2545
+ // Hoisted out of `run.level_outcomes` because it materially changes what
2546
+ // `suggestions` contains. When consolidation throws, every analyzer path
2547
+ // falls back to storing the raw union of all levels (and, for a council, all
2548
+ // voices) and STILL records status 'completed' — so a consumer branching only
2549
+ // on `ok`/`status` cannot tell a consolidated review from a duplicate-laden
2550
+ // concatenation.
2551
+ //
2552
+ // A straight passthrough of whatever the analyzer recorded, so the domain is
2553
+ // the analyzer's, not ours:
2554
+ // 'success' — consolidation ran and merged the inputs.
2555
+ // 'failed' — it threw; `suggestions` is the unmerged union. DEGRADED.
2556
+ // 'skipped' — nothing to merge (single voice / single level / an executable
2557
+ // tool that returns its own final set). HEALTHY: the suggestion
2558
+ // set is already the intended one, which is why
2559
+ // emitHeadlessResult warns on 'failed' only.
2560
+ // null — the run recorded no consolidation stage at all.
2561
+ // Deliberately NOT collapsed to a boolean or folded into null: the web UI
2562
+ // renders the same tri-state (public/js/modules/analysis-history.js), and
2563
+ // 'skipped' carries information null does not.
2564
+ consolidation: run?.level_outcomes?.consolidation ?? null,
2526
2565
  run,
2527
2566
  suggestions,
2528
2567
  count: suggestions.length
@@ -2560,6 +2599,11 @@ function buildHeadlessErrorJson({ mode, error }) {
2560
2599
  * Otherwise prints a human-readable summary to stdout. A successful run with zero
2561
2600
  * suggestions is still success — operational errors propagate to main()'s catch.
2562
2601
  *
2602
+ * Both output modes flag a failed consolidation, which completes the run but
2603
+ * replaces the consolidated review with the raw union of every level/voice.
2604
+ *
2605
+ * Exported for unit testing.
2606
+ *
2563
2607
  * @param {Object} db - Database instance
2564
2608
  * @param {Object} params
2565
2609
  * @param {string} params.runId - Analysis run id
@@ -2588,6 +2632,13 @@ async function emitHeadlessResult(db, { runId, mode, flags }) {
2588
2632
  }
2589
2633
  lines.push(` Config type: ${run.config_type || 'standard'}`);
2590
2634
  lines.push(` Status: ${run.status || '(unknown)'}`);
2635
+ // A failed consolidation still completes the run, so the status line alone
2636
+ // understates it — call out that the listing below is unconsolidated.
2637
+ if (doc.consolidation === 'failed') {
2638
+ lines.push('');
2639
+ lines.push(' WARNING: consolidation failed. The suggestions below are the raw union of');
2640
+ lines.push(' every analysis level (and every council voice) — expect duplicates.');
2641
+ }
2591
2642
  if (run.summary) {
2592
2643
  lines.push('');
2593
2644
  lines.push('Summary:');
@@ -2653,7 +2704,64 @@ async function handleActionReview(args, config, db, flags = {}, poolLifecycle =
2653
2704
  */
2654
2705
  const POOL_FETCH_TICK_MS = 60 * 1000; // Check every minute
2655
2706
 
2656
- function startPoolBackgroundFetches(db, config) {
2707
+ // Ceiling for the exponential retry backoff of a repeatedly failing fetch.
2708
+ const MAX_POOL_FETCH_BACKOFF_MS = 6 * 60 * 60 * 1000; // 6 hours
2709
+
2710
+ // How often to refresh the cross-instance fetch lease while fetches run.
2711
+ // Must be comfortably below the 10-minute stale guard in tryClaimFetch.
2712
+ const POOL_FETCH_LEASE_HEARTBEAT_MS = 5 * 60 * 1000; // 5 minutes
2713
+
2714
+ // Identifies this process as the holder of a repo fetch lease. Refresh and
2715
+ // release are gated on it, so an instance whose lease went stale and was taken
2716
+ // over by another cannot extend or clear the new holder's lease.
2717
+ const POOL_FETCH_INSTANCE_ID = crypto.randomUUID();
2718
+
2719
+ // Default dependencies for the background fetch loop (overridable for testing)
2720
+ const poolFetchDefaults = {
2721
+ simpleGit,
2722
+ fs,
2723
+ cleanupOrphanedKeepFiles,
2724
+ };
2725
+
2726
+ /**
2727
+ * Decide whether a pool worktree is due for a background fetch.
2728
+ *
2729
+ * `last_fetched_at` only advances on success, so a failing entry would stay
2730
+ * permanently due and re-fetch every tick — on a large monorepo that means
2731
+ * re-downloading the same pack forever. `last_fetch_attempt_at` plus the
2732
+ * consecutive failure count gate retries behind a doubling backoff
2733
+ * (1x, 2x, 4x… the fetch interval) capped at MAX_POOL_FETCH_BACKOFF_MS — or at
2734
+ * the configured interval when that is longer, since a cap below the interval
2735
+ * would make a failing entry retry more often than a healthy one.
2736
+ *
2737
+ * @param {Object} entry - Row from WorktreePoolRepository.findAllForFetch
2738
+ * @param {number} intervalMs - Configured fetch interval in milliseconds
2739
+ * @param {number} now - Current time in milliseconds since the epoch
2740
+ * @returns {boolean} True if the entry should be fetched now
2741
+ */
2742
+ function isPoolEntryDueForFetch(entry, intervalMs, now) {
2743
+ if (entry.last_fetched_at) {
2744
+ const elapsed = now - new Date(entry.last_fetched_at).getTime();
2745
+ if (elapsed < intervalMs) return false;
2746
+ }
2747
+
2748
+ if (!entry.last_fetch_attempt_at) return true;
2749
+
2750
+ const failures = entry.fetch_failure_count || 0;
2751
+ const backoffMs = failures > 0
2752
+ ? Math.min(intervalMs * Math.pow(2, failures - 1), Math.max(intervalMs, MAX_POOL_FETCH_BACKOFF_MS))
2753
+ : intervalMs;
2754
+ return (now - new Date(entry.last_fetch_attempt_at).getTime()) >= backoffMs;
2755
+ }
2756
+
2757
+ /**
2758
+ * @param {Object} db - Database instance
2759
+ * @param {Object} config - Configuration object
2760
+ * @param {Object} [_deps] - Internal: dependency overrides for testing
2761
+ * @returns {NodeJS.Timeout} The interval timer (so callers/tests can clear it)
2762
+ */
2763
+ function startPoolBackgroundFetches(db, config, _deps = {}) {
2764
+ const deps = { ...poolFetchDefaults, ..._deps };
2657
2765
  let fetchInProgress = false;
2658
2766
 
2659
2767
  const timer = setInterval(async () => {
@@ -2678,54 +2786,140 @@ function startPoolBackgroundFetches(db, config) {
2678
2786
  const { poolSize, poolFetchIntervalMinutes } = resolvePoolConfig(config, repoName, repoSettings);
2679
2787
  if (!poolSize || !poolFetchIntervalMinutes) continue;
2680
2788
 
2789
+ // skip_bulk_fetch opts a repo out of unconditional whole-remote fetches
2790
+ // entirely, including this periodic one. The keep-file sweep below still
2791
+ // runs for it: these are the huge monorepos whose foreground fetches get
2792
+ // killed, so they are exactly the repos accumulating orphaned `.keep`
2793
+ // markers that pin packs forever.
2794
+ const skipBulk = getRepoSkipBulkFetch(config, repoName);
2795
+
2681
2796
  const intervalMs = poolFetchIntervalMinutes * 60 * 1000;
2797
+ const fetchTimeoutMs = getRepoFetchTimeout(config, repoName);
2682
2798
  const worktrees = await poolRepo.findAllForFetch(repoName);
2683
2799
 
2684
2800
  // Check if any worktree actually needs fetching before claiming the lease
2685
- const needsFetch = worktrees.some(entry => {
2686
- if (!entry.last_fetched_at) return true;
2687
- const elapsed = Date.now() - new Date(entry.last_fetched_at).getTime();
2688
- return elapsed >= intervalMs;
2689
- });
2801
+ const needsFetch = worktrees.some(entry => isPoolEntryDueForFetch(entry, intervalMs, Date.now()));
2690
2802
  if (!needsFetch) continue;
2691
2803
 
2804
+ if (skipBulk) {
2805
+ logger.debug(`Background fetch skipped for ${repoName}: skip_bulk_fetch is enabled`);
2806
+ // Sweep once for the repo: all its pool worktrees share one git
2807
+ // object store. The sweep only removes markers naming dead pids on
2808
+ // this host, so it needs no fetch lease.
2809
+ // Any surviving path reaches the shared object store, so the anchor
2810
+ // only has to exist on disk — the needsFetch gate above already held
2811
+ // the sweep to once per fetch interval. Requiring the anchor itself to
2812
+ // be due would skip the sweep entirely when the due entry's directory
2813
+ // has vanished but a not-yet-due sibling is still there.
2814
+ const keepSweepEntry = worktrees.find(entry => deps.fs.existsSync(entry.path));
2815
+ if (keepSweepEntry) {
2816
+ try {
2817
+ const keepSweepGit = deps.simpleGit(keepSweepEntry.path, { timeout: { block: fetchTimeoutMs } });
2818
+ const commonDir = await keepSweepGit.raw(['rev-parse', '--git-common-dir']);
2819
+ await deps.cleanupOrphanedKeepFiles(path.resolve(keepSweepEntry.path, commonDir.trim(), 'objects', 'pack'));
2820
+ } catch (cleanupErr) {
2821
+ logger.warn(`Pack keep-file cleanup failed for ${repoName}: ${cleanupErr.message}`);
2822
+ }
2823
+ }
2824
+ // Stamp every entry so the sweep runs once per fetch interval rather
2825
+ // than on every 60-second tick.
2826
+ for (const entry of worktrees) {
2827
+ await poolRepo.recordFetchAttempt(entry.id);
2828
+ }
2829
+ continue;
2830
+ }
2831
+
2692
2832
  // Atomically claim the fetch lease — skips if another instance holds it.
2693
2833
  // Pool worktrees share a git object store so concurrent fetches conflict.
2694
- if (!(await repoSettingsRepo.tryClaimFetch(repoName))) {
2834
+ if (!(await repoSettingsRepo.tryClaimFetch(repoName, POOL_FETCH_INSTANCE_ID))) {
2695
2835
  logger.info(`Background fetch skipped for ${repoName}: another instance is fetching`);
2696
2836
  continue;
2697
2837
  }
2838
+ // Heartbeat the lease while fetches run. fetch_timeout_seconds is an
2839
+ // IDLE timeout and --progress keeps output flowing, so a single healthy
2840
+ // fetch can legitimately run far longer than the 10-minute stale guard.
2841
+ // Without this, a second instance would deem the lease stale mid-fetch
2842
+ // and start a concurrent fetch into the same shared object store —
2843
+ // exactly the duplicate-pack scenario the lease exists to prevent.
2844
+ let heartbeatInFlight = Promise.resolve();
2845
+ const leaseHeartbeat = setInterval(() => {
2846
+ heartbeatInFlight = repoSettingsRepo.refreshFetchLease(repoName, POOL_FETCH_INSTANCE_ID).catch(() => {});
2847
+ }, POOL_FETCH_LEASE_HEARTBEAT_MS);
2848
+ if (leaseHeartbeat.unref) leaseHeartbeat.unref();
2849
+ // All pool worktrees of a repo share one git object store, so the
2850
+ // keep-file sweep runs once per repo after the entry loop rather than
2851
+ // once per entry.
2852
+ let sweepGit = null;
2853
+ let sweepEntry = null;
2698
2854
  try {
2699
2855
  for (const entry of worktrees) {
2700
- // Skip if fetched recently (within the configured interval)
2701
- if (entry.last_fetched_at) {
2702
- const elapsed = Date.now() - new Date(entry.last_fetched_at).getTime();
2703
- if (elapsed < intervalMs) continue;
2704
- }
2856
+ // Recheck freshness/backoff — the serial loop can run for a while
2857
+ if (!isPoolEntryDueForFetch(entry, intervalMs, Date.now())) continue;
2705
2858
 
2706
- if (!fs.existsSync(entry.path)) {
2859
+ if (!deps.fs.existsSync(entry.path)) {
2707
2860
  logger.warn(`Background fetch skipped for ${entry.id}: directory no longer exists (${entry.path})`);
2861
+ // Stamp the attempt so a vanished directory logs once per
2862
+ // interval rather than once per 60-second tick, forever.
2863
+ await poolRepo.recordFetchAttempt(entry.id);
2708
2864
  continue;
2709
2865
  }
2710
2866
 
2711
2867
  logger.info(`Background fetch starting for ${repoName} pool worktree ${entry.id}`);
2868
+ // simple-git's timeout.block is an IDLE timeout, so stamp the
2869
+ // attempt before starting: a fetch killed mid-pack (or a process
2870
+ // that dies outright) then still backs off instead of retrying
2871
+ // on the very next tick.
2872
+ await poolRepo.recordFetchAttempt(entry.id);
2873
+ // Construct inside the try: simple-git's constructor throws on a
2874
+ // bad path/options, and that must be recorded as a failure like any
2875
+ // other rather than escaping and killing the whole repo's loop.
2876
+ let git = null;
2712
2877
  try {
2713
- const git = simpleGit(entry.path, { timeout: { block: 300000 } });
2878
+ git = deps.simpleGit(entry.path, { timeout: { block: fetchTimeoutMs } });
2714
2879
  const remotes = await git.getRemotes();
2715
2880
  const remote = remotes.find(r => r.name === 'origin') || remotes[0];
2716
- if (remote) await fetchNoTags(git, ['--prune', remote.name]);
2881
+ // --progress forces git to emit progress without a tty, which
2882
+ // keeps the idle timeout from killing a healthy fetch during
2883
+ // long silent phases like delta resolution.
2884
+ if (remote) await fetchNoTags(git, ['--progress', '--prune', remote.name]);
2717
2885
  await poolRepo.updateLastFetched(entry.id);
2718
- // Refresh the lease so the stale guard only needs to outlive
2719
- // a single stalled fetch, not the entire serial loop.
2720
- await repoSettingsRepo.refreshFetchLease(repoName);
2721
2886
  logger.info(`Background fetch complete for ${repoName} pool worktree ${entry.id}`);
2722
2887
  } catch (fetchErr) {
2723
2888
  logger.warn(`Background fetch failed for ${entry.id}: ${fetchErr.message}`);
2889
+ try {
2890
+ await poolRepo.recordFetchFailure(entry.id);
2891
+ } catch (countErr) {
2892
+ logger.warn(`Failed to record fetch failure for ${entry.id}: ${countErr.message}`);
2893
+ }
2894
+ }
2895
+ if (git) {
2896
+ sweepGit = git;
2897
+ sweepEntry = entry;
2898
+ }
2899
+ }
2900
+ // A killed fetch leaves the pack it wrote pinned by a `pack-*.keep`
2901
+ // file; git repack silently skips kept packs, so the space is never
2902
+ // reclaimed until the marker is gone. Sweep after attempts of any
2903
+ // outcome — not just failures — so markers orphaned by a process that
2904
+ // died outright (crash, SIGKILL, power loss) are also reclaimed once
2905
+ // fetching resumes.
2906
+ if (sweepGit) {
2907
+ try {
2908
+ const commonDir = await sweepGit.raw(['rev-parse', '--git-common-dir']);
2909
+ const packDir = path.resolve(sweepEntry.path, commonDir.trim(), 'objects', 'pack');
2910
+ await deps.cleanupOrphanedKeepFiles(packDir);
2911
+ } catch (cleanupErr) {
2912
+ logger.warn(`Pack keep-file cleanup failed for ${repoName}: ${cleanupErr.message}`);
2724
2913
  }
2725
2914
  }
2726
2915
  } finally {
2916
+ clearInterval(leaseHeartbeat);
2917
+ // A heartbeat scheduled before the clear can still be in flight; let
2918
+ // it settle before releasing, or it could re-stamp pool_fetch_started_at
2919
+ // after markFetchFinished and resurrect a lease we just gave up.
2920
+ await heartbeatInFlight;
2727
2921
  try {
2728
- await repoSettingsRepo.markFetchFinished(repoName);
2922
+ await repoSettingsRepo.markFetchFinished(repoName, POOL_FETCH_INSTANCE_ID);
2729
2923
  } catch (finishErr) {
2730
2924
  logger.warn(`Failed to release fetch lease for ${repoName}: ${finishErr.message}`);
2731
2925
  }
@@ -2742,6 +2936,8 @@ function startPoolBackgroundFetches(db, config) {
2742
2936
  if (timer.unref) timer.unref();
2743
2937
 
2744
2938
  logger.info(`Background pool fetch ticker started (checking every ${POOL_FETCH_TICK_MS / 1000}s)`);
2939
+
2940
+ return timer;
2745
2941
  }
2746
2942
 
2747
2943
  /**
@@ -2789,4 +2985,4 @@ if (require.main === module) {
2789
2985
  main();
2790
2986
  }
2791
2987
 
2792
- module.exports = { main, parseArgs, detectPRFromGitHubEnvironment, printCouncilList, handleHeadlessAnalysis, handleHeadlessDelegated, runHeadlessAnalysis, buildHeadlessJson, buildHeadlessErrorJson, resolveCliInstructions };
2988
+ module.exports = { main, parseArgs, detectPRFromGitHubEnvironment, printCouncilList, handleHeadlessAnalysis, handleHeadlessDelegated, runHeadlessAnalysis, buildHeadlessJson, buildHeadlessErrorJson, emitHeadlessResult, resolveCliInstructions, startPoolBackgroundFetches, isPoolEntryDueForFetch, POOL_FETCH_TICK_MS, MAX_POOL_FETCH_BACKOFF_MS };
package/src/routes/pr.js CHANGED
@@ -26,7 +26,7 @@ const Analyzer = require('../ai/analyzer');
26
26
  const { v4: uuidv4 } = require('uuid');
27
27
  const fs = require('fs').promises;
28
28
  const path = require('path');
29
- const { resolveHostBinding, resolveBindingRepositoryFromPR, getWorktreeDisplayName, resolveLoadSkills, buildCouncilProviderOverrides, getRepoSkipBulkFetch, getSummaryEnabled, getTourEnabled } = require('../config');
29
+ const { resolveHostBinding, resolveBindingRepositoryFromPR, getWorktreeDisplayName, resolveLoadSkills, buildCouncilProviderOverrides, getSummaryEnabled, getTourEnabled } = require('../config');
30
30
  const { storedHostToOption, isDualHostRepo } = require('../utils/host-resolution');
31
31
  const { resolveHostName } = require('../links/repo-links');
32
32
  const { backgroundQueue } = require('../ai/background-queue');
@@ -590,8 +590,7 @@ router.post('/api/pr/:owner/:repo/:number/refresh', async (req, res) => {
590
590
  owner,
591
591
  repo,
592
592
  prNumber,
593
- prData,
594
- { skipBulkFetch: getRepoSkipBulkFetch(config, repository) }
593
+ prData
595
594
  );
596
595
 
597
596
  // Generate fresh diff and get changed files