symforge 7.17.3

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
//! Explicit npm-managed self-update command.
//!
//! Beyond shelling `npm install -g symforge@latest`, this orchestrates a complete
//! update so the user is never left with a half-updated mix of versions:
//!  1. stops the running daemon before the swap (a live daemon holds the old
//!     binary — a Windows file-lock — and keeps serving stale behavior) and clears
//!     a demonstrably-dead sidecar record;
//!  2. forces the OS-native platform package (`symforge-<os>-<arch>`) to the same
//!     version, because `npm install -g symforge@latest` alone can retain a stale
//!     nested platform package and leave `symforge --version` behind the wrapper;
//!  3. VERIFIES the resolved `symforge --version` reached the latest published
//!     version — and FAILS LOUDLY (stale nested package, a PATH-shadowing install,
//!     or a WSL Windows-prefix bleed) instead of a hollow success, even when the
//!     npm registry is unreachable (it floors against the running binary's version
//!     and surfaces a launcher that ran but could not resolve a binary);
//!  4. re-registers every MCP client onto the freshly-installed binary; and
//!  5. only AFTER a confirmed re-registration, clears the retired `~/.symforge/bin`
//!     durable-install leftovers and prunes dead version-registry entries.

use anyhow::{Context, bail};
use std::process::{Command, Stdio};

/// Map `(os, arch)` to the npm platform package that ships the native binary.
/// Mirrors `SUPPORTED_TARGETS` in `npm/lib/resolve-binary.js`. `os` is
/// `std::env::consts::OS`, `arch` is `std::env::consts::ARCH`.
fn platform_package_for(os: &str, arch: &str) -> Option<&'static str> {
    match (os, arch) {
        ("windows", "x86_64") => Some("symforge-windows-x64"),
        ("linux", "x86_64") => Some("symforge-linux-x64"),
        ("macos", "aarch64") => Some("symforge-macos-arm64"),
        ("macos", "x86_64") => Some("symforge-macos-x64"),
        _ => None,
    }
}

fn npm_executable_for_os(os: &str) -> &'static str {
    if os == "windows" { "npm.cmd" } else { "npm" }
}

/// The resolved `symforge` launcher name for spawning the freshly-installed
/// binary (`.cmd` shim on Windows, bare name elsewhere).
fn symforge_launcher() -> &'static str {
    if std::env::consts::OS == "windows" {
        "symforge.cmd"
    } else {
        "symforge"
    }
}

/// Build the `npm install -g` package specs. Always installs the `symforge`
/// wrapper at `@latest`; when the OS/arch is known, also names the platform
/// package explicitly so npm materializes the new nested binary instead of
/// silently reusing a stale one.
fn install_specs(os: &str, arch: &str) -> Vec<String> {
    let mut specs = vec!["symforge@latest".to_string()];
    if let Some(pkg) = platform_package_for(os, arch) {
        specs.push(format!("{pkg}@latest"));
    }
    specs
}

/// Parse a `symforge --version` semver out of arbitrary launcher output. Scans
/// EVERY line (not just the first) so a leading banner/notice on stdout does not
/// hide the version, and accepts the first digit-leading dotted token.
fn parse_symforge_version(text: &str) -> Option<String> {
    text.lines().find_map(|line| {
        line.split_whitespace()
            .map(str::trim)
            .find(|tok| tok.contains('.') && tok.chars().next().is_some_and(|c| c.is_ascii_digit()))
            .map(str::to_string)
    })
}

/// Outcome of probing the freshly-installed `symforge --version`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum InstalledProbe {
    /// The launcher ran and reported this version.
    Version(String),
    /// The launcher RAN but exited non-zero / printed no version — e.g. it could
    /// not resolve a native binary (a stale/missing platform package or the WSL
    /// Windows-prefix trap). Carries a trimmed diagnostic line from stderr.
    LauncherFailed(String),
    /// The launcher could not be executed at all (not on PATH / spawn error).
    Unprobeable,
}

