@in-the-loop-labs/pair-review 5.0.2 → 5.1.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/public/local.html CHANGED
@@ -566,6 +566,8 @@
566
566
  <!-- Markdown-it Library for rendering markdown in comments -->
567
567
  <script src="https://cdn.jsdelivr.net/npm/markdown-it@13.0.2/dist/markdown-it.min.js"></script>
568
568
  <script src="https://cdn.jsdelivr.net/npm/markdown-it-emoji@2.0.2/dist/markdown-it-emoji.min.js"></script>
569
+ <!-- DOMPurify sanitizes rendered markdown HTML (must load before markdown.js) -->
570
+ <script src="https://cdn.jsdelivr.net/npm/dompurify@3.2.6/dist/purify.min.js"></script>
569
571
 
570
572
  <!-- Markdown renderer utility -->
571
573
  <script src="/js/utils/markdown.js"></script>
package/public/pr.html CHANGED
@@ -371,6 +371,8 @@
371
371
  <!-- Markdown-it Library for rendering markdown in comments -->
372
372
  <script src="https://cdn.jsdelivr.net/npm/markdown-it@13.0.2/dist/markdown-it.min.js"></script>
373
373
  <script src="https://cdn.jsdelivr.net/npm/markdown-it-emoji@2.0.2/dist/markdown-it-emoji.min.js"></script>
374
+ <!-- DOMPurify sanitizes rendered markdown HTML (must load before markdown.js) -->
375
+ <script src="https://cdn.jsdelivr.net/npm/dompurify@3.2.6/dist/purify.min.js"></script>
374
376
 
375
377
  <!-- Markdown renderer utility -->
376
378
  <script src="/js/utils/markdown.js"></script>
@@ -3,6 +3,91 @@
3
3
  const { spawn } = require('child_process');
4
4
  const logger = require('../utils/logger');
5
5
 
