use anyhow::{Context, bail};
use std::process::Stdio;
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" }
}
fn symforge_launcher() -> &'static str {
if std::env::consts::OS == "windows" {
"symforge.cmd"
} else {
"symforge"
}
}
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
}
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)
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum InstalledProbe {
Version(String),
LauncherFailed(String),
Unprobeable,
}
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
}
}
fn durable_bin_dir() -> Option<std::path::PathBuf> {
crate::version_registry::resolve_home().map(|home| home.join("bin"))
}
fn remove_orphan_durable_bin() -> Vec<String> {
let Some(bin) = durable_bin_dir() else {
return Vec::new();
};
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;
}
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(", ")
)]
}
}
pub(crate) trait UpdateOps {
fn stop_processes(&mut self) -> String;
fn npm_install(&mut self, program: &str, args: &[&str]) -> anyhow::Result<bool>;
fn installed_version(&mut self) -> InstalledProbe;
fn latest_version(&mut self) -> Option<String>;
fn prune_registry(&mut self) -> Vec<String>;
fn reregister_clients(&mut self) -> anyhow::Result<bool>;
fn reconcile_durable(&mut self, reregistered: bool) -> Vec<String>;
fn shadow_report(&mut self) -> Option<crate::path_shadow::ShadowReport>;
}
struct RealUpdateOps;
impl UpdateOps for RealUpdateOps {
fn stop_processes(&mut self) -> String {
let mut stopped = Vec::new();
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);
}
for line in stop_other_inscope_holders() {
stopped.push(line);
}
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 = crate::process_util::hidden_command(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 {
let output = match crate::process_util::hidden_command(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);
}
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 prune_registry(&mut self) -> Vec<String> {
let Some(home) = crate::version_registry::resolve_home() else {
return Vec::new();
};
let pruned = crate::version_registry::prune_missing_entries(&home);
if pruned > 0 {
vec![format!(
"pruned {pruned} stale version-registry entr{}",
if pruned == 1 { "y" } else { "ies" }
)]
} else {
Vec::new()
}
}
fn reregister_clients(&mut self) -> anyhow::Result<bool> {
let status = crate::process_util::hidden_command(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> {
if reregistered {
remove_orphan_durable_bin()
} else {
Vec::new()
}
}
fn shadow_report(&mut self) -> Option<crate::path_shadow::ShadowReport> {
let installed = npm_installed_launcher_path()?;
crate::path_shadow::detect_shadow(&installed)
}
}
fn npm_installed_launcher_path() -> Option<std::path::PathBuf> {
let program = npm_executable_for_os(std::env::consts::OS);
let output = crate::process_util::hidden_command(program)
.args(["prefix", "-g"])
.stdin(Stdio::null())
.output()
.ok()?;
if !output.status.success() {
return None;
}
let prefix = String::from_utf8_lossy(&output.stdout);
let prefix = prefix.trim();
if prefix.is_empty() {
return None;
}
Some(launcher_path_in_prefix(
std::path::Path::new(prefix),
std::env::consts::OS,
))
}
fn launcher_path_in_prefix(prefix: &std::path::Path, os: &str) -> std::path::PathBuf {
if os == "windows" {
prefix.join("symforge.cmd")
} else {
prefix.join("bin").join("symforge")
}
}
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<()> {
let stop_summary = ops.stop_processes();
eprintln!("symforge update: {stop_summary}.");
for line in ops.prune_registry() {
eprintln!("symforge update: {line}");
}
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)? {
let plain_cmd = format!("npm install -g {}", specs.join(" "));
let init_cmd = format!("{} init --client all", symforge_launcher());
if os == "windows" {
bail!(
"symforge update failed: `{}` exited unsuccessfully.\n\
On Windows the `symforge update` process runs from the very binary npm \
replaces and cannot overwrite a running .exe. Any OTHER in-scope holders \
were stopped above (if any were found), so finish the swap from a PLAIN \
shell (NOT via `symforge`):\n {}\n\
then re-point your MCP clients onto the new binary:\n {}\n\
If it STILL fails, an MCP client (Cursor, Claude) or another symforge \
process is holding the binary — close them and rerun the command above.\n\
(The version registry was already pruned.)",
invocation_text(program, &args),
plain_cmd,
init_cmd
);
} else {
bail!(
"symforge update failed: `{}` exited unsuccessfully.\n\
Ensure no running symforge process is holding the binary, then rerun, or \
install directly from a plain shell:\n {}\n\
(The version registry was already pruned.)",
invocation_text(program, &args),
plain_cmd
);
}
}
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();
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}."
);
}
}
}
if let Some(report) = ops.shadow_report() {
eprintln!("{}", crate::path_shadow::format_shadow_warning(&report));
}
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(any(windows, test))]
fn normalize_exe_path(path: &str) -> String {
let trimmed = path.trim();
let stripped = trimmed.strip_prefix(r"\\?\").unwrap_or(trimmed);
stripped.replace('\\', "/").to_ascii_lowercase()
}
#[cfg(any(windows, test))]
fn select_inscope_holder_pids(
processes: &[(u32, String)],
self_exe: &str,
self_pid: u32,
) -> Vec<u32> {
let target = normalize_exe_path(self_exe);
processes
.iter()
.filter(|(pid, path)| *pid != self_pid && normalize_exe_path(path) == target)
.map(|(pid, _)| *pid)
.collect()
}
#[cfg(any(windows, test))]
fn process_path_matches(processes: &[(u32, String)], pid: u32, expected_exe: &str) -> bool {
let expected = normalize_exe_path(expected_exe);
processes
.iter()
.any(|(candidate_pid, path)| *candidate_pid == pid && normalize_exe_path(path) == expected)
}
#[cfg(any(windows, test))]
fn parse_symforge_process_lines(text: &str) -> Vec<(u32, String)> {
text.lines()
.filter_map(|line| {
let (pid, path) = line.trim().split_once('|')?;
let pid: u32 = pid.trim().parse().ok()?;
let path = path.trim();
if path.is_empty() {
None
} else {
Some((pid, path.to_string()))
}
})
.collect()
}
#[cfg(windows)]
fn stop_other_inscope_holders() -> Vec<String> {
let Ok(self_exe) = std::env::current_exe() else {
return Vec::new();
};
let self_exe = self_exe.to_string_lossy().to_string();
let self_pid = std::process::id();
let snapshot = enumerate_symforge_processes();
let pids = select_inscope_holder_pids(&snapshot, &self_exe, self_pid);
if pids.is_empty() {
return Vec::new();
}
for pid in &pids {
graceful_then_forced_stop(*pid, &self_exe);
}
vec![format!(
"{} other in-scope symforge holder(s) (pid {})",
pids.len(),
pids.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(", ")
)]
}
#[cfg(not(windows))]
fn stop_other_inscope_holders() -> Vec<String> {
Vec::new()
}
#[cfg(windows)]
fn enumerate_symforge_processes() -> Vec<(u32, String)> {
let script = "Get-CimInstance Win32_Process -Filter \"name='symforge.exe'\" | \
ForEach-Object { \"$($_.ProcessId)|$($_.ExecutablePath)\" }";
for shell in ["powershell", "pwsh"] {
match crate::process_util::hidden_command(shell)
.args(["-NoProfile", "-NonInteractive", "-Command", script])
.stdin(Stdio::null())
.stderr(Stdio::null())
.output()
{
Ok(out) => return parse_symforge_process_lines(&String::from_utf8_lossy(&out.stdout)),
Err(_) => continue,
}
}
Vec::new()
}
#[cfg(windows)]
fn graceful_then_forced_stop(pid: u32, expected_exe: &str) {
use std::time::{Duration, Instant};
if !taskkill_if_process_matches_path(pid, expected_exe, false) {
return;
}
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline && process_is_alive(pid) {
std::thread::sleep(Duration::from_millis(150));
}
if process_is_alive(pid) {
let _ = taskkill_if_process_matches_path(pid, expected_exe, true);
}
}
#[cfg(windows)]
fn taskkill_if_process_matches_path(pid: u32, expected_exe: &str, force: bool) -> bool {
if !process_matches_exe_path(pid, expected_exe) {
return false;
}
let pid_arg = pid.to_string();
let mut args = Vec::with_capacity(3);
if force {
args.push("/F");
}
args.extend(["/PID", pid_arg.as_str()]);
matches!(
crate::process_util::hidden_command("taskkill")
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status(),
Ok(status) if status.success()
)
}
#[cfg(windows)]
fn process_matches_exe_path(pid: u32, expected_exe: &str) -> bool {
let script = format!(
"Get-CimInstance Win32_Process -Filter \"ProcessId={pid} AND name='symforge.exe'\" | \
ForEach-Object {{ \"$($_.ProcessId)|$($_.ExecutablePath)\" }}"
);
for shell in ["powershell", "pwsh"] {
match crate::process_util::hidden_command(shell)
.args(["-NoProfile", "-NonInteractive", "-Command", &script])
.stdin(Stdio::null())
.stderr(Stdio::null())
.output()
{
Ok(out) => {
return process_path_matches(
&parse_symforge_process_lines(&String::from_utf8_lossy(&out.stdout)),
pid,
expected_exe,
);
}
Err(_) => continue,
}
}
false
}
#[cfg(windows)]
fn process_is_alive(pid: u32) -> bool {
let needle = pid.to_string();
let output = crate::process_util::hidden_command("tasklist")
.args([
"/FI",
&format!("PID eq {pid}"),
"/FI",
"IMAGENAME eq symforge.exe",
"/NH",
"/FO",
"CSV",
])
.stdin(Stdio::null())
.stderr(Stdio::null())
.output();
match output {
Ok(out) => String::from_utf8_lossy(&out.stdout).contains(needle.as_str()),
Err(_) => false,
}
}
#[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>,
prune_lines: Vec<String>,
stopped_before_install: bool,
reregistered_after_install: bool,
reconciled_with: Option<bool>,
pruned_before_install: Option<bool>,
prune_calls: usize,
shadow: Option<crate::path_shadow::ShadowReport>,
shadow_checked_after_install: 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),
prune_lines: Vec::new(),
stopped_before_install: false,
reregistered_after_install: false,
reconciled_with: None,
pruned_before_install: None,
prune_calls: 0,
shadow: None,
shadow_checked_after_install: 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 prune_registry(&mut self) -> Vec<String> {
self.prune_calls += 1;
self.pruned_before_install = Some(self.install_calls.is_empty());
self.prune_lines.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 shadow_report(&mut self) -> Option<crate::path_shadow::ShadowReport> {
self.shadow_checked_after_install = Some(!self.install_calls.is_empty());
self.shadow.clone()
}
}
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())
);
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"
);
assert_eq!(
ops.shadow_checked_after_install,
Some(true),
"PATH-shadow check must run, and only after a successful install"
);
}
#[test]
fn orchestrate_update_warns_but_succeeds_when_a_same_version_shadow_wins() {
let mut ops = ok_ops();
ops.shadow = Some(crate::path_shadow::ShadowReport {
our_path: std::path::PathBuf::from("/home/you/.npm-global/bin/symforge"),
our_version: Some("7.15.4".to_string()),
shadow_path: std::path::PathBuf::from("/usr/local/bin/symforge"),
shadow_version: Some("7.15.4".to_string()),
kind: crate::path_shadow::ShadowKind::RootSystem,
});
orchestrate_update("linux", "x86_64", &mut ops)
.expect("a same-version shadow is advisory, not fatal");
assert_eq!(
ops.shadow_checked_after_install,
Some(true),
"shadow check ran after the install even on the same-version case"
);
assert!(
ops.reregistered_after_install,
"the advisory shadow warning must not short-circuit re-registration"
);
}
#[test]
fn launcher_path_in_prefix_maps_per_os_layout() {
assert_eq!(
launcher_path_in_prefix(std::path::Path::new("C:/npm-prefix"), "windows"),
std::path::Path::new("C:/npm-prefix").join("symforge.cmd")
);
assert_eq!(
launcher_path_in_prefix(std::path::Path::new("/home/you/.npm-global"), "linux"),
std::path::Path::new("/home/you/.npm-global/bin/symforge")
);
}
#[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,
prune_lines: vec!["pruned 1 stale version-registry entry".to_string()],
..Default::default()
};
let err = orchestrate_update("linux", "x86_64", &mut ops)
.expect_err("failed npm install should be reported");
let msg = err.to_string();
assert!(msg.contains("exited unsuccessfully"), "{msg}");
assert!(
msg.contains("Ensure no running symforge process is holding the binary"),
"{msg}"
);
assert!(
msg.contains("npm install -g symforge@latest symforge-linux-x64@latest"),
"{msg}"
);
assert_eq!(
ops.prune_calls, 1,
"prune must run even on a blocked update"
);
assert_eq!(
ops.pruned_before_install,
Some(true),
"prune must run before the npm swap is attempted"
);
assert!(!ops.reregistered_after_install);
assert_eq!(ops.reconciled_with, None, "no reconcile on failed install");
}
#[test]
fn orchestrate_update_windows_failure_gives_staged_self_lock_guidance() {
let mut ops = FakeOps {
install_result: false,
..Default::default()
};
let err = orchestrate_update("windows", "x86_64", &mut ops)
.expect_err("a blocked Windows swap must fail with staged guidance");
let msg = err.to_string();
assert!(msg.contains("exited unsuccessfully"), "{msg}");
assert!(
msg.contains("running .exe") && msg.contains("PLAIN shell"),
"must name the self-lock + a plain-shell remediation: {msg}"
);
assert!(
msg.contains("npm install -g symforge@latest symforge-windows-x64@latest"),
"must print the exact install command: {msg}"
);
assert!(
msg.contains("init --client all"),
"must print the client re-registration step: {msg}"
);
assert!(
!msg.contains("All OTHER"),
"must not over-claim that all holders were stopped: {msg}"
);
assert!(
msg.contains("close them and rerun"),
"must cover an un-enumerated holder (MCP client) case: {msg}"
);
assert!(
!ops.reregistered_after_install,
"a blocked swap must not re-register clients"
);
}
#[test]
fn select_inscope_holder_pids_matches_same_path_excludes_self_and_other_installs() {
let procs = vec![
(100u32, r"C:\npm\symforge.exe".to_string()), (200u32, r"C:\NPM\SYMFORGE.EXE".to_string()), (300u32, r"D:\other\symforge.exe".to_string()), (999u32, r"C:\npm\symforge.exe".to_string()), ];
let pids = select_inscope_holder_pids(&procs, r"C:\npm\symforge.exe", 999);
assert_eq!(
pids,
vec![100, 200],
"only OTHER processes at the same executable path are in scope"
);
}
#[test]
fn select_inscope_holder_pids_empty_when_only_self_runs() {
let procs = vec![(999u32, r"C:\npm\symforge.exe".to_string())];
assert!(
select_inscope_holder_pids(&procs, r"C:\npm\symforge.exe", 999).is_empty(),
"nothing to stop when this process is the only holder"
);
}
#[test]
fn select_inscope_holder_pids_normalizes_slash_and_verbatim_path_forms() {
let procs = vec![
(100u32, r"C:\npm\symforge.exe".to_string()), (200u32, "C:/npm/symforge.exe".to_string()), (300u32, r"\\?\C:\npm\symforge.exe".to_string()), (400u32, r"C:\other\symforge.exe".to_string()), ];
let pids = select_inscope_holder_pids(&procs, r"\\?\C:\NPM\symforge.exe", 999);
assert_eq!(
pids,
vec![100, 200, 300],
"path-form variants of the same binary are all in scope (M1)"
);
}
#[test]
fn process_path_matches_requires_same_pid_and_same_executable_path() {
let procs = vec![
(100u32, r"C:\npm\symforge.exe".to_string()),
(200u32, r"D:\other\symforge.exe".to_string()),
(300u32, r"\\?\C:\NPM\symforge.exe".to_string()),
];
assert!(
process_path_matches(&procs, 100, r"C:\NPM\symforge.exe"),
"same PID and path identity should match"
);
assert!(
process_path_matches(&procs, 300, r"C:\npm\symforge.exe"),
"path form normalization should match the same executable"
);
assert!(
!process_path_matches(&procs, 200, r"C:\npm\symforge.exe"),
"a recycled PID at a different install path must not be killable"
);
assert!(
!process_path_matches(&procs, 999, r"C:\npm\symforge.exe"),
"a missing PID must not match"
);
}
#[test]
fn parse_symforge_process_lines_parses_pid_path_and_skips_malformed() {
let text = "100|C:\\npm\\symforge.exe\r\n\
200|C:\\other\\symforge.exe\n\
notapid|C:\\x\\symforge.exe\n\
300|\n\
\n\
400|C:\\a b\\symforge.exe";
let parsed = parse_symforge_process_lines(text);
assert_eq!(
parsed,
vec![
(100, "C:\\npm\\symforge.exe".to_string()),
(200, "C:\\other\\symforge.exe".to_string()),
(400, "C:\\a b\\symforge.exe".to_string()),
],
"malformed pid, empty path, and blank lines are skipped"
);
}
#[test]
fn orchestrate_update_prunes_registry_before_install_on_success() {
let mut ops = ok_ops();
ops.prune_lines = vec!["pruned 2 stale version-registry entries".to_string()];
orchestrate_update("linux", "x86_64", &mut ops).expect("update should succeed");
assert_eq!(ops.prune_calls, 1, "prune runs exactly once");
assert_eq!(
ops.pruned_before_install,
Some(true),
"prune precedes the npm swap"
);
}
#[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() {
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() {
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() {
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() {
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"));
}
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
struct SymforgeHomeGuard {
prev: Option<std::ffi::OsString>,
}
impl SymforgeHomeGuard {
#[allow(unsafe_code)] fn set(value: &std::path::Path) -> Self {
let prev = std::env::var_os("SYMFORGE_HOME");
unsafe { std::env::set_var("SYMFORGE_HOME", value) };
Self { prev }
}
}
impl Drop for SymforgeHomeGuard {
#[allow(unsafe_code)] fn drop(&mut self) {
match &self.prev {
Some(prev) => unsafe { std::env::set_var("SYMFORGE_HOME", prev) },
None => unsafe { std::env::remove_var("SYMFORGE_HOME") },
}
}
}
#[test]
fn remove_orphan_durable_bin_cleans_under_symforge_home_and_spares_self_exe() {
let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::TempDir::new().unwrap();
let bin = home.path().join("bin");
std::fs::create_dir_all(&bin).unwrap();
let leftover = bin.join("symforge.exe");
std::fs::write(&leftover, b"old-7.14.4-binary").unwrap();
let bystander = bin.join("notes.txt");
std::fs::write(&bystander, b"keep me").unwrap();
let _home_guard = SymforgeHomeGuard::set(home.path());
let self_exe = std::env::current_exe().unwrap();
assert!(self_exe.exists(), "precondition: running exe exists");
let summary = remove_orphan_durable_bin();
assert!(
!leftover.exists(),
"the retired durable leftover under $SYMFORGE_HOME/bin must be removed"
);
assert_eq!(summary.len(), 1, "exactly one summary line: {summary:?}");
assert!(
summary[0].contains("symforge.exe"),
"summary names what was removed: {summary:?}"
);
assert!(bystander.exists(), "an unwatched file must be left alone");
assert!(
self_exe.exists(),
"the binary backing the running process must never be deleted"
);
}
#[test]
fn remove_orphan_durable_bin_skips_the_running_binary_when_it_lives_in_the_bin_dir() {
let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let self_exe = match std::env::current_exe()
.ok()
.and_then(|p| std::fs::canonicalize(p).ok())
{
Some(p) => p,
None => return, };
let home = tempfile::TempDir::new().unwrap();
let bin = home.path().join("bin");
std::fs::create_dir_all(&bin).unwrap();
let watched = bin.join("symforge.exe");
if make_symlink(&self_exe, &watched).is_err() {
return;
}
let resolves_to_self =
std::fs::canonicalize(&watched).ok().as_deref() == Some(self_exe.as_path());
if !resolves_to_self {
return;
}
let _home_guard = SymforgeHomeGuard::set(home.path());
let summary = remove_orphan_durable_bin();
assert!(
watched.exists() || std::fs::symlink_metadata(&watched).is_ok(),
"the entry resolving to the running binary must NOT be removed"
);
assert!(self_exe.exists(), "the running binary itself must survive");
assert!(
summary.is_empty(),
"nothing should be reported removed: {summary:?}"
);
}
#[cfg(unix)]
fn make_symlink(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(src, dst)
}
#[cfg(windows)]
fn make_symlink(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
std::os::windows::fs::symlink_file(src, dst)
}
}