/// Clear a demonstrably-dead sidecar record for the current project (CWD
/// `.symforge`). The sidecar is NOT killed: its pid is the in-process MCP server
/// (killing it would drop the user's editor connection), and a TCP-alive probe
/// does not prove the recorded pid owns the port (recycled-pid hazard). Only a
/// `Dead` record is cleaned so the next launch starts clean.
fn clear_dead_sidecar_record() -> Option<String> {
    use crate::sidecar::port_file::{SidecarLiveness, cleanup_files_at, read_sidecar_status_at};

    let dir = std::path::Path::new(".symforge");
    let status = read_sidecar_status_at(dir, "127.0.0.1");
    if matches!(status.liveness, SidecarLiveness::Dead) {
        cleanup_files_at(dir);
        Some("cleared a stale sidecar record".to_string())
    } else {
        None
    }
}

/// Remove the retired durable-install artifacts under the DEFAULT `~/.symforge/bin`
/// (the only place the retired durable mechanism ever wrote). Guarded: skipped
/// entirely when `$SYMFORGE_HOME` is set (a binary may legitimately live under a
/// custom home), and never deletes the binary backing the current process.
/// Best-effort; callers must only invoke this AFTER clients are re-registered off
/// the orphan.
fn remove_orphan_durable_bin() -> Vec<String> {
    if std::env::var_os("SYMFORGE_HOME").is_some() {
        return Vec::new();
    }
    let Some(home) = dirs::home_dir() else {
        return Vec::new();
    };
    let bin = home.join(".symforge").join("bin");
    let self_exe = std::env::current_exe()
        .ok()
        .and_then(|p| std::fs::canonicalize(p).ok());

    let mut removed = Vec::new();
    for name in [
        "symforge.exe",
        "symforge",
        "symforge.version",
        "symforge-desktop.cmd",
    ] {
        let path = bin.join(name);
        if !path.exists() {
            continue;
        }
        // Never delete the binary backing the running update process.
        if let Some(self_exe) = &self_exe
            && std::fs::canonicalize(&path).ok().as_ref() == Some(self_exe)
        {
            continue;
        }
        if std::fs::remove_file(&path).is_ok() {
            removed.push(name.to_string());
        }
    }
    if removed.is_empty() {
        Vec::new()
    } else {
        vec![format!(
            "removed retired durable-install leftover(s) from {}: {}",
            bin.display(),
            removed.join(", ")
        )]
    }
}

/// Side effects of an update, injected so the orchestration is unit-testable
/// without touching npm, the network, the daemon, or the filesystem.
pub(crate) trait UpdateOps {
    /// Stop the running daemon before the binary swap + clear a dead sidecar
    /// record. Returns a human-readable summary of what was stopped.
    fn stop_processes(&mut self) -> String;
    /// Run `<program> <args...>`; return `true` on success.
    fn npm_install(&mut self, program: &str, args: &[&str]) -> anyhow::Result<bool>;
    /// Probe the resolved `symforge --version` after install.
    fn installed_version(&mut self) -> InstalledProbe;
    /// Latest version published to the npm registry, or `None` when offline.
    fn latest_version(&mut self) -> Option<String>;
    /// Re-register every MCP client onto the freshly-installed binary by spawning
    /// the NEW launcher's `init`. Returns `true` on success.
    fn reregister_clients(&mut self) -> anyhow::Result<bool>;
    /// Prune dead version-registry entries; remove the retired durable-install
    /// leftovers ONLY when `reregistered` is true (otherwise clients still point
    /// at the orphan and deleting it would break them). Returns summary lines.
    fn reconcile_durable(&mut self, reregistered: bool) -> Vec<String>;
}

struct RealUpdateOps;

impl UpdateOps for RealUpdateOps {
    fn stop_processes(&mut self) -> String {
        let mut stopped = Vec::new();

        // Daemon (global). `main()` is synchronous, so a short-lived runtime is
        // safe (no nested-runtime panic).
        let daemon = tokio::runtime::Builder::new_current_thread()
            .enable_io()
            .enable_time()
            .build()
            .ok()
            .and_then(|rt| {
                rt.block_on(crate::daemon::stop_running_daemon_for_update())
                    .ok()
            });
        match daemon {
            Some(crate::daemon::DaemonStopOutcome::Stopped { pid }) => {
                stopped.push(format!("daemon (pid {pid})"));
            }
            Some(crate::daemon::DaemonStopOutcome::StopTimedOut { pid }) => {
                stopped.push(format!(
                    "daemon (pid {pid}) did NOT stop in time — left discoverable; rerun update or stop it manually"
                ));
            }
            Some(crate::daemon::DaemonStopOutcome::SkippedSafety) => {
                stopped.push("daemon left running (failed ownership safety check)".to_string());
            }
            _ => {}
        }

        if let Some(sidecar) = clear_dead_sidecar_record() {
            stopped.push(sidecar);
        }

        if stopped.is_empty() {
            "no running daemon found".to_string()
        } else {
            format!("stopped {}", stopped.join(", "))
        }
    }