6
+ /**
7
+ * Terminate a spawned child safely.
8
+ *
9
+ * Use this instead of a bare `child.kill('SIGTERM')` anywhere a child might
10
+ * not have started. Two hazards it exists to prevent:
11
+ *
12
+ * 1. **Self-signalling.** A child whose spawn failed (ENOENT from a missing or
13
+ * misconfigured CLI command) has no pid. Node coerces the undefined pid to
14
+ * `0`, and `kill(0, SIGTERM)` signals the CALLER'S OWN process group — so
15
+ * pair-review terminates itself. Verified directly: the call returns `true`
16
+ * and the current process receives SIGTERM.
17
+ * 2. **Orphaned grandchildren.** Under `shell: true` the child is the shell
18
+ * wrapper, not the CLI. Killing only the wrapper leaves the real CLI running
19
+ * and burning tokens, so shell-mode children are group-killed instead
20
+ * (requires the caller to have spawned with `detached: true`).
21
+ *
22
+ * Never throws — that is a contract callers rely on, not just a hope. Every
23
+ * dispatch path has its own catch, and the whole body is wrapped so even a
24
+ * malformed `child` (missing `kill`, throwing `pid` getter) or a non-object
25
+ * `opts` returns false instead of propagating. `wireAbortToChild`'s abort
26
+ * listener depends on this: a throw there would escape into the AbortSignal
27
+ * dispatch with no caller frame to catch it.
28
+ *
29
+ * @param {import('child_process').ChildProcess} child - Spawned process.
30
+ * @param {Object} [opts]
31
+ * @param {boolean} [opts.shell=false] - True when spawned with `shell: true`.
32
+ * @param {string} [opts.logPrefix] - Log prefix for diagnostics.
33
+ * @returns {boolean} True if a signal was actually dispatched.
34
+ */
35
+ function killChildSafely(child, opts = {}) {
36
+ if (!child) return false;
37
+ const options = (opts && typeof opts === 'object') ? opts : {};
38
+ const prefix = options.logPrefix || '';
39
+ const isShell = options.shell === true;
40
+
41
+ try {
42
+ if (!child.pid) {
43
+ // Spawn failed or has not completed — nothing to signal. See hazard 1.
44
+ return false;
45
+ }
46
+
47
+ if (isShell && process.platform !== 'win32') {
48
+ try {
49
+ process.kill(-child.pid, 'SIGTERM');
50
+ return true;
51
+ } catch (err) {
52
+ if (err && err.code === 'ESRCH') {
53
+ return false; // Group already gone.
54
+ }
55
+ logger.warn(
56
+ `${prefix} process.kill(-pid) failed (${err.message}); falling back to child.kill`
57
+ );
58
+ }
59
+ }
60
+
61
+ if (isShell && process.platform === 'win32') {
62
+ // Windows has no process groups: wipe the tree rooted at the shell pid.
63
+ try {
64
+ spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore' })
65
+ .on('error', (err) => {
66
+ logger.warn(`${prefix} taskkill failed: ${err.message}`);
67
+ });
68
+ return true;
69
+ } catch (err) {
70
+ logger.warn(
71
+ `${prefix} spawn(taskkill) failed (${err.message}); falling back to child.kill`
72
+ );
73
+ }
74
+ }
75
+
76
+ try {
77
+ child.kill('SIGTERM');
78
+ return true;
79
+ } catch (err) {
80
+ logger.warn(`${prefix} child.kill failed: ${err.message}`);
81
+ return false;
82
+ }
83
+ } catch (err) {
84
+ // Reached only by a child that misbehaves outside the guarded calls above
85
+ // (e.g. a throwing `pid` getter). Enforces the never-throws contract.
86
+ logger.warn(`${prefix} kill dispatch failed unexpectedly: ${err && err.message}`);
87
+ return false;
88
+ }
89
+ }
90
+
6
91
  /**
7
92
  * Attach an `AbortSignal` to a spawned child process so that aborting the
8
93
  * signal kills the child with `SIGTERM`. Returns a cleanup function that
@@ -43,53 +128,13 @@ function wireAbortToChild(child, signal, opts = {}) {
43
128
  const prefix = opts.logPrefix || '';
44
129
  const isShell = opts.shell === true;
45
130
 
46
- const killChild = () => {
47
- // `kill` / process group signaling returns false (or throws ESRCH) if
48
- // the process is already gone, which is fine — we just need the side
49
- // effect when it IS still alive.
50
- if (isShell && child.pid && process.platform !== 'win32') {
51
- // Group-kill the shell AND its CLI descendant. Requires the caller
52
- // to have spawned with `detached: true` so the child became a
53
- // process-group leader (`-pid` targets the group).
54
- try {
55
- process.kill(-child.pid, 'SIGTERM');
56
- return;
57
- } catch (err) {
58
- if (err && err.code === 'ESRCH') {
59
- // Group already gone — nothing to kill.
60
- return;
61
- }
62
- // Fall through to single-process kill as a best effort.
63
- logger.warn(
64
- `${prefix} process.kill(-pid) failed (${err.message}); falling back to child.kill`
65
- );
66
- }
67
- }
68
- if (isShell && child.pid && process.platform === 'win32') {
69
- // Windows has no process groups: spawn taskkill /T /F to wipe the
70
- // tree rooted at our shell pid.
71
- try {
72
- spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore' })
73
- .on('error', (err) => {
74
- logger.warn(`${prefix} taskkill failed: ${err.message}`);
75
- });
76
- return;
77
- } catch (err) {
78
- logger.warn(
79
- `${prefix} spawn(taskkill) failed (${err.message}); falling back to child.kill`
80
- );
81
- }
82
- }
83
- child.kill('SIGTERM');
84
- };
85
-
86
131
  const onAbort = () => {
132
+ // `cancelled` is set FIRST so the close/error handler short-circuits even
133
+ // if the kill dispatch does nothing (pidless child, group already gone).
87
134
  cancelled = true;
88
- try {
89
- killChild();
90
- } catch (err) {
91
- logger.warn(`${prefix} child.kill on abort failed: ${err.message}`);
92
- }
135
+ // killChildSafely owns the pid guard, the shell group-kill semantics and
136
+ // the never-throws contract, so no catch is needed here.
137
+ killChildSafely(child, { shell: isShell, logPrefix: prefix });
93
138
  };
94
139
 
95
140
  if (signal.aborted) {
@@ -127,4 +172,4 @@ function makeAbortError(message) {
127
172
  return err;
128
173
  }
129
174
 
130
- module.exports = { wireAbortToChild, makeAbortError };
175
+ module.exports = { wireAbortToChild, makeAbortError, killChildSafely };
@@ -131,7 +131,7 @@ async function runExecutableVoice(voiceProvider, reviewId, worktreePath, prMetad
131
131
  try {
132
132
  const executableContext = {
133
133
  title: prMetadata.title || null,
134
- description: prMetadata.description || null,
134
+ description: resolveReviewDescription(prMetadata) || null,
135
135
  cwd: worktreePath,
136
136
  outputDir: tmpDir,
137
137
  model: voiceProvider.resolvedModel !== undefined ? voiceProvider.resolvedModel : (voiceProvider.model || null),
@@ -201,18 +201,64 @@ async function runExecutableVoice(voiceProvider, reviewId, worktreePath, prMetad
201
201
  }
202
202
  }
203
203
 
204
+ /**
205
+ * Resolve the `owner/repo` identifier from review metadata.
206
+ *
207
+ * Review metadata reaches the analyzer in more than one shape:
208
+ * - the normalized `pr_metadata` row (server routes, headless PR path), where
209
+ * `repository` is the `"owner/repo"` string;
210
+ * - the raw stored `pr_data` blob, where `repository` is the GitHub API object
211
+ * `{ full_name, clone_url, ssh_url, default_branch }`;
212
+ * - local reviews, where `repository` is a bare directory name (no slash).
213
+ *
214
+ * Accept all three instead of assuming a string. Callers used to do
215
+ * `prMetadata.repository?.split('/')`, which threw `TypeError` on the object
216
+ * shape — and because every consolidation stage builds its dedup context first,
217
+ * that single throw silently disabled consolidation for the whole run (#557).
218
+ *
219
+ * @param {Object} prMetadata - PR/review metadata
220
+ * @returns {string|null} The repository identifier, or null when unavailable
221
+ */
222
+ function resolveRepositorySlug(prMetadata) {
223
+ const repository = prMetadata?.repository;
224
+ if (typeof repository === 'string') return repository || null;
225
+ if (repository && typeof repository.full_name === 'string') return repository.full_name || null;
226
+ return null;
227
+ }
228
+
229
+ /**
230
+ * Resolve the review description from review metadata.
231
+ *
232
+ * The normalized `pr_metadata` row and local metadata both use `description`;
233
+ * the raw `pr_data` blob carries the same text under the GitHub API's `body`.
234
+ * Accepting both keeps the PR description in the prompt regardless of which
235
+ * shape a caller passes — the same shape divergence behind #557.
236
+ *
237
+ * @param {Object} prMetadata - PR/review metadata
238
+ * @returns {string|null|undefined} The description, or null/undefined when unset
239
+ */
240
+ function resolveReviewDescription(prMetadata) {
241
+ return prMetadata?.description ?? prMetadata?.body;
242
+ }
243
+
204
244
  /**
205
245
  * Build the dedup context object from PR metadata and run identifiers.
206
246
  *
207
- * @param {Object} prMetadata - PR metadata with repository and pr_number
247
+ * Tolerates both metadata shapes described on {@link resolveRepositorySlug}: the
248
+ * pull request number is read from `pr_number` (normalized row) and falls back
249
+ * to `number` (raw `pr_data` blob). Local reviews carry neither and yield
250
+ * `undefined`, which the dedup consumers already treat as "not a PR".
251
+ *
252
+ * @param {Object} prMetadata - PR metadata with repository and pr_number/number
208
253
  * @param {Object} ids - { reviewId, serverPort, runId, excludeRunIds }
209
254
  * @param {string} [ids.runId] - Single run ID to exclude (backward compat)
210
255
  * @param {string[]} [ids.excludeRunIds] - Array of run IDs to exclude (takes precedence over runId)
211
256
  * @returns {Object} { owner, repo, pullNumber, reviewId, serverPort, runId, excludeRunIds }
212
257
  */
