Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix update rollback and archive on installer installs (#3278)

ktba9c6a9ad2ca
diff --git a/crates/pa-cli/src/command_registry.rs b/crates/pa-cli/src/command_registry.rs
index 6772753696..f585a44b2f 100644
--- a/crates/pa-cli/src/command_registry.rs
+++ b/crates/pa-cli/src/command_registry.rs
@@ -212,11 +212,11 @@ pub const COMMAND_SPECS: &[CommandSpec] = &[
.options(&[
"--check Print the update channel's latest release vs the running version, without installing",
"--force Reinstall the latest build of the channel",
- "--rollback Restore the previous compiled release (the managed-install flow)",
+ "--rollback Restore the previous version the last update kept",
"--nightly Switch updates to the nightly channel (the latest main build)",
"--stable Return updates to the stable channel",
- "--archive <path> Install a local release payload (the managed-install flow)",
- "--source <url> The https:// origin recorded as the release's install source (required with --archive)",
+ "--archive <path> Install a local release archive",
+ "--source <url> The https:// origin recorded as the release's install source (managed installs; required there with --archive)",
])
.description(
"Move from the TypeScript version to the Rust port in one step: `prime-agent update` \
diff --git a/crates/pa-cli/src/installer_update.rs b/crates/pa-cli/src/installer_update.rs
index f17b243b09..7fe485e062 100644
--- a/crates/pa-cli/src/installer_update.rs
+++ b/crates/pa-cli/src/installer_update.rs
@@ -126,6 +126,65 @@ pub fn run(options: &UpdateOptions) -> i32 {
}
}
+/// The local operation on an installer install: `--rollback` restores the
+/// previous version the last install kept, `--archive` installs a local
+/// release archive. Both run the installer script bundled into this build
+/// against the prefix the running binary was installed under. Returns the
+/// process exit code.
+pub fn run_local(prefix: &std::path::Path, archive: Option<&std::path::Path>) -> i32 {
+ let archive = match archive.map(std::path::absolute).transpose() {
+ Ok(archive) => archive,
+ Err(error) => {
+ eprintln!("Error: could not resolve the archive path: {error}");
+ return 1;
+ }
+ };
+ let args: Vec<&std::ffi::OsStr> = match &archive {
+ Some(path) => vec!["--archive".as_ref(), path.as_os_str()],
+ None => vec!["--rollback".as_ref()],
+ };
+ let Ok(runtime) = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ else {
+ eprintln!("Error: could not start the update runtime.");
+ return 1;
+ };
+ #[cfg(windows)]
+ let handed_off = installer::caller_owns_payload(prefix);
+ match runtime.block_on(installer::run_bundled_installer(prefix, &args)) {
+ Ok(installed) => {
+ #[cfg(windows)]
+ if handed_off {
+ // The handed-off child prints its own outcome to the
+ // inherited terminal after this process exits; this
+ // process never saw the landed version, so the "rolled
+ // back to" line would lie. The announcement rides here —
+ // the child is spawned by now, so a refused pre-flight
+ // (which returns Err below) never announced a background
+ // run that does not exist.
+ println!(
+ "the {} continues in the background after this command exits — Windows only releases the payload once this process does",
+ if archive.is_some() { "archive install" } else { "rollback" }
+ );
+ return 0;
+ }
+ let done = if archive.is_some() {
+ "installed"
+ } else {
+ "rolled back to"
+ };
+ let version = installed.version.as_deref().unwrap_or("the previous build");
+ println!("{done} {version} — restart prime-agent to run it");
+ 0
+ }
+ Err(failure) => {
+ eprintln!("Error: {}", failure.message);
+ 1
+ }
+ }
+}
+
/// Persist an explicit channel switch (`--nightly` / `--stable`) after a
/// completed update.
fn save_channel(channel: UpdateChannel) {
diff --git a/crates/pa-cli/src/public_command.rs b/crates/pa-cli/src/public_command.rs
index 98f60de310..2906295db7 100644
--- a/crates/pa-cli/src/public_command.rs
+++ b/crates/pa-cli/src/public_command.rs
@@ -334,8 +334,9 @@ fn validate_schedule_args(args: &[String]) -> bool {
}
/// Parse `update`'s options into the shared [`crate::self_update::SelfUpdateOptions`]:
-/// the TS booleans plus the direct-install pair (`--archive <path>` with the
-/// required `--source <https-url>`). Returns `None` on a usage failure
+/// the TS booleans plus the direct-install pair (`--archive <path>` with
+/// `--source <https-url>`, which only a managed install takes and requires).
+/// Returns `None` on a usage failure
/// (already reported).
fn parse_update_options(args: &[String]) -> Option<crate::self_update::SelfUpdateOptions> {
let mut invocation = crate::self_update::SelfUpdateOptions::default();
@@ -404,19 +405,11 @@ fn parse_update_options(args: &[String]) -> Option<crate::self_update::SelfUpdat
);
return None;
}
- if invocation.source.is_none() {
- fail(
- "--archive needs --source <https-url>.",
- Some(
- "The install source is recorded in the release and future updates resolve from it."
- .to_string(),
- ),
- );
- return None;
- }
- if !pa_core::update::install::install_source_is_valid(
- invocation.source.as_deref().unwrap_or_default(),
- ) {
+ if invocation
+ .source
+ .as_deref()
+ .is_some_and(|source| !pa_core::update::install::install_source_is_valid(source))
+ {
fail(
"--source must be an http(s) URL.",
Some(format!("Run \"{APP_NAME} help update\" for usage.")),
@@ -682,6 +675,44 @@ fn run_update(args: &[String]) -> PublicCommandResult {
let Some(options) = parse_update_options(args) else {
return handled_failed();
};
+ // `--rollback` and `--archive` on an installer install run the bundled
+ // installer; any other binary stays on the managed-install flow.
+ if options.rollback || options.archive.is_some() {
+ if let Some(prefix) = pa_core::update::installer::running_installer_prefix() {
+ if options.source.is_some() {
+ return fail(
+ "--source only applies to managed installs.",
+ Some(
+ "An installer install keeps updating from its release channel.".to_string(),
+ ),
+ );
+ }
+ if options.channel.is_some() {
+ return fail(
+ "--nightly and --stable do not apply to --rollback or --archive.",
+ Some(format!(
+ "Switch channels with \"{APP_NAME} update --nightly\" or \"--stable\"."
+ )),
+ );
+ }
+ // The CLI's --force is the nightly-switch confirmation skip;
+ // the installer's own forced daemon stop is a different flag
+ // the funnel never forwards either — so the local modes refuse
+ // it instead of silently dropping it.
+ if options.force {
+ return fail(
+ "--force does not apply to --rollback or --archive.",
+ Some(format!(
+ "To stop busy daemons first, run \"{APP_NAME} shutdown --force\" and re-run."
+ )),
+ );
+ }
+ return handled_with_exit(crate::installer_update::run_local(
+ &prefix,
+ options.archive.as_deref(),
+ ));
+ }
+ }
let persisted_wire = std::env::current_dir()
.ok()
.and_then(|cwd| {
@@ -700,8 +731,7 @@ fn run_update(args: &[String]) -> PublicCommandResult {
}
// The installer funnel serves the bare update and the channel flags:
// the channel is the flag, else the saved `updateChannel` setting
- // (`/nightly on|off`), else the installed one. `--rollback` and
- // `--archive` stay on the managed-install flow.
+ // (`/nightly on|off`), else the installed one.
if !options.rollback && options.archive.is_none() {
let update = crate::installer_update::UpdateOptions {
check: false,
@@ -709,6 +739,15 @@ fn run_update(args: &[String]) -> PublicCommandResult {
};
return handled_with_exit(crate::installer_update::run(&update));
}
+ if options.archive.is_some() && options.source.is_none() {
+ return fail(
+ "--archive needs --source <https-url>.",
+ Some(
+ "The install source is recorded in the release and future updates resolve from it."
+ .to_string(),
+ ),
+ );
+ }
handled_with_exit(crate::self_update::run(&options, persisted_wire.as_deref()))
}
@@ -1024,6 +1063,10 @@ mod update_options_tests {
Some(std::path::PathBuf::from("/tmp/payload"))
);
assert_eq!(invocation.source.as_deref(), Some("https://example.com"));
+ // An installer install takes the archive alone (the managed flow's
+ // --source requirement is checked once the install type is known).
+ let invocation = parse(&["--archive", "/tmp/payload"]).unwrap();
+ assert_eq!(invocation.source, None);
// The source must be an http(s) URL and must not appear alone.
assert!(parse(&[
"--archive",
diff --git a/crates/pa-cli/tests/installer_update_e2e.rs b/crates/pa-cli/tests/installer_update_e2e.rs
index e71cc293b0..0e948b0dfc 100644
--- a/crates/pa-cli/tests/installer_update_e2e.rs
+++ b/crates/pa-cli/tests/installer_update_e2e.rs
@@ -276,6 +276,464 @@ fn a_failing_installer_keeps_the_previous_install() {
sandbox.assert_session_preserved();
}
+/// A hermetic world for the real `install-rust.sh`: `HOME` and `TMPDIR`
+/// (the daemon sockets the installer probes) live in the sandbox, and
+/// `PATH` puts shims first — `uv` answers only `python find` (the
+/// installer's own Python), `npm` reports an empty global root — so the run
+/// never touches the network, the machine's daemons, or a global npm
+/// package.
+fn installer_env(command: &mut Command, sandbox: &Sandbox) {
+ let shims = sandbox.root.join("shims");
+ std::fs::create_dir_all(&shims).expect("shims dir");
+ let python = [
+ "/usr/bin/python3",
+ "/usr/local/bin/python3",
+ "/opt/homebrew/bin/python3",
+ ]
+ .into_iter()
+ .find(|path| Path::new(path).is_file())
+ .expect("a python3 for the installer's scripting steps");
+ let uv = shims.join("uv");
+ std::fs::write(
+ &uv,
+ format!("#!/bin/sh\n[ \"$1 $2\" = \"python find\" ] && echo {python} && exit 0\nexit 1\n"),
+ )
+ .expect("uv shim");
+ make_executable(&uv);
+ let npm = shims.join("npm");
+ std::fs::write(
+ &npm,
+ "#!/bin/sh\n[ \"$1\" = root ] && echo /nonexistent\nexit 0\n",
+ )
+ .expect("npm shim");
+ make_executable(&npm);
+ let tmp = sandbox.root.join("tmp");
+ std::fs::create_dir_all(&tmp).expect("tmp dir");
+ command
+ .env_clear()
+ .env("PATH", format!("{}:/usr/bin:/bin", shims.display()))
+ .env("HOME", sandbox.root.join("home"))
+ .env("TMPDIR", tmp)
+ .env(ENV_PREFIX, &sandbox.prefix)
+ .current_dir(&sandbox.root);
+}
+
+/// A release archive whose payload is a script answering `version`.
+fn fake_release(sandbox: &Sandbox, version: &str) -> PathBuf {
+ let payload = sandbox.root.join(format!("payload-{version}"));
+ std::fs::create_dir_all(&payload).expect("payload dir");
+ let binary = payload.join("prime-agent");
+ std::fs::write(&binary, format!("#!/bin/sh\necho {version}\n")).expect("payload binary");
+ make_executable(&binary);
+ let platform = pa_core::update::install::current_platform_alias();
+ let archive = sandbox
+ .root
+ .join(format!("prime-agent-{version}-{platform}.tar.gz"));
+ let status = Command::new("tar")
+ .arg("-czf")
+ .arg(&archive)
+ .arg("-C")
+ .arg(&payload)
+ .arg("prime-agent")
+ .status()
+ .expect("run tar");
+ assert!(status.success(), "tar the fake release");
+ archive
+}
+
+fn assert_ran(output: &std::process::Output, what: &str) -> String {
+ let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
+ assert!(
+ output.status.success(),
+ "{what} succeeds:\nstdout:\n{stdout}\nstderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ stdout
+}
+
+/// The version the live payload's install marker records.
+fn live_version(sandbox: &Sandbox) -> String {
+ let marker = std::fs::read_to_string(
+ sandbox
+ .prefix
+ .join("share/prime-agent/.prime-agent-install"),
+ )
+ .expect("the live payload's marker");
+ marker
+ .lines()
+ .nth(1)
+ .and_then(|line| line.strip_prefix("version "))
+ .expect("the marker's version line")
+ .to_string()
+}
+
+/// On an installer install, `update --archive` and `update --rollback` run
+/// the bundled installer: the archive goes live with the replaced payload
+/// kept, `--rollback` swaps the kept payload back (keeping the one it
+/// replaces), so a second `--rollback` undoes the first; the session store
+/// is untouched throughout.
+#[test]
+fn update_archive_and_rollback_swap_installer_payloads() {
+ let sandbox = Sandbox::new();
+ // This build, published as an installer payload.
+ let live = sandbox.prefix.join("share/prime-agent");
+ std::fs::create_dir_all(&live).expect("payload dir");
+ let binary = live.join("prime-agent");
+ std::fs::copy(env!("CARGO_BIN_EXE_prime-agent"), &binary).expect("copy this build");
+ std::fs::write(
+ live.join(".prime-agent-install"),
+ "install-rust.sh channel beta\nversion 9.9.9\n",
+ )
+ .expect("install marker");
+ let run_update = |args: &[&str]| {
+ let mut command = Command::new(&binary);
+ command.arg("update").args(args);
+ installer_env(&mut command, &sandbox);
+ command.output().expect("run the installed build")
+ };
+
+ let archive = fake_release(&sandbox, "1.0.0");
+ let stdout = assert_ran(
+ &run_update(&["--archive", archive.to_str().expect("utf-8 path")]),
+ "update --archive",
+ );
+ assert!(stdout.contains("installed 1.0.0"), "{stdout}");
+ assert_eq!(live_version(&sandbox), "1.0.0");
+
+ // The archive's payload cannot run `update`: roll back with the script
+ // itself (the bundled copy is this file).
+ let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../install-rust.sh");
+ let mut command = Command::new("/bin/sh");
+ command.arg(&script).arg("--rollback");
+ installer_env(&mut command, &sandbox);
+ assert_ran(
+ &command.output().expect("run the installer"),
+ "install-rust.sh --rollback",
+ );
+ assert_eq!(
+ live_version(&sandbox),
+ "9.9.9",
+ "the kept build is live again"
+ );
+
+ let stdout = assert_ran(&run_update(&["--rollback"]), "update --rollback");
+ assert!(stdout.contains("rolled back to 1.0.0"), "{stdout}");
+ assert_eq!(
+ live_version(&sandbox),
+ "1.0.0",
+ "a second rollback undoes the first"
+ );
+ sandbox.assert_session_preserved();
+}
+
+/// The rollback pre-flight: the installer's check mode answers the
+/// rollback question synchronously — nothing kept is its own refusal,
+/// a kept generation prints the source and exits without touching the
+/// payload (the Windows update handoff runs this exact scan before it
+/// hands the real run off, so its exit code is honest for the
+/// deterministic refusals).
+#[test]
+fn rollback_check_answers_synchronously_without_touching_the_payload() {
+ let sandbox = Sandbox::new();
+ let live = sandbox.prefix.join("share/prime-agent");
+ std::fs::create_dir_all(&live).expect("payload dir");
+ let binary = live.join("prime-agent");
+ std::fs::copy(env!("CARGO_BIN_EXE_prime-agent"), &binary).expect("copy this build");
+ std::fs::write(
+ live.join(".prime-agent-install"),
+ "install-rust.sh channel beta\nversion 9.9.9\n",
+ )
+ .expect("install marker");
+ let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../install-rust.sh");
+ let run_check = || {
+ let mut command = Command::new("/bin/sh");
+ command.arg(&script).arg("--rollback");
+ installer_env(&mut command, &sandbox);
+ command
+ .env("PRIME_AGENT_ROLLBACK_CHECK", "1")
+ .output()
+ .expect("run the installer's check mode")
+ };
+
+ let output = run_check();
+ assert_eq!(output.status.code(), Some(1));
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("nothing to roll back"), "{stderr}");
+ assert_eq!(live_version(&sandbox), "9.9.9");
+
+ let archive = fake_release(&sandbox, "1.0.0");
+ let mut command = Command::new(&binary);
+ command
+ .arg("update")
+ .arg("--archive")
+ .arg(archive.to_str().expect("utf-8 path"));
+ installer_env(&mut command, &sandbox);
+ assert_ran(
+ &command.output().expect("run the installed build"),
+ "update --archive",
+ );
+ assert_eq!(live_version(&sandbox), "1.0.0");
+
+ let output = run_check();
+ assert!(output.status.success(), "the check finds the kept build");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let source = stdout.lines().last().unwrap_or_default().to_string();
+ let kept = source.strip_prefix(sandbox.prefix.display().to_string().as_str());
+ assert!(
+ kept.is_some_and(|rest| rest.starts_with("/share/prime-agent.old.")),
+ "the source names the kept generation: {source}"
+ );
+ assert_eq!(live_version(&sandbox), "1.0.0", "the check touched nothing");
+ let leftovers: Vec<String> = std::fs::read_dir(sandbox.root.join("tmp"))
+ .expect("tmp dir")
+ .filter_map(std::result::Result::ok)
+ .filter_map(|entry| entry.file_name().into_string().ok())
+ .filter(|name| name.contains("prime-agent-download"))
+ .collect();
+ assert!(
+ leftovers.is_empty(),
+ "the check mode cleans its staging: {leftovers:?}"
+ );
+ sandbox.assert_session_preserved();
+}
+
+/// A mis-named archive is refused before the publish: the payload's own
+/// `--version` is the ground truth for the marker the install records
+/// (and the rollback later reports), so a name/payload mismatch would
+/// publish a lie.
+#[test]
+fn update_archive_refuses_a_misnamed_payload_version() {
+ let sandbox = Sandbox::new();
+ let live = sandbox.prefix.join("share/prime-agent");
+ std::fs::create_dir_all(&live).expect("payload dir");
+ let binary = live.join("prime-agent");
+ std::fs::copy(env!("CARGO_BIN_EXE_prime-agent"), &binary).expect("copy this build");
+ std::fs::write(
+ live.join(".prime-agent-install"),
+ "install-rust.sh channel beta\nversion 9.9.9\n",
+ )
+ .expect("install marker");
+ let platform = pa_core::update::install::current_platform_alias();
+ let payload_dir = sandbox.root.join("payload-misnamed");
+ std::fs::create_dir_all(&payload_dir).expect("payload dir");
+ let payload = payload_dir.join("prime-agent");
+ std::fs::write(&payload, "#!/bin/sh\necho 0.9.7\n").expect("payload binary");
+ make_executable(&payload);
+ let archive = sandbox
+ .root
+ .join(format!("prime-agent-9.9.9-{platform}.tar.gz"));
+ let status = Command::new("tar")
+ .arg("-czf")
+ .arg(&archive)
+ .arg("-C")
+ .arg(&payload_dir)
+ .arg("prime-agent")
+ .status()
+ .expect("run tar");
+ assert!(status.success(), "tar the misnamed release");
+
+ let mut command = Command::new(&binary);
+ command
+ .arg("update")
+ .arg("--archive")
+ .arg(archive.to_str().expect("utf-8 path"));
+ installer_env(&mut command, &sandbox);
+ let output = command.output().expect("run the installed build");
+ assert_eq!(output.status.code(), Some(1));
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("the archive names 9.9.9 but its payload reports 0.9.7"),
+ "{stderr}"
+ );
+ assert_eq!(live_version(&sandbox), "9.9.9", "nothing was published");
+ sandbox.assert_session_preserved();
+}
+
+/// The install.ps1 slot: the Windows-native installer keeps its replaced
+/// payload at the un-suffixed `prime-agent.old` and never writes the
+/// generations record, so the CLI's rollback must fall back to that
+/// slot — a ps1-updated machine's only automated rollback path.
+#[test]
+fn update_rollback_reads_the_unsuffixed_installer_slot() {
+ let sandbox = Sandbox::new();
+ let live = sandbox.prefix.join("share/prime-agent");
+ std::fs::create_dir_all(&live).expect("payload dir");
+ let binary = live.join("prime-agent");
+ std::fs::copy(env!("CARGO_BIN_EXE_prime-agent"), &binary).expect("copy this build");
+ std::fs::write(
+ live.join(".prime-agent-install"),
+ "install-rust.sh channel beta\nversion 9.9.9\n",
+ )
+ .expect("install marker");
+ // The install.ps1 era: the replaced payload sits at the un-suffixed
+ // name, and no generations record exists.
+ let slot = sandbox.prefix.join("share/prime-agent.old");
+ std::fs::create_dir_all(&slot).expect("slot dir");
+ std::fs::write(
+ slot.join(".prime-agent-install"),
+ "install-rust.sh channel beta\nversion 1.0.0\n",
+ )
+ .expect("slot marker");
+ std::fs::write(slot.join("prime-agent"), b"payload\n").expect("slot payload");
+ make_executable(&slot.join("prime-agent"));
+
+ let mut command = Command::new(&binary);
+ command.args(["update", "--rollback"]);
+ installer_env(&mut command, &sandbox);
+ let output = command.output().expect("run the installed build");
+ assert!(output.status.success(), "the slot is a rollback source");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(stdout.contains("rolled back to 1.0.0"), "{stdout}");
+ assert_eq!(
+ live_version(&sandbox),
+ "1.0.0",
+ "the slot's payload is live"
+ );
+ // The displaced live tree becomes a recorded generation: the machine
+ // converts to the sh bookkeeping, so the toggle keeps working.
+ let record = sandbox
+ .prefix
+ .join("share/.prime-agent-install-generations");
+ assert!(
+ record.exists(),
+ "the publish recorded the displaced payload"
+ );
+ sandbox.assert_session_preserved();
+}
+
+/// A fresh installer install has nothing to roll back: the run fails with
+/// the reason and the live payload stays.
+#[test]
+fn update_rollback_without_a_kept_version_changes_nothing() {
+ let sandbox = Sandbox::new();
+ let live = sandbox.prefix.join("share/prime-agent");
+ std::fs::create_dir_all(&live).expect("payload dir");
+ let binary = live.join("prime-agent");
+ std::fs::copy(env!("CARGO_BIN_EXE_prime-agent"), &binary).expect("copy this build");
+ std::fs::write(
+ live.join(".prime-agent-install"),
+ "install-rust.sh channel beta\nversion 9.9.9\n",
+ )
+ .expect("install marker");
+ let mut command = Command::new(&binary);
+ command.args(["update", "--rollback"]);
+ installer_env(&mut command, &sandbox);
+ let output = command.output().expect("run the installed build");
+ assert_eq!(output.status.code(), Some(1));
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("nothing to roll back"), "{stderr}");
+ assert_eq!(live_version(&sandbox), "9.9.9");
+
+ // A channel flag has nothing to switch in a local operation: refused
+ // before any prompt or install.
+ let mut command = Command::new(&binary);
+ command.args(["update", "--rollback", "--nightly"]);
+ installer_env(&mut command, &sandbox);
+ let output = command.output().expect("run the installed build");
+ assert_eq!(output.status.code(), Some(1));
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("do not apply to --rollback"), "{stderr}");
+ assert_eq!(live_version(&sandbox), "9.9.9");
+
+ // The CLI's --force is the nightly-switch confirmation skip; the
+ // local operations refuse it instead of silently dropping it.
+ let mut command = Command::new(&binary);
+ command.args(["update", "--rollback", "--force"]);
+ installer_env(&mut command, &sandbox);
+ let output = command.output().expect("run the installed build");
+ assert_eq!(output.status.code(), Some(1));
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("--force does not apply"), "{stderr}");
+ assert!(stderr.contains("shutdown --force"), "{stderr}");
+ assert_eq!(live_version(&sandbox), "9.9.9");
+}
+
+/// The archive pre-flight: the installer's check mode answers the
+/// archive question synchronously — a mis-named archive is its own
+/// refusal, a good one validates and exits without publishing (the
+/// Windows update handoff runs this exact validation before it hands
+/// the real run off, so its exit code is honest for the deterministic
+/// refusals).
+#[test]
+fn archive_check_answers_synchronously_without_publishing() {
+ let sandbox = Sandbox::new();
+ let live = sandbox.prefix.join("share/prime-agent");
+ std::fs::create_dir_all(&live).expect("payload dir");
+ let binary = live.join("prime-agent");
+ std::fs::copy(env!("CARGO_BIN_EXE_prime-agent"), &binary).expect("copy this build");
+ std::fs::write(
+ live.join(".prime-agent-install"),
+ "install-rust.sh channel beta\nversion 9.9.9\n",
+ )
+ .expect("install marker");
+ let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../install-rust.sh");
+ let run_check = |archive: &std::path::Path| {
+ let mut command = Command::new("/bin/sh");
+ command.arg(&script).arg("--archive").arg(archive);
+ installer_env(&mut command, &sandbox);
+ command
+ .env("PRIME_AGENT_ARCHIVE_CHECK", "1")
+ .output()
+ .expect("run the installer's check mode")
+ };
+
+ // A mis-named archive: the payload answers 0.9.7 under a 9.9.9 name.
+ let misnamed = fake_release_payload(&sandbox, "9.9.9", "0.9.7");
+ let output = run_check(&misnamed);
+ assert_eq!(output.status.code(), Some(1));
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("the archive names 9.9.9 but its payload reports 0.9.7"),
+ "{stderr}"
+ );
+ assert_eq!(live_version(&sandbox), "9.9.9");
+ let leftovers: Vec<String> = std::fs::read_dir(sandbox.prefix.join("share"))
+ .expect("share dir")
+ .filter_map(std::result::Result::ok)
+ .filter_map(|entry| entry.file_name().into_string().ok())
+ .filter(|name| name.contains("prime-agent.stage"))
+ .collect();
+ assert!(leftovers.is_empty(), "no stage dir survives: {leftovers:?}");
+
+ // A good archive: the check validates and exits without publishing.
+ let good = fake_release(&sandbox, "9.9.9");
+ let output = run_check(&good);
+ assert!(
+ output.status.success(),
+ "the check accepts the good archive"
+ );
+ assert_eq!(
+ live_version(&sandbox),
+ "9.9.9",
+ "the check published nothing"
+ );
+ sandbox.assert_session_preserved();
+}
+
+/// A release archive whose payload answers `reported` under the archive
+/// name `named` (the mis-naming fixture for the check-mode test).
+fn fake_release_payload(sandbox: &Sandbox, named: &str, reported: &str) -> PathBuf {
+ let payload = sandbox.root.join(format!("payload-mismatch-{named}"));
+ std::fs::create_dir_all(&payload).expect("payload dir");
+ let binary = payload.join("prime-agent");
+ std::fs::write(&binary, format!("#!/bin/sh\necho {reported}\n")).expect("payload binary");
+ make_executable(&binary);
+ let platform = pa_core::update::install::current_platform_alias();
+ let archive = sandbox
+ .root
+ .join(format!("prime-agent-{named}-{platform}.tar.gz"));
+ let status = Command::new("tar")
+ .arg("-czf")
+ .arg(&archive)
+ .arg("-C")
+ .arg(&payload)
+ .arg("prime-agent")
+ .status()
+ .expect("run tar");
+ assert!(status.success(), "tar the mismatched release");
+ archive
+}
+
fn make_executable(path: &Path) {
use std::os::unix::fs::PermissionsExt as _;
let mut permissions = std::fs::metadata(path).expect("metadata").permissions();
diff --git a/crates/pa-core/src/update/installer.rs b/crates/pa-core/src/update/installer.rs
index e752a6c70e..cc430e6d06 100644
--- a/crates/pa-core/src/update/installer.rs
+++ b/crates/pa-core/src/update/installer.rs
@@ -11,6 +11,7 @@
//! stays in the script the installer-takeover lane owns, so the two
//! surfaces can never drift from it.
+use std::io::{Seek as _, SeekFrom, Write as _};
use std::path::{Path, PathBuf};
use std::time::Duration;
@@ -42,6 +43,19 @@ pub const OFFICIAL_INSTALLER_URL: &str = "https://app.primeintellect.ai/prime-ag
/// forwards `install.sh`, so nightly updates fetch it from the base).
pub const BETA_INSTALLER_FILE: &str = "install-beta.sh";
+/// `install-rust.sh` as this build shipped it. The local operations
+/// (`prime-agent update --rollback` and `--archive`) run this copy: they
+/// need no network, and the script matches the layout this build was
+/// installed with.
+const BUNDLED_INSTALLER: &str = include_str!("../../../../install-rust.sh");
+
+/// The payload binary's file name under `<prefix>/share/prime-agent`.
+const PAYLOAD_BINARY: &str = if cfg!(windows) {
+ "prime-agent.exe"
+} else {
+ "prime-agent"
+};
+
/// The small-file budget for the script download (the script is a few KB;
/// a hung fetch must not hang the update).
const SCRIPT_FETCH_TIMEOUT: Duration = Duration::from_secs(30);
@@ -213,14 +227,252 @@ pub async fn run_installer_from(
current_target().map_err(|error| UpdateFailure {
message: format!("{error:#}"),
})?;
- let script = fetch_script(url).await.map_err(|error| UpdateFailure {
+ let (script, handle) = fetch_script(url).await.map_err(|error| UpdateFailure {
message: format!("could not download the installer from {url}: {error:#}"),
})?;
- execute_script(&script, prefix, channel, output).await?;
+ let result = execute_script(&handle, &[], prefix, channel, output).await;
+ let _ = std::fs::remove_file(&script);
+ result?;
let version = launcher_version(prefix).await;
Ok(Installed { version })
}
+/// Run the bundled `install-rust.sh` with `args` (`--rollback`, or `--archive
+/// <path>`) against the install under `prefix`. On success the version is
+/// the one the published payload's install marker records — except on the
+/// Windows payload handoff, where the caller IS the locked payload: the
+/// child is spawned detached and no version is read (the installer's own
+/// streamed output carries the outcome).
+///
+/// # Errors
+/// Returns the failure message when the script cannot be written or run,
+/// or exits nonzero (its own message already streamed to the terminal).
+pub async fn run_bundled_installer(
+ prefix: &Path,
+ args: &[&std::ffi::OsStr],
+) -> std::result::Result<Installed, UpdateFailure> {
+ // `mut` serves the Windows handoff's post-pre-flight rewind; the
+ // unix path only ever borrows the handle.
+ #[cfg_attr(not(windows), allow(unused_mut))]
+ let (script, mut handle) =
+ write_script(BUNDLED_INSTALLER.as_bytes()).map_err(|error| UpdateFailure {
+ message: format!("could not write the bundled installer: {error:#}"),
+ })?;
+ #[cfg(windows)]
+ if caller_owns_payload(prefix) {
+ // THE HANDOFF (Windows rename rule): this process's image sits inside
+ // <prefix>/share/prime-agent and Windows refuses to rename a directory
+ // that contains a running image, so the script's publish step can only
+ // succeed after this process exits. The child is spawned without
+ // waiting and inherits the terminal, so the installer's own steps and
+ // error messages still print there. The script rides the child's stdin
+ // (`bash -s --`, the curl|sh one-liner's own invocation form), so the
+ // temp file's name is removed the moment the child holds its handle —
+ // nothing of this run outlives the process, not even on a failed
+ // spawn (std opens with FILE_SHARE_DELETE; a failure leaves nobody
+ // reading and the removal is the same). The caller returns
+ // immediately; the outcome rides the installer's own output.
+ // The local-mode pre-flight (the exact-equivalence source): the
+ // rollback's generations record rides the script's OWN prefix
+ // spelling (cygpath + physical_path), and the archive's checks
+ // (name, tar, payload, the version the packaged package.json
+ // reports) are the script's staged run's own — no native mirror
+ // can answer either faithfully, so the script itself answers, in
+ // its PRIME_AGENT_ROLLBACK_CHECK / PRIME_AGENT_ARCHIVE_CHECK
+ // modes, synchronously. Neither mode claims the lock or renames
+ // the live tree (the rollback check only reads; the archive
+ // check's extraction rides a temporary stage swept on its own
+ // exit), so waiting never fights this process's locked image,
+ // and the refusal they print is the one the handed-off run
+ // would die with — the caller exits with the real status, and
+ // only the publication itself stays async (the platform-
+ // inherent residue).
+ if let Err(error) = local_mode_preflight(&handle, prefix, args).await {
+ let _ = std::fs::remove_file(&script);
+ return Err(error);
+ }
+ // The pre-flight child read the script to EOF through its own
+ // descriptor — a clone shares this handle's file position, so the
+ // real child must start from the first byte again.
+ handle.seek(SeekFrom::Start(0)).map_err(|error| {
+ let _ = std::fs::remove_file(&script);
+ UpdateFailure {
+ message: format!("could not run the installer: {error}"),
+ }
+ })?;
+ let shell = trusted_shell().inspect_err(|_| {
+ let _ = std::fs::remove_file(&script);
+ })?;
+ let mut command = installer_child(&shell, prefix, None);
+ command
+ .arg("-s")
+ .arg("--")
+ .args(args)
+ .stdin(std::process::Stdio::from(handle));
+ // THE PROCESS-CONTROL WALL (the in-house detached-spawn wrapper:
+ // CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS | CREATE_NO_WINDOW,
+ // the product's own detached-survives-parent mapping): a console-
+ // attached child dies with the caller's terminal close (the
+ // CTRL_CLOSE broadcast) — mid-publish, exactly when the handoff
+ // exists to let it finish — and Ctrl+C at the caller's terminal
+ // must not reach the installer either. The inherited stdio
+ // handles keep the installer's own steps printing to the
+ // caller's window for as long as that window lives.
+ crate::platform::process::set_new_process_group(command.as_std_mut());
+ // THE PARENT EXIT: the payload unlock this whole handoff exists
+ // for happens only when THIS process dies — the child gets the
+ // pid and the script's head waits for it (bounded) before any
+ // step touches the payload, so the release-before-publish
+ // ordering is explicit instead of a spawn-timing coincidence.
+ command.env(
+ "PRIME_AGENT_INSTALLER_PARENT_PID",
+ std::process::id().to_string(),
+ );
+ let spawned = command.spawn();
+ let _ = std::fs::remove_file(&script);
+ spawned.map_err(|error| UpdateFailure {
+ message: format!("could not run the installer: {error}"),
+ })?;
+ return Ok(Installed { version: None });
+ }
+ let result = execute_script(&handle, args, prefix, None, InstallerOutput::Inherit).await;
+ let _ = std::fs::remove_file(&script);
+ result?;
+ Ok(Installed {
+ version: installed_version(prefix),
+ })
+}
+
+/// The install prefix of an installer-owned binary: `exe` is
+/// `<prefix>/share/prime-agent/prime-agent` (`prime-agent.exe` on Windows)
+/// and that payload carries the installer's marker. `None` for any other
+/// binary (a managed release, a development build).
+#[must_use]
+fn installer_prefix_of(exe: &Path) -> Option<PathBuf> {
+ let payload = exe.parent()?;
+ let share = payload.parent()?;
+ let owned = exe.file_name()? == PAYLOAD_BINARY
+ && payload.file_name()? == "prime-agent"
+ && share.file_name()? == "share";
+ let prefix = share.parent()?;
+ (owned && installed_channel(prefix).is_some()).then(|| prefix.to_path_buf())
+}
+
+/// The install prefix of the running binary when the installer owns it
+/// (`<prefix>/share/prime-agent/prime-agent` in a marked payload).
+#[must_use]
+pub fn running_installer_prefix() -> Option<PathBuf> {
+ let exe = std::env::current_exe().ok()?;
+ // Windows answers the module path already absolute; its canonical form
+ // is the \\?\ verbatim spelling, which the installer cannot take as a
+ // prefix.
+ #[cfg(not(windows))]
+ let exe = exe.canonicalize().ok()?;
+ installer_prefix_of(&exe)
+}
+
+/// True when this process's own image is the payload binary of `prefix`
+/// (`<prefix>/share/prime-agent/prime-agent.exe` with the install marker):
+/// the Windows rename rule — a running image locks its directory, so an
+/// installer child can only publish this payload after this process exits.
+/// On unix a rename never fights a running image, so the answer is false.
+#[must_use]
+pub fn caller_owns_payload(prefix: &Path) -> bool {
+ #[cfg(not(windows))]
+ {
+ let _ = prefix;
+ false
+ }
+ #[cfg(windows)]
+ {
+ // The same helper the CLI read its prefix from: both sides then
+ // spell the path identically (canonicalizing here would answer
+ // the \\?\ verbatim form the prefix never equals).
+ running_installer_prefix().is_some_and(|self_prefix| self_prefix == prefix)
+ }
+}
+
+/// The synchronous local-mode pre-flight for the Windows handoff: run the
+/// bundled installer ITSELF in its check mode — `PRIME_AGENT_ROLLBACK_CHECK`
+/// or `PRIME_AGENT_ARCHIVE_CHECK` by the requested mode — and fail with the
+/// script's own refusal when the operation cannot run. Neither mode ever
+/// claims the publication lock or renames the live tree — the rollback
+/// check only reads, and the archive check's extraction lives in a
+/// temporary stage swept on its own exit — so waiting never fights the
+/// locked image; and the answer is the script's OWN scan, the exact
+/// equivalence the caller's exit code needs (once handed off, the
+/// outcome can no longer be this process's exit status).
+///
+/// # Errors
+/// Returns the pre-flight's captured refusal tail or the spawn failure.
+#[cfg(windows)]
+async fn local_mode_preflight(
+ script: &std::fs::File,
+ prefix: &Path,
+ args: &[&std::ffi::OsStr],
+) -> std::result::Result<(), UpdateFailure> {
+ let shell = trusted_shell()?;
+ let mut command = installer_child(&shell, prefix, None);
+ command
+ .arg("-s")
+ .arg("--")
+ .args(args)
+ .stdin(std::process::Stdio::from(script.try_clone().map_err(
+ |error| UpdateFailure {
+ message: format!("could not run the installer: {error}"),
+ },
+ )?));
+ if args.first().copied() == Some(std::ffi::OsStr::new("--rollback")) {
+ command.env("PRIME_AGENT_ROLLBACK_CHECK", "1");
+ } else {
+ command.env("PRIME_AGENT_ARCHIVE_CHECK", "1");
+ }
+ let output = command.output().await.map_err(|error| UpdateFailure {
+ message: format!("could not run the installer: {error}"),
+ })?;
+ if output.status.success() {
+ return Ok(());
+ }
+ let refusal =
+ output_tail(&output).unwrap_or_else(|| "the installer refused the request".to_string());
+ Err(UpdateFailure { message: refusal })
+}
+
+/// Flatten an install marker's ps1-era encodings to plain bytes: strip a
+/// leading UTF-8 or UTF-16 BOM, then drop the NULs (UTF-16's interleave;
+/// this script's own ASCII markers contain none). UTF-16BE text loses its
+/// byte pairing, but the marker content is ASCII, so both UTF-16 orders
+/// read back as the same ASCII bytes.
+fn normalize_marker_bytes(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> {
+ let bytes = match bytes {
+ [0xEF, 0xBB, 0xBF, rest @ ..] | [0xFF, 0xFE, rest @ ..] | [0xFE, 0xFF, rest @ ..] => rest,
+ _ => bytes,
+ };
+ if bytes.contains(&0) {
+ std::borrow::Cow::Owned(
+ bytes
+ .iter()
+ .copied()
+ .filter(|byte| *byte != 0)
+ .collect::<Vec<u8>>(),
+ )
+ } else {
+ std::borrow::Cow::Borrowed(bytes)
+ }
+}
+
+/// The installed payload's version, read from the install marker's
+/// "version <v>" line — through the same encoding normalization as
+/// [`installed_channel`]: a ps1-written marker can be UTF-16 or
+/// BOM-prefixed, and the version line of an encoded marker must read too.
+fn installed_version(prefix: &Path) -> Option<String> {
+ let bytes = std::fs::read(prefix.join("share/prime-agent/.prime-agent-install")).ok()?;
+ let normalized = normalize_marker_bytes(&bytes).into_owned();
+ let marker = String::from_utf8_lossy(&normalized);
+ let version = marker.lines().nth(1)?.strip_prefix("version ")?.trim();
+ (!version.is_empty()).then(|| version.to_string())
+}
+
/// The installed payload's channel, read from the install marker (the
/// installer's own `.prime-agent-install` under the prefix's share dir;
/// its first line is "channel <name>"). `None` when the marker is absent
@@ -228,8 +480,16 @@ pub async fn run_installer_from(
/// the update then rides the fetched script's own default.
#[must_use]
pub fn installed_channel(prefix: &Path) -> Option<&'static str> {
- let marker =
- std::fs::read_to_string(prefix.join("share/prime-agent/.prime-agent-install")).ok()?;
+ // The marker read mirrors install-rust.sh's marker_text: install.ps1's
+ // Set-Content follows $PSDefaultParameterValues['*:Encoding'], so a
+ // ps1-published live marker can be UTF-16 (NUL-interleaved, and its
+ // BOM is not valid UTF-8, failing the whole read) or BOM-prefixed.
+ // Flattening the NULs and stripping a leading BOM keeps the exact
+ // prefix check working for this script's own ASCII writes and for the
+ // ps1-written ones alike (a plain marker passes through untouched).
+ let bytes = std::fs::read(prefix.join("share/prime-agent/.prime-agent-install")).ok()?;
+ let bytes = normalize_marker_bytes(&bytes);
+ let marker = String::from_utf8_lossy(&bytes);
// The marker's first line must be the installer's OWN write shape —
// "install-rust.sh channel <name>" — not merely any line that ends in
// a channel claim: a foreign marker ("other installer channel beta")
@@ -248,13 +508,14 @@ pub fn installed_channel(prefix: &Path) -> Option<&'static str> {
}
}
-/// Fetch the installer script to a per-run temp file (the small-file
-/// budget; the file is the exact bytes the branch serves).
+/// Fetch the installer script into a per-run temp file (the small-file
+/// budget; the file is the exact bytes the branch serves) — the path with
+/// the held handle [`write_script`] created it through.
///
/// # Errors
/// Returns an error when the request fails, answers a non-success status,
/// or the body cannot be read or written.
-async fn fetch_script(url: &str) -> Result<PathBuf> {
+async fn fetch_script(url: &str) -> Result<(PathBuf, std::fs::File)> {
let response = reqwest::Client::new()
.get(url)
.header("User-Agent", update_user_agent(env!("CARGO_PKG_VERSION")))
@@ -273,71 +534,144 @@ async fn fetch_script(url: &str) -> Result<PathBuf> {
if bytes.is_empty() {
anyhow::bail!("the installer script at {url} was empty");
}
+ write_script(&bytes)
+}
+
+/// Write installer script bytes to a per-run temp file, created fresh
+/// under an unguessable name and returned together with the OPEN HANDLE
+/// the bytes were written through. The temp directory is writable by
+/// every process of this user (and, under a permissive umask, by every
+/// local user), so a script the child later re-opens BY NAME could be
+/// swapped between this write and the run — executing the swap with the
+/// credentials this funnel is hardened to guard. The handle is therefore
+/// the only thing every consumer hands to the child (as its stdin, the
+/// `curl|sh` one-liner's own invocation form): the bytes that run are
+/// the bytes written here, and the name only serves the post-run
+/// cleanup.
+fn write_script(bytes: &[u8]) -> Result<(PathBuf, std::fs::File)> {
let script = std::env::temp_dir().join(format!(
"prime-agent-update-{}.sh",
uuid::Uuid::now_v7().simple()
));
- std::fs::write(&script, &bytes).with_context(|| format!("write {}", script.display()))?;
- Ok(script)
+ let mut options = std::fs::OpenOptions::new();
+ options.create_new(true).read(true).write(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt as _;
+ // Owner-only: the default umask would leave the shared temp
+ // directory's other users a write window into the file the
+ // child is about to run.
+ options.mode(0o600);
+ }
+ let mut script_file = options
+ .open(&script)
+ .with_context(|| format!("create {}", script.display()))?;
+ script_file
+ .write_all(bytes)
+ .with_context(|| format!("write {}", script.display()))?;
+ // Every consumer hands a clone of this handle to the child as its
+ // stdin, and a clone shares the file position: start them all from
+ // the first byte.
+ script_file
+ .seek(SeekFrom::Start(0))
+ .with_context(|| format!("rewind {}", script.display()))?;
+ Ok((script, script_file))
}
-/// Exec the downloaded script (`/bin/sh`, the same interpreter the
-/// curl|sh one-liner uses, at the trusted absolute path so a poisoned
-/// `PATH` cannot substitute the interpreter that runs the installer with
-/// the inherited environment) and wait for it. The install prefix rides
-/// the child's environment as the installer's own knob, so the script
-/// publishes exactly where the probe looks — every other
-/// `PRIME_AGENT_RUST_*` knob passes through untouched.
-/// The script's own die messages already streamed with
-/// [`InstallerOutput::Inherit`]; with [`InstallerOutput::Capture`] the
-/// tail becomes the failure message.
+/// The trusted interpreter for the installer child (the `curl|sh`
+/// one-liner's own): the absolute /bin/sh on unix — never PATH-resolved,
+/// so a poisoned `PATH` cannot substitute the interpreter that runs the
+/// installer with the inherited credentials.
+#[cfg(not(windows))]
+fn trusted_shell() -> PathBuf {
+ PathBuf::from("/bin/sh")
+}
+
+/// On Windows the kernel shell resolver's TRUSTED Git Bash roots -
+/// hardcoded install-dir literals, never PATH and never `where bash.exe`
+/// (the `get_shell_config` fallback that serves the kernel shell would
+/// let a repo-controlled `PATH` place the interpreter that receives the
+/// inherited `GITHUB_TOKEN`; the funnel must not use it).
///
/// # Errors
-/// Returns the failure when the script cannot start or exits nonzero.
-async fn execute_script(
- script: &Path,
+/// Returns the failure when no trusted Git Bash root exists.
+#[cfg(windows)]
+fn trusted_shell() -> std::result::Result<std::path::PathBuf, UpdateFailure> {
+ crate::platform::shell::resolve_kernel_bash_shell(None)
+ .map(std::path::PathBuf::from)
+ .ok_or_else(|| UpdateFailure {
+ // No shellPath guidance here: the funnel, like its unix side
+ // (the hardcoded /bin/sh), resolves only the trusted roots -
+ // the settings key serves the kernel shell, not this privileged
+ // execution (the promise would lie).
+ message: "could not run the installer: no Git Bash found at \
+ the trusted install roots \
+ (C:\\Program Files\\Git\\bin\\bash.exe); install \
+ Git for Windows (https://git-scm.com/download/win) \
+ to update from this machine"
+ .to_string(),
+ })
+}
+
+/// Build the installer's child command: [`trusted_shell`]'s interpreter
+/// with the installer's env knobs (the caller completes it with the
+/// `-s --` form — the `curl|sh` one-liner's own — where the script rides
+/// the child's stdin from the handle [`write_script`] returned and
+/// `args` stay the child's positional parameters), so both wait modes
+/// ([`execute_script`]) and the Windows handoff spawn this same command:
+/// the install prefix riding the child's environment as the installer's
+/// own knob, so the script publishes exactly where the probe looks —
+/// every other `PRIME_AGENT_RUST_*` knob passes through untouched.
+fn installer_child(
+ shell: &Path,
prefix: &Path,
channel: Option<&'static str>,
- output: InstallerOutput,
-) -> std::result::Result<(), UpdateFailure> {
- // The interpreter: the trusted absolute /bin/sh on unix (never
- // PATH-resolved, so a poisoned PATH cannot substitute the interpreter
- // that runs the installer with the inherited credentials); on Windows
- // the kernel shell resolver's TRUSTED Git Bash roots - hardcoded
- // install-dir literals, never PATH and never `where bash.exe` (the
- // get_shell_config fallback that serves the kernel shell would let a
- // repo-controlled PATH place the interpreter that receives the
- // inherited GITHUB_TOKEN; the funnel must not use it).
- #[cfg(windows)]
- let shell = {
- match crate::platform::shell::resolve_kernel_bash_shell(None) {
- Some(path) => path,
- None => {
- return Err(UpdateFailure {
- // No shellPath guidance here: the funnel, like its unix
- // side (the hardcoded /bin/sh), resolves only the trusted
- // roots - the settings key serves the kernel shell, not
- // this privileged execution (the promise would lie).
- message: "could not run the installer: no Git Bash found at \
- the trusted install roots \
- (C:\\Program Files\\Git\\bin\\bash.exe); install \
- Git for Windows (https://git-scm.com/download/win) \
- to update from this machine"
- .to_string(),
- });
- }
- }
- };
- #[cfg(not(windows))]
- let shell = "/bin/sh";
+) -> tokio::process::Command {
let mut command = tokio::process::Command::new(shell);
- command.arg(script).env(ENV_PREFIX, prefix);
+ command.env(ENV_PREFIX, prefix);
+ // The check knobs are the PRE-FLIGHT's alone: a user shell carrying
+ // either would make the real run validate and exit without
+ // publishing, so the shared builder strips both (the pre-flight sets
+ // its own back after this).
+ command.env_remove("PRIME_AGENT_ROLLBACK_CHECK");
+ command.env_remove("PRIME_AGENT_ARCHIVE_CHECK");
// The requested channel wins; otherwise the update stays on the channel
// the install marker records (the fetched script's own default is the
// stable render, so a beta install would silently switch channels).
if let Some(channel) = channel.or_else(|| installed_channel(prefix)) {
command.env(ENV_RELEASE_CHANNEL, channel);
}
+ command
+}
+
+/// Exec the script and wait for it: [`trusted_shell`]'s interpreter
+/// under [`installer_child`]'s env wiring, the `-s --` form with the
+/// script riding the child's stdin from the handle [`write_script`]
+/// returned (the shared temp directory can never swap the bytes under a
+/// name — the handle IS what runs) and `args` as the child's positional
+/// parameters. The script's own
+/// die messages already streamed with [`InstallerOutput::Inherit`];
+/// with [`InstallerOutput::Capture`] the tail becomes the failure
+/// message.
+///
+/// # Errors
+/// Returns the failure when the script cannot start or exits nonzero.
+async fn execute_script(
+ script: &std::fs::File,
+ args: &[&std::ffi::OsStr],
+ prefix: &Path,
+ channel: Option<&'static str>,
+ output: InstallerOutput,
+) -> std::result::Result<(), UpdateFailure> {
+ #[cfg(windows)]
+ let shell = trusted_shell()?;
+ #[cfg(not(windows))]
+ let shell = trusted_shell();
+ let stdin = std::process::Stdio::from(script.try_clone().map_err(|error| UpdateFailure {
+ message: format!("could not run the installer: {error}"),
+ })?);
+ let mut command = installer_child(&shell, prefix, channel);
+ command.arg("-s").arg("--").args(args).stdin(stdin);
match output {
InstallerOutput::Inherit => {
let status = command.status().await.map_err(|error| UpdateFailure {
@@ -349,19 +683,19 @@ async fn execute_script(
Err(UpdateFailure {
message: match status.code() {
Some(code) => format!(
- "the installer exited with code {code}; the previous install was kept"
+ "the installer exited with code {code}; the current install was kept"
),
None => {
- "the installer was terminated by a signal; the previous install was kept"
+ "the installer was terminated by a signal; the current install was kept"
.to_string()
}
},
})
}
InstallerOutput::Capture => {
- // The TUI owns the terminal: no inherited stdin and no
- // controlling tty, so the script cannot open /dev/tty to prompt.
- command.stdin(std::process::Stdio::null());
+ // The TUI owns the terminal: no controlling tty, and the
+ // child's stdin is the script itself — so the script cannot
+ // open /dev/tty to prompt and never reads a terminal.
#[cfg(unix)]
crate::platform::process::set_new_session(command.as_std_mut());
let captured = command.output().await.map_err(|error| UpdateFailure {
@@ -487,6 +821,76 @@ mod tests {
assert!(message.contains("x86_64-pc-windows-msvc"), "{message}");
}
+ /// The ps1-era marker encodings read back as their ASCII content: a
+ /// UTF-16 or BOM-prefixed live marker (install.ps1's Set-Content
+ /// followed $`PSDefaultParameterValues`) keeps the installer-ownership
+ /// gate working instead of sending a ps1-updated machine down the
+ /// managed path.
+ #[test]
+ fn installed_channel_reads_the_ps1_encoded_marker() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let prefix = dir.path().join("prefix");
+ let payload = prefix.join("share/prime-agent");
+ std::fs::create_dir_all(&payload).unwrap();
+ let cases: [(&str, Vec<u8>, &str); 4] = [
+ (
+ "utf-16le",
+ {
+ let text: Vec<u16> = "install-rust.sh channel beta\nversion 1\n"
+ .encode_utf16()
+ .collect();
+ let mut bytes = vec![0xFF, 0xFE];
+ for unit in &text {
+ bytes.extend_from_slice(&unit.to_le_bytes());
+ }
+ bytes
+ },
+ "beta",
+ ),
+ (
+ "utf-8-bom",
+ {
+ let mut bytes = vec![0xEF, 0xBB, 0xBF];
+ bytes.extend_from_slice(b"install-rust.sh channel stable\nversion 1\n");
+ bytes
+ },
+ "stable",
+ ),
+ (
+ "utf-16be",
+ {
+ let text: Vec<u16> = "install-rust.sh channel stable\nversion 1\n"
+ .encode_utf16()
+ .collect();
+ let mut bytes = vec![0xFE, 0xFF];
+ for unit in &text {
+ bytes.extend_from_slice(&unit.to_be_bytes());
+ }
+ bytes
+ },
+ "stable",
+ ),
+ (
+ "ascii",
+ b"install-rust.sh channel stable\nversion 1\n".to_vec(),
+ "stable",
+ ),
+ ];
+ for (name, bytes, expected) in cases {
+ std::fs::write(payload.join(".prime-agent-install"), &bytes).unwrap();
+ assert_eq!(
+ installed_channel(&prefix),
+ Some(expected),
+ "{name}: the ps1-era encoding reads back as its ASCII channel"
+ );
+ assert_eq!(
+ installed_version(&prefix).as_deref(),
+ Some("1"),
+ "{name}: the version line of an encoded marker reads too"
+ );
+ }
+ }
+
/// The installed-marker channel read: a beta install's update must
/// stay on beta (the marker the installer writes at publish carries
/// the channel), a stable or pre-marker install rides the script's
@@ -530,6 +934,77 @@ mod tests {
assert_eq!(installed_channel(&prefix), None);
}
+ /// Only the payload binary of a marked installer tree is
+ /// installer-owned; the marker's version line is the installed
+ /// version.
+ #[test]
+ fn installer_prefix_of_needs_the_payload_path_and_the_marker() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let prefix = dir.path().join("prefix");
+ let payload = prefix.join("share/prime-agent");
+ std::fs::create_dir_all(&payload).unwrap();
+ let exe = payload.join(PAYLOAD_BINARY);
+ assert_eq!(installer_prefix_of(&exe), None, "no marker: not owned");
+ std::fs::write(
+ payload.join(".prime-agent-install"),
+ "install-rust.sh channel beta\nversion 0.9.9-beta.10\n",
+ )
+ .unwrap();
+ assert_eq!(installer_prefix_of(&exe), Some(prefix.clone()));
+ assert_eq!(installed_version(&prefix).as_deref(), Some("0.9.9-beta.10"));
+ // A binary elsewhere in the tree, or a managed release, is not.
+ assert_eq!(installer_prefix_of(&payload.join("other")), None);
+ assert_eq!(
+ installer_prefix_of(&prefix.join("releases/0.9.8/prime-agent")),
+ None
+ );
+ }
+
+ /// The handoff gate never opens on unix: a rename never fights a
+ /// running image, so the local operations always wait for the
+ /// installer — even a fully staged, marker-bearing payload prefix
+ /// stays closed (the platform alone decides).
+ #[test]
+ #[cfg(not(windows))]
+ fn caller_owns_payload_stays_false_for_a_staged_prefix_on_unix() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let prefix = dir.path().join("prefix");
+ let payload = prefix.join("share/prime-agent");
+ std::fs::create_dir_all(&payload).unwrap();
+ std::fs::write(
+ payload.join(".prime-agent-install"),
+ "install-rust.sh channel beta\nversion 0.9.9-beta.10\n",
+ )
+ .unwrap();
+ assert!(
+ !caller_owns_payload(&prefix),
+ "unix renames never fight a running image"
+ );
+ }
+
+ /// The handoff gate opens only when the marker-bearing payload path
+ /// IS this process's own image: the test binary never runs from a
+ /// payload dir, so even a fully staged prefix stays closed on
+ /// Windows — the true arm needs a real self-installed run (the e2e
+ /// covers the wait path).
+ #[test]
+ #[cfg(windows)]
+ fn caller_owns_payload_needs_the_running_image_on_windows() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let prefix = dir.path().join("prefix");
+ let payload = prefix.join("share/prime-agent");
+ std::fs::create_dir_all(&payload).unwrap();
+ std::fs::write(
+ payload.join(".prime-agent-install"),
+ "install-rust.sh channel beta\nversion 0.9.9-beta.10\n",
+ )
+ .unwrap();
+ assert!(
+ !caller_owns_payload(&prefix),
+ "a staged prefix never names this process's own image"
+ );
+ }
+
/// Serve `body` over one plain HTTP request (the hermetic source the
/// funnel fetches its mock installer from): bind an ephemeral loopback
/// socket, answer the first request, return the URL the funnel uses.
diff --git a/install-rust.sh b/install-rust.sh
index 2b28ea9e9f..f6624aa7e4 100755
--- a/install-rust.sh
+++ b/install-rust.sh
@@ -136,6 +136,10 @@
# channel's current version; the script is idempotent (a re-run replaces
# the payload, keeps one .old rollback generation, and re-runs the
# takeover steps as no-ops when there is nothing left to take over).
+# install-rust.sh --rollback republishes that kept generation, and
+# install-rust.sh --archive <path> publishes a local release archive
+# instead of a channel download (`prime-agent update --rollback` and
+# `--archive` run the copy of this script bundled into the binary).
#
# PREREQUISITES: curl + sh (+ the network for the download). The installer
# needs a Python for its own scripting steps (the store guard's realpath,
@@ -185,6 +189,12 @@ Options:
Never applies to the daemon this install runs under.
(from a pipe: curl -fsSL <url>/install.sh | sh -s -- --force)
--verbose the detail also goes to stdout, not just fd 3 (no animation)
+ --rollback restore the previous version the last install kept
+ (share/prime-agent.old.*); the replaced version is kept in
+ its place, so a second --rollback undoes the first
+ --archive <path>
+ install a local prime-agent-<version>-<platform>.tar.gz
+ release archive instead of downloading from the channel
Output:
stderr the title, one line per step, warnings with the command that
fixes them, and the ending; on a terminal an animated banner,
@@ -202,6 +212,14 @@ Environment:
checks still run)
PRIME_AGENT_RUST_PREFIX install prefix (~/.local by default)
PRIME_AGENT_RUST_VERBOSE 1 = the --verbose output mode
+ PRIME_AGENT_ROLLBACK_CHECK 1 = with --rollback, print the resolved
+ rollback source and exit without touching
+ the payload (the update command's
+ synchronous pre-flight)
+ PRIME_AGENT_ARCHIVE_CHECK 1 = with --archive, validate the archive
+ (its name, tar, payload, and version) and
+ exit without publishing (the same
+ pre-flight for the archive route)
USAGE
}
@@ -210,18 +228,68 @@ USAGE
# points (`prime-agent update`, the TUI /update) exec — identical to the default
# run because the flow is idempotent by construction. --verbose folds the fd-3
# progress detail onto stdout (PRIME_AGENT_RUST_VERBOSE=1 does the same).
+# --rollback and --archive pick the payload source (MODE); the default is the
+# channel download.
VERBOSE="${PRIME_AGENT_RUST_VERBOSE:-0}"
FORCE=0
+MODE="channel"
+ARCHIVE=""
+# THE TRUSTED TASKLIST: the liveness question goes to Windows's own
+# tasklist, never through the inherited PATH — this script runs with the
+# updater's environment (the funnel's own shell is trusted-rooted for
+# exactly that reason), and a repo- or user-planted lookup would run
+# BEFORE the publish with the credentials that hardening guards.
+# System32 alone answers: the machine's own SystemRoot spelling first,
+# the MSYS C: mount second. A machine offering neither (every unix; a
+# stripped Windows env) simply has no answerable liveness question, and
+# both callers treat the empty TASKLIST as "cannot ask" — the parent wait
+# proceeds, the publication lock refuses with its manual-recovery
+# message instead of trusting a miss.
+TASKLIST=""
+if [ -n "${SystemRoot:-}" ] && [ -x "${SystemRoot}/System32/tasklist.exe" ]; then
+ TASKLIST="${SystemRoot}/System32/tasklist.exe"
+elif [ -x /c/Windows/System32/tasklist.exe ]; then
+ TASKLIST=/c/Windows/System32/tasklist.exe
+fi
+# THE HANDOFF PARENT WAIT: the Windows update command spawns THIS script
+# and exits precisely so its own payload image stops locking
+# <prefix>/share/prime-agent for the publish below — but a fast child
+# could reach that rename while the parent still lives. The handoff sets
+# the parent's pid here; the payload touch happens many steps below, and
+# this bounded wait (the parent is normally gone in milliseconds) makes
+# the release-before-publish ordering explicit instead of incidental.
+# tasklist carries the liveness question to Windows the same way the
+# publication lock does (the MSYS kill cannot see a native pid).
+if [ -n "${PRIME_AGENT_INSTALLER_PARENT_PID:-}" ] && [ -n "$TASKLIST" ]; then
+ parent_waits=0
+ while MSYS2_ARG_CONV_EXCL='*' "$TASKLIST" \
+ /FI "PID eq ${PRIME_AGENT_INSTALLER_PARENT_PID}" 2>/dev/null \
+ | grep -qw "${PRIME_AGENT_INSTALLER_PARENT_PID}"; do
+ parent_waits=$((parent_waits + 1))
+ [ "$parent_waits" -gt 300 ] && die "the prime-agent process that started this installer (pid ${PRIME_AGENT_INSTALLER_PARENT_PID}) is still running after 30s; the payload it holds cannot be replaced while it lives — stop that process and re-run"
+ sleep 0.1 2>/dev/null || sleep 1
+ done
+fi
# Every argument is scanned (no positionals exist): the flags compose, so
# `--update --verbose` sets both effects instead of silently dropping one.
-for arg in "$@"; do
- case "$arg" in
+while [ $# -gt 0 ]; do
+ case "$1" in
--update) ;;
+ --rollback)
+ [ "$MODE" = archive ] && die "--rollback and --archive are exclusive"
+ MODE="rollback" ;;
+ --archive)
+ [ "$MODE" = rollback ] && die "--rollback and --archive are exclusive"
+ [ $# -ge 2 ] || { usage >&2; die "--archive needs the path of a release archive"; }
+ MODE="archive"
+ ARCHIVE="$2"
+ shift ;;
--verbose|-v) VERBOSE=1 ;;
--force) FORCE=1 ;;
-h|--help) usage; exit 0 ;;
- *) usage >&2; die "unknown argument: ${arg}" ;;
+ *) usage >&2; die "unknown argument: $1" ;;
esac
+ shift
done
# --- the output contract ------------------------------------------------------
@@ -595,9 +663,61 @@ ts_takeover_undo=""
migrated_note=""
# The renderer always restores the cursor and line wrap when it stops; the
# trap stops it on every exit path (an INT/TERM exits through it too).
-trap 'ui_stop; rm -rf "$dl"' EXIT
+# The pre-flights' exits sit far from the run's own success-path sweep
+# below, and a refused check dies before the full trap is armed — so with
+# either check knob set this run's every exit also cleans the staging.
+if [ "${PRIME_AGENT_ROLLBACK_CHECK:-}" = "1" ] || [ "${PRIME_AGENT_ARCHIVE_CHECK:-}" = "1" ]; then
+ # The stage rides too (an abort during the archive check's extraction
+ # must leave no staged tree under the prefix); `stage` is initialized
+ # before the traps, so the sweep targets only what THIS script assigns.
+ trap 'ui_stop; rm -rf "${dl:-}" "${stage:-}"' EXIT
+else
+ trap 'ui_stop; rm -rf "$dl"' EXIT
+fi
+stage=""
+publish_parked=""
+# THE PUBLISH-WINDOW RESTORE (the interrupt handler's discipline, shared
+# by the cleanup trap): the publish parks the incoming live tree at its
+# rollback slot and only then moves the new stage in — between those two
+# renames an interrupt would otherwise delete the staged payload (this
+# run's own trash, the sweep's rule) while the parked tree stays aside,
+# leaving share_dir with NOTHING live in it (the bots' finding: the
+# machine's launcher breaks until a manual rollback). The restore mirrors
+# the publish's own mv-failure branch: the parked tree goes back to the
+# live path, and the generation record's entry for the vacated slot then
+# simply names a path that no longer exists — the rollback's record read
+# skips absent entries by design. Defined before the traps that call it;
+# before the publish window it is a no-op (publish_parked stays empty).
+publish_window_restore() {
+ # share_dir ABSENT is the window's own signature: once the new stage has
+ # landed there, the publish is done, the parked tree is exactly the
+ # rollback generation it should be, and no signal may un-publish it.
+ if [ -n "${publish_parked:-}" ] && [ -d "${publish_parked}" ] \
+ && [ ! -e "${share_dir:-}" ]; then
+ if mv "${publish_parked}" "${share_dir}" 2>/dev/null; then
+ publish_parked=""
+ else
+ echo "warning: could not restore the previous prime-agent payload from ${publish_parked}; restore it with: mv '${publish_parked}' '${share_dir}'" >&2
+ fi
+ fi
+}
ui_interrupted() {
+ # The failed-step line prints FIRST: it writes the renderer's files
+ # under the download staging, and removing that mid-write would fail
+ # the UI's own teardown. Then the interrupted install leaves nothing
+ # behind it would not own — the download staging always, and the
+ # extraction stage when THIS run created it (a rollback's stage is the
+ # KEPT generation itself, never this run's trash to delete; the guard
+ # matches the cleanup trap's). `stage` is INITIALIZED to empty above —
+ # before any trap can fire — so a caller-exported `stage` in this run's
+ # environment is never the removal's target.
if [ -n "$ui_step" ]; then step_fail "$ui_step" "interrupted"; fi
+ ui_stop
+ publish_window_restore
+ rm -rf "$dl"
+ if [ -z "${rollback_from:-}" ] && [ -n "${stage:-}" ]; then
+ rm -rf "$stage"
+ fi
}
trap 'ui_interrupted; exit 130' INT
trap 'ui_interrupted; exit 143' HUP TERM
@@ -725,6 +845,9 @@ esac
# swap the payload the checksum then "verifies" into place. The one escape
# hatch is the explicitly-named knob for a local channel or e2e run
# (install.ps1 carries the same rule + knob); it warns when it is active.
+# The local modes (--rollback, --archive) download nothing, so the rule
+# guards the channel install only.
+if [ "$MODE" = channel ]; then
case "$BASE_URL" in
https://*) ;;
*)
@@ -736,6 +859,7 @@ case "$BASE_URL" in
fi
;;
esac
+fi
BASE_URL="${BASE_URL%/}"
# The channel pointer's one-line body (empty when the read fails).
@@ -744,6 +868,12 @@ read_channel_version() {
tr -d '[:space:]' < "$dl/channel-pointer"
fi
}
+# The local modes (--rollback, --archive) already have their payload: the
+# channel resolution here and the manifest, download, and checksum steps
+# below run only for the channel install (the blocks are not re-indented).
+# A rollback reads its version from the kept generation once the prefix is
+# resolved (below the Python bootstrap).
+if [ "$MODE" = channel ]; then
VERSION_PINNED="no"
if [ -n "${PRIME_AGENT_VERSION:-}" ]; then
VERSION="${PRIME_AGENT_VERSION#v}"
@@ -776,6 +906,38 @@ esac
step_clear
say "installing prime-agent ${VERSION} from the ${CHANNEL} channel (${CHANNEL_PLATFORM})"
title "${VERSION} (${CHANNEL})"
+elif [ "$MODE" = archive ]; then
+# --- --archive: a local release archive ------------------------------------------
+# The archive must carry the channel naming for this platform; the version
+# comes from the name. The channel download and its checksum checks are
+# skipped: the operator named the payload (the tarball must still contain an
+# executable payload binary, checked at extraction). On Windows a drive-letter
+# path (the C:\... form `prime-agent update --archive` passes) goes to the
+# POSIX form first: the name below splits on /, and tar reads C: as a host.
+ if [ "$WINDOWS" = "yes" ] && command -v cygpath >/dev/null 2>&1; then
+ archive_posix="$(cygpath -u "$ARCHIVE")" || die "could not resolve the archive path ${ARCHIVE}"
+ ARCHIVE="$archive_posix"
+ fi
+ [ -f "$ARCHIVE" ] || die "the release archive ${ARCHIVE} does not exist"
+ archive_name="${ARCHIVE##*/}"
+ case "$archive_name" in
+ prime-agent-?*-"${CHANNEL_PLATFORM}".tar.gz) ;;
+ *) die "${archive_name} is not a ${CHANNEL_PLATFORM} release archive (expected prime-agent-<version>-${CHANNEL_PLATFORM}.tar.gz)" ;;
+ esac
+ VERSION="${archive_name#prime-agent-}"
+ VERSION="${VERSION%-"${CHANNEL_PLATFORM}".tar.gz}"
+ # A leading v is the pin's accepted spelling too (`--rollback`'s marker
+ # versions carry none; the exact payload match below compares the bare
+ # version the binary reports).
+ VERSION="${VERSION#v}"
+ case "$VERSION" in
+ *[!0-9A-Za-z.-]*) die "invalid version in the archive name ${archive_name}: ${VERSION}" ;;
+ esac
+ asset="$ARCHIVE"
+ say "installing prime-agent ${VERSION} from the local archive ${ARCHIVE}"
+ title "${VERSION} (local archive)"
+ step_ok "Using the local archive" "$(tilde "$ARCHIVE")"
+fi
# --- the Python bootstrap: the installer must not depend on system python3 ----
# Every scripting step below (the store guard's realpath, the artifact's
@@ -876,7 +1038,16 @@ else
# alias — which also overrides any inherited value pointing into the
# shared session store (it would place uv there BEFORE the store guard
# runs).
- if [ -n "$uv_bin_dir" ]; then
+ # The download attempt is CHANNEL-install machinery on Windows: the
+ # rollback and the archive never reach a UVPY consumer there — every
+ # path they take resolves through physical_path (the store guard, the
+ # prefix), and the daemon ladder and the TS uninstall are unix-only —
+ # so a ps1-installed machine with no Python and no network can still
+ # restore its previous generation or install a local archive (the
+ # modes are local BY DESIGN; the channel manifest's JSON parsing is
+ # Python's one Windows use).
+ if [ -n "$uv_bin_dir" ] \
+ && { [ "$WINDOWS" != "yes" ] || [ "$MODE" = "channel" ]; }; then
step_start "Setting up Python (one-time)"
python_step="yes"
if uv_install_out="$(curl -fsSL --connect-timeout 10 --max-time 60 --retry 2 \
@@ -930,13 +1101,19 @@ fi
if [ "$python_step" = yes ] && [ -n "$UVPY" ]; then
step_ok "Python ready"
fi
-[ -n "$UVPY" ] \
- || die "the installer could not obtain a Python runtime, which it needs
+# The interpreter gate rides the same Windows-local exemption: on every
+# other path the machine is missing the one prerequisite the installer
+# cannot provide for itself, but the Windows rollback and archive run
+# entirely without one (see the download attempt's gate above).
+if [ -z "$UVPY" ] \
+ && { [ "$WINDOWS" != "yes" ] || [ "$MODE" = "channel" ]; }; then
+ die "the installer could not obtain a Python runtime, which it needs
for its scripting steps (the store guard, the artifact handling). Install
uv with:
curl -LsSf https://astral.sh/uv/install.sh | sh
(the installer then provisions its own Python through uv — no system
python3 required), or install python3 yourself and re-run"
+fi
# --- the preserve invariant: guard the shared store ---------------------------
# ~/.prime/agent is shared by both products BY DESIGN (sessions, leases,
@@ -1002,11 +1179,31 @@ esac
# it: a prefix whose spelling hides a symlink into the shared store must
# abort before mkdir -p ever writes there, not after. Windows resolves in
# the MSYS form (the guard's ruling above).
+# The sentinel X rides both resolvers: a resolved path that ENDS in a
+# newline would have it stripped by the command substitution's trailing
+# newline trim (the newline guard below would then never see it), and
+# the stripped spelling would target a DIFFERENT directory. The sentinel
+# is appended before the substitution and removed after — ${out%X}
+# strips exactly the one appended X, so a path ending in X (or in X then
+# a newline) comes through byte-true.
if [ "$WINDOWS" = "yes" ]; then
- PREFIX="$(physical_path "$PREFIX")"
+ PREFIX="$(physical_path "$PREFIX")X"
else
- PREFIX="$("$UVPY" -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$PREFIX")"
+ PREFIX="$("$UVPY" -c 'import os, sys; print(os.path.realpath(sys.argv[1]) + "X")' "$PREFIX")"
fi
+PREFIX="${PREFIX%X}"
+# The rollback's generations record is newline-delimited (one path per
+# line), so a prefix containing a newline can never be recorded or read
+# back — the rollback would silently misreport "nothing to roll back".
+# The check rides AFTER the full resolution above: a clean lexical
+# spelling through a symlinked ancestor can resolve to a real path that
+# contains a newline, and the record stores the RESOLVED path — the
+# refusal names the resolved spelling, before anything is created under
+# it (the same boundary discipline as the absolute-path check).
+case "$PREFIX" in
+ *'
+'*) die "PRIME_AGENT_RUST_PREFIX must not contain a newline: the rollback record is newline-delimited (resolved: ${PREFIX})" ;;
+esac
guard_preserved "$PREFIX" "${PREFIX}/share" "${PREFIX}/bin"
mkdir -p "${PREFIX}/share" "${PREFIX}/bin"
# The guard must also see THROUGH symlinked child roots: a ${PREFIX}/share or
@@ -1032,8 +1229,106 @@ old_layout_dir="${PREFIX}/share/prime-agent-rust"
legacy_dir="${PREFIX}/share/prime-agent-legacy"
lock_link="${PREFIX}/share/.prime-agent-install.lock"
legacy_lock="${PREFIX}/share/.prime-agent-rust-install.lock"
+generations_record="${PREFIX}/share/.prime-agent-install-generations"
guard_preserved "$share_dir" "$launcher" "$old_layout_dir" "$legacy_dir" "$lock_link"
+# --- --rollback: the newest kept generation ------------------------------------
+# The rollback source is the newest generation in the generations record (the
+# record is append-only, so the last usable line is the newest) that still
+# exists, carries this installer's marker, and holds a payload binary. Its
+# marker supplies the channel and version; the publish below moves it back
+# into place and keeps the replaced payload as the new generation.
+rollback_from=""
+if [ "$MODE" = rollback ]; then
+ # The marker as this script's ASCII text: this script writes plain bytes,
+ # but install.ps1's Set-Content follows $PSDefaultParameters
+ # ['*:Encoding'] — an existing ps1-published payload's marker can be
+ # UTF-16 (NUL-interleaved) or BOM-prefixed. The read flattens the NULs
+ # and strips a leading BOM (UTF-8 and both UTF-16 orders); a plain
+ # marker passes through byte-identical. Only the ps1 slot's marker needs
+ # it — the record's entries are always this script's own ASCII writes.
+ marker_text() {
+ text="$(tr -d '\0' < "$1" 2>/dev/null || true)"
+ case "$text" in
+ "$(printf '\357\273\277')"*) text="${text#"$(printf '\357\273\277')"}" ;;
+ "$(printf '\377\376')"*) text="${text#"$(printf '\377\376')"}" ;;
+ "$(printf '\376\377')"*) text="${text#"$(printf '\376\377')"}" ;;
+ esac
+ printf '%s' "$text"
+ }
+ if [ -f "$generations_record" ]; then
+ while IFS= read -r recorded; do
+ case "$recorded" in
+ "${PREFIX}/share/prime-agent.old."*) ;;
+ *) continue ;;
+ esac
+ [ -d "$recorded" ] && [ -x "${recorded}/${BINARY_NAME}" ] || continue
+ # The normalized marker read covers recorded entries too: a ps1-
+ # marked live tree this script moved aside in a ROLLBACK becomes a
+ # recorded generation, and its encoding rides with it.
+ case "$(marker_text "${recorded}/.prime-agent-install" \
+ | head -n 1)" in
+ "install-rust.sh channel "*) ;;
+ *) continue ;;
+ esac
+ rollback_from="$recorded"
+ done < "$generations_record"
+ fi
+ # The Windows-native installer's slot: install.ps1 keeps ITS replaced
+ # payload at the un-suffixed `prime-agent.old` and never writes the
+ # generations record (its own one-generation bookkeeping; its recovery
+ # is a printed manual Move-Item), so a ps1-updated machine has no
+ # recorded entry — but the CLI still sees an installer-owned payload,
+ # and `update --rollback` runs THIS script: install.ps1 has no rollback
+ # mode, so this fallback is that machine's only automated rollback. The
+ # slot takes the same three checks a recorded generation takes.
+ # THE CONFLICT POLICY: when a usable recorded entry AND the slot both
+ # exist, the RECORD wins — deliberately. No ordering signal separates
+ # the two bookkeeping systems (the asides' mtimes are publish times
+ # only until a rollback publishes a kept tree back into place with its
+ # OLD mtime, so a newer ps1 aside of a rolled-back tree compares as
+ # older than a stale record entry), and the marker check cannot tell
+ # install.ps1's slot from a user's own copy of the payload at that
+ # name — the record's entries are exactly the slots this script wrote
+ # and swept, so it stays authoritative whenever it answers. The slot
+ # serves the machines the record never covered.
+ ps1_slot="${PREFIX}/share/prime-agent.old"
+ if [ -z "$rollback_from" ] \
+ && [ -d "$ps1_slot" ] && [ -x "${ps1_slot}/${BINARY_NAME}" ] \
+ && case "$(marker_text "${ps1_slot}/.prime-agent-install" \
+ | head -n 1)" in
+ "install-rust.sh channel "*) true ;;
+ *) false ;;
+ esac; then
+ rollback_from="$ps1_slot"
+ fi
+ [ -n "$rollback_from" ] || die "nothing to roll back: no previous version is kept under ${PREFIX}/share
+(each update keeps the version it replaced; a fresh install has none)"
+ # THE ROLLBACK PRE-FLIGHT: with the knob set the resolved source is the
+ # whole answer — printed on stdout and the run stops here (no channel
+ # read, no staging, no lock, no payload touch; the install prologue's
+ # own temp staging still ran, so its sweep rides the exit too — the
+ # trap is not armed yet at this point), so a caller can ask
+ # synchronously whether a rollback CAN run before handing the real
+ # run off (the Windows update command's handoff: this process must
+ # exit for the publish to happen, so its exit code can only report the
+ # pre-flight's answer honestly).
+ if [ "${PRIME_AGENT_ROLLBACK_CHECK:-}" = "1" ]; then
+ printf '%s\n' "$rollback_from"
+ exit 0
+ fi
+ # The channel/version lines come from the normalized marker: the slot's
+ # marker can be a ps1-encoded write (see marker_text); a record entry's
+ # marker is this script's own ASCII, so the normalization is a no-op.
+ marker="$(marker_text "${rollback_from}/.prime-agent-install")"
+ CHANNEL="$(printf '%s\n' "$marker" | sed -n '1s/^install-rust.sh channel //p')"
+ VERSION="$(printf '%s\n' "$marker" | sed -n '2s/^version //p')"
+ say "rolling back to prime-agent ${VERSION} (${rollback_from})"
+ title "${VERSION} (rollback)"
+ step_ok "Found the previous version" "${VERSION}"
+fi
+
+if [ "$MODE" = channel ]; then
# --- the channel manifest: this platform's artifact row ---------------------
# The manifest carries the version plus the per-platform rows; the row's
# file must be the exact channel naming and its sha256 the 64-hex shape —
@@ -1137,6 +1432,7 @@ else
fi
say "checksum verified: ${asset_name} (${VERSION}, the ${CHANNEL} channel)"
step_ok "Verified"
+fi
# --- the TypeScript takeover, step 1: stop BOTH daemons ALWAYS ----------------
# THE ALWAYS-STOP CONTRACT (PR1's field ruling, hardened + the second
@@ -1861,12 +2157,166 @@ fi
# new stage is in place, so the live tree is never rm'd while the launcher
# still points into it. The renamed-aside tree is KEPT as a one-generation
# rollback (prime-agent.old.<pid>); the next successful install sweeps it.
+# A rollback publishes the kept generation itself as the stage: it already
+# carries its payload and its marker.
+if [ -n "$rollback_from" ]; then
+ step_start "Restoring the previous version"
+ stage="$rollback_from"
+else
step_start "Installing"
stage="$(mktemp -d "${PREFIX}/share/prime-agent.stage.XXXXXX")"
guard_preserved "$stage"
-tar -xzf "$asset" -C "$stage"
-[ -x "${stage}/${BINARY_NAME}" ] \
- || die "the tarball did not contain an executable ${BINARY_NAME} payload"
+# A bad tarball (a malformed --archive is the realistic one) leaves no
+# stage behind: the cleanup trap is not armed yet.
+if ! tar -xzf "$asset" -C "$stage"; then
+ rm -rf "$stage"
+ die "could not extract ${asset}"
+fi
+if [ ! -x "${stage}/${BINARY_NAME}" ]; then
+ rm -rf "$stage"
+ die "the tarball did not contain an executable ${BINARY_NAME} payload"
+fi
+# --ARCHIVE ONLY: the archive's name is the version contract (the marker
+# records it and the rollback later reports it), so the payload's own
+# --version must agree — a mis-named archive would publish a marker that
+# lies about its payload. The CHANNEL install is out of scope by design:
+# its tarball already passed the manifest's sha256 gate (the row's exact
+# checksum for this exact version), so the channel's integrity needs no
+# second opinion — and a probe there would add a new failure mode (a
+# cold-start binary slower than the bound) the pre-existing flow never
+# had. The probe is BOUNDED by a portable watchdog — NOT the `timeout`
+# command: on Windows `timeout` on PATH is timeout.exe, which waits
+# instead of running a command and would refuse every probe, and macOS
+# ships no GNU timeout at all. A payload whose --version blocks is
+# killed at the bound and reports nothing (the refusal below, not a
+# hang).
+# The probe's files ride the run's OWN download staging, never the
+# payload-writable stage: an extracted archive could forge a done marker
+# where the loop looks and hang past the bound (the trailing wait would
+# block on the hanging payload forever).
+if [ "$MODE" != "archive" ]; then
+ # The channel install publishes without the name probe (see the block
+ # comment above); the stage continues to the marker write.
+ :
+else
+probe_out="$dl/.version-probe.out"
+probe_done="$dl/.version-probe.done"
+probe_pid_file="$dl/.version-probe.pid"
+probe_status="$dl/.version-probe.status"
+rm -f "$probe_out" "$probe_done" "$probe_pid_file"
+# The runner: the payload is ITS child (a sibling's `wait` cannot reap
+# another shell's child), and `kill -0` keeps succeeding on a ZOMBIE, so
+# the pid alone cannot tell a finished probe from a hanging one — the
+# runner publishes the payload's pid, reaps it, and writes the done
+# marker; the loop below polls the MARKER (a fast probe costs one tick,
+# not the whole bound).
+(
+ # The probe must read the STAGED tree's own package.json: a caller's
+ # PI_PACKAGE_DIR would point the packaged-version lookup at another
+ # tree and the probe would then refuse a good archive or pass a
+ # mismatched one.
+ unset PI_PACKAGE_DIR || true
+ # The probe's redirected output is bounded (64 blocks = 32 KB, ample
+ # for a version line): a payload that continuously emits would
+ # otherwise fill the filesystem for the whole watchdog window, and the
+ # limit kills it — the invocation-status verdict refuses the probe
+ # then. The ulimit itself is GUARDED: under set -e a platform refusing
+ # the limit would take the runner down before the done marker and
+ # every --archive install would then fail at the bound.
+ ulimit -f 64 2>/dev/null || true
+ "${stage}/${BINARY_NAME}" --version >"$probe_out" 2>/dev/null &
+ printf '%s\n' "$!" >"$probe_pid_file"
+ # The probe's OWN status rides a file (set -e would take the wait's
+ # nonzero as an abort): the version line AND a successful exit are the
+ # answer — a payload that prints the right version then fails its own
+ # --version invocation is not a working launcher.
+ probe_status_val=0
+ wait "$!" || probe_status_val=$?
+ printf '%s\n' "$probe_status_val" >"$probe_status"
+ printf 'done\n' >"$probe_done"
+) &
+probe_runner=$!
+probe_waited=0
+probe_timed_out=""
+while [ ! -f "$probe_done" ]; do
+ probe_waited=$((probe_waited + 1))
+ if [ "$probe_waited" -gt 10 ]; then
+ # The bound: SIGTERM, then SIGKILL — a payload that ignores the
+ # first still dies, its runner then exits (its own wait returns),
+ # and nothing of the probe outlives this install. The timeout flag
+ # decides the verdict: a payload that printed its version BEFORE
+ # hanging was still unresponsive, and the captured stdout must not
+ # pass for an answer.
+ probe_timed_out="yes"
+ probe_pid="$(cat "$probe_pid_file" 2>/dev/null || true)"
+ if [ -n "$probe_pid" ]; then
+ kill "$probe_pid" 2>/dev/null || true
+ sleep 1
+ kill -9 "$probe_pid" 2>/dev/null || true
+ else
+ kill -9 "$probe_runner" 2>/dev/null || true
+ fi
+ break
+ fi
+ sleep 1
+done
+# A nonzero-exiting payload still answers --version (its first line is
+# already captured): the runner's reap happens inside it, and neither
+# wait's status aborts the installer under set -e.
+wait "$probe_runner" 2>/dev/null || true
+if [ -n "$probe_timed_out" ]; then
+ rm -f "$probe_out" "$probe_done" "$probe_pid_file" "$probe_status"
+ # The stage goes too: this die predates the full cleanup trap's arming
+ # (the mismatch refusal below sweeps its own stage the same way), so a
+ # hung payload on a normal install leaves no staging tree behind.
+ rm -rf "$stage"
+ die "the archive names ${VERSION} but its payload did not answer --version within 10s; refusing an unresponsive payload"
+fi
+# tr -d '\r' strips the trailing CR Git Bash text-mode redirection can
+# append (the lock-pid reader's precedent): a CR would make every exact
+# case arm miss and refuse a correctly named archive.
+reported_version="$(head -n 1 "$probe_out" 2>/dev/null | tr -d '\r')"
+probe_exit_status="$(cat "$probe_status" 2>/dev/null || true)"
+rm -f "$probe_out" "$probe_done" "$probe_pid_file" "$probe_status"
+if [ "$probe_exit_status" != "0" ]; then
+ rm -rf "$stage"
+ die "the archive names ${VERSION} but its payload's --version invocation failed (exit ${probe_exit_status}); refusing an unusable launcher"
+fi
+# The continuous-build stamp rides the reported version, not the name
+# (assemble_artifacts.py stages a package.json reporting
+# <version>-continuous.<sha> while the archive name keeps the bare
+# <version> so rolling releases overwrite assets): the exact name or its
+# documented continuous stamp both publish honestly.
+case "$reported_version" in
+ "$VERSION") ;;
+ "$VERSION-continuous."*)
+ # The stamp is exactly a 40-hex commit SHA (assemble_artifacts.py's
+ # --sha contract): a wrong-length or non-hex tail is a malformed
+ # stamp, not the built commit.
+ stamp="${reported_version#"$VERSION"-continuous.}"
+ if ! printf '%s\n' "$stamp" | grep -qE '^[0-9a-f]{40}$'; then
+ rm -rf "$stage"
+ die "the archive names ${VERSION} but its payload reports ${reported_version}; rename the archive or publish it under its real version"
+ fi
+ ;;
+ *)
+ rm -rf "$stage"
+ die "the archive names ${VERSION} but its payload reports ${reported_version:-nothing}; rename the archive or publish it under its real version"
+ ;;
+esac
+fi
+# THE ARCHIVE PRE-FLIGHT (the rollback pre-flight's sibling): with the knob
+# set, the validated stage is the whole answer — every extraction check
+# (the tar, the payload, the version) passed — so the run stops here, the
+# stage never becomes anything the caller owns, and a caller can ask
+# synchronously whether an archive CAN install before handing the real run
+# off (the Windows update handoff: this process must exit for the publish
+# to happen, so its exit code can only report the pre-flight's answer
+# honestly).
+if [ "${PRIME_AGENT_ARCHIVE_CHECK:-}" = "1" ]; then
+ rm -rf "$stage"
+ exit 0
+fi
# The ownership marker: the share tree this script publishes carries it, so
# later installs recognize the tree as theirs BY MARKER, not by shape — an
# unrelated directory that happens to contain a `prime-agent` entry is never
@@ -1874,6 +2324,7 @@ tar -xzf "$asset" -C "$stage"
# user instead).
printf 'install-rust.sh channel %s\nversion %s\n' "$CHANNEL" "$VERSION" \
> "${stage}/.prime-agent-install"
+fi
# A lock left by the pre-takeover installer (name .prime-agent-rust-install.lock):
# a live holder still owns the publish, a dead one can never publish again —
@@ -1884,7 +2335,11 @@ printf 'install-rust.sh channel %s\nversion %s\n' "$CHANNEL" "$VERSION" \
if [ -e "$legacy_lock" ] || [ -L "$legacy_lock" ]; then
held_by="$(readlink "$legacy_lock" 2>/dev/null || true)"
if [ -n "$held_by" ] && kill -0 "$held_by" 2>/dev/null; then
- die "an older prime-agent-rust installer (pid ${held_by}) is publishing to ${PREFIX}; retry when it finishes"
+ # The lock refusals below die with the stage already built, before the EXIT
+ # trap that would sweep it: a fresh install's stage is this run's own scratch,
+ # so it never outlives the refused install — a rollback's stage is the kept
+ # generation itself, never this run's trash to delete.
+ { [ -z "${rollback_from:-}" ] && rm -rf "$stage"; die "an older prime-agent-rust installer (pid ${held_by}) is publishing to ${PREFIX}; retry when it finishes"; }
fi
rm -f "$legacy_lock"
fi
@@ -1910,23 +2365,23 @@ if [ "$WINDOWS" = "yes" ]; then
sleep 1
continue
fi
- if [ -n "$held_by" ] \
- && MSYS2_ARG_CONV_EXCL='*' tasklist.exe /FI "PID eq ${held_by}" /NH 2>/dev/null \
+ if [ -n "$held_by" ] && [ -n "$TASKLIST" ] \
+ && MSYS2_ARG_CONV_EXCL='*' "$TASKLIST" /FI "PID eq ${held_by}" /NH 2>/dev/null \
| grep -qw "$held_by"; then
- die "another prime-agent installer (Windows pid ${held_by}) is publishing to ${PREFIX}; retry when it finishes"
+ { [ -z "${rollback_from:-}" ] && rm -rf "$stage"; die "another prime-agent installer (Windows pid ${held_by}) is publishing to ${PREFIX}; retry when it finishes"; }
fi
- die "a publication lock (Windows pid ${held_by:-unknown}) is held at ${lock_dir}. If no prime-agent installer (install-rust.sh or install.ps1) is running, it is stale (a crashed install); remove it and retry:
- rm -rf \"${lock_dir}\""
+ { [ -z "${rollback_from:-}" ] && rm -rf "$stage"; die "a publication lock (Windows pid ${held_by:-unknown}) is held at ${lock_dir}. If no prime-agent installer (install-rust.sh or install.ps1) is running, it is stale (a crashed install); remove it and retry:
+ rm -rf \"${lock_dir}\""; }
done
printf '%s\n' "$(cat "/proc/$$/winpid" 2>/dev/null || echo $$)" > "$lock_dir/pid"
else
until ln -s $$ "$lock_link" 2>/dev/null; do
held_by="$(readlink "$lock_link" 2>/dev/null || true)"
if [ -n "$held_by" ] && kill -0 "$held_by" 2>/dev/null; then
- die "another install-rust.sh (pid ${held_by}) is publishing to ${PREFIX}; retry when it finishes"
+ { [ -z "${rollback_from:-}" ] && rm -rf "$stage"; die "another install-rust.sh (pid ${held_by}) is publishing to ${PREFIX}; retry when it finishes"; }
fi
- die "a previous install-rust.sh (pid ${held_by:-unknown}) left a stale publication lock (a crashed install; its cleanup trap cannot have run). Remove it and retry:
- rm -f \"${lock_link}\""
+ { [ -z "${rollback_from:-}" ] && rm -rf "$stage"; die "a previous install-rust.sh (pid ${held_by:-unknown}) left a stale publication lock (a crashed install; its cleanup trap cannot have run). Remove it and retry:
+ rm -f \"${lock_link}\""; }
done
fi
@@ -1968,14 +2423,39 @@ displaced_ts_root=""
preserved_launcher=""
migrated_old_layout=""
migrated_old_layout=""
+# Defined before the EXIT trap is armed: on_exit calls it.
+restore_ts_root() {
+ if [ -n "$displaced_ts_root" ]; then
+ if [ -d "$share_dir" ]; then
+ # The half-installed Rust payload occupies the TS root's old path: it
+ # is disposable (a re-download restores it); the TS tree is not.
+ rm -rf "$share_dir"
+ fi
+ if mv "$displaced_ts_root" "$share_dir" 2>/dev/null; then
+ echo "note: the TypeScript install was restored to ${share_dir} — the install did not complete" >&2
+ else
+ echo "warning: could not restore the TypeScript install from ${displaced_ts_root}; restore it with: mv '${displaced_ts_root}' '${share_dir}'" >&2
+ fi
+ displaced_ts_root=""
+ fi
+}
on_exit() {
# The renderer stops first, so the restore notes print below its frame.
ui_stop
# Restores FIRST, lock release LAST: a second installer must not be able
# to publish into share_dir while this one still restores state — the
# restore would delete that fresh payload (cross-installer data loss).
+ publish_window_restore
[ -n "$launcher_tmp" ] && rm -f "$launcher_tmp" 2>/dev/null || true
[ -n "${cmd_tmp:-}" ] && rm -f "$cmd_tmp" 2>/dev/null || true
+ # The extraction stage is disposable on every failed path: a successful
+ # publish renamed the stage into ${share_dir}, so the stale path no longer
+ # exists and the removal is a no-op there; a rollback publishes the kept
+ # generation itself (stage == rollback_from), which is never this run's
+ # trash to delete.
+ if [ -z "${rollback_from:-}" ] && [ -n "${stage:-}" ]; then
+ rm -rf "$stage" 2>/dev/null || true
+ fi
# The user's unowned command file goes home if the Rust launcher never
# went live (the same restore discipline as the displaced TS tree): a
# failed launcher write must not leave the machine without ANY
@@ -2025,6 +2505,13 @@ on_exit() {
}
trap on_exit EXIT
+# The rollback source was chosen before the lock: another installer may have
+# swept it since. Re-check under the lock, before the sweep and before
+# anything moves.
+if [ -n "$rollback_from" ] && [ ! -x "${rollback_from}/${BINARY_NAME}" ]; then
+ die "the kept previous version ${rollback_from} was removed by another install while this one ran; nothing was changed"
+fi
+
# Sweep rollback generations from PREVIOUS installs (both name eras) before
# this run creates its own — exactly one .old generation survives each install.
# A generation is swept only when BOTH hold: it carries this installer's
@@ -2034,10 +2521,11 @@ trap on_exit EXIT
# payload, not that the SLOT is a rollback generation: a user who COPIES the
# payload into the namespace (marker and all) keeps their copy. Pre-takeover-era
# crash leftovers (prime-agent-rust.old.*, never stamped) are left in place —
-# harmless, and the user's to remove.
-generations_record="${PREFIX}/share/.prime-agent-install-generations"
+# harmless, and the user's to remove. A rollback's source generation is the
+# payload being published, never swept.
for sweep_dir in "${PREFIX}"/share/prime-agent.old.* "${PREFIX}"/share/prime-agent-rust.old.*; do
[ -d "$sweep_dir" ] || continue
+ [ "$sweep_dir" != "$rollback_from" ] || continue
[ -f "${sweep_dir}/.prime-agent-install" ] || continue
grep -qxF -- "$sweep_dir" "$generations_record" 2>/dev/null || continue
# Best-effort: an un-sweepable generation (a mounted dir, a permission
@@ -2058,21 +2546,6 @@ done
# the EXIT trap), so a half-finished install never leaves the machine with
# no working prime-agent — the TS public symlink keeps resolving the whole
# time and the TS tree returns to its original path if this install dies.
-restore_ts_root() {
- if [ -n "$displaced_ts_root" ]; then
- if [ -d "$share_dir" ]; then
- # The half-installed Rust payload occupies the TS root's old path: it
- # is disposable (a re-download restores it); the TS tree is not.
- rm -rf "$share_dir"
- fi
- if mv "$displaced_ts_root" "$share_dir" 2>/dev/null; then
- echo "note: the TypeScript install was restored to ${share_dir} — the install did not complete" >&2
- else
- echo "warning: could not restore the TypeScript install from ${displaced_ts_root}; restore it with: mv '${displaced_ts_root}' '${share_dir}'" >&2
- fi
- displaced_ts_root=""
- fi
-}
if [ -d "$share_dir" ] && ts_managed "$share_dir"; then
preserved_to="$legacy_dir"
if [ -e "$preserved_to" ]; then preserved_to="$(fresh_slot "$legacy_dir")"; fi
@@ -2139,6 +2612,14 @@ if [ -d "$old_layout_dir" ] && [ ! -d "$share_dir" ]; then
fi
if [ -d "$share_dir" ]; then
had_share_dir=1
+ # THE PUBLISH WINDOW opens with the parking rename, and the marker is
+ # set BEFORE the mv: a signal that lands while the mv runs is only
+ # handled at the mv's completion — the trap fires at that command
+ # boundary, before any assignment after the mv could run. Set-then-move
+ # lets the trap-side restore see the parked tree from the first
+ # boundary of the window; the slot's record entry is skipped by every
+ # reader while the slot is vacant (and stays if the restore cannot).
+ publish_parked="$old"
mv "$share_dir" "$old"
# The slot is a rollback generation this installer created: record its
# exact path so the next install's sweep can tell it from a user-made
@@ -2153,6 +2634,7 @@ if ! mv "$stage" "$share_dir"; then
# (a failed migration restore is the EXIT trap's job: it holds the lock
# until the tree is back, so no second installer can slip in between)
fi
+publish_parked=""
windows_installed="yes"
# A leftover old-layout tree when a new-layout tree also existed: it is
# superseded by the fresh publish. The ownership rule is EXACTLY the
@@ -2278,7 +2760,11 @@ if [ -f "$old_launcher" ] && grep -q 'launcher written by install-rust.sh' "$old
rm -f "$old_launcher"
say "removed the old ${old_launcher} launcher (the keyword is prime-agent now)"
fi
-step_ok "Installed"
+if [ -n "$rollback_from" ]; then
+ step_ok "Restored the previous version" "${VERSION}"
+else
+ step_ok "Installed"
+fi
# --- the TypeScript takeover completes AFTER the publish ----------------------
# The TS-side steps that RETIRE the old command — the always-stop daemon
@@ -2476,11 +2962,17 @@ say "launcher: ${launcher}"
say "payload: ${share_dir}"
if [ -d "$old" ] && grep -qxF -- "$old" "$generations_record" 2>/dev/null; then
say "rollback: ${old} (the previous payload, one generation; swept on the next install)"
+ say " restore it with: prime-agent update --rollback (the live"
+ say " build must carry the update rollback; an older payload may not)"
elif [ -d "$old" ]; then
say "rollback: ${old} (the migrated pre-takeover tree; kept — remove it by hand"
say " once you no longer need the rollback)"
fi
-say "source: the ${CHANNEL} channel at ${BASE_URL} (prime-agent ${VERSION})"
+case "$MODE" in
+ rollback) say "source: the kept previous version (prime-agent ${VERSION}, the ${CHANNEL} channel)" ;;
+ archive) say "source: the local archive ${ARCHIVE} (prime-agent ${VERSION})" ;;
+ *) say "source: the ${CHANNEL} channel at ${BASE_URL} (prime-agent ${VERSION})" ;;
+esac
if [ "$WINDOWS" = "yes" ]; then
# The Windows stop ran before the publish (a Windows process holds its
# binary open); its summary rides here. A fresh install prints nothing:
diff --git a/install.ps1 b/install.ps1
index 94f23206f3..d2987f5a1a 100644
--- a/install.ps1
+++ b/install.ps1
@@ -285,7 +285,11 @@ if (-not (Test-Path $payloadExe -PathType Leaf)) { Fail "the tarball did not con
# funnel's channel-stickiness read keys on it).
$channelLine = "install-rust.sh channel $channel"
$marker = "$channelLine`nversion $version"
-Set-Content -LiteralPath (Join-Path $stage '.prime-agent-install') -Value $marker -NoNewline
+# -Encoding Ascii keeps the marker byte-exact: Set-Content's default
+# encoding follows $PSDefaultParameterValues['*:Encoding'] (UTF-16 or a
+# BOM), and the update funnel's channel-stickiness read + the rollback's
+# marker validation grep the raw ASCII line.
+Set-Content -LiteralPath (Join-Path $stage '.prime-agent-install') -Value $marker -Encoding Ascii -NoNewline
# The launcher paths (the section below the publish writes both).
$launcher = Join-Path $bin 'prime-agent.cmd'