    fn npm_install(&mut self, program: &str, args: &[&str]) -> anyhow::Result<bool> {
        let status = Command::new(program)
            .args(args)
            .stdin(Stdio::inherit())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status()
            .with_context(|| format!("failed to start `{}`", invocation_text(program, args)))?;
        Ok(status.success())
    }

    fn installed_version(&mut self) -> InstalledProbe {
        // Spawn the freshly-resolved launcher (this update process is still the
        // OLD binary, so we ask the launcher what it now resolves to). Inspect
        // BOTH stdout and the exit status: the npm launcher prints resolve errors
        // to stderr and exits non-zero with empty stdout, which must surface as a
        // loud failure, not a silent "could not probe".
        let output = match Command::new(symforge_launcher()).arg("--version").output() {
            Ok(output) => output,
            Err(_) => return InstalledProbe::Unprobeable,
        };
        if let Some(version) = parse_symforge_version(&String::from_utf8_lossy(&output.stdout)) {
            return InstalledProbe::Version(version);
        }
        // Ran but produced no version: surface the launcher's own diagnostic.
        let stderr = String::from_utf8_lossy(&output.stderr);
        let detail = stderr
            .lines()
            .map(str::trim)
            .find(|line| !line.is_empty())
            .unwrap_or("launcher produced no version output")
            .to_string();
        InstalledProbe::LauncherFailed(detail)
    }

    fn latest_version(&mut self) -> Option<String> {
        crate::cli::version::latest_npm_version()
    }

    fn reregister_clients(&mut self) -> anyhow::Result<bool> {
        // Spawn the NEW launcher's init so clients are registered at the freshly
        // installed binary (this update process is still the OLD binary, so an
        // in-process `run_init` would re-register the OLD path).
        let status = Command::new(symforge_launcher())
            .args(["init", "--client", "all"])
            .stdin(Stdio::null())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status();
        Ok(matches!(status, Ok(s) if s.success()))
    }

    fn reconcile_durable(&mut self, reregistered: bool) -> Vec<String> {
        let mut out = Vec::new();
        if let Some(home) = crate::version_registry::resolve_home() {
            let pruned = crate::version_registry::prune_missing_entries(&home);
            if pruned > 0 {
                out.push(format!(
                    "pruned {pruned} stale version-registry entr{}",
                    if pruned == 1 { "y" } else { "ies" }
                ));
            }
        }
        if reregistered {
            out.extend(remove_orphan_durable_bin());
        }
        out
    }
}

pub fn run_update() -> anyhow::Result<()> {
    orchestrate_update(
        std::env::consts::OS,
        std::env::consts::ARCH,
        &mut RealUpdateOps,
    )
}

