@in-the-loop-labs/pair-review 5.0.3 → 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.
@@ -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 };
@@ -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
 
@@ -21,7 +21,7 @@ const logger = require('../utils/logger');
21
21
  const { extractJSON } = require('../utils/json-extractor');
22
22
  const { CancellationError, isAnalysisCancelled } = require('../routes/shared');
23
23
  const { StreamParser, parseCursorAgentLine } = require('./stream-parser');
24
- const { wireAbortToChild, makeAbortError } = require('./abort-signal-wiring');
24
+ const { wireAbortToChild, makeAbortError, killChildSafely } = require('./abort-signal-wiring');
25
25
 
26
26
  // Directory containing bin scripts (git-diff-lines, etc.)
27
27
  const BIN_DIR = path.join(__dirname, '..', '..', 'bin');
@@ -316,7 +316,7 @@ class CursorAgentProvider extends AIProvider {
316
316
  if (timeout) {
317
317
  timeoutId = setTimeout(() => {
318
318
  logger.error(`${levelPrefix} Process ${pid} timed out after ${timeout}ms`);
319
- agent.kill('SIGTERM');
319
+ killChildSafely(agent, { logPrefix: levelPrefix, shell: this.useShell });
320
320
  settle(reject, new Error(`${levelPrefix} Cursor Agent CLI timed out after ${timeout}ms`));
321
321
  }, timeout);
322
322
  }
@@ -420,6 +420,15 @@ class CursorAgentProvider extends AIProvider {
420
420
  logger.info(`${levelPrefix} LLM fallback input length: ${llmFallbackInput.length} characters (${parsed.textContent ? 'text content' : 'raw stdout'})`);
421
421
  logger.info(`${levelPrefix} Attempting LLM-based JSON extraction fallback...`);
422
422
 
423
+ // The agent child has already exited, so a cancel arriving now only
424
+ // makes the abort wiring kill something already dead. The `settled`
425
+ // guard below only covers a cancel that landed BEFORE the await, so
426
+ // without the checks below one landing during extraction would settle
427
+ // as a normal result. The signal is read alongside the wiring flag as
428
+ // the source of truth.
429
+ const cancelledDuringExtraction = () =>
430
+ abortWiring.cancelled() || abortSignal?.aborted === true;
431
+
423
432
  // Use async IIFE to handle the async LLM extraction
424
433
  (async () => {
425
434
  try {
@@ -427,7 +436,14 @@ class CursorAgentProvider extends AIProvider {
427
436
  // orphan processes if timeout fired between close-handler entry
428
437
  // and reaching this point.
429
438
  if (settled) return;
430
- const llmExtracted = await this.extractJSONWithLLM(llmFallbackInput, { level, analysisId, registerProcess, logPrefix: levelPrefix });
439
+ // `abortSignal` lets the extraction spawn be killed rather than
440
+ // merely abandoned until its own 60s timeout.
441
+ const llmExtracted = await this.extractJSONWithLLM(llmFallbackInput, { level, analysisId, registerProcess, logPrefix: levelPrefix, abortSignal });
442
+ if (cancelledDuringExtraction()) {
443
+ logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
444
+ settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
445
+ return;
446
+ }
431
447
  if (llmExtracted.success) {
432
448
  logger.success(`${levelPrefix} LLM extraction fallback succeeded`);
433
449
  settle(resolve, llmExtracted.data);
@@ -437,6 +453,13 @@ class CursorAgentProvider extends AIProvider {
437
453
  settle(resolve, { raw: llmFallbackInput, parsed: false });
438
454
  }
439
455
  } catch (llmError) {
456
+ // An abort that kills the extraction spawn surfaces here as a
457
+ // thrown error; it is a cancellation, not a parse failure.
458
+ if (cancelledDuringExtraction()) {
459
+ logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
460
+ settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
461
+ return;
462
+ }
440
463
  logger.warn(`${levelPrefix} LLM extraction fallback error: ${llmError.message}`);
441
464
  settle(resolve, { raw: llmFallbackInput, parsed: false });
442
465
  }
@@ -465,7 +488,9 @@ class CursorAgentProvider extends AIProvider {
465
488
  agent.stdin.write(prompt, (err) => {
466
489
  if (err) {
467
490
  logger.error(`${levelPrefix} Failed to write prompt to stdin: ${err}`);
468
- agent.kill('SIGTERM');
491
+ // A failed spawn (ENOENT) EPIPEs stdin and lands here with a pidless
492
+ // child; killChildSafely skips the self-directed kill(0).
493
+ killChildSafely(agent, { logPrefix: levelPrefix, shell: this.useShell });
469
494
  settle(reject, new Error(`${levelPrefix} Failed to write prompt to stdin: ${err}`));
470
495
  }
471
496
  });
@@ -815,7 +840,9 @@ class CursorAgentProvider extends AIProvider {
815
840
  if (settled) return;
816
841
  settled = true;
817
842
  logger.warn(`Cursor Agent CLI availability check timed out after ${Math.round(timeoutMs / 1000)}s`);
818
- try { agent.kill(); } catch { /* ignore */ }
843
+ // Not `shell: useShell`: the probe spawn is not `detached`, so
844
+ // group-kill would ESRCH and leave the child running.
845
+ killChildSafely(agent, { logPrefix: '[availability]' });
819
846
  resolve(false);
820
847
  }, timeoutMs);
821
848
 
@@ -18,6 +18,7 @@ const { glob } = require('glob');
18
18
  const fs = require('fs').promises;
19
19
  const path = require('path');
20
20
  const logger = require('../utils/logger');
21
+ const { killChildSafely } = require('./abort-signal-wiring');
21
22
  const jsonExtractor = require('../utils/json-extractor');
22
23
  const configModule = require('../config');
23
24
 
@@ -266,7 +267,10 @@ function createExecutableProviderClass(id, config) {
266
267
  if (stderr.trim()) {
267
268
  logger.warn(`[${id}] stderr before timeout: ${stderr.trim().slice(0, 2000)}`);
268
269
  }
269
- child.kill('SIGTERM');
270
+ // Not `shell: this.useShell`: this spawn is not `detached`, so
271
+ // group-kill would ESRCH and leave the child running — and it
272
+ // would bypass the kill wrapper above that records `cancelled`.
273
+ killChildSafely(child, { logPrefix: `[${id}]` });
270
274
  }, timeout);
271
275
  }
272
276
 
@@ -480,7 +484,9 @@ function createExecutableProviderClass(id, config) {
480
484
  if (settled) return;
481
485
  settled = true;
482
486
  logger.warn(`${id} availability check timed out after ${Math.round(timeoutMs / 1000)}s`);
483
- try { child.kill(); } catch { /* ignore */ }
487
+ // Not `shell: true` (as spawned): the probe is not `detached`, so
488
+ // group-kill would ESRCH and leave the child running.
489
+ killChildSafely(child, { logPrefix: `[${id}]` });
484
490
  resolve(false);
485
491
  }, timeoutMs);
486
492
 
package/src/ai/index.js CHANGED
@@ -55,6 +55,7 @@ require('./copilot-provider');
55
55
  require('./opencode-provider');
56
56
  require('./cursor-agent-provider');
57
57
  require('./pi-provider');
58
+ require('./muse-provider');
58
59
 
59
60
  // Export the unified API
60
61
  module.exports = {