@in-the-loop-labs/pair-review 4.1.0 → 5.0.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.
Files changed (71) hide show
  1. package/README.md +81 -13
  2. package/package.json +6 -2
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
  5. package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
  6. package/plugin-pair-loop/skills/loop/SKILL.md +17 -8
  7. package/public/css/ai-summary-modal.css +1 -1
  8. package/public/css/analysis-config.css +33 -49
  9. package/public/css/council-card.css +118 -0
  10. package/public/css/council-dropdown.css +164 -0
  11. package/public/css/pr.css +666 -394
  12. package/public/css/repo-settings.css +15 -305
  13. package/public/css/settings.css +1141 -0
  14. package/public/css/snippet-manager.css +233 -0
  15. package/public/index.html +40 -59
  16. package/public/js/components/AIPanel.js +82 -16
  17. package/public/js/components/ChatPanel.js +401 -5
  18. package/public/js/components/CouncilCard.js +202 -0
  19. package/public/js/components/CouncilDropdown.js +292 -0
  20. package/public/js/components/DiffOptionsDropdown.js +177 -4
  21. package/public/js/components/SnippetManager.js +463 -0
  22. package/public/js/index.js +7 -30
  23. package/public/js/local.js +20 -2
  24. package/public/js/modules/comment-manager.js +8 -1
  25. package/public/js/modules/comment-minimizer.js +249 -190
  26. package/public/js/modules/external-comment-manager.js +414 -48
  27. package/public/js/modules/file-comment-manager.js +28 -21
  28. package/public/js/modules/hunk-summary-renderer.js +155 -29
  29. package/public/js/modules/pierre-bridge.js +2513 -0
  30. package/public/js/modules/pierre-context.js +345 -0
  31. package/public/js/modules/suggestion-manager.js +176 -20
  32. package/public/js/modules/tour-renderer.js +400 -184
  33. package/public/js/pr.js +1434 -150
  34. package/public/js/repo-settings.js +60 -284
  35. package/public/js/settings.js +1086 -0
  36. package/public/js/theme-bootstrap.js +40 -0
  37. package/public/js/theme.js +247 -0
  38. package/public/js/utils/provider-model.js +3 -3
  39. package/public/js/utils/suggestion-ui.js +157 -8
  40. package/public/local.html +20 -31
  41. package/public/pr.html +14 -23
  42. package/public/repo-settings.html +24 -14
  43. package/public/settings.html +138 -0
  44. package/public/setup.html +8 -13
  45. package/src/ai/codex-provider.js +59 -11
  46. package/src/chat/api-reference.js +9 -5
  47. package/src/chat/prompt-builder.js +8 -1
  48. package/src/config.js +15 -6
  49. package/src/database.js +307 -14
  50. package/src/external/github-adapter.js +39 -5
  51. package/src/headless/delegate.js +682 -0
  52. package/src/local-review.js +10 -10
  53. package/src/local-scope.js +9 -0
  54. package/src/main.js +276 -157
  55. package/src/mcp-stdio.js +24 -1
  56. package/src/review-config.js +93 -25
  57. package/src/routes/chat.js +2 -2
  58. package/src/routes/config.js +12 -10
  59. package/src/routes/external-comments.js +5 -1
  60. package/src/routes/local.js +2 -4
  61. package/src/routes/mcp.js +18 -13
  62. package/src/routes/reviews.js +223 -4
  63. package/src/routes/settings.js +252 -0
  64. package/src/routes/setup.js +80 -1
  65. package/src/routes/shared.js +31 -29
  66. package/src/routes/snippets.js +154 -0
  67. package/src/routes/stack-analysis.js +17 -14
  68. package/src/server.js +86 -18
  69. package/src/settings/global-settings-service.js +472 -0
  70. package/src/settings/registry.js +624 -0
  71. package/src/utils/db-identity.js +44 -0