pub(crate) fn orchestrate_update(
    os: &str,
    arch: &str,
    ops: &mut impl UpdateOps,
) -> anyhow::Result<()> {
    // Stop first: a live daemon holds the old binary (Windows file-lock) and
    // would keep serving stale behavior. It respawns lazily on next use.
    let stop_summary = ops.stop_processes();
    eprintln!("symforge update: {stop_summary}.");

    let program = npm_executable_for_os(os);
    let specs = install_specs(os, arch);
    let args: Vec<&str> = ["install", "-g"]
        .into_iter()
        .chain(specs.iter().map(String::as_str))
        .collect();

    if !ops.npm_install(program, &args)? {
        bail!(
            "symforge update failed: `{}` exited unsuccessfully",
            invocation_text(program, &args)
        );
    }

    // Verify the install actually took effect. npm can report success while the
    // resolved binary stays behind, so this is the load-bearing safety net.
    let running = env!("CARGO_PKG_VERSION");
    let pkg = platform_package_for(os, arch).unwrap_or("symforge-<os>-<arch>");
    match ops.installed_version() {
        InstalledProbe::LauncherFailed(detail) => {
            bail!(
                "symforge update incomplete: the freshly-installed `symforge` launcher could not \
                 resolve a native binary. Launcher reported:\n  {detail}\n\
                 This is usually a stale/missing platform package or a WSL Windows-prefix bleed. Try: \
                 npm install -g symforge@latest {pkg}@latest --force; on WSL, ensure your Linux npm \
                 prefix bin is on PATH ahead of /usr/local and /mnt."
            );
        }
        InstalledProbe::Unprobeable => {
            eprintln!(
                "symforge update: WARNING — could not run `symforge --version` to verify the result \
                 (the npm prefix bin may not be on PATH). The install ran; confirm with `symforge --version`."
            );
        }
        InstalledProbe::Version(installed) => {
            let latest = ops.latest_version();
            // When the registry is reachable, require the resolved binary to be
            // at the latest; otherwise floor against the version of the binary
            // running this update — the swap must produce something at least as
            // new, or it demonstrably did not take effect.
            let (stale, target) = match &latest {
                Some(l) => (
                    crate::cli::version::is_newer_version(l, &installed),
                    l.clone(),
                ),
                None => (
                    crate::cli::version::is_newer_version(running, &installed),
                    running.to_string(),
                ),
            };
            if stale {
                bail!(
                    "symforge update incomplete: npm reported success but `symforge --version` still \
                     reports {installed}, behind {target}. The resolved `symforge` is not the one just \
                     installed. Likely causes:\n  \
                     - stale nested platform package — retry: npm install -g symforge@latest {pkg}@latest --force\n  \
                     - a PATH-shadowing install — run `which -a symforge`; a root /usr/local copy can win over your npm prefix\n  \
                     - on WSL, a Windows npm prefix bleeding in via /mnt — put your Linux npm prefix bin ahead of /usr/local and /mnt on PATH\n  \
                     - on Windows, a running symforge can lock its own .exe — run the npm install from a separate shell"
                );
            }
            if latest.is_none() {
                eprintln!(
                    "symforge update: `symforge --version` reports {installed} (could not reach the npm \
                     registry to confirm it is the very latest)."
                );
            } else {
                eprintln!(
                    "symforge update complete — `symforge --version` now reports {installed}."
                );
            }
        }
    }

    // Re-point all clients at the freshly-installed binary. Only AFTER a confirmed
    // re-registration do we clear the retired durable-install artifacts — deleting
    // the orphan while a client still references it would break that client.
    let reregistered = match ops.reregister_clients() {
        Ok(true) => {
            eprintln!("symforge update: re-registered all MCP clients onto the new binary.");
            true
        }
        Ok(false) => {
            eprintln!(
                "symforge update: client re-registration did not complete — run `symforge init \
                 --client all` manually. Leaving the durable-install leftovers in place until then."
            );
            false
        }
        Err(error) => {
            eprintln!(
                "symforge update: client re-registration error ({error}) — run `symforge init \
                 --client all` manually. Leaving the durable-install leftovers in place until then."
            );
            false
        }
    };
    for line in ops.reconcile_durable(reregistered) {
        eprintln!("symforge update: {line}");
    }

    Ok(())
}

fn invocation_text(program: &str, args: &[&str]) -> String {
    let mut parts = Vec::with_capacity(args.len() + 1);
    parts.push(program.to_string());
    parts.extend(args.iter().map(|arg| (*arg).to_string()));
    parts.join(" ")
}

#[cfg(test)]
mod tests {
    use super::*;

    struct FakeOps {
        install_calls: Vec<(String, Vec<String>)>,
        install_result: bool,
        installed: InstalledProbe,
        latest: Option<String>,
        reregister_result: anyhow::Result<bool>,
        stopped_before_install: bool,
        reregistered_after_install: bool,
        reconciled_with: Option<bool>,
    }

    impl Default for FakeOps {
        fn default() -> Self {
            Self {
                install_calls: Vec::new(),
                install_result: false,
                installed: InstalledProbe::Unprobeable,
                latest: None,
                reregister_result: Ok(true),
                stopped_before_install: false,
                reregistered_after_install: false,
                reconciled_with: None,
            }
        }
    }

