@in-the-loop-labs/pair-review 4.1.1 → 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 (70) 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/chat/api-reference.js +9 -5
  46. package/src/chat/prompt-builder.js +8 -1
  47. package/src/config.js +15 -6
  48. package/src/database.js +307 -14
  49. package/src/external/github-adapter.js +39 -5
  50. package/src/headless/delegate.js +682 -0
  51. package/src/local-review.js +10 -10
  52. package/src/local-scope.js +9 -0
  53. package/src/main.js +276 -157
  54. package/src/mcp-stdio.js +24 -1
  55. package/src/review-config.js +93 -25
  56. package/src/routes/chat.js +2 -2
  57. package/src/routes/config.js +12 -10
  58. package/src/routes/external-comments.js +5 -1
  59. package/src/routes/local.js +2 -4
  60. package/src/routes/mcp.js +18 -13
  61. package/src/routes/reviews.js +223 -4
  62. package/src/routes/settings.js +252 -0
  63. package/src/routes/setup.js +80 -1
  64. package/src/routes/shared.js +31 -29
  65. package/src/routes/snippets.js +154 -0
  66. package/src/routes/stack-analysis.js +17 -14
  67. package/src/server.js +86 -18
  68. package/src/settings/global-settings-service.js +472 -0
  69. package/src/settings/registry.js +624 -0
  70. package/src/utils/db-identity.js +44 -0
