@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.
- package/README.md +81 -13
- package/package.json +6 -2
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
- package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
- package/plugin-pair-loop/skills/loop/SKILL.md +17 -8
- package/public/css/ai-summary-modal.css +1 -1
- package/public/css/analysis-config.css +33 -49
- package/public/css/council-card.css +118 -0
- package/public/css/council-dropdown.css +164 -0
- package/public/css/pr.css +666 -394
- package/public/css/repo-settings.css +15 -305
- package/public/css/settings.css +1141 -0
- package/public/css/snippet-manager.css +233 -0
- package/public/index.html +40 -59
- package/public/js/components/AIPanel.js +82 -16
- package/public/js/components/ChatPanel.js +401 -5
- package/public/js/components/CouncilCard.js +202 -0
- package/public/js/components/CouncilDropdown.js +292 -0
- package/public/js/components/DiffOptionsDropdown.js +177 -4
- package/public/js/components/SnippetManager.js +463 -0
- package/public/js/index.js +7 -30
- package/public/js/local.js +20 -2
- package/public/js/modules/comment-manager.js +8 -1
- package/public/js/modules/comment-minimizer.js +249 -190
- package/public/js/modules/external-comment-manager.js +414 -48
- package/public/js/modules/file-comment-manager.js +28 -21
- package/public/js/modules/hunk-summary-renderer.js +155 -29
- package/public/js/modules/pierre-bridge.js +2513 -0
- package/public/js/modules/pierre-context.js +345 -0
- package/public/js/modules/suggestion-manager.js +176 -20
- package/public/js/modules/tour-renderer.js +400 -184
- package/public/js/pr.js +1434 -150
- package/public/js/repo-settings.js +60 -284
- package/public/js/settings.js +1086 -0
- package/public/js/theme-bootstrap.js +40 -0
- package/public/js/theme.js +247 -0
- package/public/js/utils/provider-model.js +3 -3
- package/public/js/utils/suggestion-ui.js +157 -8
- package/public/local.html +20 -31
- package/public/pr.html +14 -23
- package/public/repo-settings.html +24 -14
- package/public/settings.html +138 -0
- package/public/setup.html +8 -13
- package/src/ai/codex-provider.js +59 -11
- package/src/chat/api-reference.js +9 -5
- package/src/chat/prompt-builder.js +8 -1
- package/src/config.js +15 -6
- package/src/database.js +307 -14
- package/src/external/github-adapter.js +39 -5
- package/src/headless/delegate.js +682 -0
- package/src/local-review.js +10 -10
- package/src/local-scope.js +9 -0
- package/src/main.js +276 -157
- package/src/mcp-stdio.js +24 -1
- package/src/review-config.js +93 -25
- package/src/routes/chat.js +2 -2
- package/src/routes/config.js +12 -10
- package/src/routes/external-comments.js +5 -1
- package/src/routes/local.js +2 -4
- package/src/routes/mcp.js +18 -13
- package/src/routes/reviews.js +223 -4
- package/src/routes/settings.js +252 -0
- package/src/routes/setup.js +80 -1
- package/src/routes/shared.js +31 -29
- package/src/routes/snippets.js +154 -0
- package/src/routes/stack-analysis.js +17 -14
- package/src/server.js +86 -18
- package/src/settings/global-settings-service.js +472 -0
- package/src/settings/registry.js +624 -0
- package/src/utils/db-identity.js +44 -0
|
@@ -0,0 +1,682 @@
|
|
|
1
|
+
// Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Server-delegated headless execution.
|
|
5
|
+
*
|
|
6
|
+
* When `pair-review --headless` detects a healthy, version- and DB-compatible
|
|
7
|
+
* pair-review server on `config.port`, it delegates the ANALYSIS EXECUTION to
|
|
8
|
+
* that server (so the run populates the server's live council view + WebSocket
|
|
9
|
+
* progress exactly like a button-click run) and waits for completion, then the
|
|
10
|
+
* CLI emits the byte-identical `--json` document via `buildHeadlessJson`
|
|
11
|
+
* (main.js) reading purely from the shared SQLite DB.
|
|
12
|
+
*
|
|
13
|
+
* This module owns the CLI side of the handshake in the plan
|
|
14
|
+
* `plans/delegated-headless-live-view.md`:
|
|
15
|
+
* 1. `probeServer` — GET /health, gate on service/version/dbId.
|
|
16
|
+
* 2. setup — POST /api/setup/{local,pr/...}, poll the setup status.
|
|
17
|
+
* 3. launch — POST the resolved analysis config to the analyze route.
|
|
18
|
+
* 4. wait — poll GET /api/analyses/:id/status, echo progress, and
|
|
19
|
+
* emit a clear error if the server dies mid-run.
|
|
20
|
+
*
|
|
21
|
+
* Follows the dependency-injection convention from `src/protocol-handler.js`: a
|
|
22
|
+
* module-level `defaults` object (fetch impl, delay timer, process signal
|
|
23
|
+
* hookup, logger) merged with an optional `_deps` override so every timer and
|
|
24
|
+
* network call is deterministic under test. Node's global `fetch` is the
|
|
25
|
+
* default transport.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
const logger = require('../utils/logger');
|
|
29
|
+
const { AnalysisRunRepository } = require('../database');
|
|
30
|
+
const { computeDbId, resolveDbPath } = require('../utils/db-identity');
|
|
31
|
+
const { version: packageVersion } = require('../../package.json');
|
|
32
|
+
|
|
33
|
+
// Per-request network deadlines. The health probe is short (a missing server
|
|
34
|
+
// must fail fast into the in-process fallback); setup/launch/status requests
|
|
35
|
+
// tolerate a busier server.
|
|
36
|
+
const HEALTH_TIMEOUT_MS = 2000;
|
|
37
|
+
const REQUEST_TIMEOUT_MS = 15000;
|
|
38
|
+
// The cancel POST fired on Ctrl-C uses a short deadline so an interrupt never
|
|
39
|
+
// hangs on a wedged server — the process is exiting regardless.
|
|
40
|
+
const CANCEL_TIMEOUT_MS = 3000;
|
|
41
|
+
|
|
42
|
+
// Poll cadences. Setup usually completes in a few seconds; analysis runs for
|
|
43
|
+
// minutes, so it is polled less aggressively.
|
|
44
|
+
const SETUP_POLL_INTERVAL_MS = 1000;
|
|
45
|
+
const ANALYSIS_POLL_INTERVAL_MS = 3000;
|
|
46
|
+
|
|
47
|
+
// After this many CONSECUTIVE failed analysis-status polls, we consult the DB
|
|
48
|
+
// run row: a terminal row means the run finished (the server may have shed the
|
|
49
|
+
// in-memory entry); a still-running row means the server died mid-run.
|
|
50
|
+
const MAX_CONSECUTIVE_POLL_FAILURES = 5;
|
|
51
|
+
|
|
52
|
+
const TERMINAL_STATUSES = new Set(['completed', 'failed', 'cancelled']);
|
|
53
|
+
const isTerminal = (status) => TERMINAL_STATUSES.has(status);
|
|
54
|
+
|
|
55
|
+
const SERVER_DIED_MESSAGE =
|
|
56
|
+
'The pair-review server became unreachable while the analysis was still ' +
|
|
57
|
+
'running. It may have crashed or been stopped mid-run; the analysis did not ' +
|
|
58
|
+
'complete. Re-run without a server (or with --no-server) to analyze in-process.';
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Look up the persisted status of an analysis run row (the delegation fallback
|
|
62
|
+
* source of truth when the server's in-memory status is gone). Injectable so
|
|
63
|
+
* tests can drive the death/404 paths without a real database.
|
|
64
|
+
*
|
|
65
|
+
* @param {Object} db - Database instance
|
|
66
|
+
* @param {string} runId - Analysis run id
|
|
67
|
+
* @returns {Promise<string|null>} The run's status, or null if the row is absent
|
|
68
|
+
*/
|
|
69
|
+
async function defaultGetRunStatus(db, runId) {
|
|
70
|
+
const run = await new AnalysisRunRepository(db).getById(runId, { includeDiff: false });
|
|
71
|
+
return run ? run.status : null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Default dependencies (overridable for testing).
|
|
75
|
+
const defaults = {
|
|
76
|
+
// Node's global fetch. Kept as a property so tests inject a stub and every
|
|
77
|
+
// request in this module routes through it.
|
|
78
|
+
fetch: (...args) => globalThis.fetch(...args),
|
|
79
|
+
// Awaitable delay between polls. Injected as an immediate resolve in tests so
|
|
80
|
+
// no wall-clock time elapses (see tests/CONVENTIONS.md — no fixed sleeps).
|
|
81
|
+
delay: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
82
|
+
// Signal source + exit hook for cancel-on-SIGINT/SIGTERM. Injected in tests
|
|
83
|
+
// so a simulated signal neither kills the test runner nor waits on the OS.
|
|
84
|
+
process,
|
|
85
|
+
exit: (code) => process.exit(code),
|
|
86
|
+
logger,
|
|
87
|
+
// DB run-row lookup (delegation fallback). Injected in tests.
|
|
88
|
+
getRunStatus: defaultGetRunStatus,
|
|
89
|
+
// Digest helpers — real by default; injected only to force a mismatch.
|
|
90
|
+
computeDbId,
|
|
91
|
+
resolveDbPath,
|
|
92
|
+
// The CLI's own version, compared against the server's /health version.
|
|
93
|
+
cliVersion: packageVersion,
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Perform a JSON HTTP request and return the parsed result without throwing on
|
|
98
|
+
* a non-2xx status (the caller inspects `status`). Rejects only on a transport
|
|
99
|
+
* failure (connection refused, timeout, DNS) — mirroring `fetch`'s own contract
|
|
100
|
+
* — so callers can distinguish "server answered with an error" from "server is
|
|
101
|
+
* unreachable".
|
|
102
|
+
*
|
|
103
|
+
* @param {Object} deps - Merged dependencies (must provide `fetch`)
|
|
104
|
+
* @param {string} method - HTTP method
|
|
105
|
+
* @param {string} url - Absolute URL
|
|
106
|
+
* @param {Object|null} body - JSON body (omitted for GET/null)
|
|
107
|
+
* @param {number} timeoutMs - Abort deadline
|
|
108
|
+
* @returns {Promise<{status: number, json: Object|null}>}
|
|
109
|
+
*/
|
|
110
|
+
async function httpJson(deps, method, url, body, timeoutMs) {
|
|
111
|
+
const options = {
|
|
112
|
+
method,
|
|
113
|
+
headers: { Accept: 'application/json' },
|
|
114
|
+
// AbortSignal.timeout guards against a hung socket. Tests stub `fetch` and
|
|
115
|
+
// ignore the signal, so this stays deterministic there.
|
|
116
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
117
|
+
};
|
|
118
|
+
if (body != null) {
|
|
119
|
+
options.headers['Content-Type'] = 'application/json';
|
|
120
|
+
options.body = JSON.stringify(body);
|
|
121
|
+
}
|
|
122
|
+
const res = await deps.fetch(url, options);
|
|
123
|
+
let json = null;
|
|
124
|
+
try {
|
|
125
|
+
json = await res.json();
|
|
126
|
+
} catch {
|
|
127
|
+
json = null;
|
|
128
|
+
}
|
|
129
|
+
return { status: res.status, json };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Probe the configured port for a compatible pair-review server.
|
|
134
|
+
*
|
|
135
|
+
* Delegation is allowed only when the server is a pair-review instance whose
|
|
136
|
+
* version EXACTLY matches this CLI's version and whose resolved database file
|
|
137
|
+
* is the same as this CLI's (compared via `computeDbId` digests so the raw path
|
|
138
|
+
* is never exposed over HTTP). Any other outcome — no server, foreign service,
|
|
139
|
+
* version skew, different DB — returns `delegate: false` with a human-readable
|
|
140
|
+
* `reason` for the stderr fallback note.
|
|
141
|
+
*
|
|
142
|
+
* @param {Object} config - Loaded config (uses `config.port`)
|
|
143
|
+
* @param {Object} [_deps] - Dependency overrides for testing
|
|
144
|
+
* @returns {Promise<{delegate: boolean, reason: string, baseUrl: string, serverVersion: string|null}>}
|
|
145
|
+
*/
|
|
146
|
+
async function probeServer(config, _deps) {
|
|
147
|
+
const deps = { ...defaults, ..._deps };
|
|
148
|
+
const port = config.port;
|
|
149
|
+
const baseUrl = `http://localhost:${port}`;
|
|
150
|
+
|
|
151
|
+
let result;
|
|
152
|
+
try {
|
|
153
|
+
result = await httpJson(deps, 'GET', `${baseUrl}/health`, null, HEALTH_TIMEOUT_MS);
|
|
154
|
+
} catch {
|
|
155
|
+
return { delegate: false, reason: `no server responding on port ${port}`, baseUrl, serverVersion: null };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const body = result.json || {};
|
|
159
|
+
if (result.status < 200 || result.status >= 300 || body.service !== 'pair-review') {
|
|
160
|
+
return {
|
|
161
|
+
delegate: false,
|
|
162
|
+
reason: `port ${port} is not serving a pair-review instance`,
|
|
163
|
+
baseUrl,
|
|
164
|
+
serverVersion: null,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const serverVersion = body.version || null;
|
|
169
|
+
if (serverVersion !== deps.cliVersion) {
|
|
170
|
+
return {
|
|
171
|
+
delegate: false,
|
|
172
|
+
reason: `server version ${serverVersion || '(unknown)'} does not match CLI version ${deps.cliVersion}`,
|
|
173
|
+
baseUrl,
|
|
174
|
+
serverVersion,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const expectedDbId = deps.computeDbId(deps.resolveDbPath(config));
|
|
179
|
+
if (body.dbId !== expectedDbId) {
|
|
180
|
+
return {
|
|
181
|
+
delegate: false,
|
|
182
|
+
reason: 'server is using a different database file',
|
|
183
|
+
baseUrl,
|
|
184
|
+
serverVersion,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return { delegate: true, reason: 'compatible server', baseUrl, serverVersion };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Generic status poller shared by setup and analysis waits.
|
|
193
|
+
*
|
|
194
|
+
* Owns every cross-cutting concern the two callers used to duplicate (and had
|
|
195
|
+
* already drifted on): transport-error retry, 404 routing, non-2xx accounting
|
|
196
|
+
* (INCLUDING 5xx — `httpJson` resolves rather than throws on a 500/503, so a
|
|
197
|
+
* naive "reset the counter before the 2xx check" loop spins forever), the
|
|
198
|
+
* consecutive-failure threshold, and recording WHICH failure kind ultimately
|
|
199
|
+
* tripped it (so a transport-error streak capped by one stray 404 does not
|
|
200
|
+
* report the misleading 404 message). Callers own only the semantics:
|
|
201
|
+
*
|
|
202
|
+
* @param {Object} deps - Merged dependencies
|
|
203
|
+
* @param {Object} opts
|
|
204
|
+
* @param {string} opts.url - Absolute status URL to GET
|
|
205
|
+
* @param {number} opts.intervalMs - Delay between polls
|
|
206
|
+
* @param {(json: Object) => ({done: boolean, value?: *}|undefined|Promise<...>)} opts.handleOk
|
|
207
|
+
* - Called on a confirmed 2xx. Return `{done:true, value}` to stop, a falsy
|
|
208
|
+
* value to keep polling, or throw to fail. Resets the failure counter.
|
|
209
|
+
* @param {(deps: Object) => ({done: boolean, value?: *}|undefined|Promise<...>)} [opts.handle404]
|
|
210
|
+
* - Optional 404 handler. Return `{done:true, value}` to stop; a falsy value
|
|
211
|
+
* lets the 404 count as a failure. Absent → 404 is always a failure.
|
|
212
|
+
* @param {(failure: {kind: string, status?: number, body?: Object, error?: Error}) => ({done: boolean, value?: *}|Promise<...>)} opts.onExhausted
|
|
213
|
+
* - Called once the failure threshold is crossed, with the LAST failure. Must
|
|
214
|
+
* return `{done:true, value}` or throw.
|
|
215
|
+
* @returns {Promise<*>} The `value` from whichever handler resolved
|
|
216
|
+
*/
|
|
217
|
+
async function pollUntil(deps, { url, intervalMs, handleOk, handle404, onExhausted }) {
|
|
218
|
+
let consecutiveFailures = 0;
|
|
219
|
+
// eslint-disable-next-line no-constant-condition
|
|
220
|
+
while (true) {
|
|
221
|
+
let resp;
|
|
222
|
+
try {
|
|
223
|
+
resp = await httpJson(deps, 'GET', url, null, REQUEST_TIMEOUT_MS);
|
|
224
|
+
} catch (err) {
|
|
225
|
+
if (++consecutiveFailures >= MAX_CONSECUTIVE_POLL_FAILURES) {
|
|
226
|
+
return (await onExhausted({ kind: 'transport', error: err })).value;
|
|
227
|
+
}
|
|
228
|
+
await deps.delay(intervalMs);
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (resp.status === 404) {
|
|
233
|
+
if (handle404) {
|
|
234
|
+
const handled = await handle404(deps);
|
|
235
|
+
if (handled && handled.done) return handled.value;
|
|
236
|
+
}
|
|
237
|
+
if (++consecutiveFailures >= MAX_CONSECUTIVE_POLL_FAILURES) {
|
|
238
|
+
return (await onExhausted({ kind: '404', status: 404, body: resp.json })).value;
|
|
239
|
+
}
|
|
240
|
+
await deps.delay(intervalMs);
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (resp.status < 200 || resp.status >= 300) {
|
|
245
|
+
const kind = resp.status >= 500 ? '5xx' : 'http';
|
|
246
|
+
if (++consecutiveFailures >= MAX_CONSECUTIVE_POLL_FAILURES) {
|
|
247
|
+
return (await onExhausted({ kind, status: resp.status, body: resp.json })).value;
|
|
248
|
+
}
|
|
249
|
+
await deps.delay(intervalMs);
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// Confirmed 2xx — clear the streak and let the caller decide.
|
|
254
|
+
consecutiveFailures = 0;
|
|
255
|
+
const handled = await handleOk(resp.json || {});
|
|
256
|
+
if (handled && handled.done) return handled.value;
|
|
257
|
+
await deps.delay(intervalMs);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Poll a setup operation to completion via {@link pollUntil}.
|
|
263
|
+
*
|
|
264
|
+
* Resolves when the status reports `complete`; throws on `error`. A 404 or a
|
|
265
|
+
* transport/5xx failure is tolerated up to MAX_CONSECUTIVE_POLL_FAILURES
|
|
266
|
+
* consecutive occurrences — a CLI that polls in the instant between "server
|
|
267
|
+
* returns setupId" and "status map seeded" would otherwise abort spuriously —
|
|
268
|
+
* after which the message reflects the actual failure kind.
|
|
269
|
+
*
|
|
270
|
+
* @param {Object} deps - Merged dependencies
|
|
271
|
+
* @param {string} baseUrl - Server base URL
|
|
272
|
+
* @param {string} setupId - Setup operation id
|
|
273
|
+
* @returns {Promise<{reviewUrl?: string, reviewId?: number}>}
|
|
274
|
+
*/
|
|
275
|
+
async function pollSetupStatus(deps, baseUrl, setupId) {
|
|
276
|
+
return pollUntil(deps, {
|
|
277
|
+
url: `${baseUrl}/api/setup/${setupId}/status`,
|
|
278
|
+
intervalMs: SETUP_POLL_INTERVAL_MS,
|
|
279
|
+
handleOk: (status) => {
|
|
280
|
+
if (status.status === 'error') {
|
|
281
|
+
throw new Error(`Server-side review setup failed: ${status.error || 'unknown error'}`);
|
|
282
|
+
}
|
|
283
|
+
if (status.status === 'complete') {
|
|
284
|
+
return { done: true, value: { reviewUrl: status.reviewUrl, reviewId: status.reviewId } };
|
|
285
|
+
}
|
|
286
|
+
return undefined; // 'running' — keep polling.
|
|
287
|
+
},
|
|
288
|
+
onExhausted: (failure) => {
|
|
289
|
+
if (failure.kind === 'transport') {
|
|
290
|
+
throw new Error(`Lost contact with the pair-review server during setup: ${failure.error.message}`);
|
|
291
|
+
}
|
|
292
|
+
if (failure.kind === '404') {
|
|
293
|
+
throw new Error('The pair-review server forgot the setup operation before it completed.');
|
|
294
|
+
}
|
|
295
|
+
const detail = (failure.body && failure.body.error) || `HTTP ${failure.status}`;
|
|
296
|
+
throw new Error(`Server error during review setup: ${detail}`);
|
|
297
|
+
},
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Derive a local reviewId from a setup result. Prefers the explicit numeric
|
|
303
|
+
* `reviewId`; falls back to parsing the trailing id out of a `/local/:id`
|
|
304
|
+
* review URL (the short-circuit shape carries only a URL).
|
|
305
|
+
*
|
|
306
|
+
* @param {{reviewId?: number|string, reviewUrl?: string}} result
|
|
307
|
+
* @returns {number|null}
|
|
308
|
+
*/
|
|
309
|
+
function deriveLocalReviewId(result) {
|
|
310
|
+
if (result && result.reviewId != null) {
|
|
311
|
+
const n = parseInt(result.reviewId, 10);
|
|
312
|
+
if (!Number.isNaN(n)) return n;
|
|
313
|
+
}
|
|
314
|
+
const match = result && result.reviewUrl && /\/local\/(\d+)/.exec(result.reviewUrl);
|
|
315
|
+
return match ? parseInt(match[1], 10) : null;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Drive server-side local review setup and return the resolved reviewId.
|
|
320
|
+
*
|
|
321
|
+
* @param {Object} deps - Merged dependencies
|
|
322
|
+
* @param {string} baseUrl - Server base URL
|
|
323
|
+
* @param {{path: string, scope: string|null, base: string|null}} params
|
|
324
|
+
* @returns {Promise<{reviewId: number, reviewUrl: string}>}
|
|
325
|
+
*/
|
|
326
|
+
async function setupLocal(deps, baseUrl, { path, scope, base }) {
|
|
327
|
+
const body = { path };
|
|
328
|
+
if (scope) body.scope = scope;
|
|
329
|
+
if (base) body.base = base;
|
|
330
|
+
|
|
331
|
+
const resp = await httpJson(deps, 'POST', `${baseUrl}/api/setup/local`, body, REQUEST_TIMEOUT_MS);
|
|
332
|
+
if (resp.status < 200 || resp.status >= 300) {
|
|
333
|
+
const detail = (resp.json && resp.json.error) || `HTTP ${resp.status}`;
|
|
334
|
+
throw new Error(`Failed to start local review setup on the server: ${detail}`);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const data = resp.json || {};
|
|
338
|
+
// Short-circuit shape: server may resolve an existing review inline with no
|
|
339
|
+
// setupId (defensive — handle it without polling a nonexistent operation).
|
|
340
|
+
let result = data;
|
|
341
|
+
if (data.setupId) {
|
|
342
|
+
result = await pollSetupStatus(deps, baseUrl, data.setupId);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const reviewId = deriveLocalReviewId(result);
|
|
346
|
+
if (reviewId == null) {
|
|
347
|
+
throw new Error('Server completed local setup but did not return a usable review id.');
|
|
348
|
+
}
|
|
349
|
+
return { reviewId, reviewUrl: result.reviewUrl || `/local/${reviewId}` };
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Drive server-side PR review setup. The server owns the worktree-pool hold, so
|
|
354
|
+
* the delegating CLI never acquires a pool slot. Returns the canonical review
|
|
355
|
+
* URL; the owner/repo/number the CLI already parsed drive the analyze launch,
|
|
356
|
+
* so no server-side reviewId is needed.
|
|
357
|
+
*
|
|
358
|
+
* @param {Object} deps - Merged dependencies
|
|
359
|
+
* @param {string} baseUrl - Server base URL
|
|
360
|
+
* @param {{owner: string, repo: string, number: number, host?: string|null}} params
|
|
361
|
+
* @returns {Promise<{reviewUrl: string}>}
|
|
362
|
+
*/
|
|
363
|
+
async function setupPr(deps, baseUrl, { owner, repo, number, host }) {
|
|
364
|
+
const body = {};
|
|
365
|
+
// Forward the host per the endpoint's body contract (null = github.com, a
|
|
366
|
+
// string = that alt api_host; omit to let the server derive via stored host
|
|
367
|
+
// or a probe). Only the raw parser value is faithful here — the URL 'github'
|
|
368
|
+
// sentinel is a browser-relay convention, not the body contract.
|
|
369
|
+
if (host !== undefined) body.host = host;
|
|
370
|
+
|
|
371
|
+
const resp = await httpJson(
|
|
372
|
+
deps, 'POST', `${baseUrl}/api/setup/pr/${owner}/${repo}/${number}`, body, REQUEST_TIMEOUT_MS
|
|
373
|
+
);
|
|
374
|
+
if (resp.status < 200 || resp.status >= 300) {
|
|
375
|
+
const detail = (resp.json && resp.json.error) || `HTTP ${resp.status}`;
|
|
376
|
+
throw new Error(`Failed to start PR review setup on the server: ${detail}`);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const data = resp.json || {};
|
|
380
|
+
// Idempotent short-circuit: an already-set-up PR returns { existing, reviewUrl }
|
|
381
|
+
// with no setupId — navigate directly without polling.
|
|
382
|
+
if (data.existing || !data.setupId) {
|
|
383
|
+
return { reviewUrl: data.reviewUrl || `/pr/${owner}/${repo}/${number}` };
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const result = await pollSetupStatus(deps, baseUrl, data.setupId);
|
|
387
|
+
return { reviewUrl: result.reviewUrl || `/pr/${owner}/${repo}/${number}` };
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Build the analyze-endpoint URL + request body for a resolved review config.
|
|
392
|
+
*
|
|
393
|
+
* The server never re-resolves: it receives the CLI-resolved explicit values
|
|
394
|
+
* (council id, or provider/model), mirroring the repo convention of passing
|
|
395
|
+
* resolved values down. `customInstructions` carries ONLY the per-run
|
|
396
|
+
* `--instructions` text — the server derives global + repo instructions from
|
|
397
|
+
* its own (shared) config/DB and merges them identically to the in-process
|
|
398
|
+
* headless path, so the effective prompt matches.
|
|
399
|
+
*
|
|
400
|
+
* @param {string} baseUrl - Server base URL
|
|
401
|
+
* @param {'local'|'pr'} mode
|
|
402
|
+
* @param {Object} target - { reviewId } for local, { owner, repo, number } for PR
|
|
403
|
+
* @param {Object} reviewConfig - resolveReviewConfig result (single|council)
|
|
404
|
+
* @param {string|null} customInstructions - Per-run instructions (or null)
|
|
405
|
+
* @returns {{url: string, body: Object}}
|
|
406
|
+
*/
|
|
407
|
+
function buildLaunchRequest(baseUrl, mode, target, reviewConfig, customInstructions) {
|
|
408
|
+
const prefix = mode === 'local'
|
|
409
|
+
? `${baseUrl}/api/local/${target.reviewId}`
|
|
410
|
+
: `${baseUrl}/api/pr/${target.owner}/${target.repo}/${target.number}`;
|
|
411
|
+
|
|
412
|
+
if (reviewConfig.type === 'council') {
|
|
413
|
+
return {
|
|
414
|
+
url: `${prefix}/analyses/council`,
|
|
415
|
+
body: {
|
|
416
|
+
councilId: reviewConfig.council.id,
|
|
417
|
+
configType: reviewConfig.configType,
|
|
418
|
+
customInstructions,
|
|
419
|
+
},
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
return {
|
|
423
|
+
url: `${prefix}/analyses`,
|
|
424
|
+
body: {
|
|
425
|
+
provider: reviewConfig.provider,
|
|
426
|
+
model: reviewConfig.model,
|
|
427
|
+
customInstructions,
|
|
428
|
+
},
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Launch analysis on the server and return the identifiers to wait on.
|
|
434
|
+
*
|
|
435
|
+
* @param {Object} deps - Merged dependencies
|
|
436
|
+
* @param {string} baseUrl - Server base URL
|
|
437
|
+
* @param {'local'|'pr'} mode
|
|
438
|
+
* @param {Object} target - { reviewId } (local) or { owner, repo, number } (PR)
|
|
439
|
+
* @param {Object} reviewConfig - resolveReviewConfig result
|
|
440
|
+
* @param {string|null} customInstructions
|
|
441
|
+
* @returns {Promise<{analysisId: string, runId: string}>}
|
|
442
|
+
*/
|
|
443
|
+
async function launchAnalysis(deps, baseUrl, mode, target, reviewConfig, customInstructions) {
|
|
444
|
+
const { url, body } = buildLaunchRequest(baseUrl, mode, target, reviewConfig, customInstructions);
|
|
445
|
+
const resp = await httpJson(deps, 'POST', url, body, REQUEST_TIMEOUT_MS);
|
|
446
|
+
if (resp.status < 200 || resp.status >= 300) {
|
|
447
|
+
const detail = (resp.json && resp.json.error) || `HTTP ${resp.status}`;
|
|
448
|
+
// A 409 from the analyze endpoint is a PRECONDITION failure (empty scope,
|
|
449
|
+
// worktree lock) whose server message is already user-meaningful. Surface it
|
|
450
|
+
// VERBATIM so a delegated empty-scope run reads identically to the
|
|
451
|
+
// in-process run (both emit the same `{ ok:false, error }` message) rather
|
|
452
|
+
// than wrapping it. Every other non-2xx keeps the request-context prefix.
|
|
453
|
+
if (resp.status === 409 && resp.json && resp.json.error) {
|
|
454
|
+
throw new Error(resp.json.error);
|
|
455
|
+
}
|
|
456
|
+
throw new Error(`Server rejected the analysis request: ${detail}`);
|
|
457
|
+
}
|
|
458
|
+
const data = resp.json || {};
|
|
459
|
+
if (!data.analysisId || !data.runId) {
|
|
460
|
+
throw new Error('Server accepted the analysis request but did not return analysisId/runId.');
|
|
461
|
+
}
|
|
462
|
+
return { analysisId: data.analysisId, runId: data.runId };
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Best-effort cancel of an in-flight delegated analysis (fired on SIGINT/SIGTERM).
|
|
467
|
+
* Swallows all errors — the process is exiting regardless.
|
|
468
|
+
*
|
|
469
|
+
* @param {Object} deps - Merged dependencies
|
|
470
|
+
* @param {string} baseUrl - Server base URL
|
|
471
|
+
* @param {string} analysisId
|
|
472
|
+
*/
|
|
473
|
+
async function cancelAnalysis(deps, baseUrl, analysisId) {
|
|
474
|
+
try {
|
|
475
|
+
await httpJson(deps, 'POST', `${baseUrl}/api/analyses/${analysisId}/cancel`, {}, CANCEL_TIMEOUT_MS);
|
|
476
|
+
} catch {
|
|
477
|
+
// Best-effort only.
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Install SIGINT/SIGTERM handlers that cancel the delegated run before exiting.
|
|
483
|
+
* Returns a cleanup function that removes them (call in a finally).
|
|
484
|
+
*
|
|
485
|
+
* A re-entry guard makes the FIRST interrupt fire the (short-deadline) cancel
|
|
486
|
+
* POST and then exit, while a SECOND interrupt exits immediately — an impatient
|
|
487
|
+
* double Ctrl-C never waits on the network or queues a duplicate cancel.
|
|
488
|
+
*
|
|
489
|
+
* @param {Object} deps - Merged dependencies
|
|
490
|
+
* @param {string} baseUrl - Server base URL
|
|
491
|
+
* @param {string} analysisId
|
|
492
|
+
* @returns {() => void} cleanup
|
|
493
|
+
*/
|
|
494
|
+
function installCancelHandlers(deps, baseUrl, analysisId) {
|
|
495
|
+
let cancelling = false;
|
|
496
|
+
const handler = async () => {
|
|
497
|
+
if (cancelling) {
|
|
498
|
+
// Second interrupt — don't wait on the in-flight cancel, exit now.
|
|
499
|
+
deps.exit(130);
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
cancelling = true;
|
|
503
|
+
deps.logger.info('Received interrupt — cancelling the delegated analysis on the server...');
|
|
504
|
+
await cancelAnalysis(deps, baseUrl, analysisId);
|
|
505
|
+
// 130 = terminated by SIGINT, the conventional shell exit code.
|
|
506
|
+
deps.exit(130);
|
|
507
|
+
};
|
|
508
|
+
deps.process.on('SIGINT', handler);
|
|
509
|
+
deps.process.on('SIGTERM', handler);
|
|
510
|
+
return () => {
|
|
511
|
+
deps.process.removeListener('SIGINT', handler);
|
|
512
|
+
deps.process.removeListener('SIGTERM', handler);
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Condense an analysis status snapshot into one concise progress line for
|
|
518
|
+
* stderr, so identical repeated polls can be throttled by the caller.
|
|
519
|
+
*
|
|
520
|
+
* @param {Object} status - activeAnalyses snapshot
|
|
521
|
+
* @returns {string}
|
|
522
|
+
*/
|
|
523
|
+
function summarizeProgress(status) {
|
|
524
|
+
if (!status) return '';
|
|
525
|
+
const parts = [];
|
|
526
|
+
if (status.status) parts.push(status.status);
|
|
527
|
+
if (status.progress) parts.push(status.progress);
|
|
528
|
+
if (status.levels && typeof status.levels === 'object') {
|
|
529
|
+
const levelSummary = Object.entries(status.levels)
|
|
530
|
+
.map(([key, value]) => `${key}:${(value && value.status) || '?'}`)
|
|
531
|
+
.join(' ');
|
|
532
|
+
if (levelSummary) parts.push(`(${levelSummary})`);
|
|
533
|
+
}
|
|
534
|
+
return parts.join(' ');
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Wait for a delegated analysis to reach a terminal state via {@link pollUntil},
|
|
539
|
+
* echoing concise progress to stderr along the way.
|
|
540
|
+
*
|
|
541
|
+
* Poll semantics (per the plan):
|
|
542
|
+
* - GET /api/analyses/:id/status every ~3s.
|
|
543
|
+
* - A 404 means the server dropped its in-memory entry: consult the DB run row
|
|
544
|
+
* — terminal → done; still running → let it count as a poll failure.
|
|
545
|
+
* - A transport/5xx failure is a poll failure. Once the threshold is crossed
|
|
546
|
+
* with a still-non-terminal DB row, the server is presumed dead and we
|
|
547
|
+
* resolve a `failed` outcome explaining why.
|
|
548
|
+
*
|
|
549
|
+
* The DB row fetched on the LAST 404 is reused by the exhaustion handler (no
|
|
550
|
+
* redundant re-fetch); a transport/5xx streak re-reads fresh, since no 404
|
|
551
|
+
* branch ran to populate it and the server may have written a terminal row.
|
|
552
|
+
*
|
|
553
|
+
* @param {Object} deps - Merged dependencies
|
|
554
|
+
* @param {string} baseUrl - Server base URL
|
|
555
|
+
* @param {string} analysisId
|
|
556
|
+
* @param {string} runId
|
|
557
|
+
* @param {Object} db - Database instance (for the DB-row fallback)
|
|
558
|
+
* @returns {Promise<{status: string, error?: string}>}
|
|
559
|
+
*/
|
|
560
|
+
async function waitForAnalysis(deps, baseUrl, analysisId, runId, db) {
|
|
561
|
+
let lastSummary = null;
|
|
562
|
+
let lastDbStatus; // populated by the 404 branch so onExhausted can reuse it
|
|
563
|
+
|
|
564
|
+
return pollUntil(deps, {
|
|
565
|
+
url: `${baseUrl}/api/analyses/${analysisId}/status`,
|
|
566
|
+
intervalMs: ANALYSIS_POLL_INTERVAL_MS,
|
|
567
|
+
handleOk: (status) => {
|
|
568
|
+
const summary = summarizeProgress(status);
|
|
569
|
+
if (summary && summary !== lastSummary) {
|
|
570
|
+
deps.logger.info(`Analysis progress: ${summary}`);
|
|
571
|
+
lastSummary = summary;
|
|
572
|
+
}
|
|
573
|
+
if (isTerminal(status.status)) {
|
|
574
|
+
return { done: true, value: { status: status.status, error: status.error || status.progress } };
|
|
575
|
+
}
|
|
576
|
+
return undefined;
|
|
577
|
+
},
|
|
578
|
+
handle404: async () => {
|
|
579
|
+
// In-memory entry gone — the DB row is authoritative. Cache it so a 404
|
|
580
|
+
// streak that trips the threshold doesn't re-fetch in onExhausted.
|
|
581
|
+
lastDbStatus = await deps.getRunStatus(db, runId);
|
|
582
|
+
if (isTerminal(lastDbStatus)) return { done: true, value: { status: lastDbStatus } };
|
|
583
|
+
return undefined;
|
|
584
|
+
},
|
|
585
|
+
onExhausted: async (failure) => {
|
|
586
|
+
// A 404 streak already read the DB row this iteration — reuse it. A
|
|
587
|
+
// transport/5xx streak did not, so read fresh (the run may have finished).
|
|
588
|
+
const dbStatus = failure.kind === '404' ? lastDbStatus : await deps.getRunStatus(db, runId);
|
|
589
|
+
if (isTerminal(dbStatus)) return { done: true, value: { status: dbStatus } };
|
|
590
|
+
return { done: true, value: { status: 'failed', error: SERVER_DIED_MESSAGE } };
|
|
591
|
+
},
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Orchestrate a full delegated headless run: set up the review on the server,
|
|
597
|
+
* launch the resolved analysis, and wait for it to finish. Returns the server's
|
|
598
|
+
* `runId` so the caller emits the standard headless JSON from the shared DB.
|
|
599
|
+
*
|
|
600
|
+
* Throws on any failure (setup error, rejected launch, failed/cancelled run, or
|
|
601
|
+
* a server that dies mid-run) so the CLI's existing `--json` error path emits
|
|
602
|
+
* `{ ok: false, error }` and exits non-zero — identical failure semantics to
|
|
603
|
+
* the in-process path.
|
|
604
|
+
*
|
|
605
|
+
* @param {Object} params
|
|
606
|
+
* @param {string} params.baseUrl - Compatible server base URL (from probeServer)
|
|
607
|
+
* @param {'local'|'pr'} params.mode
|
|
608
|
+
* @param {Object} params.reviewConfig - resolveReviewConfig result (single|council)
|
|
609
|
+
* @param {string|null} params.customInstructions - Per-run `--instructions` text
|
|
610
|
+
* @param {Object} [params.prInfo] - { owner, repo, number } (PR mode)
|
|
611
|
+
* @param {string|null} [params.host] - PR host body value (PR mode)
|
|
612
|
+
* @param {string} [params.localPath] - Resolved repo path (local mode)
|
|
613
|
+
* @param {string|null} [params.scope] - `--scope` (local mode)
|
|
614
|
+
* @param {string|null} [params.base] - `--base` (local mode)
|
|
615
|
+
* @param {Object} params.db - Database instance (DB-row fallback + final emit)
|
|
616
|
+
* @param {Object} [params._deps] - Dependency overrides for testing
|
|
617
|
+
* @returns {Promise<{runId: string, mode: 'local'|'pr'}>}
|
|
618
|
+
*/
|
|
619
|
+
async function runDelegatedAnalysis({
|
|
620
|
+
baseUrl, mode, reviewConfig, customInstructions,
|
|
621
|
+
prInfo, host, localPath, scope, base, db, _deps,
|
|
622
|
+
}) {
|
|
623
|
+
const deps = { ...defaults, ..._deps };
|
|
624
|
+
|
|
625
|
+
deps.logger.info(`Delegating headless analysis to the running pair-review server at ${baseUrl}`);
|
|
626
|
+
|
|
627
|
+
// 1. Setup (server owns the worktree/pool in PR mode).
|
|
628
|
+
let target;
|
|
629
|
+
let reviewUrl;
|
|
630
|
+
if (mode === 'local') {
|
|
631
|
+
const setup = await setupLocal(deps, baseUrl, { path: localPath, scope, base });
|
|
632
|
+
target = { reviewId: setup.reviewId };
|
|
633
|
+
reviewUrl = setup.reviewUrl;
|
|
634
|
+
} else {
|
|
635
|
+
const setup = await setupPr(deps, baseUrl, {
|
|
636
|
+
owner: prInfo.owner, repo: prInfo.repo, number: prInfo.number, host,
|
|
637
|
+
});
|
|
638
|
+
target = { owner: prInfo.owner, repo: prInfo.repo, number: prInfo.number };
|
|
639
|
+
reviewUrl = setup.reviewUrl;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// 2. Launch the resolved analysis.
|
|
643
|
+
const { analysisId, runId } = await launchAnalysis(
|
|
644
|
+
deps, baseUrl, mode, target, reviewConfig, customInstructions
|
|
645
|
+
);
|
|
646
|
+
|
|
647
|
+
// Surface the live view early so a human can open it while the agent waits.
|
|
648
|
+
deps.logger.info(`Live review view: ${baseUrl}${reviewUrl}`);
|
|
649
|
+
|
|
650
|
+
// 3. Wait, cancelling on interrupt.
|
|
651
|
+
const cleanup = installCancelHandlers(deps, baseUrl, analysisId);
|
|
652
|
+
let outcome;
|
|
653
|
+
try {
|
|
654
|
+
outcome = await waitForAnalysis(deps, baseUrl, analysisId, runId, db);
|
|
655
|
+
} finally {
|
|
656
|
+
cleanup();
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
if (outcome.status !== 'completed') {
|
|
660
|
+
const suffix = outcome.error ? `: ${outcome.error}` : '';
|
|
661
|
+
throw new Error(`Delegated analysis ${outcome.status}${suffix}`);
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
return { runId, mode };
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
module.exports = {
|
|
668
|
+
probeServer,
|
|
669
|
+
runDelegatedAnalysis,
|
|
670
|
+
// Exported for focused unit tests.
|
|
671
|
+
setupLocal,
|
|
672
|
+
setupPr,
|
|
673
|
+
launchAnalysis,
|
|
674
|
+
waitForAnalysis,
|
|
675
|
+
buildLaunchRequest,
|
|
676
|
+
summarizeProgress,
|
|
677
|
+
deriveLocalReviewId,
|
|
678
|
+
installCancelHandlers,
|
|
679
|
+
cancelAnalysis,
|
|
680
|
+
HEALTH_TIMEOUT_MS,
|
|
681
|
+
MAX_CONSECUTIVE_POLL_FAILURES,
|
|
682
|
+
};
|