    impl UpdateOps for FakeOps {
        fn stop_processes(&mut self) -> String {
            self.stopped_before_install = self.install_calls.is_empty();
            "no running daemon found".to_string()
        }
        fn npm_install(&mut self, program: &str, args: &[&str]) -> anyhow::Result<bool> {
            self.install_calls.push((
                program.to_string(),
                args.iter().map(|a| a.to_string()).collect(),
            ));
            Ok(self.install_result)
        }
        fn installed_version(&mut self) -> InstalledProbe {
            self.installed.clone()
        }
        fn latest_version(&mut self) -> Option<String> {
            self.latest.clone()
        }
        fn reregister_clients(&mut self) -> anyhow::Result<bool> {
            self.reregistered_after_install = !self.install_calls.is_empty();
            match &self.reregister_result {
                Ok(value) => Ok(*value),
                Err(error) => Err(anyhow::anyhow!("{error}")),
            }
        }
        fn reconcile_durable(&mut self, reregistered: bool) -> Vec<String> {
            self.reconciled_with = Some(reregistered);
            Vec::new()
        }
    }

    fn ok_ops() -> FakeOps {
        FakeOps {
            install_result: true,
            installed: InstalledProbe::Version("7.15.4".to_string()),
            latest: Some("7.15.4".to_string()),
            ..Default::default()
        }
    }

    #[test]
    fn npm_executable_is_npm_cmd_on_windows_else_npm() {
        assert_eq!(npm_executable_for_os("windows"), "npm.cmd");
        assert_eq!(npm_executable_for_os("linux"), "npm");
        assert_eq!(npm_executable_for_os("macos"), "npm");
    }

    #[test]
    fn install_specs_force_the_os_native_platform_package() {
        assert_eq!(
            install_specs("windows", "x86_64"),
            vec!["symforge@latest", "symforge-windows-x64@latest"]
        );
        assert_eq!(
            install_specs("linux", "x86_64"),
            vec!["symforge@latest", "symforge-linux-x64@latest"]
        );
        assert_eq!(
            install_specs("macos", "aarch64"),
            vec!["symforge@latest", "symforge-macos-arm64@latest"]
        );
    }

    #[test]
    fn install_specs_falls_back_to_wrapper_only_for_unknown_target() {
        assert_eq!(install_specs("linux", "riscv64"), vec!["symforge@latest"]);
        assert_eq!(install_specs("plan9", "x86_64"), vec!["symforge@latest"]);
    }

    #[test]
    fn parse_symforge_version_scans_all_lines_past_leading_banner() {
        assert_eq!(
            parse_symforge_version("symforge 7.15.4\nUpdate available: 7.16.0"),
            Some("7.15.4".to_string())
        );
        // A leading banner/notice line must not hide the version.
        assert_eq!(
            parse_symforge_version("(node:1) ExperimentalWarning: blah\nsymforge 7.15.4"),
            Some("7.15.4".to_string())
        );
        assert_eq!(parse_symforge_version("no version here"), None);
        assert_eq!(parse_symforge_version(""), None);
    }

    #[test]
    fn orchestrate_update_runs_full_sequence_on_success() {
        let mut ops = ok_ops();
        orchestrate_update("linux", "x86_64", &mut ops).expect("update should succeed");

        assert!(ops.stopped_before_install, "stop must precede install");
        assert_eq!(
            ops.install_calls,
            vec![(
                "npm".to_string(),
                vec![
                    "install".to_string(),
                    "-g".to_string(),
                    "symforge@latest".to_string(),
                    "symforge-linux-x64@latest".to_string(),
                ]
            )]
        );
        assert!(
            ops.reregistered_after_install,
            "clients re-registered after install"
        );
        assert_eq!(
            ops.reconciled_with,
            Some(true),
            "orphan reconcile must run with reregistered=true on success"
        );
    }

    #[test]
    fn orchestrate_update_uses_npm_cmd_and_windows_package_on_windows() {
        let mut ops = ok_ops();
        orchestrate_update("windows", "x86_64", &mut ops).expect("update should succeed");

        let (program, args) = &ops.install_calls[0];
        assert_eq!(program, "npm.cmd");
        assert!(args.contains(&"symforge-windows-x64@latest".to_string()));
    }

    #[test]
    fn orchestrate_update_reports_failed_npm_without_reregistering() {
        let mut ops = FakeOps {
            install_result: false,
            ..Default::default()
        };

        let err = orchestrate_update("linux", "x86_64", &mut ops)
            .expect_err("failed npm install should be reported");

        assert!(err.to_string().contains("exited unsuccessfully"), "{err:?}");
        assert!(!ops.reregistered_after_install);
        assert_eq!(ops.reconciled_with, None, "no reconcile on failed install");
    }

