@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
@@ -0,0 +1,252 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Global Settings Routes
4
+ *
5
+ * Backs the /settings page. All effective-value resolution, validation, and
6
+ * persistence live in the GlobalSettingsService (app.get('globalSettings')).
7
+ * Write endpoints re-set the live config object via app.set('config', ...) so
8
+ * every per-request `req.app.get('config')` reader immediately honors an
9
+ * override (dynamic settings) — startup-captured settings are flagged
10
+ * `restartRequired` and take effect on next launch.
11
+ */
12
+
13
+ const express = require('express');
14
+ const { query } = require('../database');
15
+ const logger = require('../utils/logger');
16
+ const { getRegistry, getPath, hasPath, setPath } = require('../settings/registry');
17
+
18
+ const router = express.Router();
19
+
20
+ // Repo_settings columns that count as a user having *configured* a repo. Rows
21
+ // created solely by local_path auto-register or pool leases (local_path /
22
+ // pool_fetch_* timestamps) do NOT count — matching the plan's "known vs
23
+ // configured" distinction. auto_branch_review is handled separately below: its
24
+ // schema default is 0 ("ask"), so mere presence of a value is NOT configuration
25
+ // — only an explicit 1 ("always") or -1 ("never") counts.
26
+ const CONFIGURED_REPO_COLUMNS = [
27
+ 'default_instructions',
28
+ 'default_provider',
29
+ 'default_model',
30
+ 'default_council_id',
31
+ 'default_tab',
32
+ 'default_chat_instructions',
33
+ 'pool_size',
34
+ 'pool_fetch_interval_minutes',
35
+ 'load_skills'
36
+ ];
37
+
38
+ // auto_branch_review values that represent a deliberate user choice (vs. the
39
+ // schema default of 0 = "ask each time", which is indistinguishable from unset).
40
+ const CONFIGURED_AUTO_BRANCH_REVIEW_VALUES = new Set([1, -1]);
41
+
42
+ // Registry keys whose consumers latch their value at process startup (route
43
+ // mounting, middleware, static-file caching, retention sweeps). These are
44
+ // flagged restartRequired in the registry. A post-boot write persists the
45
+ // override and advertises "restart required" in the UI, but the value MUST NOT
46
+ // be folded into the live app config — the running process cannot honor it, so
47
+ // app.get('config') advertising the new value while behavior is unchanged is a
48
+ // lie. We snapshot the boot values once and re-apply them over every rebuilt
49
+ // effective config before app.set('config', ...).
50
+ const RESTART_REQUIRED_KEYS = getRegistry()
51
+ .filter((entry) => entry.restartRequired)
52
+ .map((entry) => entry.key);
53
+
54
+ /** JSON deep clone so snapshotted object values (providers/repos/hooks) can't alias the live config. */
55
+ function cloneValue(value) {
56
+ return value === undefined ? undefined : JSON.parse(JSON.stringify(value));
57
+ }
58
+
59
+ /**
60
+ * Snapshot the boot-time value of every restart-required key, memoized on the
61
+ * app. Captured lazily on the first write: no prior write can have mutated the
62
+ * config (a write is the only thing that re-sets it), so app.get('config') still
63
+ * holds the values the process actually latched at launch — including any DB
64
+ * override that was present at boot and folded in then.
65
+ * @param {import('express').Application} app
66
+ * @returns {Object} map of restart-required key -> boot value (present keys only)
67
+ */
68
+ function bootRestartValues(app) {
69
+ let snapshot = app.get('restartRequiredBootConfig');
70
+ if (!snapshot) {
71
+ const config = app.get('config') || {};
72
+ snapshot = {};
73
+ for (const key of RESTART_REQUIRED_KEYS) {
74
+ if (hasPath(config, key)) {
75
+ snapshot[key] = cloneValue(getPath(config, key));
76
+ }
77
+ }
78
+ app.set('restartRequiredBootConfig', snapshot);
79
+ }
80
+ return snapshot;
81
+ }
82
+
83
+ /**
84
+ * Overlay boot-time restart-required values onto a freshly rebuilt effective
85
+ * config so the live config never advertises a post-boot value the running
86
+ * process cannot honor. Also strips a same-request restart-required override
87
+ * (setOverride folds ALL persisted overrides, so a later write to a DYNAMIC key
88
+ * would otherwise re-fold a pending restart-required override). Mutates and
89
+ * returns `effectiveConfig`.
90
+ * @param {import('express').Application} app
91
+ * @param {Object} effectiveConfig
92
+ * @returns {Object}
93
+ */
94
+ function preserveBootRestartValues(app, effectiveConfig) {
95
+ const snapshot = bootRestartValues(app);
96
+ for (const key of Object.keys(snapshot)) {
97
+ setPath(effectiveConfig, key, cloneValue(snapshot[key]));
98
+ }
99
+ return effectiveConfig;
100
+ }
101
+
102
+ /**
103
+ * GET /api/settings — `{ sections, settings }`. `settings` is the descriptor
104
+ * list for every VISIBLE registry entry (hidden entries omitted); `sections` is
105
+ * the ordered section metadata (title/description/badge) for sections that have
106
+ * at least one visible setting.
107
+ */
108
+ router.get('/api/settings', (req, res) => {
109
+ const service = req.app.get('globalSettings');
110
+ if (!service) {
111
+ return res.status(503).json({ error: 'Global settings service unavailable' });
112
+ }
113
+ try {
114
+ const settings = service.describe();
115
+ // Sections drive the page nav (order, titles, badges); empty sections are
116
+ // omitted. Descriptors are already hidden-filtered by describe().
117
+ res.json({ sections: service.describeSections(settings), settings });
118
+ } catch (error) {
119
+ logger.error('Error describing global settings:', error);
120
+ res.status(500).json({ error: 'Failed to load global settings' });
121
+ }
122
+ });
123
+
124
+ /**
125
+ * PUT /api/settings/:key — set an in-app override.
126
+ * Body: { value: <typed> }. Rejects unknown/read-only keys and type/enum
127
+ * validation failures with 400. On success re-sets the live config and returns
128
+ * the updated descriptor.
129
+ */
130
+ router.put('/api/settings/:key', async (req, res) => {
131
+ const service = req.app.get('globalSettings');
132
+ if (!service) {
133
+ return res.status(503).json({ error: 'Global settings service unavailable' });
134
+ }
135
+ const { key } = req.params;
136
+ if (!req.body || !Object.prototype.hasOwnProperty.call(req.body, 'value')) {
137
+ return res.status(400).json({ error: 'Request body must include a "value" field' });
138
+ }
139
+ try {
140
+ const result = await service.setOverride(key, req.body.value);
141
+ if (!result.ok) {
142
+ return res.status(result.status || 400).json({ error: result.error });
143
+ }
144
+ // The returned descriptor (result.setting) already reflects the NEW value +
145
+ // restartRequired flag; only the LIVE config keeps boot values for
146
+ // restart-required keys (see preserveBootRestartValues).
147
+ req.app.set('config', preserveBootRestartValues(req.app, result.effectiveConfig));
148
+ logger.info(`Global setting "${key}" set via /settings`);
149
+ res.json({ setting: result.setting });
150
+ } catch (error) {
151
+ logger.error(`Error setting global setting "${key}":`, error);
152
+ res.status(500).json({ error: 'Failed to save setting' });
153
+ }
154
+ });
155
+
156
+ /**
157
+ * DELETE /api/settings/:key — clear an in-app override (idempotent). Unknown
158
+ * key -> 400; clearing an unset override still returns 200 with the recomputed
159
+ * descriptor + source.
160
+ */
161
+ router.delete('/api/settings/:key', async (req, res) => {
162
+ const service = req.app.get('globalSettings');
163
+ if (!service) {
164
+ return res.status(503).json({ error: 'Global settings service unavailable' });
165
+ }
166
+ const { key } = req.params;
167
+ try {
168
+ const result = await service.clearOverride(key);
169
+ if (!result.ok) {
170
+ return res.status(result.status || 400).json({ error: result.error });
171
+ }
172
+ // Clearing a restart-required override doesn't un-latch the running process,
173
+ // so the live config keeps the boot value until restart (the descriptor
174
+ // shows the recomputed value + restartRequired flag).
175
+ req.app.set('config', preserveBootRestartValues(req.app, result.effectiveConfig));
176
+ logger.info(`Global setting "${key}" cleared via /settings`);
177
+ res.json({ setting: result.setting });
178
+ } catch (error) {
179
+ logger.error(`Error clearing global setting "${key}":`, error);
180
+ res.status(500).json({ error: 'Failed to clear setting' });
181
+ }
182
+ });
183
+
184
+ /**
185
+ * GET /api/settings/repos — the union of repos configured in the DB
186
+ * (repo_settings) and in config files (config.repos). Each entry reports
187
+ * whether it is configured in each store, its known local path, and when it
188
+ * was last updated. Rows that are merely "known" (local_path only, no
189
+ * user-facing settings) are included with hasDbSettings=false.
190
+ */
191
+ router.get('/api/settings/repos', async (req, res) => {
192
+ const db = req.app.get('db');
193
+ const config = req.app.get('config') || {};
194
+ try {
195
+ const rows = await query(db, `
196
+ SELECT repository, default_instructions, default_provider, default_model,
197
+ default_council_id, default_tab, default_chat_instructions,
198
+ pool_size, pool_fetch_interval_minutes, load_skills,
199
+ auto_branch_review, local_path, updated_at
200
+ FROM repo_settings
201
+ `);
202
+
203
+ const byRepo = new Map();
204
+
205
+ for (const row of rows) {
206
+ const hasDbSettings =
207
+ CONFIGURED_REPO_COLUMNS.some(
208
+ (col) => row[col] !== null && row[col] !== undefined
209
+ ) ||
210
+ // auto_branch_review defaults to 0 ("ask"); only an explicit always/never
211
+ // choice counts, so a row holding just the default doesn't look configured.
212
+ CONFIGURED_AUTO_BRANCH_REVIEW_VALUES.has(row.auto_branch_review);
213
+ byRepo.set(row.repository.toLowerCase(), {
214
+ repository: row.repository,
215
+ hasDbSettings,
216
+ hasFileConfig: false,
217
+ localPath: row.local_path || null,
218
+ updatedAt: row.updated_at || null
219
+ });
220
+ }
221
+
222
+ // Fold in file-config repos. A repos[...] entry always counts as configured.
223
+ const fileRepos = config.repos || {};
224
+ for (const repoKey of Object.keys(fileRepos)) {
225
+ const lower = repoKey.toLowerCase();
226
+ const existing = byRepo.get(lower);
227
+ if (existing) {
228
+ existing.hasFileConfig = true;
229
+ } else {
230
+ byRepo.set(lower, {
231
+ repository: repoKey,
232
+ hasDbSettings: false,
233
+ hasFileConfig: true,
234
+ localPath: null,
235
+ updatedAt: null
236
+ });
237
+ }
238
+ }
239
+
240
+ // Drop rows that are neither configured nor even "known" (no local path).
241
+ const repos = Array.from(byRepo.values())
242
+ .filter((r) => r.hasDbSettings || r.hasFileConfig || r.localPath)
243
+ .sort((a, b) => a.repository.localeCompare(b.repository));
244
+
245
+ res.json({ repos });
246
+ } catch (error) {
247
+ logger.error('Error listing configured repos:', error);
248
+ res.status(500).json({ error: 'Failed to list repositories' });
249
+ }
250
+ });
251
+
252
+ module.exports = router;
@@ -25,8 +25,47 @@ const logger = require('../utils/logger');
25
25
 