@@ -1051,18 +1051,18 @@ async function handleLocalReview(targetPath, flags = {}) {
1051
1051
  const session = await setupLocalReviewSession({ db, config, repoPath, flags });
1052
1052
  setupComplete = true;
1053
1053
 
1054
- // Skipped when --council is set: council voices carry their own per-voice models.
1055
- if (flags.model && !flags.council) {
1056
- process.env.PAIR_REVIEW_MODEL = flags.model;
1057
- }
1058
- // Mirror --provider too so the local web/UI routes (which read
1059
- // PAIR_REVIEW_PROVIDER via getProvider(req)) honor it, matching --model above.
1060
- if (flags.provider) {
1061
- process.env.PAIR_REVIEW_PROVIDER = flags.provider;
1062
- }
1054
+ // Per-run provider/model overrides from --provider/--model, threaded
1055
+ // explicitly into the server (no env side channel) so the local web/UI
1056
+ // analyze routes honor them via app.get('cliOverrides'). The model override
1057
+ // is skipped when --council is set: council voices carry their own per-voice
1058
+ // models. (--provider is not council-gated, matching the PR path.)
1059
+ const cliOverrides = {
1060
+ provider: flags.provider || undefined,
1061
+ model: (flags.model && !flags.council) ? flags.model : undefined
1062
+ };
1063
1063
 
1064
1064
  console.log('Starting server...');
1065
- const port = await startServer(db);
1065
+ const port = await startServer(db, null, { cliOverrides });
1066
1066
 
1067
1067
  let url = `http://localhost:${port}/local/${session.sessionId}`;
1068
1068
  const shouldAnalyze = flags.ai || flags.council;
@@ -4,6 +4,14 @@ const STOPS = ['branch', 'staged', 'unstaged', 'untracked'];
4
4
 
5
5
  const DEFAULT_SCOPE = { start: 'unstaged', end: 'untracked' };
6
6
 
7
+ // Canonical "the selected scope resolves to zero changed files" message, shared
8
+ // so every entry point reports it identically: the web routes' 409 guard
9
+ // (rejectIfEmptyScope) and the headless in-process guard, which now fails the
10
+ // run (exit non-zero) instead of recording a zero-suggestion success. A
11
+ // delegated headless run surfaces the same 409 body verbatim, so all three
12
+ // paths match byte-for-byte.
13
+ const EMPTY_SCOPE_MESSAGE = 'No changes found in the selected scope. Check that your scope includes files with modifications, or adjust the scope range.';
14
+
7
15
  const UNSTAGED_INDEX = STOPS.indexOf('unstaged');
8
16
 
9
17
  function isValidScope(start, end) {
@@ -166,6 +174,7 @@ function scopeGitHints(start, end, baseBranch) {
166
174
  const LocalScope = {
167
175
  STOPS,
168
176
  DEFAULT_SCOPE,
177
+ EMPTY_SCOPE_MESSAGE,
169
178
  VALID_SCOPE_RANGES,
170
179
  isValidScope,
171
180
  parseScopeArg,
package/src/main.js CHANGED
@@ -17,10 +17,11 @@ const { resolveCouncilHandle, getCouncilLastUsedRepos, shortId } = require('./co
17
17
  const { runHeadlessCouncilAnalysis } = require('./councils/headless-council');
18
18
  const { normalizeCouncilConfig, validateCouncilConfig } = require('./routes/councils');
19
19
  const { resolveReviewConfig } = require('./review-config');
20
+ const { GlobalSettingsService } = require('./settings/global-settings-service');
20
21
  const { redirectConsoleToStderr } = require('./mcp-stdio');
21
22
  const { getChangedFiles } = require('./routes/executable-analysis');
22
23
  const { safeParseJson } = require('./utils/safe-parse-json');
23
- const { includesBranch, parseScopeArg, VALID_SCOPE_RANGES } = require('./local-scope');
24
+ const { includesBranch, parseScopeArg, VALID_SCOPE_RANGES, EMPTY_SCOPE_MESSAGE } = require('./local-scope');
24
25
  const { storePRData, resolvePrHostBinding, registerRepositoryLocation, findRepositoryPath } = require('./setup/pr-setup');
25
26
  const { isDualHostRepo, resolvePreflightBinding, hostSetupParamValue } = require('./utils/host-resolution');
26
27
  const { fireReviewStartedHook } = require('./hooks/payloads');
@@ -34,6 +35,7 @@ const { getEmoji: getCategoryEmoji } = require('./utils/category-emoji');
34
35
  const open = (...args) => process.env.PAIR_REVIEW_NO_OPEN ? Promise.resolve() : import('open').then(({default: open}) => open(...args));
35
36
  const { registerProtocolHandler, unregisterProtocolHandler } = require('./protocol-handler');
36
37
  const { attemptDelegation } = require('./single-port');
38
+ const { probeServer, runDelegatedAnalysis } = require('./headless/delegate');
37
39
 
38
40
  let db = null;
39
41
 
@@ -162,8 +164,13 @@ OPTIONS:
162
164
  Auto-detects PR in GitHub Actions environment
163
165
  --headless Run AI analysis, store it in the local database, and
164
166
  report the results to stdout/stderr, then exit. No
165
- server, no browser, no GitHub post. Works with a
166
- <pr> argument or --local.
167
+ browser, no GitHub post. Works with a <pr> argument
168
+ or --local. If a compatible pair-review server is
169
+ already running on the configured port, the run is
170
+ delegated to it so the web UI shows live progress
171
+ (the CLI still waits and prints the same result);
172
+ otherwise it runs in-process. See --no-server /
173
+ --require-server.
167
174
  --json With --headless, emit the completed run plus its
168
175
  consolidated final suggestions as a single JSON
169
176
  document on a clean stdout. For any outcome of the
@@ -177,6 +184,16 @@ OPTIONS:
177
184
  first. stderr is quiet by default (only
178
185
  warnings/errors); add --debug for verbose progress
179
186
  logs. Only valid together with --headless.
187
+ --no-server (Headless mode) Always analyze in-process, even when
188
+ a compatible pair-review server is running. Skips the
189
+ delegation probe. Use when you want a fully isolated
190
+ run with no live UI. (--use-checkout and --yolo also
191
+ force in-process, since a delegated server cannot
192
+ honor them.)
193
+ --require-server (Headless mode) Require delegation to a compatible
194
+ running server (so the UI shows live progress). If no
195
+ such server is available, fail fast (exit 1) instead
196
+ of falling back to an in-process run.
180
197
  --instructions <text> Per-run custom instructions for the analysis.
181
198
  Applies to any mode that runs analysis: --headless,
182
199
  --ai, --ai-draft, --ai-review, or --council (with
@@ -257,8 +274,6 @@ ENVIRONMENT VARIABLES:
257
274
  PAIR_REVIEW_CLAUDE_CMD Custom command to invoke Claude CLI (default: claude)
258
275
  PAIR_REVIEW_ANTIGRAVITY_CMD Custom command to invoke Antigravity CLI (default: agy)
259
276
  PAIR_REVIEW_CODEX_CMD Custom command to invoke Codex CLI (default: codex)
260
- PAIR_REVIEW_MODEL Override the AI model (same as --model flag, default: opus)
261
- PAIR_REVIEW_PROVIDER Override the AI provider (same as --provider flag, default: claude)
262
277
 
263
278
  CONFIGURATION:
264
279
  Config file: ~/.pair-review/config.json
@@ -464,6 +479,14 @@ function parseArgs(args) {
464
479
  flags.aiReview = true;
465
480
  } else if (arg === '--headless') {
466
481
  flags.headless = true;
482
+ } else if (arg === '--no-server') {
483
+ // Force in-process headless analysis even when a compatible server is
484
+ // running (skip the delegation probe). Headless-only; validated below.
485
+ flags.noServer = true;
486
+ } else if (arg === '--require-server') {
487
+ // Require delegation to a compatible running server; fail fast (exit 1)
488
+ // instead of falling back to in-process. Headless-only; validated below.
489
+ flags.requireServer = true;
467
490
  } else if (arg === '--json') {
468
491
  flags.json = true;
469
492
  } else if (arg === '--instructions') {
@@ -570,32 +593,6 @@ function parseArgs(args) {
570
593
  return { prArgs, flags };
571
594
  }
572
595
 
573
- /**
574
- * Fold the PAIR_REVIEW_PROVIDER / PAIR_REVIEW_MODEL env vars into parsed flags.
575
- *
576
- * `--provider`/`--model` and their env-var twins are two channels for the same
577
- * override, but only the flags are threaded through single-port delegation
578
- * (`buildDelegationUrl` forwards `flags.provider`/`flags.model`). Without this
579
- * fold, an env-only invocation (`PAIR_REVIEW_PROVIDER=codex pair-review 123
580
- * --ai`) delegates with an empty `flags.provider` and the override is silently
581
- * dropped at the process boundary. Normalizing env→flags once here gives every
582
- * downstream reader — delegation, the flags→env mirror, headless resolvers — a
583
- * single effective value. Explicit flags always win over env.
584
- *
585
- * @param {object} flags - Parsed CLI flags (mutated in place)
586
- * @param {object} [env] - Environment source (defaults to process.env; injectable for tests)
587
- * @returns {object} the same `flags`, for chaining
588
- */
589
- function normalizeProviderModelFlags(flags, env = process.env) {
590
- if (!flags.provider && env.PAIR_REVIEW_PROVIDER) {
591
- flags.provider = env.PAIR_REVIEW_PROVIDER;
592
- }
593
- if (!flags.model && env.PAIR_REVIEW_MODEL) {
594
- flags.model = env.PAIR_REVIEW_MODEL;
595
- }
596
- return flags;
597
- }
598
-
599
596
  /**
600
597
  * Main application entry point
601
598
  */
@@ -666,8 +663,6 @@ ENVIRONMENT VARIABLES:
666
663
  PAIR_REVIEW_CLAUDE_CMD Custom Claude CLI command (default: claude)
667
664
  PAIR_REVIEW_ANTIGRAVITY_CMD Custom Antigravity CLI command (default: agy)
668
665
  PAIR_REVIEW_CODEX_CMD Custom Codex CLI command (default: codex)
669
- PAIR_REVIEW_MODEL Default AI model (e.g., opus, sonnet, haiku)
670
- PAIR_REVIEW_PROVIDER Default AI provider (e.g., claude, antigravity, codex)
671
666
  PAIR_REVIEW_DB_NAME Custom database filename (overrides config)
672
667
 
673
668
  LOCAL CONFIG:
@@ -725,7 +720,7 @@ AI PROVIDERS:
725
720
  }
726
721
 
727
722
  // Load configuration
728
- const { config, isFirstRun } = await loadConfig();
723
+ const { config, isFirstRun, layers } = await loadConfig();
729
724
 
730
725
  // Show welcome message on first run (after early-exit flags are handled
731
726
  // above). Suppressed in headless --json mode so nothing reaches stdout but
@@ -738,10 +733,6 @@ AI PROVIDERS:
738
733
  // single-port delegation can skip DB entirely)
739
734
  const { prArgs, flags } = parseArgs(args);
740
735
 
741
- // Normalize env→flags before delegation so an env-only provider/model
742
- // override rides the single-port delegation URL to the running server.
743
- normalizeProviderModelFlags(flags);
744
-
745
736
  // Headless-mode flag validation (fail fast, before any DB/server work).
746
737
  // --instructions and --instructions-file are mutually exclusive.
747
738
  if (flags.instructions && flags.instructionsFile) {
@@ -755,6 +746,21 @@ AI PROVIDERS:
755
746
  if (flags.headless && prArgs.length === 0 && !flags.local) {
756
747
  throw new Error('--headless flag requires a pull request number/URL or --local to run analysis.');
757
748
  }
749
+ // --no-server / --require-server tune headless server delegation and are
750
+ // meaningless without --headless. They are also mutually exclusive: one
751
+ // forbids delegation, the other requires it.
752
+ if ((flags.noServer || flags.requireServer) && !flags.headless) {
753
+ throw new Error('--no-server/--require-server only apply to --headless runs.');
754
+ }
755
+ if (flags.noServer && flags.requireServer) {
756
+ throw new Error('--no-server and --require-server are mutually exclusive.');
757
+ }
758
+ // --require-server demands delegation, but --use-checkout and --yolo force
759
+ // in-process execution (a delegated server can honor neither). The
760
+ // combination is contradictory — reject it rather than silently ignore one.
761
+ if (flags.requireServer && (flags.useCheckout || flags.yolo)) {
762
+ throw new Error('--require-server cannot be combined with --use-checkout or --yolo (those flags require in-process execution).');
763
+ }
758
764
  // --scope and --base are local-review diff controls. They require --local
759
765
  // and cannot be combined with a PR positional. They do NOT imply --local
760
766
  // (explicit flags only — no magic mode switching).
@@ -809,19 +815,12 @@ AI PROVIDERS:
809
815
  // No redirect is repeated here: it would be too late to matter and is
810
816
  // redundant given the early call.
811
817
 
812
- // Apply debug_stream from config if not already enabled by CLI flag
813
- if (!flags.debugStream && config.debug_stream) {
814
- flags.debugStream = true;
815
- logger.setStreamDebugEnabled(true);
816
- }
817
-
818
- // Apply yolo mode from CLI flag or config
819
- if (flags.yolo || config.yolo) {
820
- // config.yolo: used by applyConfigOverrides() for this process
821
- config.yolo = true;
822
- // Env var: bridges to server.js which reloads config from disk independently
823
- process.env.PAIR_REVIEW_YOLO = 'true';
824
- }
818
+ // NOTE: debug_stream handling, the yolo env bridge, and applyConfigOverrides
819
+ // are deliberately deferred until AFTER the global-settings overlay is folded
820
+ // into `config` (below, right after DB init). Each latches a config value that
821
+ // an in-app /settings override can change (debug_stream, yolo → the
822
+ // provider-runtime yoloMode), so running them here — on the pre-overlay file
823
+ // config — would ignore a restart-required override.
825
824
 
826
825
  // --model is ignored when --council is set: council voices use their own
827
826
  // per-voice models, so a top-level --model has no effect on the analysis.
@@ -829,12 +828,6 @@ AI PROVIDERS:
829
828
  console.warn('Warning: --model is ignored when --council is set; council voices use their own per-voice models.');
830
829
  }
831
830
 
832
- // Apply provider config overrides (including yolo) for all code paths
833
- // (interactive, headless, local). server.js calls this independently on
834
- // startup, but headless paths (--ai-draft, --ai-review) never start the
835
- // server, so we must also apply here.
836
- applyConfigOverrides(config);
837
-
838
831
  // --list-councils: print the saved councils and exit. Needs the database
839
832
  // but no server, no PR/local context, and no single-port delegation.
840
833
  if (flags.listCouncils) {
@@ -931,6 +924,91 @@ AI PROVIDERS:
931
924
  db = await initializeDatabase(resolveDbName(config));
932
925
  }
933
926
 
927
+ // Overlay in-app global-settings overrides onto the CLI's config object so
928
+ // restart-required settings (worktree/review retention, dev_mode, etc.) and
929
+ // provider/model defaults honor DB values on this launch — the server that
930
+ // startServer() spins up applies its own overlay independently. Guarded so a
931
+ // DB read failure leaves the file config intact rather than aborting startup.
932
+ //
933
+ // Paths that exit BEFORE this point run on the pre-overlay file config and
934
+ // therefore cannot see in-app overrides — this is intentional: `--list-councils`
935
+ // only reads DB rows (no config-driven behavior), and a single-port delegated
936
+ // launch hands off to an already-running server that applies its own overlay.
937
+ try {
938
+ const overlay = new GlobalSettingsService({ db, baseConfig: config, layers });
939
+ Object.assign(config, overlay.buildEffectiveConfig());
940
+ } catch (overlayError) {
941
+ logger.warn(`Could not apply global-settings overrides: ${overlayError.message}`);
942
+ }
943
+
944
+ // Config consumers that latch an overlay-affected value — deferred to here so
945
+ // an in-app /settings override takes effect on this launch (they were NOT run
946
+ // earlier on the pre-overlay file config). Ordered before headless analysis
947
+ // and startServer, both of which depend on them.
948
+
949
+ // Apply debug_stream from config if not already enabled by CLI flag.
950
+ if (!flags.debugStream && config.debug_stream) {
951
+ flags.debugStream = true;
952
+ logger.setStreamDebugEnabled(true);
953
+ }
954
+
955
+ // Apply yolo mode from CLI flag or config.
956
+ if (flags.yolo || config.yolo) {
957
+ // config.yolo: used by applyConfigOverrides() for this process
958
+ config.yolo = true;
959
+ // Env var: bridges to server.js which reloads config from disk independently
960
+ process.env.PAIR_REVIEW_YOLO = 'true';
961
+ }
962
+
963
+ // Apply provider config overrides (including yolo) for all code paths
964
+ // (interactive, headless, local). server.js calls this independently on
965
+ // startup, but headless paths (--ai-draft, --ai-review) never start the
966
+ // server, so we must also apply here.
967
+ applyConfigOverrides(config);
968
+
969
+ // Headless server delegation: when a compatible pair-review server is
970
+ // already running on the configured port, hand analysis EXECUTION to it so
971
+ // its web UI shows the live council view, then wait and emit the same JSON.
972
+ // Decided HERE — before the worktree/pool setup below — so a delegated run
973
+ // never disturbs the local worktree pool the server owns. --no-server forces
974
+ // the in-process path (skip the probe); --require-server fails fast (exit 1)
975
+ // when no compatible server is available instead of falling back. Anything
976
+ // that isn't a clean delegation falls through to the UNCHANGED in-process
977
+ // headless path (pool rehydrate + handleHeadlessAnalysis) below.
978
+ if (flags.headless) {
979
+ // Flags that force in-process execution and therefore SKIP the probe:
980
+ // --no-server — explicit opt-out.
981
+ // --use-checkout — the analysis must run against THIS process's current
982
+ // checkout; a delegated server uses its own worktree,
983
+ // so delegating would silently ignore the flag.
984
+ // --yolo — permission relaxation applies to the provider spawned
985
+ // by THIS process; the server applies its own yolo/
986
+ // permission config, so delegating would not honor it.
987
+ // Skipping the probe (rather than delegating and dropping the flag) keeps
988
+ // the flag's semantics intact. `--require-server` with either flag is
989
+ // rejected at validation, so it cannot reach the skip branches here.
990
+ let probe;
991
+ if (flags.noServer) {
992
+ probe = { delegate: false, reason: '--no-server set' };
993
+ } else if (flags.useCheckout) {
994
+ probe = { delegate: false, reason: '--use-checkout requires the current checkout, which a delegated server cannot use' };
995
+ } else if (flags.yolo) {
996
+ probe = { delegate: false, reason: '--yolo permissions apply to this process, not a delegated server' };
997
+ } else {
998
+ probe = await probeServer(config);
999
+ }
1000
+ if (probe.delegate) {
1001
+ await handleHeadlessDelegated(prArgs, config, db, flags, probe);
1002
+ return;
1003
+ }
1004
+ if (flags.requireServer) {
1005
+ throw new Error(
1006
+ `--require-server: no compatible pair-review server is available to delegate to (${probe.reason}).`
1007
+ );
1008
+ }
1009
+ logger.info(`Running headless analysis in-process (${probe.reason}).`);
1010
+ }
1011
+
934
1012
  // Migrate existing worktrees to database (if any)
935
1013
  const path = require('path');
936
1014
  const worktreeBaseDir = path.join(getConfigDir(), 'worktrees');
@@ -1017,7 +1095,7 @@ AI PROVIDERS:
1017
1095
 
1018
1096
  // No PR arguments - just start the server
1019
1097
  console.log('No pull request specified. Starting server...');
1020
- await startServerOnly(config, poolLifecycle);
1098
+ await startServerOnly(config, poolLifecycle, flags);
1021
1099
  }
1022
1100
 
1023
1101
  } catch (error) {
@@ -1100,18 +1178,15 @@ async function handlePullRequest(args, config, db, flags = {}, poolLifecycle = n
1100
1178
  await registerRepositoryLocation(db, currentDir, prInfo.owner, prInfo.repo);
1101
1179
  }
1102
1180
 
1103
- // Set model override if provided via CLI flag. Skipped when --council is
1104
- // set: council voices carry their own per-voice models.
1105
- if (flags.model && !flags.council) {
1106
- process.env.PAIR_REVIEW_MODEL = flags.model;
1107
- }
1108
-
1109
- // Set provider override if provided via CLI flag. Mirrored into the env
1110
- // var so the web/UI analysis paths (which read PAIR_REVIEW_PROVIDER via
1111
- // getProvider()) honor it too, matching how --model works.
1112
- if (flags.provider) {
1113
- process.env.PAIR_REVIEW_PROVIDER = flags.provider;
1114
- }
1181
+ // Per-run provider/model overrides from --provider/--model, threaded
1182
+ // explicitly into the server (no env side channel). The web/UI analyze
1183
+ // routes read these via app.get('cliOverrides'). The model override is
1184
+ // skipped when --council is set: council voices carry their own per-voice
1185
+ // models. (--provider is not council-gated, matching prior behavior.)
1186
+ const cliOverrides = {
1187
+ provider: flags.provider || undefined,
1188
+ model: (flags.model && !flags.council) ? flags.model : undefined
1189
+ };
1115
1190
 
1116
1191
  // Resolve the council handle FAIL-FAST before starting the server, so a bad
1117
1192
  // handle surfaces as a clean error (caught below) instead of after the
@@ -1122,7 +1197,7 @@ async function handlePullRequest(args, config, db, flags = {}, poolLifecycle = n
1122
1197
  }
1123
1198
 
1124
1199
  // Start server and open browser to setup page
1125
- const port = await startServer(db, poolLifecycle);
1200
+ const port = await startServer(db, poolLifecycle, { cliOverrides });
1126
1201
 
1127
1202
  // Async cleanup of stale worktrees and reviews (don't block startup)
1128
1203
  cleanupStaleWorktreesAsync(config);
@@ -1169,9 +1244,17 @@ async function handlePullRequest(args, config, db, flags = {}, poolLifecycle = n
1169
1244
  * Start server without PR context
1170
1245
  * @param {Object} config - Application configuration
1171
1246
  * @param {import('./git/worktree-pool-lifecycle').WorktreePoolLifecycle} [poolLifecycle] - Pool lifecycle instance
1247
+ * @param {Object} [flags] - Parsed CLI flags (for --provider/--model overrides)
1172
1248
  */
1173
- async function startServerOnly(config, poolLifecycle = null) {
1174
- const port = await startServer(db, poolLifecycle);
1249
+ async function startServerOnly(config, poolLifecycle = null, flags = {}) {
1250
+ // Per-run provider/model overrides carry through to browser-triggered
1251
+ // analyses even when no PR was named on the CLI. Model is council-gated to
1252
+ // match handlePullRequest.
1253
+ const cliOverrides = {
1254
+ provider: flags.provider || undefined,
1255
+ model: (flags.model && !flags.council) ? flags.model : undefined
1256
+ };
1257
+ const port = await startServer(db, poolLifecycle, { cliOverrides });
1175
1258
 
1176
1259
  // Async cleanup of stale worktrees and reviews (don't block startup)
1177
1260
  cleanupStaleWorktreesAsync(config);
@@ -1492,7 +1575,7 @@ async function performHeadlessReview(args, config, db, flags, options, externalP
1492
1575
  // --council; resolveReviewConfig re-resolves the same handle (cheap in-memory
1493
1576
  // match) and unifies single/council selection with the headless path.
1494
1577
  // --provider (flags.provider) rides in as an explicit single-model pick; the
1495
- // resolver's ladder (explicit › PAIR_REVIEW_PROVIDER › repo › config › 'claude')
1578
+ // resolver's ladder (explicit › repo › in-app override › config › 'claude')
1496
1579
  // delivers the CLI override that commit 662e introduced.
1497
1580
  const reviewConfig = await resolveReviewConfig(
1498
1581
  db,
@@ -2095,11 +2178,11 @@ async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycl
2095
2178
 
2096
2179
  // Thread --provider (flags.provider) through as an explicit single-model pick,
2097
2180
  // exactly as the PR-submit path at the top of the file and the local headless
2098
- // path do. handleHeadlessAnalysis dispatches BEFORE the local/PR split (and thus
2099
- // before handlePullRequest's PAIR_REVIEW_PROVIDER env mirror), so omitting it
2100
- // here would let `pair-review <pr> --headless --provider <p>` silently fall
2101
- // through to the default provider (or, with a repo default council, switch to
2102
- // council mode) — while --model in the same invocation was honored.
2181
+ // path do. handleHeadlessAnalysis dispatches BEFORE the local/PR split, and the
2182
+ // headless resolvers read only these explicit flags (no env side channel), so
2183
+ // omitting it here would let `pair-review <pr> --headless --provider <p>`
2184
+ // silently fall through to the default provider (or, with a repo default
2185
+ // council, switch to council mode) — while --model was honored.
2103
2186
  const reviewConfig = await resolveReviewConfig(
2104
2187
  db,
2105
2188
  repository,
@@ -2141,48 +2224,6 @@ async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycl
2141
2224
  }
2142
2225
  }
2143
2226
 
2144
- /**
2145
- * Record a completed, zero-suggestion analysis run for an empty-scope headless
2146
- * local review (the analyzer is never invoked). Mirrors the web routes'
2147
- * empty-scope guard but, lacking an HTTP response, persists a normal-shaped run
2148
- * so `buildHeadlessJson` emits the standard `{ run, suggestions: [], count: 0 }`
2149
- * envelope and the command still exits 0 ("zero suggestions is still success").
2150
- * The run is attributed to whatever `reviewConfig` resolved (single or council).
2151
- *
2152
- * @param {Object} db - Database instance
2153
- * @param {Object} params
2154
- * @param {number} params.reviewId - Review id the run belongs to
2155
- * @param {Object} params.reviewConfig - resolveReviewConfig result (single|council)
2156
- * @param {Object} params.instructions - { globalInstructions, repoInstructions, requestInstructions }
2157
- * @param {string|null} params.headSha - Head SHA recorded on the run
2158
- * @returns {Promise<string>} The created run id
2159
- */
2160
- async function recordEmptyScopeRun(db, { reviewId, reviewConfig, instructions, headSha }) {
2161
- const runId = uuidv4();
2162
- const runRepo = new AnalysisRunRepository(db);
2163
- const isCouncil = reviewConfig.type === 'council';
2164
- await runRepo.create({
2165
- id: runId,
2166
- reviewId,
2167
- provider: isCouncil ? 'council' : reviewConfig.provider,
2168
- model: isCouncil ? reviewConfig.council.id : reviewConfig.model,
2169
- tier: null,
2170
- globalInstructions: instructions?.globalInstructions || null,
2171
- repoInstructions: instructions?.repoInstructions || null,
2172
- requestInstructions: instructions?.requestInstructions || null,
2173
- headSha: headSha || null,
2174
- configType: isCouncil ? reviewConfig.configType : 'single',
2175
- levelsConfig: null
2176
- });
2177
- await runRepo.update(runId, {
2178
- status: 'completed',
2179
- summary: 'No changes found in the selected scope — analysis skipped.',
2180
- totalSuggestions: 0,
2181
- filesAnalyzed: 0
2182
- });
2183
- return runId;
2184
- }
2185
-
2186
2227
  /**
2187
2228
  * Headless analysis-only handler: run analysis (single or council), store it in
2188
2229
  * the DB, report the consolidated run to stdout/stderr, and exit. No server, no
@@ -2197,6 +2238,88 @@ async function recordEmptyScopeRun(db, { reviewId, reviewConfig, instructions, h
2197
2238
  * for PR-mode pool acquisition so the rehydrated in-memory tracker is used;
2198
2239
  * local mode has no worktree/pool and ignores it.
2199
2240
  */
2241
+ /**
2242
+ * Headless DELEGATED handler: hand analysis EXECUTION to a compatible running
2243
+ * pair-review server (so its web UI shows the live council view) and wait for
2244
+ * completion, then emit the same headless JSON/summary the in-process path
2245
+ * produces — the result is read from the shared SQLite DB via
2246
+ * `buildHeadlessJson`, so the `--json` document is byte-identical.
2247
+ *
2248
+ * The server owns setup (including the PR worktree-pool hold), so this path
2249
+ * NEVER acquires a pool slot — releasing one the server is analyzing in would
2250
+ * hand the worktree to another consumer mid-run. Config is resolved CLI-side
2251
+ * exactly like the in-process path (`resolveReviewConfig` with the explicit
2252
+ * `--council`/`--provider`/`--model` flags; the council handle is resolved to an
2253
+ * id here) and passed to the server as resolved, explicit values — the server
2254
+ * never re-resolves. `--instructions`/`--instructions-file` flow through as the
2255
+ * launch endpoints' `customInstructions`; the server derives global + repo
2256
+ * instructions from its own (shared) config/DB and merges them identically, so
2257
+ * the effective prompt matches the in-process path.
2258
+ *
2259
+ * @param {Array<string>} prArgs - PR identifier args (empty for --local)
2260
+ * @param {Object} config - Application configuration
2261
+ * @param {Object} db - Database instance (shared with the server)
2262
+ * @param {Object} flags - Parsed CLI flags
2263
+ * @param {{baseUrl: string}} probe - probeServer result (delegate === true)
2264
+ */
2265
+ async function handleHeadlessDelegated(prArgs, config, db, flags, probe) {
2266
+ const requestInstructions = await resolveCliInstructions(flags);
2267
+ const mode = flags.local ? 'local' : 'pr';
2268
+
2269
+ let repository;
2270
+ let prInfo = null;
2271
+ let localPath = null;
2272
+ let host;
2273
+ if (flags.local) {
2274
+ localPath = require('path').resolve(flags.localPath || process.cwd());
2275
+ const repoRoot = await findGitRoot(localPath);
2276
+ repository = await getRepositoryName(repoRoot);
2277
+ } else {
2278
+ const parser = new PRArgumentParser(config);
2279
+ prInfo = await parser.parsePRArguments(prArgs);
2280
+ repository = normalizeRepository(prInfo.owner, prInfo.repo);
2281
+ // Forward the parsed host verbatim to the setup body (null = github.com, a
2282
+ // string = alt api_host); `undefined` is omitted so the server derives it.
2283
+ host = prInfo.host;
2284
+ }
2285
+
2286
+ // Resolve council/provider/model CLI-side (council handle → id). Throws on a
2287
+ // bad handle or invalid council config — fail-fast parity with the in-process
2288
+ // path, before any server round-trip.
2289
+ const reviewConfig = await resolveReviewConfig(
2290
+ db,
2291
+ repository,
2292
+ { council: flags.council, provider: flags.provider, model: flags.model },
2293
+ config
2294
+ );
2295
+
2296
+ // Take ownership of the interrupt signals for the delegated run. `require`ing
2297
+ // ./server (main.js top) registered server.js's module-level gracefulShutdown
2298
+ // on SIGINT/SIGTERM; in headless mode the server never started, so
2299
+ // gracefulShutdown would hit `process.exit(0)` synchronously — preempting the
2300
+ // delegate's best-effort cancel POST and exiting 0 instead of 130. Remove
2301
+ // those handlers so runDelegatedAnalysis's installCancelHandlers owns the
2302
+ // signals. Scoped to this delegated handler only: the in-process fallback
2303
+ // (handleHeadlessAnalysis) is never reached from here and keeps its handlers.
2304
+ process.removeAllListeners('SIGINT');
2305
+ process.removeAllListeners('SIGTERM');
2306
+
2307
+ const { runId } = await runDelegatedAnalysis({
2308
+ baseUrl: probe.baseUrl,
2309
+ mode,
2310
+ reviewConfig,
2311
+ customInstructions: requestInstructions,
2312
+ prInfo,
2313
+ host,
2314
+ localPath,
2315
+ scope: flags.scope || null,
2316
+ base: flags.base || null,
2317
+ db
2318
+ });
2319
+
2320
+ await emitHeadlessResult(db, { runId, mode, flags });
2321
+ }
2322
+
2200
2323
  async function handleHeadlessAnalysis(prArgs, config, db, flags, poolLifecycle) {
2201
2324
  // NOTE: In --json mode, redirectConsoleToStderr() is already called in main()
2202
2325
  // BEFORE the DB-init/migration/pool-rehydrate block, so stdout is clean by the
@@ -2299,42 +2422,38 @@ async function handleHeadlessAnalysis(prArgs, config, db, flags, poolLifecycle)
2299
2422
  const isEmptyScope = !session.diff || session.diff.trim().length === 0;
2300
2423
 
2301
2424
  if (isEmptyScope) {
2302
- // Empty-scope guard, mirroring the web routes' rejectIfEmptyScope (which
2303
- // returns 409). Headless has no HTTP response, so instead emit a normal-
2304
- // shaped, completed run with zero suggestions: emitHeadlessResult then
2305
- // produces the standard { mode, run, suggestions: [], count: 0 } envelope
2306
- // and exits 0 (zero suggestions is still success). Skipping the analyzer
2307
- // avoids spending provider tokens on a guaranteed-empty result.
2308
- runId = await recordEmptyScopeRun(db, {
2309
- reviewId: session.sessionId,
2310
- reviewConfig,
2311
- instructions,
2312
- headSha: session.headSha
2313
- });
2314
- } else {
2315
- // Scope is non-empty (diff present), so the analyzer needs the scope-aware
2316
- // changed-file list for suggestion validation. Use the throwing variant:
2317
- // since we KNOW the scope is non-empty, a [] from a swallowed git error
2318
- // would be a lie — surface it as a non-zero exit instead.
2319
- const changedFiles = await getChangedFiles(repoPath, {
2320
- scopeStart: session.scopeStart,
2321
- scopeEnd: session.scopeEnd,
2322
- baseBranch: session.baseBranch || null,
2323
- }, { throwOnError: true });
2425
+ // Empty-scope guard, matching the web routes' rejectIfEmptyScope (409) in
2426
+ // BOTH outcome and message: an empty scope is a FAILURE, not a success.
2427
+ // Recording a zero-suggestion "completed" run here (the prior behavior)
2428
+ // let `pair-loop` read exit 0 / empty findings and declare convergence
2429
+ // having reviewed nothing. Throwing the shared EMPTY_SCOPE_MESSAGE routes
2430
+ // through main()'s catch → `{ ok:false, error }` on stdout + non-zero
2431
+ // exit, identical to a delegated run (whose 409 body is surfaced verbatim).
2432
+ throw new Error(EMPTY_SCOPE_MESSAGE);
2433
+ }
2434
+
2435
+ // Scope is non-empty (diff present), so the analyzer needs the scope-aware
2436
+ // changed-file list for suggestion validation. Use the throwing variant:
2437
+ // since we KNOW the scope is non-empty, a [] from a swallowed git error
2438
+ // would be a lie — surface it as a non-zero exit instead.
2439
+ const changedFiles = await getChangedFiles(repoPath, {
2440
+ scopeStart: session.scopeStart,
2441
+ scopeEnd: session.scopeEnd,
2442
+ baseBranch: session.baseBranch || null,
2443
+ }, { throwOnError: true });
2324
2444
 
2325
- ({ runId } = await runHeadlessAnalysis(db, config, {
2326
- reviewId: session.sessionId,
2327
- worktreePath: repoPath,
2328
- prMetadata: localMetadata,
2329
- changedFiles,
2330
- repository,
2331
- repoSettings,
2332
- instructions,
2333
- reviewConfig,
2334
- providerOverrides,
2335
- githubClient: undefined
2336
- }));
2337
- }
2445
+ ({ runId } = await runHeadlessAnalysis(db, config, {
2446
+ reviewId: session.sessionId,
2447
+ worktreePath: repoPath,
2448
+ prMetadata: localMetadata,
2449
+ changedFiles,
2450
+ repository,
2451
+ repoSettings,
2452
+ instructions,
2453
+ reviewConfig,
2454
+ providerOverrides,
2455
+ githubClient: undefined
2456
+ }));
2338
2457
  } else {
2339
2458
  mode = 'pr';
2340
2459
  // Forward the session's rehydrated pool lifecycle so pool acquisition goes
@@ -2669,4 +2788,4 @@ if (require.main === module) {
2669
2788
  main();
2670
2789
  }
2671
2790
 
2672
- module.exports = { main, parseArgs, normalizeProviderModelFlags, detectPRFromGitHubEnvironment, printCouncilList, handleHeadlessAnalysis, runHeadlessAnalysis, recordEmptyScopeRun, buildHeadlessJson, buildHeadlessErrorJson, resolveCliInstructions };
2791
+ module.exports = { main, parseArgs, detectPRFromGitHubEnvironment, printCouncilList, handleHeadlessAnalysis, handleHeadlessDelegated, runHeadlessAnalysis, buildHeadlessJson, buildHeadlessErrorJson, resolveCliInstructions };