    #[test]
    fn orchestrate_update_fails_loudly_when_resolved_version_stays_stale() {
        let mut ops = FakeOps {
            install_result: true,
            installed: InstalledProbe::Version("7.15.2".to_string()),
            latest: Some("7.15.4".to_string()),
            ..Default::default()
        };

        let err = orchestrate_update("linux", "x86_64", &mut ops)
            .expect_err("stale resolved version must fail loudly");

        let msg = err.to_string();
        assert!(msg.contains("incomplete"), "{msg}");
        assert!(msg.contains("7.15.2") && msg.contains("7.15.4"), "{msg}");
        assert!(msg.contains("PATH-shadowing"), "{msg}");
        assert!(
            !ops.reregistered_after_install,
            "no re-register on a drifted install"
        );
    }

    #[test]
    fn orchestrate_update_bails_on_launcher_failure_surfacing_stderr() {
        // The marquee WSL/launcher case: install "succeeds" but the launcher
        // cannot resolve a binary. Must bail loudly, not report "skipped".
        let mut ops = FakeOps {
            install_result: true,
            installed: InstalledProbe::LauncherFailed(
                "symforge: platform package symforge-linux-x64 not found".to_string(),
            ),
            latest: Some("7.15.4".to_string()),
            ..Default::default()
        };

        let err = orchestrate_update("linux", "x86_64", &mut ops)
            .expect_err("a launcher that cannot resolve a binary must fail loudly");

        let msg = err.to_string();
        assert!(msg.contains("could not resolve a native binary"), "{msg}");
        assert!(msg.contains("symforge-linux-x64 not found"), "{msg}");
        assert!(!ops.reregistered_after_install);
    }

    #[test]
    fn orchestrate_update_floors_against_running_version_when_registry_offline() {
        // Registry unreachable (latest=None) AND the resolved binary is older than
        // the binary running the update — the swap demonstrably failed, so bail
        // even without a registry answer.
        let mut ops = FakeOps {
            install_result: true,
            installed: InstalledProbe::Version("0.0.1".to_string()),
            latest: None,
            ..Default::default()
        };

        let err = orchestrate_update("linux", "x86_64", &mut ops)
            .expect_err("a binary older than the running update binary must fail even offline");

        assert!(err.to_string().contains("incomplete"), "{err:?}");
        assert!(!ops.reregistered_after_install);
    }

    #[test]
    fn orchestrate_update_warns_but_succeeds_when_probe_is_unavailable() {
        // Launcher genuinely not spawnable: install ran, so don't fail; still
        // re-register + reconcile.
        let mut ops = FakeOps {
            install_result: true,
            installed: InstalledProbe::Unprobeable,
            latest: Some("7.15.4".to_string()),
            ..Default::default()
        };
        orchestrate_update("linux", "x86_64", &mut ops)
            .expect("unprobeable launcher must not fail an otherwise-successful update");
        assert!(ops.reregistered_after_install);
        assert_eq!(ops.reconciled_with, Some(true));
    }

    #[test]
    fn orchestrate_update_does_not_remove_orphan_when_reregistration_fails() {
        // reconcile must be told reregistered=false so the orphan (still
        // referenced by clients) is NOT deleted.
        let mut ops = FakeOps {
            install_result: true,
            installed: InstalledProbe::Version("7.15.4".to_string()),
            latest: Some("7.15.4".to_string()),
            reregister_result: Ok(false),
            ..Default::default()
        };
        orchestrate_update("linux", "x86_64", &mut ops).expect("update should still succeed");
        assert_eq!(
            ops.reconciled_with,
            Some(false),
            "failed re-registration must prevent orphan removal"
        );
    }

    #[test]
    fn install_invocation_uses_no_shell_wrappers() {
        let mut ops = ok_ops();
        orchestrate_update("windows", "x86_64", &mut ops).unwrap();

        let (program, args) = &ops.install_calls[0];
        let text = invocation_text(
            program,
            &args.iter().map(String::as_str).collect::<Vec<_>>(),
        )
        .to_ascii_lowercase();
        assert!(!text.contains("powershell"));
        assert!(!text.contains("cmd /c"));
        assert!(!text.contains("executionpolicy"));
    }
}