@in-the-loop-labs/pair-review 5.0.3 → 5.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +26 -3
  2. package/package.json +4 -3
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
  5. package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
  6. package/plugin-pair-loop/skills/loop/SKILL.md +21 -6
  7. package/public/css/pr.css +2 -2
  8. package/public/js/vendor/pierre-diffs-worker.js +3446 -5992
  9. package/public/js/vendor/pierre-diffs.js +731 -1047
  10. package/src/ai/abort-signal-wiring.js +91 -46
  11. package/src/ai/analyzer.js +191 -27
  12. package/src/ai/antigravity-provider.js +31 -5
  13. package/src/ai/claude-cli.js +8 -2
  14. package/src/ai/claude-provider.js +34 -5
  15. package/src/ai/codex-provider.js +31 -5
  16. package/src/ai/copilot-provider.js +28 -4
  17. package/src/ai/cursor-agent-provider.js +32 -5
  18. package/src/ai/executable-provider.js +8 -2
  19. package/src/ai/index.js +1 -0
  20. package/src/ai/muse-provider.js +1224 -0
  21. package/src/ai/opencode-provider.js +31 -5
  22. package/src/ai/pi-provider.js +29 -4
  23. package/src/ai/provider.js +111 -28
  24. package/src/ai/stream-parser.js +71 -0
  25. package/src/config.js +35 -2
  26. package/src/database.js +96 -16
  27. package/src/git/fetch-helpers.js +48 -0
  28. package/src/git/pack-cleanup.js +120 -0
  29. package/src/git/worktree.js +65 -43
  30. package/src/main.js +176 -27
  31. package/src/routes/analyses.js +6 -2
  32. package/src/routes/local.js +6 -5
  33. package/src/routes/mcp.js +5 -2
  34. package/src/routes/pr.js +8 -7
  35. package/src/routes/shared.js +27 -0
  36. package/src/routes/stack-analysis.js +4 -1
  37. package/src/utils/json-extractor.js +162 -41
