@in-the-loop-labs/pair-review 5.0.3 → 5.1.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 (37) hide show
  1. package/README.md +26 -3
  2. package/package.json +4 -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/plugin-pair-loop/skills/loop/SKILL.md +21 -6
  7. package/public/css/pr.css +2 -2
  8. package/public/js/vendor/pierre-diffs-worker.js +3446 -5992
  9. package/public/js/vendor/pierre-diffs.js +731 -1047
  10. package/src/ai/abort-signal-wiring.js +91 -46
  11. package/src/ai/analyzer.js +191 -27
  12. package/src/ai/antigravity-provider.js +31 -5
  13. package/src/ai/claude-cli.js +8 -2
  14. package/src/ai/claude-provider.js +34 -5
  15. package/src/ai/codex-provider.js +31 -5
  16. package/src/ai/copilot-provider.js +28 -4
  17. package/src/ai/cursor-agent-provider.js +32 -5
  18. package/src/ai/executable-provider.js +8 -2
  19. package/src/ai/index.js +1 -0
  20. package/src/ai/muse-provider.js +1224 -0
  21. package/src/ai/opencode-provider.js +31 -5
  22. package/src/ai/pi-provider.js +29 -4
  23. package/src/ai/provider.js +111 -28
  24. package/src/ai/stream-parser.js +71 -0
  25. package/src/config.js +35 -2
  26. package/src/database.js +96 -16
  27. package/src/git/fetch-helpers.js +48 -0
  28. package/src/git/pack-cleanup.js +120 -0
  29. package/src/git/worktree.js +65 -43
  30. package/src/main.js +176 -27
  31. package/src/routes/analyses.js +6 -2
  32. package/src/routes/local.js +6 -5
  33. package/src/routes/mcp.js +5 -2
  34. package/src/routes/pr.js +8 -7
  35. package/src/routes/shared.js +27 -0
  36. package/src/routes/stack-analysis.js +4 -1
  37. package/src/utils/json-extractor.js +162 -41
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');
6
+ const { loadConfig, getConfigDir, showWelcomeMessage, resolveDbName, resolveRepoOptions, resolvePoolConfig, getRepoResetScript, getRepoSkipBulkFetch, getRepoFetchTimeout, resolveLoadSkills, buildCouncilProviderOverrides } = require('./config');
5
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) {
@@ -2285,7 +2289,7 @@ async function handleHeadlessDelegated(prArgs, config, db, flags, probe) {
2285
2289
  let localPath = null;
2286
2290
  let host;
2287
2291
  if (flags.local) {
2288
- localPath = require('path').resolve(flags.localPath || process.cwd());
2292
+ localPath = path.resolve(flags.localPath || process.cwd());
2289
2293
  const repoRoot = await findGitRoot(localPath);
2290
2294
  repository = await getRepositoryName(repoRoot);
2291
2295
  } else {
@@ -2365,7 +2369,7 @@ async function handleHeadlessAnalysis(prArgs, config, db, flags, poolLifecycle)
2365
2369
  }
2366
2370
  }
2367
2371
 
2368
- const resolvedPath = require('path').resolve(flags.localPath || process.cwd());
2372
+ const resolvedPath = path.resolve(flags.localPath || process.cwd());
2369
2373
  console.log(`Finding git repository root from ${resolvedPath}...`);
2370
2374
  const repoPath = await findGitRoot(resolvedPath);
2371
2375
  console.log(`Found git repository at: ${repoPath}`);
@@ -2700,7 +2704,64 @@ async function handleActionReview(args, config, db, flags = {}, poolLifecycle =
2700
2704
  */
2701
2705
  const POOL_FETCH_TICK_MS = 60 * 1000; // Check every minute
2702
2706
 
2703
- 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 };
2704
2765
  let fetchInProgress = false;
2705
2766
 
2706
2767
  const timer = setInterval(async () => {
@@ -2725,54 +2786,140 @@ function startPoolBackgroundFetches(db, config) {
2725
2786
  const { poolSize, poolFetchIntervalMinutes } = resolvePoolConfig(config, repoName, repoSettings);
2726
2787
  if (!poolSize || !poolFetchIntervalMinutes) continue;
2727
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
+
2728
2796
  const intervalMs = poolFetchIntervalMinutes * 60 * 1000;
2797
+ const fetchTimeoutMs = getRepoFetchTimeout(config, repoName);
2729
2798
  const worktrees = await poolRepo.findAllForFetch(repoName);
2730
2799
 
2731
2800
  // Check if any worktree actually needs fetching before claiming the lease
2732
- const needsFetch = worktrees.some(entry => {
2733
- if (!entry.last_fetched_at) return true;
2734
- const elapsed = Date.now() - new Date(entry.last_fetched_at).getTime();
2735
- return elapsed >= intervalMs;
2736
- });
2801
+ const needsFetch = worktrees.some(entry => isPoolEntryDueForFetch(entry, intervalMs, Date.now()));
2737
2802
  if (!needsFetch) continue;
2738
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
+
2739
2832
  // Atomically claim the fetch lease — skips if another instance holds it.
2740
2833
  // Pool worktrees share a git object store so concurrent fetches conflict.
2741
- if (!(await repoSettingsRepo.tryClaimFetch(repoName))) {
2834
+ if (!(await repoSettingsRepo.tryClaimFetch(repoName, POOL_FETCH_INSTANCE_ID))) {
2742
2835
  logger.info(`Background fetch skipped for ${repoName}: another instance is fetching`);
2743
2836
  continue;
2744
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;
2745
2854
  try {
2746
2855
  for (const entry of worktrees) {
2747
- // Skip if fetched recently (within the configured interval)
2748
- if (entry.last_fetched_at) {
2749
- const elapsed = Date.now() - new Date(entry.last_fetched_at).getTime();
2750
- if (elapsed < intervalMs) continue;
2751
- }
2856
+ // Recheck freshness/backoff — the serial loop can run for a while
2857
+ if (!isPoolEntryDueForFetch(entry, intervalMs, Date.now())) continue;
2752
2858
 
2753
- if (!fs.existsSync(entry.path)) {
2859
+ if (!deps.fs.existsSync(entry.path)) {
2754
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);
2755
2864
  continue;
2756
2865
  }
2757
2866
 
2758
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;
2759
2877
  try {
2760
- const git = simpleGit(entry.path, { timeout: { block: 300000 } });
2878
+ git = deps.simpleGit(entry.path, { timeout: { block: fetchTimeoutMs } });
2761
2879
  const remotes = await git.getRemotes();
2762
2880
  const remote = remotes.find(r => r.name === 'origin') || remotes[0];
2763
- 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]);
2764
2885
  await poolRepo.updateLastFetched(entry.id);
2765
- // Refresh the lease so the stale guard only needs to outlive
2766
- // a single stalled fetch, not the entire serial loop.
2767
- await repoSettingsRepo.refreshFetchLease(repoName);
2768
2886
  logger.info(`Background fetch complete for ${repoName} pool worktree ${entry.id}`);
2769
2887
  } catch (fetchErr) {
2770
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}`);
2771
2913
  }
2772
2914
  }
2773
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;
2774
2921
  try {
2775
- await repoSettingsRepo.markFetchFinished(repoName);
2922
+ await repoSettingsRepo.markFetchFinished(repoName, POOL_FETCH_INSTANCE_ID);
2776
2923
  } catch (finishErr) {
2777
2924
  logger.warn(`Failed to release fetch lease for ${repoName}: ${finishErr.message}`);
2778
2925
  }
@@ -2789,6 +2936,8 @@ function startPoolBackgroundFetches(db, config) {
2789
2936
  if (timer.unref) timer.unref();
2790
2937
 
2791
2938
  logger.info(`Background pool fetch ticker started (checking every ${POOL_FETCH_TICK_MS / 1000}s)`);
2939
+
2940
+ return timer;
2792
2941
  }
2793
2942
 
2794
2943
  /**
@@ -2836,4 +2985,4 @@ if (require.main === module) {
2836
2985
  main();
2837
2986
  }
2838
2987
 
2839
- module.exports = { main, parseArgs, detectPRFromGitHubEnvironment, printCouncilList, handleHeadlessAnalysis, handleHeadlessDelegated, runHeadlessAnalysis, buildHeadlessJson, buildHeadlessErrorJson, emitHeadlessResult, 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 };
@@ -31,7 +31,8 @@ const {
31
31
  localReviewDiffs,
32
32
  broadcastProgress,
33
33
  killProcesses,
34
- createProgressCallback
34
+ createProgressCallback,
35
+ finalizeConsolidationLevel
35
36
  } = require('./shared');
36
37
  const { generateScopedDiff, computeScopedDigest, getCurrentBranch } = require('../local-review');
37
38
  const { reviewScope } = require('../local-scope');
@@ -675,7 +676,10 @@ async function launchCouncilAnalysis(db, modeContext, councilConfig, councilId,
675
676
  suggestionsCount: result.suggestions.length,
676
677
  levels: {
677
678
  ...currentStatus.levels,
678
- 4: { status: 'completed', progress: 'Results finalized' }
679
+ // Derive the terminal consolidation state from the authoritative
680
+ // result — the run finishing does not mean consolidation succeeded,
681
+ // and some council paths never emit a terminal orchestration event
682
+ 4: finalizeConsolidationLevel(result, currentStatus.levels?.[4])
679
683
  }
680
684
  };
681
685
  for (const levelKey of ['1', '2', '3', 'exec']) {
@@ -54,6 +54,7 @@ const {
54
54
  broadcastProgress,
55
55
  CancellationError,
56
56
  createProgressCallback,
57
+ finalizeConsolidationLevel,
57
58
  parseEnabledLevels,
58
59
  registerProcess: registerProcessForCancellation
59
60
  } = require('./shared');
@@ -1657,11 +1658,11 @@ router.post('/api/local/:reviewId/analyses', async (req, res) => {
1657
1658
  };
1658
1659
  }
1659
1660
 
1660
- // Mark orchestration (level 4) as completed
1661
- currentStatus.levels[4] = {
1662
- status: 'completed',
1663
- progress: 'Results finalized'
1664
- };
1661
+ // Derive the terminal consolidation (level 4) state from the
1662
+ // authoritative result — the run finishing does not mean the
1663
+ // consolidation step succeeded, and some council paths never emit a
1664
+ // terminal orchestration progress event
1665
+ currentStatus.levels[4] = finalizeConsolidationLevel(result, currentStatus.levels?.[4]);
1665
1666
 
1666
1667
  const completedStatus = {
1667
1668
  ...currentStatus,
package/src/routes/mcp.js CHANGED
@@ -22,7 +22,8 @@ const {
22
22
  localReviewDiffs,
23
23
  determineCompletionInfo,
24
24
  broadcastProgress,
25
- createProgressCallback
25
+ createProgressCallback,
26
+ finalizeConsolidationLevel
26
27
  } = require('./shared');
27
28
  const { safeParseJson } = require('../utils/safe-parse-json');
28
29
  const { resolveLoadSkills, resolveHostBinding } = require('../config');
@@ -56,7 +57,9 @@ async function handleAnalysisCompletion(analysisId, runId, result, savePersisten
56
57
  currentStatus.levels[i] = { status: 'completed', progress: `Level ${i} complete` };
57
58
  }
58
59
  }
59
- currentStatus.levels[4] = { status: 'completed', progress: 'Results finalized' };
60
+ // Derive the terminal consolidation state from the authoritative result —
61
+ // the run finishing does not mean the consolidation step succeeded
62
+ currentStatus.levels[4] = finalizeConsolidationLevel(result, currentStatus.levels?.[4]);
60
63
 
61
64
  const completedStatus = {
62
65
  ...currentStatus,
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');
@@ -47,6 +47,7 @@ const {
47
47
  determineCompletionInfo,
48
48
  broadcastProgress,
49
49
  createProgressCallback,
50
+ finalizeConsolidationLevel,
50
51
  parseEnabledLevels,
51
52
  registerProcess: registerProcessForCancellation
52
53
  } = require('./shared');
@@ -590,8 +591,7 @@ router.post('/api/pr/:owner/:repo/:number/refresh', async (req, res) => {
590
591
  owner,
591
592
  repo,
592
593
  prNumber,
593
- prData,
594
- { skipBulkFetch: getRepoSkipBulkFetch(config, repository) }
594
+ prData
595
595
  );
596
596
 
597
597
  // Generate fresh diff and get changed files
@@ -2482,10 +2482,11 @@ router.post('/api/pr/:owner/:repo/:number/analyses', async (req, res) => {
2482
2482
  };
2483
2483
  }
2484
2484
 
2485
- currentStatus.levels[4] = {
2486
- status: 'completed',
2487
- progress: 'Results finalized'
2488
- };
2485
+ // Derive the terminal consolidation (level 4) state from the
2486
+ // authoritative result — the run finishing does not mean the
2487
+ // consolidation step succeeded, and some council paths never emit a
2488
+ // terminal orchestration progress event
2489
+ currentStatus.levels[4] = finalizeConsolidationLevel(result, currentStatus.levels?.[4]);
2489
2490
 
2490
2491
  const completedStatus = {
2491
2492
  ...currentStatus,
@@ -521,6 +521,32 @@ function createProgressCallback(analysisId) {
521
521
  };
522
522
  }
523
523
 
524
+ /**
525
+ * Build the terminal level-4 (consolidation) progress state for a completed
526
+ * analysis. The outcome is driven by the authoritative analyzer result rather
527
+ * than the transient progress state alone — some council paths never emit a
528
+ * terminal voiceId-less orchestration event, so levels[4] can still read
529
+ * 'running' even when consolidation failed (issue #560).
530
+ *
531
+ * @param {Object} result - Analyzer result (may carry levelOutcomes / orchestrationFailed)
532
+ * @param {Object} [level4] - Current levels[4] progress state, if any
533
+ * @returns {Object} Terminal level-4 state (preserves existing steps/voices maps)
534
+ */
535
+ function finalizeConsolidationLevel(result, level4) {
536
+ const consolidationFailed =
537
+ result?.levelOutcomes?.consolidation === 'failed' ||
538
+ result?.orchestrationFailed === true ||
539
+ level4?.status === 'failed';
540
+ return {
541
+ // Spread keeps the `steps` / `voices` maps a plain
542
+ // `{ status, progress }` replacement would silently drop
543
+ ...level4,
544
+ ...(consolidationFailed
545
+ ? { status: 'failed', progress: 'Consolidation failed — showing unconsolidated results' }
546
+ : { status: 'completed', progress: 'Results finalized' })
547
+ };
548
+ }
549
+
524
550
  /**
525
551
  * Parse enabledLevels from a request body into a normalized { 1: bool, 2: bool, 3: bool } object.
526
552
  *
@@ -570,5 +596,6 @@ module.exports = {
570
596
  killProcesses,
571
597
  isAnalysisCancelled,
572
598
  createProgressCallback,
599
+ finalizeConsolidationLevel,
573
600
  parseEnabledLevels
574
601
  };
@@ -43,6 +43,7 @@ const {
43
43
  determineCompletionInfo,
44
44
  broadcastProgress,
45
45
  createProgressCallback,
46
+ finalizeConsolidationLevel,
46
47
  parseEnabledLevels,
47
48
  registerProcess: registerProcessForCancellation,
48
49
  killProcesses
@@ -586,7 +587,9 @@ async function launchStackSingleAnalysis(deps, db, config, {
586
587
  for (let lvl = 1; lvl <= completionInfo.completedLevel; lvl++) {
587
588
  currentStatus.levels[lvl] = { status: 'completed', progress: `Level ${lvl} complete` };
588
589
  }
589
- currentStatus.levels[4] = { status: 'completed', progress: 'Results finalized' };
590
+ // Derive the terminal consolidation state from the authoritative result —
591
+ // the run finishing does not mean the consolidation step succeeded
592
+ currentStatus.levels[4] = finalizeConsolidationLevel(result, currentStatus.levels?.[4]);
590
593
  const completedStatus = {
591
594
  ...currentStatus,
592
595
  status: 'completed',