213
258
  function buildDedupContext(prMetadata, { reviewId, serverPort, runId, excludeRunIds }) {
214
- const [owner, repo] = prMetadata.repository?.split('/') || [];
215
- return { owner, repo, pullNumber: prMetadata.pr_number, reviewId, serverPort, runId, excludeRunIds };
259
+ const [owner, repo] = resolveRepositorySlug(prMetadata)?.split('/') || [];
260
+ const pullNumber = prMetadata?.pr_number ?? prMetadata?.number;
261
+ return { owner, repo, pullNumber, reviewId, serverPort, runId, excludeRunIds };
216
262
  }
217
263
 
218
264
  /**
@@ -1219,20 +1265,25 @@ Or simply ignore any changes to files matching these patterns in your analysis.
1219
1265
  * @returns {string} Context section or empty string
1220
1266
  */
1221
1267
  buildPRContextSection(prMetadata, criticalNote) {
1268
+ const description = resolveReviewDescription(prMetadata);
1222
1269
  // Check for null/undefined explicitly to include section even if fields are empty strings
1223
- if (prMetadata.title != null || prMetadata.description != null) {
1270
+ if (prMetadata.title != null || description != null) {
1224
1271
  const isLocal = prMetadata.reviewType === 'local';
1225
1272
  const sectionTitle = isLocal ? 'Review Context' : 'Pull Request Context';
1226
1273
  const descriptionLabel = isLocal ? 'Description:' : "Author's Description:";
1227
1274
 
1228
- // Build metadata lines (repository for both modes, PR-specific fields only for PR mode)
1275
+ // Build metadata lines (repository for both modes, PR-specific fields only for PR mode).
1276
+ // Both fields go through the shape-tolerant resolvers so a raw `pr_data`
1277
+ // blob renders "owner/repo" rather than "[object Object]" (#557).
1229
1278
  const lines = [];
1230
- if (prMetadata.repository) {
1231
- lines.push(`**Repository:** ${prMetadata.repository}`);
1279
+ const repositorySlug = resolveRepositorySlug(prMetadata);
1280
+ if (repositorySlug) {
1281
+ lines.push(`**Repository:** ${repositorySlug}`);
1232
1282
  }
1233
1283
  if (!isLocal) {
1234
- if (prMetadata.pr_number) {
1235
- lines.push(`**PR #:** ${prMetadata.pr_number}`);
1284
+ const pullNumber = prMetadata.pr_number ?? prMetadata.number;
1285
+ if (pullNumber) {
1286
+ lines.push(`**PR #:** ${pullNumber}`);
1236
1287
  }
1237
1288
  if (prMetadata.author) {
1238
1289
  lines.push(`**Author:** @${prMetadata.author}`);
@@ -1245,7 +1296,7 @@ Or simply ignore any changes to files matching these patterns in your analysis.
1245
1296
  ${metadataLines}**Title:** ${prMetadata.title || '(No title provided)'}
1246
1297
 
1247
1298
  **${descriptionLabel}**
1248
- ${prMetadata.description || '(No description provided)'}
1299
+ ${description || '(No description provided)'}
1249
1300
 
1250
1301
  ⚠️ **Critical Note:** ${criticalNote}
1251
1302
 
@@ -4158,5 +4209,7 @@ File-level suggestions should NOT have a line number. They apply to the entire f
4158
4209
 
4159
4210
  module.exports = Analyzer;
4160
4211
  module.exports.buildDedupContext = buildDedupContext;
4212
+ module.exports.resolveRepositorySlug = resolveRepositorySlug;
4213
+ module.exports.resolveReviewDescription = resolveReviewDescription;
4161
4214
  module.exports.buildDedupInstructions = buildDedupInstructions;
4162
4215
  module.exports.fetchExistingReviewComments = fetchExistingReviewComments;
@@ -49,7 +49,7 @@ const { AIProvider, registerProvider, quoteShellArgs } = require('./provider');
49
49
  const logger = require('../utils/logger');
50
50
  const { extractJSON } = require('../utils/json-extractor');
51
51
  const { CancellationError, isAnalysisCancelled } = require('../routes/shared');
52
- const { wireAbortToChild, makeAbortError } = require('./abort-signal-wiring');
52
+ const { wireAbortToChild, makeAbortError, killChildSafely } = require('./abort-signal-wiring');
53
53
 
54
54
  // Directory containing bin scripts (kept on PATH for parity with other providers)
55
55
  const BIN_DIR = path.join(__dirname, '..', '..', 'bin');
@@ -339,7 +339,7 @@ class AntigravityProvider extends AIProvider {
339
339
  const backstopMs = budgetMs + TIMEOUT_BACKSTOP_GRACE_MS;
340
340
  timeoutId = setTimeout(() => {
341
341
  logger.error(`${levelPrefix} Process ${pid} exceeded its ${budgetMs}ms timeout budget (backstop fired at ${backstopMs}ms)`);
342
- agy.kill('SIGTERM');
342
+ killChildSafely(agy, { logPrefix: levelPrefix, shell: this.useShell });
343
343
  settle(reject, new Error(`${levelPrefix} Antigravity CLI timed out after ${budgetMs}ms`));
344
344
  }, backstopMs);
345
345
 
@@ -415,9 +415,24 @@ class AntigravityProvider extends AIProvider {
415
415
  timeoutId = null;
416
416
  }
417
417
 
418
+ // agy has already exited, so a cancel arriving now only makes the abort
419
+ // wiring kill something already dead. Nothing else on this path consults
420
+ // it, so without the checks below a cancelled analysis would settle as a
421
+ // normal result. The signal is read alongside the wiring flag as the
422
+ // source of truth.
423
+ const cancelledDuringExtraction = () =>
424
+ abortWiring.cancelled() || abortSignal?.aborted === true;
425
+
418
426
  (async () => {
419
427
  try {
420
- const llmExtracted = await this.extractJSONWithLLM(stdout, { level, analysisId, registerProcess, logPrefix: levelPrefix });
428
+ // `abortSignal` lets the extraction spawn be killed rather than
429
+ // merely abandoned until its own 60s timeout.
430
+ const llmExtracted = await this.extractJSONWithLLM(stdout, { level, analysisId, registerProcess, logPrefix: levelPrefix, abortSignal });
431
+ if (cancelledDuringExtraction()) {
432
+ logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
433
+ settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
434
+ return;
435
+ }
421
436
  if (llmExtracted.success) {
422
437
  logger.success(`${levelPrefix} LLM extraction fallback succeeded`);
423
438
  settle(resolve, llmExtracted.data);
@@ -427,6 +442,13 @@ class AntigravityProvider extends AIProvider {
427
442
  settle(resolve, { raw: stdout, parsed: false });
428
443
  }
429
444
  } catch (llmError) {
445
+ // An abort that kills the extraction spawn surfaces here as a thrown
446
+ // error; it is a cancellation, not a parse failure.
447
+ if (cancelledDuringExtraction()) {
448
+ logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
449
+ settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
450
+ return;
451
+ }
430
452
  logger.warn(`${levelPrefix} LLM extraction fallback error: ${llmError.message}`);
431
453
  settle(resolve, { raw: stdout, parsed: false });
432
454
  }
@@ -452,7 +474,9 @@ class AntigravityProvider extends AIProvider {
452
474
  agy.stdin.write(prompt, (err) => {
453
475
  if (err) {
454
476
  logger.error(`${levelPrefix} Failed to write prompt to stdin: ${err}`);
455
- agy.kill('SIGTERM');
477
+ // A failed spawn (ENOENT) EPIPEs stdin and lands here with a pidless
478
+ // child; killChildSafely skips the self-directed kill(0).
479
+ killChildSafely(agy, { logPrefix: levelPrefix, shell: this.useShell });
456
480
  settle(reject, new Error(`${levelPrefix} Failed to write prompt to stdin: ${err}`));
457
481
  }
458
482
  });
@@ -535,7 +559,9 @@ class AntigravityProvider extends AIProvider {
535
559
  if (settled) return;
536
560
  settled = true;
537
561
  logger.warn(`Antigravity CLI availability check timed out after ${Math.round(timeoutMs / 1000)}s`);
538
- try { agy.kill(); } catch { /* ignore */ }
562
+ // Not `shell: useShell`: the probe spawn is not `detached`, so
563
+ // group-kill would ESRCH and leave the child running.
564
+ killChildSafely(agy, { logPrefix: '[availability]' });
539
565
  resolve(false);
540
566
  }, timeoutMs);
541
567
 
@@ -3,6 +3,7 @@ const { spawn } = require('child_process');
3
3
  const path = require('path');
4
4
  const logger = require('../utils/logger');
5
5
  const { extractJSON } = require('../utils/json-extractor');
6
+ const { killChildSafely } = require('./abort-signal-wiring');
6
7
 
7
8
  class ClaudeCLI {
8
9
  constructor(model = 'opus') {
@@ -62,10 +63,13 @@ class ClaudeCLI {
62
63
  let timeoutId = null;
63
64
 
64
65
  // Set timeout
66
+ // Not `shell: this.useShell`: this spawn is not `detached`, so there is
67
+ // no process group to signal — group-kill would ESRCH and leave the
68
+ // child running. Plain child.kill, with killChildSafely's pid guard.
65
69
  if (timeout) {
66
70
  timeoutId = setTimeout(() => {
67
71
  logger.error(`${levelPrefix} Process ${pid} timed out after ${timeout}ms`);
68
- claude.kill('SIGTERM');
72
+ killChildSafely(claude, { logPrefix: levelPrefix });
69
73
  reject(new Error(`${levelPrefix} Claude CLI timed out after ${timeout}ms`));
70
74
  }, timeout);
71
75
  }
@@ -135,7 +139,9 @@ class ClaudeCLI {
135
139
  if (err) {
136
140
  logger.error(`${levelPrefix} Failed to write prompt to stdin: ${err}`);
137
141
  if (timeoutId) clearTimeout(timeoutId);
138
- claude.kill('SIGTERM'); // Prevent resource leak
142
+ // A failed spawn (ENOENT) EPIPEs stdin and lands here with a pidless
143
+ // child; killChildSafely skips the self-directed kill(0).
144
+ killChildSafely(claude, { logPrefix: levelPrefix }); // Prevent resource leak
139
145
  reject(new Error(`${levelPrefix} Failed to write prompt to stdin: ${err}`));
140
146
  }
141
147
  });
@@ -12,7 +12,7 @@ const logger = require('../utils/logger');
12
12
  const { extractJSON } = require('../utils/json-extractor');
13
13
  const { CancellationError, isAnalysisCancelled } = require('../routes/shared');
14
14
  const { StreamParser, parseClaudeLine } = require('./stream-parser');
15
- const { wireAbortToChild, makeAbortError } = require('./abort-signal-wiring');
15
+ const { wireAbortToChild, makeAbortError, killChildSafely } = require('./abort-signal-wiring');
16
16
 
17
17
  // Directory containing bin scripts (git-diff-lines, etc.)
18
18
  const BIN_DIR = path.join(__dirname, '..', '..', 'bin');
@@ -428,7 +428,7 @@ class ClaudeProvider extends AIProvider {
428
428
  if (timeout) {
429
429
  timeoutId = setTimeout(() => {
430
430
  logger.error(`${levelPrefix} Process ${pid} timed out after ${timeout}ms`);
431
- claude.kill('SIGTERM');
431
+ killChildSafely(claude, { logPrefix: levelPrefix, shell: this.useShell });
432
432
  settle(reject, new Error(`${levelPrefix} Claude CLI timed out after ${timeout}ms`));
433
433
  }, timeout);
434
434
  }
@@ -543,10 +543,28 @@ class ClaudeProvider extends AIProvider {
543
543
  logger.info(`${levelPrefix} LLM fallback input length: ${llmFallbackInput.length} characters (${parsed.textContent ? 'text content' : 'raw stdout'})`);
544
544
  logger.info(`${levelPrefix} Attempting LLM-based JSON extraction fallback...`);
545
545
 
546
+ // A cancel that lands now still reaches the abort wiring, but the
547
+ // Claude child has already exited — the wiring kills something already
548
+ // dead, and nothing else on this path consults it. Without the checks
549
+ // below a cancelled analysis would settle as a normal result.
550
+ //
551
+ // Reads the signal as well as the wiring flag: `settle` (which detaches
552
+ // the listener) has not run on any path that reaches here, so the flag
553
+ // is live — but the signal is the source of truth.
554
+ const cancelledDuringExtraction = () =>
555
+ abortWiring.cancelled() || abortSignal?.aborted === true;
556
+
546
557
  // Use async IIFE to handle the async LLM extraction
547
558
  (async () => {
548
559
  try {
549
- const llmExtracted = await this.extractJSONWithLLM(llmFallbackInput, { level, analysisId, registerProcess, logPrefix: levelPrefix });
560
+ // `abortSignal` lets the extraction spawn be killed rather than
561
+ // merely abandoned until its own 60s timeout.
562
+ const llmExtracted = await this.extractJSONWithLLM(llmFallbackInput, { level, analysisId, registerProcess, logPrefix: levelPrefix, abortSignal });
563
+ if (cancelledDuringExtraction()) {
564
+ logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
565
+ settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
566
+ return;
567
+ }
550
568
  if (llmExtracted.success) {
551
569
  logger.success(`${levelPrefix} LLM extraction fallback succeeded`);
552
570
  settle(resolve, llmExtracted.data);
@@ -556,6 +574,13 @@ class ClaudeProvider extends AIProvider {
556
574
  settle(resolve, { raw: llmFallbackInput, parsed: false });
557
575
  }
558
576
  } catch (llmError) {
577
+ // An abort that kills the extraction spawn surfaces here as a
578
+ // thrown error; it is a cancellation, not a parse failure.
579
+ if (cancelledDuringExtraction()) {
580
+ logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
581
+ settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
582
+ return;
583
+ }
559
584
  logger.warn(`${levelPrefix} LLM extraction fallback error: ${llmError.message}`);
560
585
  settle(resolve, { raw: llmFallbackInput, parsed: false });
561
586
  }
@@ -584,7 +609,9 @@ class ClaudeProvider extends AIProvider {
584
609
  claude.stdin.write(prompt, (err) => {
585
610
  if (err) {
586
611
  logger.error(`${levelPrefix} Failed to write prompt to stdin: ${err}`);
587
- claude.kill('SIGTERM');
612
+ // A failed spawn (ENOENT) EPIPEs stdin and lands here with a pidless
613
+ // child; killChildSafely skips the self-directed kill(0).
614
+ killChildSafely(claude, { logPrefix: levelPrefix, shell: this.useShell });
588
615
  settle(reject, new Error(`${levelPrefix} Failed to write prompt to stdin: ${err}`));
589
616
  }
590
617
  });
@@ -935,7 +962,9 @@ class ClaudeProvider extends AIProvider {
935
962
  if (settled) return;
936
963
  settled = true;
937
964
  logger.warn(`Claude CLI availability check timed out after ${Math.round(timeoutMs / 1000)}s`);
938
- try { claude.kill(); } catch { /* ignore */ }
965
+ // Not `shell: useShell`: the probe spawn is not `detached`, so
966
+ // group-kill would ESRCH and leave the child running.
967
+ killChildSafely(claude, { logPrefix: '[availability]' });
939
968
  resolve(false);
940
969
  }, timeoutMs);
941
970
 
@@ -13,7 +13,7 @@ const logger = require('../utils/logger');
13
13
  const { extractJSON } = require('../utils/json-extractor');
14
14
  const { CancellationError, isAnalysisCancelled } = require('../routes/shared');
15
15
  const { StreamParser, parseCodexLine } = require('./stream-parser');
16
- const { wireAbortToChild, makeAbortError } = require('./abort-signal-wiring');
16
+ const { wireAbortToChild, makeAbortError, killChildSafely } = require('./abort-signal-wiring');
17
17
 
18
18
  // Directory containing bin scripts (git-diff-lines, etc.)
19
19
  const BIN_DIR = path.join(__dirname, '..', '..', 'bin');
@@ -351,7 +351,7 @@ class CodexProvider extends AIProvider {
351
351
  if (timeout) {
352
352
  timeoutId = setTimeout(() => {
353
353
  logger.error(`${levelPrefix} Process ${pid} timed out after ${timeout}ms`);
354
- codex.kill('SIGTERM');
354
+ killChildSafely(codex, { logPrefix: levelPrefix, shell: this.useShell });
355
355
  settle(reject, new Error(`${levelPrefix} Codex CLI timed out after ${timeout}ms`));
356
356
  }, timeout);
357
357
  }
@@ -455,10 +455,25 @@ class CodexProvider extends AIProvider {
455
455
  logger.info(`${levelPrefix} LLM fallback input length: ${llmFallbackInput.length} characters (${parsed.textContent ? 'text content' : 'raw stdout'})`);
456
456
  logger.info(`${levelPrefix} Attempting LLM-based JSON extraction fallback...`);
457
457
 
458
+ // The Codex child has already exited, so a cancel arriving now only
459
+ // makes the abort wiring kill something already dead. Nothing else on
460
+ // this path consults it, so without the checks below a cancelled
461
+ // analysis would settle as a normal result. The signal is read
462
+ // alongside the wiring flag as the source of truth.
463
+ const cancelledDuringExtraction = () =>
464
+ abortWiring.cancelled() || abortSignal?.aborted === true;
465
+
458
466
  // Use async IIFE to handle the async LLM extraction
459
467
  (async () => {
460
468
  try {
461
- const llmExtracted = await this.extractJSONWithLLM(llmFallbackInput, { level, analysisId, registerProcess, logPrefix: levelPrefix });
469
+ // `abortSignal` lets the extraction spawn be killed rather than
470
+ // merely abandoned until its own 60s timeout.
471
+ const llmExtracted = await this.extractJSONWithLLM(llmFallbackInput, { level, analysisId, registerProcess, logPrefix: levelPrefix, abortSignal });
472
+ if (cancelledDuringExtraction()) {
473
+ logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
474
+ settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
475
+ return;
476
+ }
462
477
  if (llmExtracted.success) {
463
478
  logger.success(`${levelPrefix} LLM extraction fallback succeeded`);
464
479
  settle(resolve, llmExtracted.data);
@@ -468,6 +483,13 @@ class CodexProvider extends AIProvider {
468
483
  settle(resolve, { raw: llmFallbackInput, parsed: false });
469
484
  }
470
485
  } catch (llmError) {
486
+ // An abort that kills the extraction spawn surfaces here as a
487
+ // thrown error; it is a cancellation, not a parse failure.
488
+ if (cancelledDuringExtraction()) {
489
+ logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
490
+ settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
491
+ return;
492
+ }
471
493
  logger.warn(`${levelPrefix} LLM extraction fallback error: ${llmError.message}`);
472
494
  settle(resolve, { raw: llmFallbackInput, parsed: false });
473
495
  }
@@ -496,7 +518,9 @@ class CodexProvider extends AIProvider {
496
518
  codex.stdin.write(prompt, (err) => {
497
519
  if (err) {
498
520
  logger.error(`${levelPrefix} Failed to write prompt to stdin: ${err}`);
499
- codex.kill('SIGTERM');
521
+ // A failed spawn (ENOENT) EPIPEs stdin and lands here with a pidless
522
+ // child; killChildSafely skips the self-directed kill(0).
523
+ killChildSafely(codex, { logPrefix: levelPrefix, shell: this.useShell });
500
524
  settle(reject, new Error(`${levelPrefix} Failed to write prompt to stdin: ${err}`));
501
525
  }
502
526
  });
@@ -844,7 +868,9 @@ class CodexProvider extends AIProvider {
844
868
  if (settled) return;
845
869
  settled = true;
846
870
  logger.warn(`Codex CLI availability check timed out after ${Math.round(timeoutMs / 1000)}s`);
847
- try { codex.kill(); } catch { /* ignore */ }
871
+ // Not `shell: useShell`: the probe spawn is not `detached`, so
872
+ // group-kill would ESRCH and leave the child running.
873
+ killChildSafely(codex, { logPrefix: '[availability]' });
848
874
  resolve(false);
849
875
  }, timeoutMs);
850
876
 
@@ -12,7 +12,7 @@ const { AIProvider, registerProvider, quoteShellArgs } = require('./provider');
12
12
  const logger = require('../utils/logger');
13
13
  const { extractJSON } = require('../utils/json-extractor');
14
14
  const { CancellationError, isAnalysisCancelled } = require('../routes/shared');
15
- const { wireAbortToChild, makeAbortError } = require('./abort-signal-wiring');
15
+ const { wireAbortToChild, makeAbortError, killChildSafely } = require('./abort-signal-wiring');
16
16
 
17
17
  // Directory containing bin scripts (git-diff-lines, etc.)
18
18
  const BIN_DIR = path.join(__dirname, '..', '..', 'bin');
@@ -286,7 +286,7 @@ class CopilotProvider extends AIProvider {
286
286
  if (timeout) {
287
287
  timeoutId = setTimeout(() => {
288
288
  logger.error(`${levelPrefix} Process ${pid} timed out after ${timeout}ms`);
289
- copilot.kill('SIGTERM');
289
+ killChildSafely(copilot, { logPrefix: levelPrefix, shell: this.useShell });
290
290
  settle(reject, new Error(`${levelPrefix} Copilot CLI timed out after ${timeout}ms`));
291
291
  }, timeout);
292
292
  }
@@ -348,10 +348,25 @@ class CopilotProvider extends AIProvider {
348
348
  logger.info(`${levelPrefix} Raw response length: ${stdout.length} characters`);
349
349
  logger.info(`${levelPrefix} Attempting LLM-based JSON extraction fallback...`);
350
350
 
351
+ // The Copilot child has already exited, so a cancel arriving now only
352
+ // makes the abort wiring kill something already dead. Nothing else on
353
+ // this path consults it, so without the checks below a cancelled
354
+ // analysis would settle as a normal result. The signal is read
355
+ // alongside the wiring flag as the source of truth.
356
+ const cancelledDuringExtraction = () =>
357
+ abortWiring.cancelled() || abortSignal?.aborted === true;
358
+
351
359
  // Use async IIFE to handle the async LLM extraction
352
360
  (async () => {
353
361
  try {
354
- const llmExtracted = await this.extractJSONWithLLM(stdout, { level, analysisId, registerProcess, logPrefix: levelPrefix });
362
+ // `abortSignal` lets the extraction spawn be killed rather than
363
+ // merely abandoned until its own 60s timeout.
364
+ const llmExtracted = await this.extractJSONWithLLM(stdout, { level, analysisId, registerProcess, logPrefix: levelPrefix, abortSignal });
365
+ if (cancelledDuringExtraction()) {
366
+ logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
367
+ settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
368
+ return;
369
+ }
355
370
  if (llmExtracted.success) {
356
371
  logger.success(`${levelPrefix} LLM extraction fallback succeeded`);
357
372
  settle(resolve, llmExtracted.data);
@@ -361,6 +376,13 @@ class CopilotProvider extends AIProvider {
361
376
  settle(resolve, { raw: stdout, parsed: false });
362
377
  }
363
378
  } catch (llmError) {
379
+ // An abort that kills the extraction spawn surfaces here as a
380
+ // thrown error; it is a cancellation, not a parse failure.
381
+ if (cancelledDuringExtraction()) {
382
+ logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
383
+ settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
384
+ return;
385
+ }
364
386
  logger.warn(`${levelPrefix} LLM extraction fallback error: ${llmError.message}`);
365
387
  settle(resolve, { raw: stdout, parsed: false });
366
388
  }
@@ -473,7 +495,9 @@ class CopilotProvider extends AIProvider {
473
495
  if (settled) return;
474
496
  settled = true;
475
497
  logger.warn(`Copilot CLI availability check timed out after ${Math.round(timeoutMs / 1000)}s`);
476
- try { copilot.kill(); } catch { /* ignore */ }
498
+ // Not `shell: useShell`: the probe spawn is not `detached`, so
499
+ // group-kill would ESRCH and leave the child running.
500
+ killChildSafely(copilot, { logPrefix: '[availability]' });
477
501
  resolve(false);
478
502
  }, timeoutMs);
479
503