@@ -0,0 +1,1224 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Muse AI Provider
4
+ *
5
+ * Implements the AI provider interface for Meta's Muse Code CLI.
6
+ * Uses the `muse exec` command for non-interactive (headless) execution.
7
+ */
8
+
9
+ const path = require('path');
10
+ const os = require('os');
11
+ const fs = require('fs');
12
+ const { spawn } = require('child_process');
13
+ const { AIProvider, registerProvider, quoteShellArgs } = require('./provider');
14
+ const logger = require('../utils/logger');
15
+ const { extractJSON } = require('../utils/json-extractor');
16
+ const { CancellationError, isAnalysisCancelled } = require('../routes/shared');
17
+ const { StreamParser, parseMuseLine } = require('./stream-parser');
18
+ const { wireAbortToChild, makeAbortError, killChildSafely } = require('./abort-signal-wiring');
19
+
20
+ // Directory containing bin scripts (git-diff-lines, etc.)
21
+ const BIN_DIR = path.join(__dirname, '..', '..', 'bin');
22
+
23
+ /**
24
+ * Split a configured command string into argv words so a multi-word command
25
+ * (`docker exec container muse`, `devx muse --`) can be spawned WITHOUT a shell.
26
+ *
27
+ * Only quote grouping is honoured — enough for a path containing spaces
28
+ * (`"/Applications/My Tools/muse"`). Shell expansions (`~`, `$VAR`, pipes,
29
+ * `VAR=x` prefixes) are NOT interpreted; a command needing those must already be
30
+ * a wrapper script, since single-word commands never went through a shell either.
31
+ *
32
+ * The configured command names the muse BINARY only — never muse's `exec`
33
+ * subcommand, which the provider supplies itself (see stripExecSubcommand).
34
+ *
35
+ * Empty words are dropped rather than emitted: `foo "" bar` yields
36
+ * `['foo', 'bar']`, because an empty argv element would reach muse as an empty
37
+ * positional prompt (and `""` alone would become `spawn('')`). `current` cannot
38
+ * distinguish "a quoted empty token" from "no token accumulated yet" — both are
39
+ * the empty string — so emptiness is the only thing that decides, and the old
40
+ * `started` flag (set by an opening quote) is gone.
41
+ *
42
+ * @param {string} command - Raw command string from env/config
43
+ * @returns {string[]} argv words; never empty and never containing an empty word
44
+ * @throws {Error} on an unterminated quote, or when nothing but quotes and
45
+ * whitespace was supplied. Both are unrunnable, and a named error beats
46
+ * spawning `''` or silently gluing `foo "bar baz` into one nonexistent
47
+ * command name.
48
+ */
49
+ function splitCommandWords(command) {
50
+ const words = [];
51
+ let current = '';
52
+ let quote = null;
53
+
54
+ const flush = () => {
55
+ if (current) words.push(current);
56
+ current = '';
57
+ };
58
+
59
+ for (const ch of command) {
60
+ if (quote) {
61
+ if (ch === quote) quote = null;
62
+ else current += ch;
63
+ continue;
64
+ }
65
+ if (ch === '"' || ch === "'") {
66
+ quote = ch;
67
+ continue;
68
+ }
69
+ if (/\s/.test(ch)) {
70
+ flush();
71
+ continue;
72
+ }
73
+ current += ch;
74
+ }
75
+
76
+ if (quote) {
77
+ throw new Error(
78
+ `Muse command has an unterminated ${quote === '"' ? 'double' : 'single'} quote: ${command}`
79
+ );
80
+ }
81
+ flush();
82
+
83
+ if (words.length === 0) {
84
+ throw new Error(`Muse command is empty: ${JSON.stringify(command)}`);
85
+ }
86
+ return words;
87
+ }
88
+
89
+ /**
90
+ * Drop muse's `exec` subcommand from a configured command string.
91
+ *
92
+ * The provider supplies `exec` itself — in `baseArgs` for the analysis path and
93
+ * in `buildArgsForModel` for extraction — so a command configured as
94
+ * `muse exec` would spawn `muse exec exec --json …` on BOTH paths, which muse
95
+ * rejects. Normalizing here (rather than at each spawn site) is what keeps the
96
+ * two paths consistent, and it runs before `useShell` is derived so a stripped
97
+ * `muse exec` also stops needlessly going through a shell.
98
+ *
99
+ * DECISION — strip and warn, rather than only documenting "don't do that":
100
+ * `<cmd> exec exec` has no valid meaning, so nothing is lost by removing it,
101
+ * and the warning still tells the user their config is wrong. Nothing is
102
+ * swallowed silently.
103
+ *
104
+ * This cannot damage a `docker exec`-style wrapper. Only a bare, unquoted,
105
+ * TRAILING `exec` is removed, and a container-exec invocation can never end
106
+ * with `exec` — the container and the command to run must follow it, so
107
+ * `docker exec container muse` and `kubectl exec -it pod -- muse` both end at
108
+ * the muse binary and are left untouched. A quoted trailing token
109
+ * (`"/opt/my exec"`) ends with the quote character, so the pattern cannot match
110
+ * inside quotes either.
111
+ *
112
+ * @param {string} command - Trimmed command string from env/config
113
+ * @returns {string} The command without a trailing `exec` subcommand
114
+ */
115
+ function stripExecSubcommand(command) {
116
+ const stripped = command.replace(/\s+exec\s*$/, '');
117
+ if (stripped !== command) {
118
+ logger.warn(
119
+ `Muse command "${command}" ends with the \`exec\` subcommand, which pair-review adds itself; ` +
120
+ `using "${stripped}". Configure the muse binary only, with no subcommand.`
121
+ );
122
+ }
123
+ return stripped;
124
+ }
125
+
126
+ /**
127
+ * The attempt a Muse record belongs to — one `muse exec` run.
128
+ *
129
+ * Verified against real `muse exec --json` stdout (Muse Code 0.1.0): every
130
+ * record of a run carries the same command UUID in three places — top-level
131
+ * `causation_id`, `payload.command_id`, and `payload.run_stream.id` (whose
132
+ * `kind` is `"run"`). A resumed or retried run is a new `turn.submit` command,
133
+ * so it gets a new UUID and every one of those fields changes with it.
134
+ *
135
+ * Deliberately NOT the top-level `stream`: on stdout that is the SESSION stream
136
+ * (`{kind: "session", id: …}`) and is identical for every attempt, so scoping by
137
+ * it would scope to nothing. `sequence` is likewise session-scoped and
138
+ * monotonic across attempts — it orders records but never delimits them.
139
+ *
140
+ * Reading all three fields is belt-and-braces against a future record that
141
+ * carries only one of them; older fixtures carrying none yield null, which
142
+ * callers treat as a single unnamed attempt.
143
+ *
144
+ * @param {Object} record - A parsed Muse JSONL record
145
+ * @returns {string|null} Attempt identifier, or null when the record names none
146
+ */
147
+ function attemptIdOf(record) {
148
+ const payload = record?.payload;
149
+ return payload?.run_stream?.id || payload?.command_id || record?.causation_id || null;
150
+ }
151
+
152
+ /**
153
+ * The provider's default model.
154
+ *
155
+ * DELIBERATE: this is the NON-contributor model, even though the muse CLI's own
156
+ * default is `muse-spark-1.2-contributor`. Pair-review sends potentially
157
+ * proprietary source code to the model, and the contributor tier is discounted
158
+ * precisely because Meta may use that content for product improvement. Opting
159
+ * into data sharing must be an explicit user choice, never a silent default.
160
+ */
161
+ const DEFAULT_MUSE_MODEL = 'muse-spark-1.2-high';
162
+
163
+ /**
164
+ * Muse model definitions with tier mappings.
165
+ *
166
+ * Muse exposes exactly two real CLI model IDs; everything below is a
167
+ * reasoning-effort variant over those two, using the same `cli_model` +
168
+ * `extra_args` pattern as the Codex provider:
169
+ * - muse-spark-1.2 — $1.25/$4.25 per MTok, ~1M context, 256k max output
170
+ * - muse-spark-1.2-contributor — $0.10/$0.20 per MTok, discounted because
171
+ * submitted content may be used by Meta for product improvement
172
+ *
173
+ * `--reasoning-effort` accepts none|minimal|low|medium|high|xhigh|ultra
174
+ * (muse's own default is `high`).
175
+ *
176
+ * Ordering matters: each reasoning effort is listed as a non-contributor entry
177
+ * followed by its contributor twin, so that getFastTierModel() — which picks the
178
+ * FIRST `fast` model — selects the non-data-sharing model for auxiliary work
179
+ * like JSON extraction. Never put a contributor entry ahead of its twin.
180
+ */
181
+ const MUSE_MODELS = [
182
+ {
183
+ id: 'muse-spark-1.2-ultra',
184
+ cli_model: 'muse-spark-1.2',
185
+ extra_args: ['--reasoning-effort', 'ultra'],
186
+ name: 'Muse Spark 1.2 Ultra',
187
+ tier: 'thorough',
188
+ tagline: 'Maximum Depth',
189
+ description: 'Muse Spark at the highest reasoning effort for the hardest reviews: architecture, concurrency, and security-sensitive changes.',
190
+ badge: 'Max Reasoning',
191
+ badgeClass: 'badge-power'
192
+ },
193
+ {
194
+ id: 'muse-spark-1.2-contributor-ultra',
195
+ cli_model: 'muse-spark-1.2-contributor',
196
+ extra_args: ['--reasoning-effort', 'ultra'],
197
+ name: 'Muse Spark 1.2 Contributor Ultra',
198
+ tier: 'thorough',
199
+ tagline: 'Discounted Depth',
200
+ description: 'Same model and highest reasoning effort at roughly a tenth of the cost. Content you send on this tier may be used by Meta for product improvement—do not select it for proprietary code.',
201
+ badge: 'Shares Data',
202
+ badgeClass: 'badge-power'
203
+ },
204
+ {
205
+ id: 'muse-spark-1.2-xhigh',
206
+ cli_model: 'muse-spark-1.2',
207
+ extra_args: ['--reasoning-effort', 'xhigh'],
208
+ name: 'Muse Spark 1.2 XHigh',
209
+ tier: 'thorough',
210
+ tagline: 'Frontier Depth',
211
+ description: 'Muse Spark with extra-high reasoning effort for difficult architectural reviews and subtle behavioral regressions.',
212
+ badge: 'Extra High',
213
+ badgeClass: 'badge-power'
214
+ },
215
+ {
216
+ id: 'muse-spark-1.2-contributor-xhigh',
217
+ cli_model: 'muse-spark-1.2-contributor',
218
+ extra_args: ['--reasoning-effort', 'xhigh'],
219
+ name: 'Muse Spark 1.2 Contributor XHigh',
220
+ tier: 'thorough',
221
+ tagline: 'Discounted Frontier',
222
+ description: 'Same model and extra-high reasoning effort at roughly a tenth of the cost. Content you send on this tier may be used by Meta for product improvement—do not select it for proprietary code.',
223
+ badge: 'Shares Data',
224
+ badgeClass: 'badge-power'
225
+ },
226
+ {
227
+ id: 'muse-spark-1.2-high',
228
+ // Aliases keep results/councils saved under a bare model ID resolving here.
229
+ aliases: ['muse-spark-1.2', 'muse-spark'],
230
+ cli_model: 'muse-spark-1.2',
231
+ extra_args: ['--reasoning-effort', 'high'],
232
+ name: 'Muse Spark 1.2 High',
233
+ tier: 'balanced',
234
+ tagline: 'Best Balance',
235
+ description: 'Meta\'s coding model with high reasoning effort and roughly 1M tokens of context—strong everyday PR review across large diffs.',
236
+ badge: 'Recommended',
237
+ badgeClass: 'badge-recommended',
238
+ default: true
239
+ },
240
+ {
241
+ id: 'muse-spark-1.2-contributor-high',
242
+ aliases: ['muse-spark-1.2-contributor'],
243
+ cli_model: 'muse-spark-1.2-contributor',
244
+ extra_args: ['--reasoning-effort', 'high'],
245
+ name: 'Muse Spark 1.2 Contributor High',
246
+ tier: 'balanced',
247
+ tagline: 'Discounted Tier',
248
+ description: 'Same model and high reasoning effort at roughly a tenth of the cost. Content you send on this tier may be used by Meta for product improvement—do not select it for proprietary code.',
249
+ badge: 'Shares Data',
250
+ badgeClass: 'badge-balanced'
251
+ },
252
+ {
253
+ id: 'muse-spark-1.2-low',
254
+ cli_model: 'muse-spark-1.2',
255
+ extra_args: ['--reasoning-effort', 'low'],
256
+ name: 'Muse Spark 1.2 Low',
257
+ tier: 'fast',
258
+ tagline: 'Quick Pass',
259
+ description: 'Muse Spark with low reasoning effort for fast surface scans of small, straightforward changes.',
260
+ badge: 'Fastest',
261
+ badgeClass: 'badge-speed'
262
+ },
263
+ {
264
+ id: 'muse-spark-1.2-contributor-low',
265
+ cli_model: 'muse-spark-1.2-contributor',
266
+ extra_args: ['--reasoning-effort', 'low'],
267
+ name: 'Muse Spark 1.2 Contributor Low',
268
+ tier: 'fast',
269
+ tagline: 'Lowest Cost',
270
+ description: 'The cheapest option: low reasoning effort on the discounted tier. Content you send on this tier may be used by Meta for product improvement—do not select it for proprietary code.',
271
+ badge: 'Shares Data',
272
+ badgeClass: 'badge-speed'
273
+ }
274
+ ];
275
+
276
+ class MuseProvider extends AIProvider {
277
+ /**
278
+ * @param {string} model - Model identifier
279
+ * @param {Object} configOverrides - Config overrides from providers config
280
+ * @param {string} configOverrides.command - Custom CLI command
281
+ * @param {string[]} configOverrides.extra_args - Additional CLI arguments (appended)
282
+ * @param {Object} configOverrides.env - Additional environment variables
283
+ * @param {Object[]} configOverrides.models - Custom model definitions
284
+ * @param {boolean} configOverrides.yolo - Bypass approval and sandbox
285
+ */
286
+ constructor(model = DEFAULT_MUSE_MODEL, configOverrides = {}) {
287
+ super(model);
288
+
289
+ // Command precedence: ENV > config > default. A blank or whitespace-only
290
+ // override is treated as absent rather than passed on as an unspawnable
291
+ // command name.
292
+ const envCmd = process.env.PAIR_REVIEW_MUSE_CMD;
293
+ const configCmd = configOverrides.command;
294
+ const rawCmd = [envCmd, configCmd]
295
+ .map(c => (typeof c === 'string' ? c.trim() : ''))
296
+ .find(c => c) || 'muse';
297
+
298
+ // Normalize once, here, so the analysis path (baseArgs) and the extraction
299
+ // path (buildArgsForModel) can never disagree about whether `exec` is
300
+ // already present, and so `useShell` below is derived from the real command.
301
+ const museCmd = stripExecSubcommand(rawCmd);
302
+
303
+ // Store for use in execute, getExtractionConfig and testAvailability
304
+ this.museCmd = museCmd;
305
+ this.configOverrides = configOverrides;
306
+
307
+ // For multi-word commands, use shell mode (same pattern as Claude/Codex)
308
+ this.useShell = museCmd.includes(' ');
309
+
310
+ // SECURITY: Muse approval and sandbox flags
311
+ //
312
+ // `muse exec` is already headless, and with DEFAULT flags its tools are
313
+ // auto-approved by policy (side_effect_intent records report
314
+ // policy_decision: "allow:policy") — nothing blocks waiting for input.
315
+ // So the non-yolo path passes NO approval or sandbox flags at all.
316
+ //
317
+ // Do NOT add `--approval-mode never`: it DENIES every tool rather than
318
+ // auto-approving, so no tool runs and the process never emits a terminal
319
+ // record. `--yolo` is muse's documented "disable approval and sandbox and
320
+ // trust this workspace" switch and is the equivalent of Claude's
321
+ // --dangerously-skip-permissions.
322
+ //
323
+ // `--disable-write` blocks the write_file tool. It is defense in depth, not
324
+ // a guarantee: it only covers NON-shell writes, and review analysis needs
325
+ // shell so the model can run grep/find and the bundled git-diff-lines
326
+ // helper. A determined model can still write via bash. Blocking that would
327
+ // require `--disable-shell`, which also disables git-diff-lines and Level 3
328
+ // codebase exploration — the same tradeoff Codex documents for its
329
+ // workspace-write sandbox. Verified empirically: with `--disable-write`
330
+ // alone the model falls back to bash and the write succeeds; adding
331
+ // `--disable-shell` blocks it. See the writeBlockKnownLimitation note in
332
+ // scripts/verify-ai-permissions.js.
333
+ const safetyArgs = configOverrides.yolo ? ['--yolo'] : ['--disable-write'];
334
+
335
+ // Resolve cli_model + extra_args + env from built-in model, provider config,
336
+ // and per-model config. This is what lets reasoning variants like
337
+ // muse-spark-1.2-ultra pass `--model muse-spark-1.2` plus
338
+ // `--reasoning-effort ultra`.
339
+ const { cliModel, extraArgs, env } = this._resolveModelConfig(model);
340
+
341
+ // A cli_model of explicitly `null` omits --model entirely, letting muse pick
342
+ // its own default (Codex convention).
343
+ const modelArgs = cliModel === null ? [] : ['--model', cliModel];
344
+
345
+ this.extraEnv = env;
346
+
347
+ // Everything up to (but excluding) the `--prompt-file <path>` pair, which is
348
+ // appended in execute() once the temp file exists. Keeping the pair strictly
349
+ // last means no extra_args can displace the prompt.
350
+ //
351
+ // `extraArgs` is already the three-way merge (built-in model → provider
352
+ // config → per-model config) performed by _resolveModelConfig, so provider
353
+ // extra_args must NOT be spliced in again here.
354
+ this.baseArgs = ['exec', '--json', ...modelArgs, ...safetyArgs, ...extraArgs];
355
+ }
356
+
357
+ /**
358
+ * Resolve model configuration by looking up built-in and config override definitions.
359
+ * Produces the CLI model ID (for `--model`), merged extra_args, and merged env.
360
+ *
361
+ * Precedence for cli_model: config model > built-in model > modelId.
362
+ *
363
+ * @param {string} modelId
364
+ * @returns {{ builtIn: Object|undefined, configModel: Object|undefined, cliModel: string|null, extraArgs: string[], env: Object }}
365
+ * @private
366
+ */
367
+ _resolveModelConfig(modelId) {
368
+ const configOverrides = this.configOverrides || {};
369
+
370
+ const builtIn = MUSE_MODELS.find(m => m.id === modelId || (m.aliases && m.aliases.includes(modelId)));
371
+ const configModel = configOverrides.models?.find(m => m.id === modelId);
372
+
373
+ const cliModel = configModel?.cli_model !== undefined
374
+ ? configModel.cli_model
375
+ : (builtIn?.cli_model !== undefined ? builtIn.cli_model : modelId);
376
+
377
+ // Three-way merge for extra_args: built-in model → provider config → per-model config
378
+ const builtInArgs = builtIn?.extra_args || [];
379
+ const providerArgs = configOverrides.extra_args || [];
380
+ const configModelArgs = configModel?.extra_args || [];
381
+ const extraArgs = [...builtInArgs, ...providerArgs, ...configModelArgs];
382
+
383
+ // Three-way merge for env: built-in model → provider config → per-model config
384
+ const env = {
385
+ ...(builtIn?.env || {}),
386
+ ...(configOverrides.env || {}),
387
+ ...(configModel?.env || {})
388
+ };
389
+
390
+ return { builtIn, configModel, cliModel, extraArgs, env };
391
+ }
392
+
393
+ /**
394
+ * Build the command/args the ANALYSIS path spawns, wrapping for shell mode.
395
+ *
396
+ * `execute()` is the only other caller and routes through here, so an external
397
+ * inspector — notably scripts/verify-ai-permissions.js, which must exercise the
398
+ * real analysis invocation to make its findings meaningful — cannot drift from
399
+ * what actually runs. Do NOT reconstruct the invocation from
400
+ * getExtractionConfig(): that describes the JSON-extraction fallback, which is
401
+ * free to adopt a different tool/safety posture.
402
+ *
403
+ * @param {string[]} [trailingArgs=[]] - Args appended after baseArgs. execute()
404
+ * passes `['--prompt-file', <tmp path>]`; callers without a per-run temp file
405
+ * can pass the prompt as a single positional instead, since
406
+ * `muse exec [OPTIONS] [PROMPT]` accepts one and never reads stdin.
407
+ * @returns {{command: string, args: string[], useShell: boolean}}
408
+ */
409
+ getAnalysisSpawnConfig(trailingArgs = []) {
410
+ const args = [...this.baseArgs, ...trailingArgs];
411
+
412
+ if (this.useShell) {
413
+ return {
414
+ command: `${this.museCmd} ${quoteShellArgs(args).join(' ')}`,
415
+ args: [],
416
+ useShell: true
417
+ };
418
+ }
419
+ return { command: this.museCmd, args, useShell: false };
420
+ }
421
+
422
+ /**
423
+ * Execute Muse CLI with a prompt
424
+ * @param {string} prompt - The prompt to send to Muse
425
+ * @param {Object} options - Optional configuration
426
+ * @returns {Promise<Object>} Parsed response or error
427
+ */
428
+ async execute(prompt, options = {}) {
429
+ return new Promise((resolve, reject) => {
430
+ const { cwd = process.cwd(), timeout = 300000, level = 'unknown', analysisId, registerProcess, onStreamEvent, logPrefix, abortSignal } = options;
431
+
432
+ const levelPrefix = logPrefix || `[Level ${level}]`;
433
+
434
+ // Already cancelled before we started: reject before creating a temp dir,
435
+ // writing a prompt that can run to megabytes, and spawning a process only
436
+ // to SIGTERM it. This runs ahead of the mkdtempSync below, so the early
437
+ // return cannot leak a temp dir — there is nothing yet to clean up.
438
+ // Semantics are unchanged; wireAbortToChild already handled a pre-aborted
439
+ // signal correctly, just after doing all that work.
440
+ if (abortSignal?.aborted) {
441
+ logger.info(`${levelPrefix} Skipping Muse CLI run: already cancelled`);
442
+ reject(makeAbortError(`${levelPrefix} Cancelled by user`));
443
+ return;
444
+ }
445
+
446
+ logger.info(`${levelPrefix} Executing Muse CLI...`);
447
+ logger.info(`${levelPrefix} Writing prompt: ${prompt.length} bytes`);
448
+
449
+ // `muse exec` takes the prompt either as a positional argument or via
450
+ // --prompt-file; it does NOT read stdin (it exits 2 with "missing prompt").
451
+ // Review prompts embed whole diffs, so a file is the only safe delivery —
452
+ // a positional arg would risk E2BIG. mkdtempSync (never a fixed /tmp path)
453
+ // keeps concurrent analyses from colliding.
454
+ let tmpDir;
455
+ let tmpFile;
456
+
457
+ // Idempotent: called from settle() (covers close/timeout/error/abort), and
458
+ // eagerly on close so the file is gone as soon as muse exits, even when the
459
+ // async LLM-extraction fallback delays settling. Declared BEFORE the write
460
+ // so the failure path below can use it: mkdtempSync creates the directory
461
+ // first, so a failing writeFileSync (ENOSPC/EACCES/EIO/EROFS/quota) would
462
+ // otherwise leak an empty directory with no child process to clean it up.
463
+ let tmpCleaned = false;
464
+ const cleanupTmpFile = () => {
465
+ if (tmpCleaned || !tmpDir) return;
466
+ tmpCleaned = true;
467
+ try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* ignore */ }
468
+ };
469
+
470
+ try {
471
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pair-review-muse-'));
472
+ tmpFile = path.join(tmpDir, 'prompt.txt');
473
+ fs.writeFileSync(tmpFile, prompt);
474
+ } catch (err) {
475
+ cleanupTmpFile();
476
+ reject(new Error(`${levelPrefix} Failed to write Muse prompt file: ${err.message}`));
477
+ return;
478
+ }
479
+
480
+ const { command: fullCommand, args: fullArgs } = this.getAnalysisSpawnConfig(['--prompt-file', tmpFile]);
481
+
482
+ const muse = spawn(fullCommand, fullArgs, {
483
+ cwd,
484
+ env: {
485
+ ...process.env,
486
+ ...this.extraEnv,
487
+ PATH: `${BIN_DIR}:${process.env.PATH}`
488
+ },
489
+ shell: this.useShell,
490
+ // Detach in shell mode so wireAbortToChild can group-kill via
491
+ // process.kill(-pid). See claude-provider for the rationale.
492
+ detached: this.useShell
493
+ });
494
+
495
+ // Prompt is delivered via --prompt-file; close stdin so any wrapper script
496
+ // waiting on it doesn't keep the process alive.
497
+ muse.stdin.on('error', (err) => {
498
+ logger.debug(`${levelPrefix} stdin error (ignorable, prompt goes via file): ${err.message}`);
499
+ });
500
+ muse.stdin.end();
501
+
502
+ const pid = muse.pid;
503
+ logger.debug(`${levelPrefix} Muse CLI command: ${fullCommand} ${fullArgs.join(' ')}`);
504
+ logger.info(`${levelPrefix} Spawned Muse CLI process: PID ${pid}`);
505
+
506
+ // Register process for cancellation tracking if analysisId provided
507
+ if (analysisId && registerProcess) {
508
+ registerProcess(analysisId, muse);
509
+ logger.info(`${levelPrefix} Registered process ${pid} for analysis ${analysisId}`);
510
+ }
511
+
512
+ // Wire AbortSignal -> SIGTERM for tour/summary cancellation.
513
+ // shell flag triggers group-kill so the CLI grandchild dies with the shell.
514
+ const abortWiring = wireAbortToChild(muse, abortSignal, { logPrefix: levelPrefix, shell: this.useShell });
515
+
516
+ let stdout = '';
517
+ let stderr = '';
518
+ let timeoutId = null;
519
+ let settled = false; // Guard against multiple resolve/reject calls
520
+ let lineBuffer = ''; // Buffer for incomplete JSONL lines
521
+ let lineCount = 0; // Count of JSONL events for progress tracking
522
+
523
+ // Centralize detach and temp-file cleanup in `settle` so they happen
524
+ // regardless of which exit path (close/timeout/error/abort) wins. Avoids
525
+ // leaking a listener on the per-job AbortSignal that tour/summary
526
+ // generators reuse across many provider.execute() calls.
527
+ const settle = (fn, value) => {
528
+ if (settled) return;
529
+ settled = true;
530
+ if (timeoutId) clearTimeout(timeoutId);
531
+ abortWiring.detach();
532
+ cleanupTmpFile();
533
+ fn(value);
534
+ };
535
+
536
+ // Set up side-channel stream parser for live progress events
537
+ const streamParser = onStreamEvent
538
+ ? new StreamParser(parseMuseLine, onStreamEvent, { cwd })
539
+ : null;
540
+
541
+ // Set timeout
542
+ if (timeout) {
543
+ timeoutId = setTimeout(() => {
544
+ logger.error(`${levelPrefix} Process ${pid} timed out after ${timeout}ms`);
545
+ // Shell-aware: in shell mode `muse` is the shell wrapper (spawned
546
+ // detached above), so a bare kill would leave the real CLI running
547
+ // after this promise has already rejected.
548
+ killChildSafely(muse, { shell: this.useShell, logPrefix: levelPrefix });
549
+ settle(reject, new Error(`${levelPrefix} Muse CLI timed out after ${timeout}ms`));
550
+ }, timeout);
551
+ }
552
+
553
+ // Collect stdout with streaming JSONL parsing for debug visibility
554
+ muse.stdout.on('data', (data) => {
555
+ const chunk = data.toString();
556
+ stdout += chunk;
557
+
558
+ // Feed side-channel stream parser for live progress events
559
+ if (streamParser) {
560
+ streamParser.feed(chunk);
561
+ }
562
+
563
+ // Parse JSONL lines as they arrive for streaming debug output
564
+ lineBuffer += chunk;
565
+ const lines = lineBuffer.split('\n');
566
+ // Keep the last incomplete line in buffer
567
+ lineBuffer = lines.pop() || '';
568
+
569
+ for (const line of lines) {
570
+ if (line.trim()) {
571
+ lineCount++;
572
+ this.logStreamLine(line, lineCount, levelPrefix);
573
+ }
574
+ }
575
+ });
576
+
577
+ // Collect stderr
578
+ muse.stderr.on('data', (data) => {
579
+ stderr += data.toString();
580
+ });
581
+
582
+ // Handle completion
583
+ muse.on('close', (code) => {
584
+ cleanupTmpFile();
585
+ if (settled) return; // Already settled by timeout or error
586
+
587
+ // Flush any remaining stream parser buffer
588
+ if (streamParser) {
589
+ streamParser.flush();
590
+ }
591
+
592
+ // BackgroundQueue-driven cancellation — mirror of claude-provider.
593
+ if (abortWiring.cancelled()) {
594
+ logger.info(`${levelPrefix} Muse CLI terminated by user cancel (exit code ${code})`);
595
+ settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
596
+ return;
597
+ }
598
+
599
+ // Check for cancellation signals (SIGTERM=143, SIGKILL=137)
600
+ const isCancellationCode = code === 143 || code === 137;
601
+ if (isCancellationCode && analysisId && isAnalysisCancelled(analysisId)) {
602
+ logger.info(`${levelPrefix} Muse CLI terminated due to analysis cancellation (exit code ${code})`);
603
+ settle(reject, new CancellationError(`${levelPrefix} Analysis cancelled by user`));
604
+ return;
605
+ }
606
+
607
+ // Muse writes all human-facing noise (workspace root notice, skills
608
+ // warnings, untrusted-workspace notices) to stderr even on success, so
609
+ // stderr content alone is NOT an error signal — only the exit code is.
610
+ if (stderr.trim()) {
611
+ if (code !== 0) {
612
+ logger.error(`${levelPrefix} Muse CLI stderr (exit code ${code}): ${stderr}`);
613
+ } else {
614
+ logger.debug(`${levelPrefix} Muse CLI stderr (success): ${stderr}`);
615
+ }
616
+ }
617
+
618
+ // The terminal record carries the authoritative outcome. On failure its
619
+ // `reason` is far more useful than stderr, which only says
620
+ // "run ended with Failed".
621
+ const terminal = this.extractTerminalRecord(stdout);
622
+
623
+ if (code !== 0) {
624
+ logger.error(`${levelPrefix} Muse CLI exited with code ${code}`);
625
+ settle(reject, this.createExitError(code, stderr, levelPrefix, terminal?.reason));
626
+ return;
627
+ }
628
+
629
+ // Log completion with event count (only for successful completion)
630
+ logger.info(`${levelPrefix} Muse CLI completed: ${lineCount} JSONL events received`);
631
+
632
+ // Process any remaining buffered line
633
+ if (lineBuffer.trim()) {
634
+ lineCount++;
635
+ this.logStreamLine(lineBuffer, lineCount, levelPrefix);
636
+ }
637
+
638
+ // Parse the Muse JSONL response
639
+ const parsed = this.parseMuseResponse(stdout, level, levelPrefix);
640
+ if (parsed.success) {
641
+ logger.success(`${levelPrefix} Successfully parsed JSON response`);
642
+ // Dump the parsed data for debugging
643
+ const dataPreview = JSON.stringify(parsed.data, null, 2);
644
+ logger.debug(`${levelPrefix} [parsed_data] ${dataPreview.substring(0, 3000)}${dataPreview.length > 3000 ? '...' : ''}`);
645
+ // Log suggestion count if present
646
+ if (parsed.data?.suggestions) {
647
+ const count = Array.isArray(parsed.data.suggestions) ? parsed.data.suggestions.length : 0;
648
+ logger.info(`${levelPrefix} [response] ${count} suggestions in parsed response`);
649
+ }
650
+ settle(resolve, parsed.data);
651
+ } else if (!parsed.textContent) {
652
+ // No model-authored text to extract from — only muse's own transport
653
+ // envelopes. Feeding those to any extractor risks returning a
654
+ // lifecycle/terminal frame as though it were the review payload, so
655
+ // an empty run is reported as the failure it is.
656
+ logger.warn(`${levelPrefix} Regex extraction failed: ${parsed.error}`);
657
+ logger.warn(`${levelPrefix} No assistant text in Muse output; skipping LLM extraction fallback`);
658
+ settle(resolve, { raw: stdout, parsed: false });
659
+ } else {
660
+ // Regex extraction failed, try LLM-based extraction as fallback
661
+ logger.warn(`${levelPrefix} Regex extraction failed: ${parsed.error}`);
662
+ const llmFallbackInput = parsed.textContent;
663
+ logger.info(`${levelPrefix} LLM fallback input length: ${llmFallbackInput.length} characters`);
664
+ logger.info(`${levelPrefix} Attempting LLM-based JSON extraction fallback...`);
665
+
666
+ // A cancel that arrives while the extraction child is running reaches
667
+ // the abort wiring, but by then the muse child has already exited, so
668
+ // the wiring only kills something already dead. Nothing else here
669
+ // consults it — so without this check a cancelled analysis still
670
+ // settles with a normal result.
671
+ //
672
+ // Reads BOTH the wiring flag and the signal itself: `settle()` (which
673
+ // detaches the listener) has not run on any path that reaches here, so
674
+ // the flag is live — but the signal is the source of truth and stays
675
+ // correct no matter how the wiring evolves.
676
+ const cancelledDuringExtraction = () =>
677
+ abortWiring.cancelled() || abortSignal?.aborted === true;
678
+
679
+ // Use async IIFE to handle the async LLM extraction
680
+ (async () => {
681
+ try {
682
+ // `abortSignal` also lets the extraction spawn itself be killed
683
+ // rather than merely abandoned; providers that ignore the option
684
+ // simply run to completion and are caught by the check below.
685
+ const llmExtracted = await this.extractJSONWithLLM(llmFallbackInput, { level, analysisId, registerProcess, logPrefix: levelPrefix, abortSignal });
686
+ if (cancelledDuringExtraction()) {
687
+ logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
688
+ settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
689
+ return;
690
+ }
691
+ if (llmExtracted.success) {
692
+ logger.success(`${levelPrefix} LLM extraction fallback succeeded`);
693
+ settle(resolve, llmExtracted.data);
694
+ } else {
695
+ logger.warn(`${levelPrefix} LLM extraction fallback also failed: ${llmExtracted.error}`);
696
+ logger.info(`${levelPrefix} Raw response preview: ${llmFallbackInput.substring(0, 500)}...`);
697
+ settle(resolve, { raw: llmFallbackInput, parsed: false });
698
+ }
699
+ } catch (llmError) {
700
+ // An abort that kills the extraction spawn surfaces here as a
701
+ // thrown error; it is a cancellation, not a parse failure.
702
+ if (cancelledDuringExtraction()) {
703
+ logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
704
+ settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
705
+ return;
706
+ }
707
+ logger.warn(`${levelPrefix} LLM extraction fallback error: ${llmError.message}`);
708
+ settle(resolve, { raw: llmFallbackInput, parsed: false });
709
+ }
710
+ })();
711
+ }
712
+ });
713
+
714
+ // Handle errors
715
+ muse.on('error', (error) => {
716
+ cleanupTmpFile();
717
+ if (error.code === 'ENOENT') {
718
+ logger.error(`${levelPrefix} Muse CLI not found. Please ensure Muse Code is installed.`);
719
+ settle(reject, new Error(`${levelPrefix} Muse CLI not found. ${MuseProvider.getInstallInstructions()}`));
720
+ } else {
721
+ logger.error(`${levelPrefix} Muse process error: ${error}`);
722
+ settle(reject, error);
723
+ }
724
+ });
725
+ });
726
+ }
727
+
728
+ /**
729
+ * Find the run's terminal record in Muse JSONL output.
730
+ *
731
+ * Muse names the terminal record after its outcome — `run.terminal.completed`,
732
+ * `run.terminal.failed`, `run.terminal.cancelled` — but all of them share
733
+ * `payload.kind === 'run_terminal'` and carry `terminal`, `text` and `reason`.
734
+ * Matching on the `kind` discriminator therefore catches failures too, which
735
+ * matching only `run.terminal.completed` would miss.
736
+ *
737
+ * `attemptId` identifies which attempt this outcome belongs to, so the delta
738
+ * fallback in parseMuseResponse can be scoped to the SAME attempt instead of
739
+ * ranging over the whole transcript. See attemptIdOf.
740
+ *
741
+ * @param {string} stdout - Raw stdout from Muse CLI (JSONL format)
742
+ * @returns {{terminal: string, text: string, reason: string|null, attemptId: string|null}|null}
743
+ */
744
+ extractTerminalRecord(stdout) {
745
+ if (!stdout || !stdout.trim()) return null;
746
+
747
+ let found = null;
748
+ for (const line of stdout.split('\n')) {
749
+ if (!line.trim()) continue;
750
+ try {
751
+ const record = JSON.parse(line);
752
+ const payload = record.payload;
753
+ if (payload?.kind === 'run_terminal') {
754
+ // Keep the last one: a resumed/retried run can emit more than one.
755
+ found = {
756
+ terminal: payload.terminal || 'unknown',
757
+ text: payload.text || '',
758
+ reason: payload.reason || null,
759
+ attemptId: attemptIdOf(record)
760
+ };
761
+ }
762
+ } catch {
763
+ // Skip malformed lines — the caller degrades to delta accumulation.
764
+ }
765
+ }
766
+ return found;
767
+ }
768
+
769
+ /**
770
+ * Parse Muse CLI JSONL response.
771
+ *
772
+ * Every record is an envelope keyed by `payload_type`. The authoritative
773
+ * answer is the terminal record's `payload.text`; if that is missing we fall
774
+ * back to concatenating `run.output.delta` chunks in `sequence` order — but
775
+ * only those belonging to the SAME attempt the terminal record reports, so a
776
+ * multi-attempt transcript can never answer with a superseded attempt's text.
777
+ *
778
+ * Only model-authored text is ever handed to an extractor. Muse's envelopes
779
+ * are themselves valid JSON objects, so running the generic extractor over the
780
+ * raw JSONL could return a lifecycle/terminal frame as though it were the
781
+ * review payload — turning an empty or failed run into a false success. Raw
782
+ * stdout is therefore only parsed when it contains no envelopes at all (a
783
+ * wrapper that printed bare JSON, or output produced without `--json`).
784
+ *
785
+ * No outer try/catch: every JSON.parse below has its own, extractJSON returns
786
+ * a result object rather than throwing, and the remaining string operations
787
+ * are guarded by the type check at the top.
788
+ *
789
+ * @param {string} stdout - Raw stdout from Muse CLI (JSONL format)
790
+ * @param {string|number} level - Analysis level for logging
791
+ * @param {string} logPrefix - Logging prefix
792
+ * @returns {{success: boolean, data?: Object, error?: string, textContent?: string}}
793
+ * `textContent` is set only when there is material safe to forward to the
794
+ * LLM extraction fallback; its absence means "nothing but transport frames".
795
+ */
796
+ parseMuseResponse(stdout, level, logPrefix) {
797
+ const levelPrefix = logPrefix || `[Level ${level}]`;
798
+
799
+ if (typeof stdout !== 'string' || !stdout.trim()) {
800
+ return { success: false, error: 'Muse produced no output' };
801
+ }
802
+
803
+ const terminal = this.extractTerminalRecord(stdout);
804
+ let responseText = terminal?.text || '';
805
+ let source = 'terminal record';
806
+ // Whether stdout looks like muse's JSONL transport at all.
807
+ let sawEnvelope = terminal !== null;
808
+
809
+ if (!responseText) {
810
+ // Fall back to streamed deltas, ordered by the envelope's `sequence`
811
+ // so out-of-order chunks can't scramble the text.
812
+ const deltas = [];
813
+ for (const line of stdout.split('\n')) {
814
+ if (!line.trim()) continue;
815
+ try {
816
+ const record = JSON.parse(line);
817
+ if (record && (typeof record.payload_type === 'string' || typeof record.payload === 'object')) {
818
+ sawEnvelope = true;
819
+ }
820
+ if (record.payload_type === 'run.output.delta' && record.payload?.text) {
821
+ deltas.push({
822
+ sequence: record.sequence ?? 0,
823
+ attemptId: attemptIdOf(record),
824
+ text: record.payload.text
825
+ });
826
+ }
827
+ } catch {
828
+ logger.debug(`${levelPrefix} Skipping malformed JSONL line: ${line.substring(0, 100)}`);
829
+ }
830
+ }
831
+ deltas.sort((a, b) => a.sequence - b.sequence);
832
+
833
+ // Scope the deltas to ONE attempt, the same way extractTerminalRecord
834
+ // scopes the outcome to the last terminal record. Reading the two sources
835
+ // with different scoping rules is what let a multi-attempt transcript
836
+ // report a review the finishing attempt never produced: when the final
837
+ // attempt ended with no text, an unscoped concatenation resurrected an
838
+ // EARLIER attempt's deltas and presented them as that run's answer.
839
+ //
840
+ // The scope is the terminal record's attempt when there is one, otherwise
841
+ // the attempt of the last delta — which mirrors "keep the last" for a
842
+ // transcript that was cut off before any terminal record arrived.
843
+ // Transcripts naming no attempt at all (older shapes, hand-written
844
+ // fixtures) collapse to a single null scope, i.e. the previous behaviour.
845
+ const scopeId = terminal?.attemptId ?? (deltas.length ? deltas[deltas.length - 1].attemptId : null);
846
+ const scoped = deltas.filter(d => d.attemptId === scopeId);
847
+
848
+ if (scoped.length !== deltas.length) {
849
+ logger.info(
850
+ `${levelPrefix} Ignoring ${deltas.length - scoped.length} output delta(s) from earlier Muse attempts ` +
851
+ `(keeping attempt ${scopeId})`
852
+ );
853
+ }
854
+
855
+ // A terminal record whose attempt contributed no deltas leaves this
856
+ // empty on purpose: the run really did produce no answer, and the caller
857
+ // reports that instead of mining another attempt's text.
858
+ responseText = scoped.map(d => d.text).join('');
859
+ source = `${scoped.length} output deltas`;
860
+ }
861
+
862
+ if (responseText) {
863
+ logger.debug(`${levelPrefix} Extracted ${responseText.length} chars of assistant text from JSONL (${source})`);
864
+ const extracted = extractJSON(responseText, level, levelPrefix);
865
+ if (extracted.success) {
866
+ return extracted;
867
+ }
868
+
869
+ // Return textContent so the caller feeds the assistant text — never the
870
+ // raw JSONL — to the LLM extraction fallback.
871
+ logger.warn(`${levelPrefix} Assistant text is not JSON, treating as raw text`);
872
+ return { success: false, error: 'Assistant text is not valid JSON', textContent: responseText };
873
+ }
874
+
875
+ if (sawEnvelope) {
876
+ // Envelopes but no assistant text: the run produced no answer. Report that
877
+ // honestly rather than letting an extractor mine the transport frames.
878
+ logger.warn(`${levelPrefix} Muse emitted no assistant text (terminal: ${terminal?.terminal || 'none'})`);
879
+ return {
880
+ success: false,
881
+ error: `Muse produced no assistant text (terminal record: ${terminal?.terminal || 'none'}${terminal?.reason ? `, reason: ${terminal.reason}` : ''})`
882
+ };
883
+ }
884
+
885
+ // Not muse JSONL at all — safe to treat the whole output as model text.
886
+ const extracted = extractJSON(stdout, level, levelPrefix);
887
+ if (extracted.success) {
888
+ return extracted;
889
+ }
890
+ return { success: false, error: extracted.error || 'Output is not valid JSON', textContent: stdout };
891
+ }
892
+
893
+ /**
894
+ * Log a streaming JSONL line for debugging visibility.
895
+ *
896
+ * Muse records are envelopes discriminated by `payload_type`. Uses
897
+ * logger.streamDebug() which only logs when --debug-stream is enabled, except
898
+ * for the terminal record which is summarized at info level.
899
+ *
900
+ * Muse emits NO token usage in any record, so there is no token line to log.
901
+ *
902
+ * @param {string} line - A single JSONL line
903
+ * @param {number} lineNum - Line number for reference
904
+ * @param {string} levelPrefix - Logging prefix
905
+ */
906
+ logStreamLine(line, lineNum, levelPrefix) {
907
+ const streamEnabled = logger.isStreamDebugEnabled();
908
+
909
+ try {
910
+ const record = JSON.parse(line);
911
+ const payloadType = record.payload_type;
912
+ const payload = record.payload || {};
913
+
914
+ if (payload.kind === 'run_terminal') {
915
+ // Always summarize the terminal record at info level. Muse reports no
916
+ // token usage anywhere, so there are no counts to include.
917
+ const reasonPart = payload.reason ? ` reason=${payload.reason}` : '';
918
+ logger.info(`${levelPrefix} [run.terminal] ${payload.terminal || 'unknown'} (tokens not reported by Muse)${reasonPart}`);
919
+ return;
920
+ }
921
+
922
+ if (!streamEnabled) return;
923
+
924
+ if (payloadType === 'run.model.configured') {
925
+ const label = payload.display_label || payload.model_id || 'unknown';
926
+ logger.streamDebug(`${levelPrefix} [#${lineNum}] model: ${label}`);
927
+
928
+ } else if (payloadType === 'run.output.delta') {
929
+ const text = payload.text || '';
930
+ const preview = text.replace(/\n/g, '\\n').substring(0, 60);
931
+ logger.streamDebug(`${levelPrefix} [#${lineNum}] output.delta: ${preview}${text.length > 60 ? '...' : ''}`);
932
+
933
+ } else if (payloadType === 'task.lifecycle.side_effect_intent') {
934
+ const operation = payload.event?.operation || 'unknown';
935
+ const decision = payload.event?.policy_decision;
936
+ const decisionPart = decision ? ` [${decision}]` : '';
937
+ logger.streamDebug(`${levelPrefix} [#${lineNum}] side_effect_intent: ${operation}${decisionPart}`);
938
+
939
+ } else if (payloadType === 'tool.result') {
940
+ const callId = payload.call_id || '';
941
+ const toolName = payload.correlation_facts?.tool_name || '';
942
+ const outcome = payload.correlation_facts?.outcome || '';
943
+ const text = payload.text || '';
944
+ const preview = text.replace(/\n/g, '\\n').substring(0, 60);
945
+ const idPart = callId ? ` [${callId.substring(0, 12)}]` : '';
946
+ const namePart = toolName ? ` ${toolName}` : '';
947
+ const outcomePart = outcome ? ` ${outcome}` : '';
948
+ logger.streamDebug(`${levelPrefix} [#${lineNum}] tool.result${namePart}${idPart}${outcomePart} ${preview}${text.length > 60 ? '...' : ''}`);
949
+
950
+ } else if (payloadType === 'task.lifecycle.output') {
951
+ const chunk = payload.event?.chunk || '';
952
+ const preview = chunk.replace(/\n/g, '\\n').substring(0, 60);
953
+ logger.streamDebug(`${levelPrefix} [#${lineNum}] task.output: ${preview}${chunk.length > 60 ? '...' : ''}`);
954
+
955
+ } else if (payloadType === 'task.lifecycle.rejected') {
956
+ // `skip_if_running` is a benign internal reminder-task event — it is NOT
957
+ // an error and must never be surfaced as one. Every OTHER reason is a
958
+ // real tool/policy rejection, so it is logged visibly instead of being
959
+ // buried at stream-debug level under a "benign" label.
960
+ const reason = payload.event?.reason || 'unknown';
961
+ if (reason === 'skip_if_running') {
962
+ logger.streamDebug(`${levelPrefix} [#${lineNum}] task.rejected (benign): ${reason}`);
963
+ } else {
964
+ logger.warn(`${levelPrefix} [#${lineNum}] task.rejected: ${reason}`);
965
+ }
966
+
967
+ } else if (payloadType === 'task.lifecycle.failed') {
968
+ // A single background task (e.g. a reminder plugin) can fail while the
969
+ // run as a whole succeeds; the exit code and terminal record decide.
970
+ const reason = payload.event?.reason || 'unknown';
971
+ logger.streamDebug(`${levelPrefix} [#${lineNum}] task.failed: ${reason}`);
972
+
973
+ } else if (payloadType) {
974
+ logger.streamDebug(`${levelPrefix} [#${lineNum}] ${payloadType}`);
975
+ }
976
+ // Silently ignore records with no payload_type
977
+
978
+ } catch (parseError) {
979
+ if (streamEnabled) {
980
+ logger.streamDebug(`${levelPrefix} [#${lineNum}] (malformed: ${line.substring(0, 50)}${line.length > 50 ? '...' : ''})`);
981
+ }
982
+ }
983
+ }
984
+
985
+ /**
986
+ * Build args for Muse CLI extraction, applying provider and model extra_args.
987
+ *
988
+ * Note the deliberate absence of a trailing prompt marker: the shared
989
+ * extraction helper appends `--prompt-file <path>` itself, from the
990
+ * `promptFileArg` field getExtractionConfig sets.
991
+ *
992
+ * @param {string} model - The model identifier to use
993
+ * @param {Object} [resolved] - Pre-resolved output of `_resolveModelConfig(model)`.
994
+ * Lets getExtractionConfig resolve once and reuse it for both args and env.
995
+ * @returns {string[]} Complete args array for the CLI
996
+ */
997
+ buildArgsForModel(model, resolved = null) {
998
+ const { cliModel, extraArgs } = resolved || this._resolveModelConfig(model);
999
+ const modelArgs = cliModel === null ? [] : ['--model', cliModel];
1000
+
1001
+ // Extraction only reformats already-captured text into JSON — it needs no
1002
+ // filesystem or shell access at all. So unlike the analysis path (which
1003
+ // keeps shell for grep/find and git-diff-lines), extraction is fully locked
1004
+ // down. This mirrors Codex's `--sandbox read-only` extraction posture.
1005
+ // Verified empirically: muse still returns bare JSON with both flags set.
1006
+ const safetyArgs = this.configOverrides?.yolo
1007
+ ? ['--yolo']
1008
+ : ['--disable-write', '--disable-shell'];
1009
+
1010
+ return ['exec', '--json', ...modelArgs, ...safetyArgs, ...extraArgs];
1011
+ }
1012
+
1013
+ /**
1014
+ * Get CLI configuration for LLM extraction.
1015
+ *
1016
+ * Prompt delivery: `--prompt-file <path>`, the same mechanism the analysis
1017
+ * path uses, and NEVER through a shell. Extraction input is an entire
1018
+ * malformed model response, so keeping it off argv is what stops a large one
1019
+ * from failing with E2BIG at the OS single-argument limit.
1020
+ *
1021
+ * The other two delivery modes the shared helper offers do not fit muse:
1022
+ * - promptViaStdin fails outright: `muse exec` with no prompt argument exits 2
1023
+ * with "missing prompt"; it never reads stdin.
1024
+ * - promptViaFile appends `@<path>` as a positional arg — Pi's @file syntax.
1025
+ * Muse would read the literal string "@/tmp/..." as the prompt.
1026
+ *
1027
+ * SECURITY — why `useShell` stays false here even now that the prompt is off
1028
+ * argv: this spawn is not `detached`, so under `shell: true` a cancel or
1029
+ * timeout would kill only the `/bin/sh` wrapper and orphan the real CLI (see
1030
+ * the kill comment in extractJSONWithLLM). A multi-word command needs no
1031
+ * shell anyway: `docker exec c muse` spawns `docker` with the rest as leading
1032
+ * args. Anything needing genuine shell expansion must be a wrapper script —
1033
+ * see splitCommandWords.
1034
+ *
1035
+ * @param {string} model - The model to use for extraction
1036
+ * @returns {Object} Configuration for spawning extraction process
1037
+ */
1038
+ getExtractionConfig(model) {
1039
+ // One resolve, reused for both the args and the merged env.
1040
+ const resolved = this._resolveModelConfig(model);
1041
+ const args = this.buildArgsForModel(model, resolved);
1042
+
1043
+ const [command, ...commandArgs] = splitCommandWords(this.museCmd);
1044
+
1045
+ return {
1046
+ command,
1047
+ args: [...commandArgs, ...args],
1048
+ useShell: false,
1049
+ promptViaStdin: false,
1050
+ promptFileArg: '--prompt-file',
1051
+ env: resolved.env
1052
+ };
1053
+ }
1054
+
1055
+ /**
1056
+ * Build an actionable error for Muse CLI process failures.
1057
+ *
1058
+ * @param {number} code - Process exit code
1059
+ * @param {string} stderr - Captured stderr
1060
+ * @param {string} levelPrefix - Logging prefix
1061
+ * @param {string} [terminalReason] - `reason` from the run's terminal record,
1062
+ * which carries the real failure detail when stderr only says
1063
+ * "run ended with Failed".
1064
+ * @returns {Error}
1065
+ */
1066
+ createExitError(code, stderr, levelPrefix, terminalReason) {
1067
+ const stderrText = stderr.trim();
1068
+ // The terminal record's reason is the more specific diagnostic; check both
1069
+ // it and stderr when classifying.
1070
+ const diagnostic = [stderrText, terminalReason].filter(Boolean).join(' | ');
1071
+
1072
+ if (this.isAuthError(diagnostic)) {
1073
+ return new Error(
1074
+ `${levelPrefix} Muse CLI authentication failed. Run \`muse login\` (or set META_API_KEY) and try again. ` +
1075
+ `Original error: ${diagnostic}`
1076
+ );
1077
+ }
1078
+
1079
+ if (this.isUnknownModelError(diagnostic)) {
1080
+ return new Error(
1081
+ `${levelPrefix} Muse CLI rejected the model "${this.model}" as unknown. ` +
1082
+ `Check the model ID (and any cli_model override) against Muse's catalog. ` +
1083
+ `Original error: ${diagnostic}`
1084
+ );
1085
+ }
1086
+
1087
+ const detail = diagnostic || '(no error output)';
1088
+ return new Error(`${levelPrefix} Muse CLI exited with code ${code}: ${detail}`);
1089
+ }
1090
+
1091
+ /**
1092
+ * Detect authentication failures reported by the Muse CLI.
1093
+ *
1094
+ * Muse's own wording for an expired token is
1095
+ * "still unauthorized after a token refresh; run `muse login` again".
1096
+ *
1097
+ * @param {string} text - Captured stderr and/or terminal reason
1098
+ * @returns {boolean}
1099
+ */
1100
+ isAuthError(text) {
1101
+ return /(?:still unauthorized after a token refresh|no login to refresh a key from|run `muse login`|starting logged out|401\s+Unauthorized|HTTP error:\s*401|\bUnauthorized\b)/i.test(text || '');
1102
+ }
1103
+
1104
+ /**
1105
+ * Detect an unknown/hidden model rejection. Muse fails fast with
1106
+ * "model `X` is not in the catalog".
1107
+ *
1108
+ * @param {string} text - Captured stderr and/or terminal reason
1109
+ * @returns {boolean}
1110
+ */
1111
+ isUnknownModelError(text) {
1112
+ return /is (?:not in|hidden in) the catalog/i.test(text || '');
1113
+ }
1114
+
1115
+ /**
1116
+ * Test if Muse CLI is available.
1117
+ * Uses a fast `--version` check instead of running a prompt.
1118
+ * Uses the command configured in the instance (respects ENV > config > default).
1119
+ * @param {number} [timeoutMs=10000] - Timeout in milliseconds for the probe
1120
+ * @returns {Promise<boolean>}
1121
+ */
1122
+ async testAvailability(timeoutMs = 10000) {
1123
+ return new Promise((resolve) => {
1124
+ const useShell = this.useShell;
1125
+ const command = useShell ? `${this.museCmd} --version` : this.museCmd;
1126
+ const args = useShell ? [] : ['--version'];
1127
+
1128
+ // Log the actual command for debugging config/override issues
1129
+ const fullCmd = useShell ? command : `${command} ${args.join(' ')}`;
1130
+ logger.debug(`Muse availability check: ${fullCmd}`);
1131
+
1132
+ const muse = spawn(command, args, {
1133
+ env: {
1134
+ ...process.env,
1135
+ // Same merged env execute() and getExtractionConfig() use. A setup
1136
+ // whose muse only runs with `providers.muse.env` (or per-model env)
1137
+ // set would otherwise be reported unavailable while the real
1138
+ // invocation works fine.
1139
+ ...this.extraEnv,
1140
+ PATH: `${BIN_DIR}:${process.env.PATH}`
1141
+ },
1142
+ shell: useShell
1143
+ });
1144
+
1145
+ let stdout = '';
1146
+ let stderr = '';
1147
+ let settled = false;
1148
+
1149
+ // Timeout guard: if the CLI hangs, resolve false
1150
+ const availabilityTimeout = setTimeout(() => {
1151
+ if (settled) return;
1152
+ settled = true;
1153
+ logger.warn(`Muse CLI availability check timed out after ${Math.round(timeoutMs / 1000)}s`);
1154
+ // No `shell` flag even in shell mode: this probe does not spawn
1155
+ // detached, so the child is not a process-group leader and a
1156
+ // `process.kill(-pid)` would fail with ESRCH instead of terminating
1157
+ // anything. The helper is still used for its pid guard, which stops a
1158
+ // failed spawn (pid undefined -> 0) from signalling our own group.
1159
+ killChildSafely(muse, { logPrefix: '[Muse availability]' });
1160
+ resolve(false);
1161
+ }, timeoutMs);
1162
+
1163
+ muse.stdout.on('data', (data) => {
1164
+ stdout += data.toString();
1165
+ });
1166
+
1167
+ muse.stderr.on('data', (data) => {
1168
+ stderr += data.toString();
1169
+ });
1170
+
1171
+ muse.on('close', (code) => {
1172
+ if (settled) return;
1173
+ settled = true;
1174
+ clearTimeout(availabilityTimeout);
1175
+ if (code === 0) {
1176
+ logger.info(`Muse CLI available: ${stdout.trim()}`);
1177
+ resolve(true);
1178
+ } else {
1179
+ const stderrMsg = stderr.trim() ? `: ${stderr.trim()}` : '';
1180
+ logger.warn(`Muse CLI not available or returned unexpected output (exit code ${code})${stderrMsg}`);
1181
+ resolve(false);
1182
+ }
1183
+ });
1184
+
1185
+ muse.on('error', (error) => {
1186
+ if (settled) return;
1187
+ settled = true;
1188
+ clearTimeout(availabilityTimeout);
1189
+ logger.warn(`Muse CLI not available: ${error.message}`);
1190
+ resolve(false);
1191
+ });
1192
+ });
1193
+ }
1194
+
1195
+ static getProviderName() {
1196
+ return 'Muse';
1197
+ }
1198
+
1199
+ static getProviderId() {
1200
+ return 'muse';
1201
+ }
1202
+
1203
+ static getModels() {
1204
+ return MUSE_MODELS;
1205
+ }
1206
+
1207
+ static getDefaultModel() {
1208
+ return DEFAULT_MUSE_MODEL;
1209
+ }
1210
+
1211
+ static getInstallInstructions() {
1212
+ // `muse` on PATH is a self-updating launcher script that downloads the real
1213
+ // binary alongside itself (macOS and Linux, arm64 and x86_64).
1214
+ return 'Install Muse Code (macOS/Linux):\n' +
1215
+ ' curl -fsSL https://api.meta.ai/muse-launcher.sh -o ~/.local/bin/muse && chmod +x ~/.local/bin/muse\n' +
1216
+ 'Then authenticate: muse login (or set META_API_KEY)\n' +
1217
+ 'Run `muse --help` for usage. Requires a directory on your PATH, e.g. ~/.local/bin.';
1218
+ }
1219
+ }
1220
+
1221
+ // Register this provider
1222
+ registerProvider('muse', MuseProvider);
1223
+
1224
+ module.exports = MuseProvider;