package/src/mcp-stdio.js CHANGED
@@ -69,13 +69,17 @@ async function startMCPStdio() {
69
69
  const { startServer } = require('./server');
70
70
  const { loadConfig, resolveDbName } = require('./config');
71
71
  const { createMCPServer } = require('./routes/mcp');
72
+ const { GlobalSettingsService } = require('./settings/global-settings-service');
72
73
  const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
73
74
 
74
- // Load config BEFORE database so we can resolve db_name
75
+ // Load config BEFORE database so we can resolve db_name. `layers` is retained
76
+ // for the global-settings overlay applied after the DB opens (below).
75
77
  let config = {};
78
+ let layers = [];
76
79
  try {
77
80
  const loaded = await loadConfig();
78
81
  config = loaded.config || {};
82
+ layers = loaded.layers || [];
79
83
  } catch (err) {
80
84
  console.error(`[MCP] Warning: failed to load config, using defaults: ${err.message}`);
81
85
  }
@@ -88,6 +92,25 @@ async function startMCPStdio() {
88
92
  process.env.PAIR_REVIEW_SINGLE_PORT = 'false';
89
93
 
90
94
  const db = await initializeDatabase(resolveDbName(config));
95
+
96
+ // Fold in-app /settings overrides onto the config BEFORE it is handed to
97
+ // createMCPServer, so `start_analysis` over stdio honors default_provider /
98
+ // default_model (and other) overrides — matching the precedence documented in
99
+ // src/routes/mcp.js (which reads `config._globalOverrides`). Without this the
100
+ // stdio tool path resolves as if no in-app override existed. startServer(db)
101
+ // applies its own overlay independently for the web-UI routes.
102
+ //
103
+ // Boot-time overlay: overrides changed after this process starts require an
104
+ // MCP-server restart to take effect (the config is captured once when the
105
+ // tools are registered). Guarded so a DB read failure leaves the file config
106
+ // intact rather than aborting the transport.
107
+ try {
108
+ const globalSettings = new GlobalSettingsService({ db, baseConfig: config, layers });
109
+ config = globalSettings.buildEffectiveConfig();
110
+ } catch (overlayError) {
111
+ console.error(`[MCP] Warning: could not apply global-settings overrides: ${overlayError.message}`);
112
+ }
113
+
91
114
  const port = await startServer(db);
92
115
 
93
116
  const mcpServer = createMCPServer(db, { port, config });
@@ -49,41 +49,55 @@ function _buildCouncilSelection(council) {
49
49
  /**
50
50
  * Resolve the single-provider/model pair from the per-field precedence ladders.
51
51
  *
52
- * Mirrors the canonical (pre-refactor) headless derivation in
53
- * `performHeadlessReview` and the MCP ladder (`src/routes/mcp.js`), which both
54
- * let a deliberate per-invocation environment override win over a sticky,
55
- * persisted repo default:
56
- * provider: explicit › PAIR_REVIEW_PROVIDER › repo default › config.default_provider › config.provider › 'claude'
57
- * model: explicit › PAIR_REVIEW_MODEL › repo default › config.default_model › config.model › 'opus'
52
+ * Precedence (highest first), per the global-settings design ("specificity
53
+ * first, then in-app > files"):
54
+ * provider: explicit › repo default › global in-app override › config.default_provider › config.provider › 'claude'
55
+ * model: explicit › repo default › global in-app override › config.default_model › config.model › 'opus'
58
56
  *
59
- * The environment variables sit ABOVE the repo defaults on purpose: `--ai-draft`
60
- * / `--ai-review` (which route through this resolver via `performHeadlessReview`)
61
- * historically resolved env-first, and CI/agent callers set `PAIR_REVIEW_MODEL` /
62
- * `PAIR_REVIEW_PROVIDER` as one-shot overrides that should beat a repo's saved
63
- * `default_model` / `default_provider`. (The interactive web "Analyze" route keeps
64
- * its own repo-before-env single ladder in `src/routes/{pr,local}.js`; this
65
- * resolver is consulted there only to detect council mode, not to pick the model.)
57
+ * The global in-app override (from the /settings page, carried on
58
+ * `config._globalOverrides`) sits ABOVE the config files but BELOW the repo
59
+ * default. The effective config also folds the override into
60
+ * `config.default_provider`; reading it from `_globalOverrides` here lets us
61
+ * rank it above the config-file value explicitly.
62
+ *
63
+ * `explicit` carries the per-run `--provider`/`--model` CLI flags (there is no
64
+ * env-var side channel). `--ai-draft`/`--ai-review` and the interactive analyze
65
+ * routes thread the flags in as `explicit`, so per-run intent stays supreme.
66
+ *
67
+ * When `default_provider`/`default_model` is locked as final by configuration,
68
+ * the effective config already excludes the key from `_globalOverrides` and
69
+ * folds its config-file value into `cfg.default_*`, so the value resolves from
70
+ * the config file (or the hardcoded fallback) here without any special-casing.
71
+ * A repo-scoped default and an explicit per-run flag are more specific and
72
+ * still win.
73
+ *
74
+ * The interactive web "Analyze" route keeps its own single ladder in
75
+ * `src/routes/{pr,local}.js` (`resolveProviderModel`, which ranks the CLI-flag
76
+ * override above repo settings); it consults this resolver only to detect
77
+ * council mode, not to pick the model.
66
78
  *
67
79
  * Each field falls through independently, so supplying only `explicit.model`
68
- * still resolves the provider from env/repo/config defaults (and vice versa).
80
+ * still resolves the provider from repo/override/config defaults (and vice
81
+ * versa).
69
82
  *
70
83
  * @param {Object} explicit - { provider, model } (either may be undefined)
71
84
  * @param {Object|null} repoSettings - Row from RepoSettingsRepository.getRepoSettings
72
- * @param {Object} config - Global config object
85
+ * @param {Object} config - Global config object (may carry `_globalOverrides`)
73
86
  * @returns {{ type: 'single', provider: string, model: string }}
74
87
  * @private
75
88
  */
76
89
  function _buildSingleSelection(explicit, repoSettings, config) {
77
90
  const cfg = config || {};
91
+ const overrides = cfg._globalOverrides || {};
78
92
  const provider = explicit.provider
79
- || process.env.PAIR_REVIEW_PROVIDER
80
93
  || repoSettings?.default_provider
94
+ || overrides.default_provider
81
95
  || cfg.default_provider
82
96
  || cfg.provider
83
97
  || 'claude';
84
98
  const model = explicit.model
85
- || process.env.PAIR_REVIEW_MODEL
86
99
  || repoSettings?.default_model
100
+ || overrides.default_model
87
101
  || cfg.default_model
88
102
  || cfg.model
89
103
  || 'opus';
@@ -103,11 +117,14 @@ function _buildSingleSelection(explicit, repoSettings, config) {
103
117
  * `CouncilRepository.getById` (we already hold the UUID, so no handle
104
118
  * matching is needed). If the id points to a council that no longer exists,
105
119
  * a warning is logged and resolution falls through to the single default.
106
- * 4. `PAIR_REVIEW_PROVIDER` / `PAIR_REVIEW_MODEL` — one-shot env overrides
107
- * (deliberately above repo defaults — see `_buildSingleSelection`).
108
- * 5. `repo_settings.default_provider` / `default_model` — single selection.
109
- * 6. Global `config` defaults — single selection (final hardcoded fallbacks
110
- * 'claude' / 'opus').
120
+ * 4. Global default council — `config._globalOverrides.default_council_id`
121
+ * (an in-app /settings override) or a config-file `default_council_id`.
122
+ * Resolved by id like the repo tier; a stale id logs a warning and falls
123
+ * through. Sits ABOVE the single ladder, so it also outranks a repo's
124
+ * single provider/model default.
125
+ * 5. `repo_settings.default_provider` / `default_model`, then global in-app
126
+ * override (`config._globalOverrides`) › global `config` defaults — single
127
+ * selection (final hardcoded fallbacks 'claude' / 'opus').
111
128
  *
112
129
  * @param {Object} db - Database instance.
113
130
  * @param {string} repository - Repository in `owner/repo` form (may be null/undefined
@@ -139,6 +156,7 @@ async function resolveReviewConfig(db, repository, explicit = {}, config = {}) {
139
156
  }
140
157
 
141
158
  // No explicit pick — consult the repo's saved defaults.
159
+ const cfg = config || {};
142
160
  const repoSettings = repository
143
161
  ? await new RepoSettingsRepository(db).getRepoSettings(repository)
144
162
  : null;
@@ -157,8 +175,58 @@ async function resolveReviewConfig(db, repository, explicit = {}, config = {}) {
157
175
  );
158
176
  }
159
177
 
160
- // 4 & 5. Single selection from repo defaults, then global config, then hardcoded.
161
- return _buildSingleSelection({}, repoSettings, config);
178
+ // 4. Global default council (from the /settings page, carried on
179
+ // `config._globalOverrides.default_council_id`, or a config-file
180
+ // `default_council_id`). Mirrors the repo-council tier but sits below it:
181
+ // a repo's own council still wins, while a global council outranks the
182
+ // single provider/model ladder — INCLUDING a repo's single default — so a
183
+ // global council is the default analysis mode wherever a repo hasn't
184
+ // chosen its own council. NOTE: single-model resolvers
185
+ // (`resolveSingleProviderModel`, used by MCP `start_analysis`, hunk
186
+ // summaries, and tours) intentionally never reach this tier, so a global
187
+ // default council does not fire on those paths — consistent with repo
188
+ // default councils.
189
+ const globalCouncilId = (cfg._globalOverrides && cfg._globalOverrides.default_council_id)
190
+ || cfg.default_council_id;
191
+ if (globalCouncilId) {
192
+ const council = await new CouncilRepository(db).getById(globalCouncilId);
193
+ if (council) {
194
+ return { type: 'council', ..._buildCouncilSelection(council) };
195
+ }
196
+ // Stale global council id (the council was deleted). Match the repo-council
197
+ // behavior: warn and fall through to the single-provider default.
198
+ logger.warn(
199
+ `Global default council "${globalCouncilId}" was not found; ` +
200
+ `falling back to default provider/model.`
201
+ );
202
+ }
203
+
204
+ // 5. Single selection from repo defaults, then global config, then hardcoded.
205
+ return _buildSingleSelection({}, repoSettings, cfg);
206
+ }
207
+
208
+ /**
209
+ * Resolve a single provider/model pair from the canonical per-field precedence
210
+ * ladders, WITHOUT any council dispatch.
211
+ *
212
+ * This is the same ladder `resolveReviewConfig` applies for the single-selection
213
+ * case (explicit › repo default › global in-app override › config-file › legacy
214
+ * keys › hardcoded). It is exported for callers that intentionally run a single
215
+ * provider/model only and must NOT consult a council — the MCP `start_analysis`
216
+ * tool (src/routes/mcp.js) documents this divergence. This deliberately bypasses
217
+ * BOTH the repo default council AND the global default council
218
+ * (`config.default_council_id`): a global default council never fires on these
219
+ * single-model paths (hunk summaries, tours, MCP start_analysis), by design.
220
+ * Those callers reuse this helper so they inherit the in-app-override tier
221
+ * instead of maintaining a parallel inline ladder.
222
+ *
223
+ * @param {Object} [explicit] - { provider, model } (either may be undefined)
224
+ * @param {Object|null} [repoSettings] - Row from RepoSettingsRepository.getRepoSettings
225
+ * @param {Object} [config] - Global config object (may carry `_globalOverrides`)
226
+ * @returns {{ type: 'single', provider: string, model: string }}
227
+ */
228
+ function resolveSingleProviderModel(explicit = {}, repoSettings = null, config = {}) {
229
+ return _buildSingleSelection(explicit, repoSettings, config);
162
230
  }
163
231
 
164
- module.exports = { resolveReviewConfig };
232
+ module.exports = { resolveReviewConfig, resolveSingleProviderModel };
@@ -288,7 +288,7 @@ router.post('/api/chat/session', async (req, res) => {
288
288
  SELECT
289
289
  id, ai_run_id, ai_level, ai_confidence,
290
290
  file, line_start, line_end, type, title, body,
291
- reasoning, status, is_file_level, severity
291
+ reasoning, status, status_reason, is_file_level, severity
292
292
  FROM comments
293
293
  WHERE review_id = ?
294
294
  AND source = 'ai'
@@ -653,7 +653,7 @@ router.get('/api/chat/analysis-context/:runId', async (req, res) => {
653
653
  SELECT
654
654
  id, ai_run_id, ai_level, ai_confidence,
655
655
  file, line_start, line_end, type, title, body,
656
- reasoning, status, is_file_level, severity
656
+ reasoning, status, status_reason, is_file_level, severity
657
657
  FROM comments
658
658
  WHERE review_id = ?
659
659
  AND source = 'ai'
@@ -128,6 +128,7 @@ function resolveDefaultProviderModel(config) {
128
128
 
129
129
  router.get('/api/config', (req, res) => {
130
130
  const config = req.app.get('config') || {};
131
+ const cliOverrides = req.app.get('cliOverrides') || {};
131
132
  const defaultPair = resolveDefaultProviderModel(config);
132
133
 
133
134
  // Build chat_providers array with availability
@@ -168,16 +169,17 @@ router.get('/api/config', (req, res) => {
168
169
  comment_format: config.comment_format || 'legacy',
169
170
  default_provider: defaultPair.provider,
170
171
  default_model: defaultPair.model,
171
- // CLI/env override (PAIR_REVIEW_PROVIDER / PAIR_REVIEW_MODEL, set by
172
- // `--provider` / `--model`). Surfaced as a DEDICATED signal — not folded
173
- // into default_provider/default_model above — because every frontend seed
174
- // site resolves `resolveProviderModelPair([repoSettings, appConfig])` with
175
- // repo settings FIRST. Folding the override into appConfig would still lose
176
- // to a repo's saved default, violating the documented `CLI/env > repo
177
- // settings` contract. The frontend prepends this override ahead of
178
- // repoSettings via buildProviderModelScopes(). null when unset.
179
- provider_override: process.env.PAIR_REVIEW_PROVIDER || null,
180
- model_override: process.env.PAIR_REVIEW_MODEL || null,
172
+ // Per-run CLI override from `--provider` / `--model`, threaded explicitly
173
+ // from the CLI entry point via app.get('cliOverrides'). Surfaced as a
174
+ // DEDICATED signal — not folded into default_provider/default_model above —
175
+ // because every frontend seed site resolves
176
+ // `resolveProviderModelPair([repoSettings, appConfig])` with repo settings
177
+ // FIRST. Folding the override into appConfig would still lose to a repo's
178
+ // saved default, violating the documented `CLI flag > repo settings`
179
+ // contract. The frontend prepends this override ahead of repoSettings via
180
+ // buildProviderModelScopes(). null when unset.
181
+ provider_override: cliOverrides.provider || null,
182
+ model_override: cliOverrides.model || null,
181
183
  // Include npx detection for frontend command examples
182
184
  is_running_via_npx: isRunningViaNpx(),
183
185
  enable_chat: config.enable_chat !== false,
@@ -187,7 +187,11 @@ async function executeSync({ db, config, review, source, _deps }) {
187
187
  continue;
188
188
  }
189
189
 
190
- if (mapped.line_end == null && mapped.original_line_end == null) {
190
+ // File-level comments legitimately have NO line anchor (both current and
191
+ // original line fields null) — they render in the per-file comments zone,
192
+ // not on a diff line. Only treat a NON-file-level row with both anchors
193
+ // null as a lost anchor.
194
+ if (!mapped.is_file_level && mapped.line_end == null && mapped.original_line_end == null) {
191
195
  lostAnchors++;
192
196
  continue;
193
197
  }
@@ -28,7 +28,7 @@ const { getGitHubToken, resolveLoadSkills, buildCouncilProviderOverrides, getSum
28
28
  const { backgroundQueue } = require('../ai/background-queue');
29
29
  const localReview = require('../local-review');
30
30
  const { generateScopedDiff, computeScopedDigest, getBranchCommitCount, getFirstCommitSubject, detectAndBuildBranchInfo, findMergeBase, getCurrentBranch, getRepositoryName } = localReview;
31
- const { STOPS, isValidScope, normalizeScope, reviewScope, includesBranch, DEFAULT_SCOPE } = require('../local-scope');
31
+ const { STOPS, isValidScope, normalizeScope, reviewScope, includesBranch, DEFAULT_SCOPE, EMPTY_SCOPE_MESSAGE } = require('../local-scope');
32
32
  const { getGeneratedFilePatterns } = require('../git/gitattributes');
33
33
  const { getShaAbbrevLength } = require('../git/sha-abbrev');
34
34
  const { validateCouncilConfig, normalizeCouncilConfig } = require('./councils');
@@ -94,9 +94,7 @@ async function rejectIfEmptyScope(res, review, localPath) {
94
94
  };
95
95
  const changedFiles = await getChangedFiles(localPath, scopeContext);
96
96
  if (changedFiles.length === 0) {
97
- res.status(409).json({
98
- error: 'No changes found in the selected scope. Check that your scope includes files with modifications, or adjust the scope range.'
99
- });
97
+ res.status(409).json({ error: EMPTY_SCOPE_MESSAGE });
100
98
  return true;
101
99
  }
102
100
  return false;
package/src/routes/mcp.js CHANGED
@@ -27,6 +27,7 @@ const {
27
27
  const { safeParseJson } = require('../utils/safe-parse-json');
28
28
  const { resolveLoadSkills, resolveHostBinding } = require('../config');
29
29
  const { GitHubClient } = require('../github/client');
30
+ const { resolveSingleProviderModel } = require('../review-config');
30
31
 
31
32
  // All valid tier values: canonical tiers + aliases (for Zod enum validation)
32
33
  const ALL_TIER_VALUES = /** @type {[string, ...string[]]} */ ([...TIERS, ...Object.keys(TIER_ALIASES)]);
@@ -421,6 +422,7 @@ function createMCPServer(db, options = {}) {
421
422
  ai_confidence: s.ai_confidence,
422
423
  severity: s.severity,
423
424
  status: s.status,
425
+ status_reason: s.status_reason,
424
426
  reasoning: safeParseJson(s.reasoning),
425
427
  }))
426
428
  }, null, 2)
@@ -575,15 +577,17 @@ function createMCPServer(db, options = {}) {
575
577
  //
576
578
  // INTENTIONAL DIVERGENCE (documented in the tool description): MCP
577
579
  // resolves a single provider/model here and does NOT consult
578
- // resolveReviewConfig()/repo_settings.default_council_id, so a repo's
579
- // default council is ignored on this path (the CLI --headless and the
580
- // web "Analyze" action DO honor it). This ladder is also env-first
581
- // (PAIR_REVIEW_* over repo defaults), matching review-config.js's
582
- // _buildSingleSelection. Routing this through resolveReviewConfig (and
583
- // adding council dispatch) is a deliberate follow-up, not an oversight.
580
+ // repo_settings.default_council_id, so a repo's default council is
581
+ // ignored on this path (the CLI --headless and the web "Analyze"
582
+ // action DO honor it). Routing this through the full resolveReviewConfig
583
+ // (and adding council dispatch) is a deliberate follow-up, not an
584
+ // oversight. The single-provider ladder itself, however, must match the
585
+ // canonical precedence, so we reuse resolveSingleProviderModel rather
586
+ // than hand-rolling the ternaries: explicit (none here) › repo default
587
+ // › global in-app override (config._globalOverrides) › config file ›
588
+ // legacy keys › hardcoded claude/opus.
584
589
  const repoSettings = repository ? await repoSettingsRepo.getRepoSettings(repository) : null;
585
- const provider = process.env.PAIR_REVIEW_PROVIDER || repoSettings?.default_provider || config.default_provider || config.provider || 'claude';
586
- const model = process.env.PAIR_REVIEW_MODEL || repoSettings?.default_model || config.default_model || config.model || 'opus';
590
+ const { provider, model } = resolveSingleProviderModel({}, repoSettings, config);
587
591
 
588
592
  // Create unified run/analysis ID and DB record immediately
589
593
  const runId = uuidv4();
@@ -736,12 +740,13 @@ function createMCPServer(db, options = {}) {
736
740
  const { review } = await reviewRepo.getOrCreate({ prNumber, repository });
737
741
 
738
742
  // Resolve provider and model. INTENTIONAL DIVERGENCE: single
739
- // provider/model only — no resolveReviewConfig / default-council
740
- // dispatch (see the local branch above and the tool description). The
741
- // env-first ladder matches review-config.js's _buildSingleSelection.
743
+ // provider/model only — no default-council dispatch (see the local
744
+ // branch above and the tool description). The single-provider ladder
745
+ // reuses the canonical resolveSingleProviderModel so it stays in step
746
+ // with review-config.js (repo default › global in-app override › env ›
747
+ // config file › legacy keys › hardcoded).
742
748
  const repoSettings = await repoSettingsRepo.getRepoSettings(repository);
743
- const provider = process.env.PAIR_REVIEW_PROVIDER || repoSettings?.default_provider || config.default_provider || config.provider || 'claude';
744
- const model = process.env.PAIR_REVIEW_MODEL || repoSettings?.default_model || config.default_model || config.model || 'opus';
749
+ const { provider, model } = resolveSingleProviderModel({}, repoSettings, config);
745
750
 
746
751
  // Create unified run/analysis ID and DB record immediately
747
752
  const runId = uuidv4();
@@ -24,9 +24,51 @@ const { resolveFormat, formatAdoptedComment: formatComment } = require('../utils
24
24
  const { safeParseJson } = require('../utils/safe-parse-json');
25
25
  const { resolveOriginalFileContentSpecs } = require('../utils/diff-file-content');
26
26
  const validateReviewId = require('./middleware/validate-review-id');
27
+ const { reviewScope, scopeIncludes, includesBranch } = require('../local-scope');
28
+ const { findMergeBase } = require('../local-review');
27
29
 
28
30
  const router = express.Router();
29
31
 
32
+ /**
33
+ * Resolve the worktree path and base_sha for a PR-mode review.
34
+ * Returns { worktreePath, baseSha } or throws with { status, error } on failure.
35
+ */
36
+ async function resolveWorktreeForReview(review, db) {
37
+ const prNumber = review.pr_number;
38
+ const repository = review.repository;
39
+
40
+ if (!prNumber || !repository) {
41
+ const err = new Error('Review missing PR metadata');
42
+ err.statusCode = 400;
43
+ throw err;
44
+ }
45
+
46
+ const [owner, repo] = repository.split('/');
47
+ const worktreeManager = new GitWorktreeManager(db);
48
+
49
+ if (!await worktreeManager.worktreeExists({ owner, repo, number: prNumber })) {
50
+ const err = new Error('Worktree not found for this PR. The PR may need to be reloaded.');
51
+ err.statusCode = 404;
52
+ throw err;
53
+ }
54
+
55
+ const worktreePath = await worktreeManager.getWorktreePath({ owner, repo, number: prNumber });
56
+
57
+ // Load cached PR metadata so callers can resolve exact diff blobs.
58
+ const normalizedRepo = normalizeRepository(owner, repo);
59
+ const prRecord = await queryOne(db, `
60
+ SELECT pr_data FROM pr_metadata
61
+ WHERE pr_number = ? AND repository = ? COLLATE NOCASE
62
+ `, [prNumber, normalizedRepo]);
63
+
64
+ const prData = safeParseJson(prRecord?.pr_data, null);
65
+ if (prRecord?.pr_data && !prData) {
66
+ logger.warn('Could not parse pr_data for review');
67
+ }
68
+
69
+ return { worktreePath, prData };
70
+ }
71
+
30
72
  /**
31
73
  * GET /api/reviews/:reviewId/comments
32
74
  * Get all comments for a review.
@@ -530,6 +572,7 @@ router.get('/api/reviews/:reviewId/suggestions', validateReviewId, async (req, r
530
572
  suggestion_text,
531
573
  reasoning,
532
574
  status,
575
+ status_reason,
533
576
  is_file_level,
534
577
  severity,
535
578
  created_at,
@@ -592,7 +635,7 @@ router.get('/api/reviews/:reviewId/suggestions', validateReviewId, async (req, r
592
635
  router.post('/api/reviews/:reviewId/suggestions/:id/status', validateReviewId, async (req, res) => {
593
636
  try {
594
637
  const { id } = req.params;
595
- const { status } = req.body;
638
+ const { status, reason } = req.body;
596
639
 
597
640
  if (!['dismissed', 'active'].includes(status)) {
598
641
  if (status === 'adopted') {
@@ -605,6 +648,30 @@ router.post('/api/reviews/:reviewId/suggestions/:id/status', validateReviewId, a
605
648
  });
606
649
  }
607
650
 
651
+ // A dismissal reason is only meaningful when dismissing. Reject it on restore
652
+ // so callers can't silently attach a reason that would immediately be cleared.
653
+ if (reason !== undefined && reason !== null && status !== 'dismissed') {
654
+ return res.status(400).json({
655
+ error: 'A reason may only be provided when status is "dismissed"'
656
+ });
657
+ }
658
+
659
+ // Normalize the reason: coerce to string, trim, enforce max length, empty → null.
660
+ const MAX_REASON_LENGTH = 2000;
661
+ let normalizedReason = null;
662
+ if (reason !== undefined && reason !== null) {
663
+ if (typeof reason !== 'string') {
664
+ return res.status(400).json({ error: 'Reason must be a string' });
665
+ }
666
+ const trimmed = reason.trim();
667
+ if (trimmed.length > MAX_REASON_LENGTH) {
668
+ return res.status(400).json({
669
+ error: `Reason must be ${MAX_REASON_LENGTH} characters or fewer`
670
+ });
671
+ }
672
+ normalizedReason = trimmed || null;
673
+ }
674
+
608
675
  const db = req.app.get('db');
609
676
  const commentRepo = new CommentRepository(db);
610
677
 
@@ -624,12 +691,14 @@ router.post('/api/reviews/:reviewId/suggestions/:id/status', validateReviewId, a
624
691
  });
625
692
  }
626
693
 
627
- // Update suggestion status using repository
628
- await commentRepo.updateSuggestionStatus(id, status);
694
+ // Update suggestion status using repository. Restoring to 'active' clears any
695
+ // stored reason inside updateSuggestionStatus, so status_reason is always null then.
696
+ await commentRepo.updateSuggestionStatus(id, status, null, normalizedReason);
629
697
 
630
698
  res.json({
631
699
  success: true,
632
- status
700
+ status,
701
+ status_reason: status === 'dismissed' ? normalizedReason : null
633
702
  });
634
703
  broadcastReviewEvent(req.reviewId, { type: 'review:suggestions_changed' }, { sourceClientId: req.get('X-Client-Id') });
635
704
 
@@ -1184,6 +1253,156 @@ async function handleJobCancel(req, res) {
1184
1253
 
1185
1254
  router.post('/api/reviews/:reviewId/jobs/:jobKey/cancel', validateReviewId, handleJobCancel);
1186
1255
 
1256
+ /**
1257
+ * GET /api/reviews/:reviewId/file-contents/:fileName(*)
1258
+ * Fetch old and new file contents for hunk expansion in @pierre/diffs.
1259
+ * Returns { fileName, oldContents, newContents } with string values (or null).
1260
+ */
1261
+ const MAX_FILE_CONTENTS_SIZE = 2 * 1024 * 1024; // 2MB
1262
+
1263
+ router.get('/api/reviews/:reviewId/file-contents/:fileName(*)', validateReviewId, async (req, res) => {
1264
+ try {
1265
+ const fileName = decodeURIComponent(req.params.fileName);
1266
+ const { status, oldPath } = req.query;
1267
+ const review = req.review;
1268
+ const db = req.app.get('db');
1269
+
1270
+ // Validate fileName
1271
+ if (fileName.includes('\0')) {
1272
+ return res.status(400).json({ error: 'Invalid file name' });
1273
+ }
1274
+
1275
+ const oldFilePath = oldPath || fileName;
1276
+
1277
+ /**
1278
+ * Helper: read content via git show, return string or null on failure.
1279
+ */
1280
+ async function gitShow(repoPath, ref) {
1281
+ try {
1282
+ const git = simpleGit(repoPath);
1283
+ return await git.show([ref]);
1284
+ } catch {
1285
+ return null;
1286
+ }
1287
+ }
1288
+
1289
+ /**
1290
+ * Helper: read file from filesystem with traversal guard.
1291
+ * Returns string or null on failure.
1292
+ */
1293
+ async function readFromFs(basePath, relPath) {
1294
+ const filePath = path.join(basePath, relPath);
1295
+ try {
1296
+ const realFilePath = await fs.realpath(filePath);
1297
+ const realBasePath = await fs.realpath(basePath);
1298
+ if (!realFilePath.startsWith(realBasePath + path.sep) && realFilePath !== realBasePath) {
1299
+ return null;
1300
+ }
1301
+ return await fs.readFile(realFilePath, 'utf8');
1302
+ } catch {
1303
+ return null;
1304
+ }
1305
+ }
1306
+
1307
+ /**
1308
+ * Helper: check for binary content (null bytes) and size limits.
1309
+ * Returns a response object if content should be rejected, or null if OK.
1310
+ */
1311
+ function checkContent(oldContents, newContents) {
1312
+ const hasBinary = (s) => s != null && s.includes('\0');
1313
+ if (hasBinary(oldContents) || hasBinary(newContents)) {
1314
+ return { binary: true, oldContents: null, newContents: null };
1315
+ }
1316
+ const tooLarge = (s) => s != null && Buffer.byteLength(s, 'utf8') > MAX_FILE_CONTENTS_SIZE;
1317
+ if (tooLarge(oldContents) || tooLarge(newContents)) {
1318
+ return { tooLarge: true, oldContents: null, newContents: null };
1319
+ }
1320
+ return null;
1321
+ }
1322
+
1323
+ let oldContents = null;
1324
+ let newContents = null;
1325
+
1326
+ // --- Local mode ---
1327
+ if (review.review_type === 'local' || review.local_path) {
1328
+ const localPath = review.local_path;
1329
+ if (!localPath) {
1330
+ return res.status(404).json({ error: 'Local review missing path' });
1331
+ }
1332
+
1333
+ // Determine old-side git ref based on scope
1334
+ const { start, end } = reviewScope(review);
1335
+
1336
+ if (status !== 'added') {
1337
+ if (includesBranch(start)) {
1338
+ if (!review.local_base_branch) {
1339
+ // No base branch configured — old side unavailable
1340
+ oldContents = null;
1341
+ } else {
1342
+ try {
1343
+ const mergeBaseSha = await findMergeBase(localPath, review.local_base_branch);
1344
+ oldContents = await gitShow(localPath, `${mergeBaseSha}:${oldFilePath}`);
1345
+ } catch (mbError) {
1346
+ logger.warn(`Could not find merge-base for old file: ${mbError.message}`);
1347
+ oldContents = null;
1348
+ }
1349
+ }
1350
+ } else if (scopeIncludes(start, end, 'staged')) {
1351
+ // Staged is in scope but not branch — old is HEAD
1352
+ oldContents = await gitShow(localPath, `HEAD:${oldFilePath}`);
1353
+ } else {
1354
+ // Unstaged only — old is the index (staged version)
1355
+ oldContents = await gitShow(localPath, `:${oldFilePath}`);
1356
+ }
1357
+ }
1358
+
1359
+ if (status !== 'deleted') {
1360
+ // New file: always from filesystem
1361
+ newContents = await readFromFs(localPath, fileName);
1362
+ }
1363
+
1364
+ const rejection = checkContent(oldContents, newContents);
1365
+ if (rejection) return res.json({ fileName, ...rejection });
1366
+
1367
+ return res.json({ fileName, oldContents, newContents });
1368
+ }
1369
+
1370
+ // --- PR mode ---
1371
+ let worktreePath, prData;
1372
+ try {
1373
+ ({ worktreePath, prData } = await resolveWorktreeForReview(review, db));
1374
+ } catch (resolveErr) {
1375
+ return res.status(resolveErr.statusCode || 500).json({ error: resolveErr.message });
1376
+ }
1377
+
1378
+ if (status !== 'added') {
1379
+ // Prefer the exact blob from the cached diff snapshot; fall back to base_sha.
1380
+ // Matches the /file-content endpoint so both stay consistent with stale PR metadata.
1381
+ const contentSpecs = resolveOriginalFileContentSpecs(prData, oldFilePath);
1382
+ for (const contentSpec of contentSpecs) {
1383
+ const content = await gitShow(worktreePath, contentSpec.gitSpec);
1384
+ if (content != null) {
1385
+ oldContents = content;
1386
+ break;
1387
+ }
1388
+ logger.debug(`Could not read old file ${oldFilePath} from ${contentSpec.source}`);
1389
+ }
1390
+ }
1391
+
1392
+ if (status !== 'deleted') {
1393
+ newContents = await gitShow(worktreePath, `HEAD:${fileName}`);
1394
+ }
1395
+
1396
+ const rejection = checkContent(oldContents, newContents);
1397
+ if (rejection) return res.json({ fileName, ...rejection });
1398
+
1399
+ return res.json({ fileName, oldContents, newContents });
1400
+ } catch (error) {
1401
+ logger.error('Error retrieving file contents:', error);
1402
+ res.status(500).json({ error: 'Internal server error while retrieving file contents' });
1403
+ }
1404
+ });
1405
+
1187
1406
  module.exports = router;
1188
1407
  module.exports.handleJobCancel = handleJobCancel;
1189
1408
  module.exports.CANCELLABLE_JOB_PREFIXES = CANCELLABLE_JOB_PREFIXES;