26
26
  const router = express.Router();
27
27
 
28
+ // Terminal-state entries linger this long so a delegating CLI that finishes its
29
+ // own work slightly after setup completes can still read the result. Mirrors the
30
+ // activeAnalyses 30-minute auto-cleanup in src/routes/mcp.js.
31
+ const SETUP_STATUS_TTL_MS = 30 * 60 * 1000;
32
+
33
+ // Poll-friendly mirror of the `setup:{setupId}` WebSocket pushes. Keyed by
34
+ // setupId (the same UUID handed back to the client), value is the latest
35
+ // { status, reviewUrl?, reviewId?, error?, progress? } snapshot. The delegating
36
+ // CLI polls GET /api/setup/:setupId/status instead of opening a WebSocket, which
37
+ // sidesteps the missed-event race between "server returns setupId" and "CLI
38
+ // subscribes". Not exported: it is process-local runtime state, never persisted.
39
+ const setupStatuses = new Map();
40
+
28
41
  /**
29
- * Send a setup progress event via WebSocket.
42
+ * Record (or patch) the polling status for a setup operation. The first write
43
+ * establishes the entry as `running`; later writes shallow-merge onto it. On a
44
+ * terminal status (`complete`/`error`) an expiry timer is armed so the map does
45
+ * not grow without bound — matching the activeAnalyses cleanup pattern.
46
+ *
47
+ * @param {string} setupId - Setup operation ID
48
+ * @param {Object} patch - Partial status fields to merge (must include `status`
49
+ * on the first call; typically `{ status, reviewUrl?, reviewId?, error?, progress? }`)
50
+ */
51
+ function setSetupStatus(setupId, patch) {
52
+ const prev = setupStatuses.get(setupId) || {};
53
+ const next = { ...prev, ...patch };
54
+ setupStatuses.set(setupId, next);
55
+
56
+ if (next.status === 'complete' || next.status === 'error') {
57
+ // Do not let the cleanup timer keep the process alive; if the process is
58
+ // exiting the map dies with it anyway.
59
+ const timer = setTimeout(() => setupStatuses.delete(setupId), SETUP_STATUS_TTL_MS);
60
+ if (typeof timer.unref === 'function') timer.unref();
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Send a setup progress event via WebSocket AND update the polling status map so
66
+ * both delivery channels stay in lock-step. Terminal events ('complete'/'error')
67
+ * map to the polling states 'complete'/'error'; 'step' events refresh the
68
+ * `progress` field but leave the status 'running'.
30
69
  *
31
70
  * Converts the named event pattern to a WebSocket message with a `type`
32
71
  * field so the client can dispatch on `msg.type` (e.g. 'step', 'complete', 'error').
@@ -37,6 +76,19 @@ const router = express.Router();
37
76
  */
38
77
  function sendSetupEvent(setupId, eventType, data) {
39
78
  broadcastSetupProgress(setupId, { type: eventType, ...data });
79
+
80
+ if (eventType === 'complete') {
81
+ setSetupStatus(setupId, {
82
+ status: 'complete',
83
+ reviewUrl: data.reviewUrl,
84
+ reviewId: data.reviewId
85
+ });
86
+ } else if (eventType === 'error') {
87
+ setSetupStatus(setupId, { status: 'error', error: data.message });
88
+ } else if (eventType === 'step') {
89
+ // Keep status 'running'; surface the human-readable step message as progress.
90
+ setSetupStatus(setupId, { status: 'running', progress: data.message });
91
+ }
40
92
  }
41
93
 
42
94
  // ---------------------------------------------------------------------------
@@ -160,6 +212,9 @@ router.post('/api/setup/pr/:owner/:repo/:number', async (req, res) => {
160
212
 
161
213
  // Start the async setup
162
214
  const setupId = crypto.randomUUID();
215
+ // Seed the polling status so a CLI that polls immediately (before the first
216
+ // 'step' WS push) still observes 'running' rather than a spurious 404.
217
+ setSetupStatus(setupId, { status: 'running' });
163
218
 
164
219
  const promise = (async () => {
165
220
  try {
@@ -263,6 +318,9 @@ router.post('/api/setup/local', async (req, res) => {
263
318
  }
264
319
 
265
320
  const setupId = crypto.randomUUID();
321
+ // Seed the polling status so a CLI that polls immediately (before the first
322
+ // 'step' WS push) still observes 'running' rather than a spurious 404.
323
+ setSetupStatus(setupId, { status: 'running' });
266
324
 
267
325
  const promise = (async () => {
268
326
  try {
@@ -300,4 +358,25 @@ router.post('/api/setup/local', async (req, res) => {
300
358
  }
301
359
  });
302
360
 
361
+ // ---------------------------------------------------------------------------
362
+ // GET /api/setup/:setupId/status
363
+ // ---------------------------------------------------------------------------
364
+
365
+ /**
366
+ * Poll the current status of a setup operation.
367
+ *
368
+ * The delegating CLI polls this instead of opening a WebSocket, avoiding the
369
+ * missed-event race between receiving the setupId and subscribing. Returns the
370
+ * latest snapshot recorded alongside the `setup:{setupId}` WS pushes. Unknown
371
+ * ids (never started, or expired after their terminal-state TTL) → 404.
372
+ */
373
+ router.get('/api/setup/:setupId/status', (req, res) => {
374
+ const { setupId } = req.params;
375
+ const status = setupStatuses.get(setupId);
376
+ if (!status) {
377
+ return res.status(404).json({ error: 'Setup not found' });
378
+ }
379
+ return res.json(status);
380
+ });
381
+
303
382
  module.exports = router;
@@ -42,18 +42,20 @@ const activeSetups = new Map();
42
42
 
43
43
  /**
44
44
  * Get the model to use for AI analysis
45
- * Priority: CLI flag (PAIR_REVIEW_MODEL env var) > config.default_model > 'opus' default
45
+ * Priority: config.default_model > config.model (legacy) > 'opus' default
46
+ *
47
+ * The effective config already folds any in-app (/settings) override into
48
+ * `default_model`, and a key locked as final by configuration resolves to its
49
+ * config-file value here (the effective config excludes final keys from the
50
+ * in-app override). Per-run `--model` intent is applied by the caller via
51
+ * `resolveProviderModel`, not here.
46
52
  * @param {Object} req - Express request object
47
53
  * @returns {string} Model name to use
48
54
  */
49
55
  function getModel(req) {
50
- // CLI flag takes priority (passed via environment variable)
51
- if (process.env.PAIR_REVIEW_MODEL) {
52
- return process.env.PAIR_REVIEW_MODEL;
53
- }
56
+ const config = req.app.get('config');
54
57
 
55
58
  // Config file setting (default_model preferred, model for backwards compatibility)
56
- const config = req.app.get('config');
57
59
  if (config) {
58
60
  if (config.default_model) {
59
61
  return config.default_model;
@@ -70,21 +72,16 @@ function getModel(req) {
70
72
 
71
73
  /**
72
74
  * Get the provider to use for AI analysis
73
- * Priority: CLI flag (PAIR_REVIEW_PROVIDER env var) > config.default_provider
74
- * > config.provider (legacy) > 'claude' default
75
- * Mirrors getModel() so the --provider CLI flag / PAIR_REVIEW_PROVIDER env var
76
- * is honored by the web/UI analysis paths the same way --model is.
75
+ * Priority: config.default_provider > config.provider (legacy) > 'claude' default
76
+ * Mirrors getModel(). Per-run `--provider` intent is applied by the caller via
77
+ * `resolveProviderModel`, not here.
77
78
  * @param {Object} req - Express request object
78
79
  * @returns {string} Provider id to use
79
80
  */
80
81
  function getProvider(req) {
81
- // CLI flag takes priority (passed via environment variable)
82
- if (process.env.PAIR_REVIEW_PROVIDER) {
83
- return process.env.PAIR_REVIEW_PROVIDER;
84
- }
82
+ const config = req.app.get('config');
85
83
 
86
84
  // Config file setting (default_provider preferred, provider for backwards compatibility)
87
- const config = req.app.get('config');
88
85
  if (config) {
89
86
  if (config.default_provider) {
90
87
  return config.default_provider;
@@ -104,21 +101,24 @@ function getProvider(req) {
104
101
  *
105
102
  * Precedence (highest first):
106
103
  * 1. request body (requestProvider / requestModel)
107
- * 2. env/CLI override (PAIR_REVIEW_PROVIDER / PAIR_REVIEW_MODEL, via getProvider/getModel)
104
+ * 2. CLI override (`app.get('cliOverrides')`) — the per-run `--provider` /
105
+ * `--model` flags, threaded explicitly from the CLI entry point
108
106
  * 3. saved repo settings (default_provider / default_model)
109
- * 4. config/legacy defaults (via getProvider/getModel, ending at 'claude'/'opus')
107
+ * 4. config defaults via getProvider/getModel — the effective config already
108
+ * folds any in-app (/settings) override into default_provider/default_model,
109
+ * and a final key resolves to its locked config-file value here
110
+ * 5. legacy provider/model keys, ending at 'claude'/'opus'
110
111
  *
111
- * The env/CLI override intentionally outranks saved repo settings to match the
112
- * documented `CLI/env > repo settings` contract already honored by the
113
- * headless/stack/MCP paths. Because getProvider()/getModel() read the env var
114
- * first, calling them in the env branch returns the override; the final branch
115
- * (reached only when the env var is unset) returns config/legacy/default.
112
+ * The request and CLI-flag tiers deliberately beat repo settings AND a `final`
113
+ * lock: they are per-run intent, not stored settings — matching review-config's
114
+ * explicit-first behavior. (A final key only locks the settings/config layers;
115
+ * it never blocks an explicit per-invocation flag.)
116
116
  *
117
117
  * Both the PR route (src/routes/pr.js) and the local route (src/routes/local.js)
118
118
  * MUST use this helper so the two paths resolve the same pair — keeping the
119
119
  * resolution logic in one place prevents the paths from silently diverging.
120
120
  *
121
- * @param {Object} req - Express request (source of config + env-backed helpers)
121
+ * @param {Object} req - Express request (source of config + cliOverrides)
122
122
  * @param {Object} [opts]
123
123
  * @param {string} [opts.requestProvider] - provider from the request body
124
124
  * @param {string} [opts.requestModel] - model from the request body
@@ -126,26 +126,28 @@ function getProvider(req) {
126
126
  * @returns {{ provider: string, model: string }}
127
127
  */
128
128
  function resolveProviderModel(req, { requestProvider, requestModel, repoSettings } = {}) {
129
+ const cliOverrides = req.app.get('cliOverrides') || {};
130
+
129
131
  let provider;
130
132
  if (requestProvider) {
131
133
  provider = requestProvider;
132
- } else if (process.env.PAIR_REVIEW_PROVIDER) {
133
- provider = getProvider(req); // env/CLI override
134
+ } else if (cliOverrides.provider) {
135
+ provider = cliOverrides.provider; // --provider flag (per-run intent)
134
136
  } else if (repoSettings && repoSettings.default_provider) {
135
137
  provider = repoSettings.default_provider;
136
138
  } else {
137
- provider = getProvider(req); // config/legacy/'claude'
139
+ provider = getProvider(req); // in-app-folded config/legacy/'claude'
138
140
  }
139
141
 
140
142
  let model;
141
143
  if (requestModel) {
142
144
  model = requestModel;
143
- } else if (process.env.PAIR_REVIEW_MODEL) {
144
- model = getModel(req); // env/CLI override
145
+ } else if (cliOverrides.model) {
146
+ model = cliOverrides.model; // --model flag (per-run intent)
145
147
  } else if (repoSettings && repoSettings.default_model) {
146
148
  model = repoSettings.default_model;
147
149
  } else {
148
- model = getModel(req); // config/legacy/'opus'
150
+ model = getModel(req); // in-app-folded config/legacy/'opus'
149
151
  }
150
152
 
151
153
  return { provider, model };
@@ -0,0 +1,154 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Chat Snippet Routes
4
+ *
5
+ * CRUD endpoints for the reusable chat prompt snippets library. Snippets are
6
+ * global (user-level) body-only prompts inserted into the chat input, ordered
7
+ * most-recently-used first.
8
+ */
9
+
10
+ const express = require('express');
11
+ const logger = require('../utils/logger');
12
+ const { ChatSnippetRepository } = require('../database');
13
+
14
+ const router = express.Router();
15
+
16
+ const MAX_BODY_LENGTH = 10000;
17
+
18
+ /**
19
+ * Validate a snippet body value.
20
+ * @param {*} body - Candidate body
21
+ * @returns {string|null} Error message or null if valid
22
+ */
23
+ function validateBody(body) {
24
+ if (typeof body !== 'string' || !body.trim()) {
25
+ return 'body is required and must be a non-empty string';
26
+ }
27
+ if (body.length > MAX_BODY_LENGTH) {
28
+ return `body must be ${MAX_BODY_LENGTH} characters or fewer`;
29
+ }
30
+ return null;
31
+ }
32
+
33
+ /**
34
+ * Parse a route :id param into an integer, or null if not a valid number.
35
+ * @param {string} raw - Raw param value
36
+ * @returns {number|null}
37
+ */
38
+ function parseId(raw) {
39
+ const id = Number.parseInt(raw, 10);
40
+ return Number.isNaN(id) ? null : id;
41
+ }
42
+
43
+ /**
44
+ * GET /api/snippets — List all snippets in MRU order
45
+ */
46
+ router.get('/api/snippets', async (req, res) => {
47
+ try {
48
+ const repo = new ChatSnippetRepository(req.app.get('db'));
49
+ const snippets = await repo.list();
50
+ res.json({ snippets });
51
+ } catch (error) {
52
+ logger.error('Error listing snippets:', error);
53
+ res.status(500).json({ error: 'Failed to list snippets' });
54
+ }
55
+ });
56
+
57
+ /**
58
+ * POST /api/snippets — Create a new snippet
59
+ */
60
+ router.post('/api/snippets', async (req, res) => {
61
+ try {
62
+ const { body } = req.body || {};
63
+
64
+ const validationError = validateBody(body);
65
+ if (validationError) {
66
+ return res.status(400).json({ error: validationError });
67
+ }
68
+
69
+ const repo = new ChatSnippetRepository(req.app.get('db'));
70
+ const snippet = await repo.create({ body });
71
+ res.status(201).json({ snippet });
72
+ } catch (error) {
73
+ logger.error('Error creating snippet:', error);
74
+ res.status(500).json({ error: 'Failed to create snippet' });
75
+ }
76
+ });
77
+
78
+ /**
79
+ * PUT /api/snippets/:id — Update a snippet's body
80
+ */
81
+ router.put('/api/snippets/:id', async (req, res) => {
82
+ try {
83
+ const id = parseId(req.params.id);
84
+ if (id === null) {
85
+ return res.status(400).json({ error: 'Invalid snippet id' });
86
+ }
87
+
88
+ const { body } = req.body || {};
89
+ const validationError = validateBody(body);
90
+ if (validationError) {
91
+ return res.status(400).json({ error: validationError });
92
+ }
93
+
94
+ const repo = new ChatSnippetRepository(req.app.get('db'));
95
+ const updated = await repo.update(id, { body });
96
+ if (!updated) {
97
+ return res.status(404).json({ error: 'Snippet not found' });
98
+ }
99
+
100
+ const snippet = await repo.getById(id);
101
+ res.json({ snippet });
102
+ } catch (error) {
103
+ logger.error('Error updating snippet:', error);
104
+ res.status(500).json({ error: 'Failed to update snippet' });
105
+ }
106
+ });
107
+
108
+ /**
109
+ * DELETE /api/snippets/:id — Delete a snippet
110
+ */
111
+ router.delete('/api/snippets/:id', async (req, res) => {
112
+ try {
113
+ const id = parseId(req.params.id);
114
+ if (id === null) {
115
+ return res.status(400).json({ error: 'Invalid snippet id' });
116
+ }
117
+
118
+ const repo = new ChatSnippetRepository(req.app.get('db'));
119
+ const existed = await repo.delete(id);
120
+ if (!existed) {
121
+ return res.status(404).json({ error: 'Snippet not found' });
122
+ }
123
+
124
+ res.json({ success: true });
125
+ } catch (error) {
126
+ logger.error('Error deleting snippet:', error);
127
+ res.status(500).json({ error: 'Failed to delete snippet' });
128
+ }
129
+ });
130
+
131
+ /**
132
+ * POST /api/snippets/:id/touch — Bump last_used_at for MRU tracking
133
+ */
134
+ router.post('/api/snippets/:id/touch', async (req, res) => {
135
+ try {
136
+ const id = parseId(req.params.id);
137
+ if (id === null) {
138
+ return res.status(400).json({ error: 'Invalid snippet id' });
139
+ }
140
+
141
+ const repo = new ChatSnippetRepository(req.app.get('db'));
142
+ const touched = await repo.touchLastUsedAt(id);
143
+ if (!touched) {
144
+ return res.status(404).json({ error: 'Snippet not found' });
145
+ }
146
+
147
+ res.json({ success: true });
148
+ } catch (error) {
149
+ logger.error('Error touching snippet:', error);
150
+ res.status(500).json({ error: 'Failed to touch snippet' });
151
+ }
152
+ });
153
+
154
+ module.exports = router;