Lightweight coding agent that runs in your terminal
Rust
Allow daemon updates to restore pinned packages to latest stable (#45780)
Eric Traut321dcf5a6f35
diff --git a/codex-rs/app-server-daemon/README.md b/codex-rs/app-server-daemon/README.mdindex 74fb9ff2c0..74721c8b8d 100644--- a/codex-rs/app-server-daemon/README.md+++ b/codex-rs/app-server-daemon/README.md@@ -58,14 +58,13 @@ Positive minute intervals have no configured cap. `daemon restart` applies theenabled state; the next updater wait reads a new interval. The preference doesnot affect an explicit `codex update` command or `daemon update`.-`daemon update` checks the latest stable release once, even with automatic-updates disabled. It requires an installer-owned latest-channel package in either-the dedicated daemon root or the retained legacy root. JSON reports `updated`,-`noUpdate`, or `unsupported`, with installed-and running versions. The updater owns scheduled and manual installs. A manual-update restarts a running managed daemon, so active or queued work may be-interrupted.-Accepted updates continue if the CLI exits. Installer errors return nonzero.+`daemon update` selects the latest stable release, even with automatic updates+disabled. It also returns pinned or local managed packages to production update+eligibility, preserving the automatic-update preference. Legacy installations+migrate to the dedicated root once the published installer and release support+migration. JSON reports `updated`, `noUpdate`, or `unsupported`, with installed+and running versions. A running daemon restarts, so active or queued work may be+interrupted; a stopped daemon stays stopped. Installer errors return nonzero.The updater uses saved network settings; CLI `-c` overrides do not reach it.For all managed app-server shutdowns, including explicit stop and restart anddiff --git a/codex-rs/app-server-daemon/src/backend/mod.rs b/codex-rs/app-server-daemon/src/backend/mod.rsindex faa99a5a17..8d7d488f05 100644--- a/codex-rs/app-server-daemon/src/backend/mod.rs+++ b/codex-rs/app-server-daemon/src/backend/mod.rs@@ -32,7 +32,11 @@ pub(crate) fn pid_backend(paths: BackendPaths) -> PidBackend {}pub(crate) fn pid_update_loop_backend(paths: BackendPaths) -> PidBackend {- PidBackend::new_update_loop(paths.codex_bin, paths.update_pid_file)+ PidBackend::new_update_loop(+ paths.codex_bin,+ paths.update_pid_file,+ /*restore_release*/ None,+ )}pub(crate) async fn append_stderr_log_tail_context(pid_file: &Path, context: &mut String) {diff --git a/codex-rs/app-server-daemon/src/backend/pid.rs b/codex-rs/app-server-daemon/src/backend/pid.rsindex a24414094d..ee98e03140 100644--- a/codex-rs/app-server-daemon/src/backend/pid.rs+++ b/codex-rs/app-server-daemon/src/backend/pid.rs@@ -78,11 +78,11 @@ enum PidFileState {Running(PidRecord),}-#[derive(Debug, Clone, Copy)]+#[derive(Debug, Clone)]#[cfg_attr(not(any(unix, windows)), allow(dead_code))]enum PidCommandKind {AppServer { remote_control_enabled: bool },- UpdateLoop,+ UpdateLoop { restore_release: Option<String> },}impl PidBackend {@@ -107,13 +107,17 @@ impl PidBackend {}}- pub(crate) fn new_update_loop(codex_bin: PathBuf, pid_file: PathBuf) -> Self {+ pub(crate) fn new_update_loop(+ codex_bin: PathBuf,+ pid_file: PathBuf,+ restore_release: Option<String>,+ ) -> Self {let lock_file = pid_file.with_extension("pid.lock");Self {codex_bin,pid_file,lock_file,- command_kind: PidCommandKind::UpdateLoop,+ command_kind: PidCommandKind::UpdateLoop { restore_release },}}@@ -190,7 +194,7 @@ impl PidBackend {tracing::warn!(%pid, %err, "managed app-server shutdown request failed; waiting for force deadline");}}- PidCommandKind::UpdateLoop => {+ PidCommandKind::UpdateLoop { .. } => {fs::write(self.pid_file.with_extension("shutdown"), pid.to_string()).await.context("failed to request updater shutdown")?;@@ -358,15 +362,21 @@ impl PidBackend {}#[cfg(any(unix, windows))]- fn command_args(&self) -> Vec<&'static str> {- match self.command_kind {+ fn command_args(&self) -> Vec<&str> {+ match &self.command_kind {PidCommandKind::AppServer {remote_control_enabled: true,} => vec!["app-server", "--remote-control", "--listen", "unix://"],PidCommandKind::AppServer {remote_control_enabled: false,} => vec!["app-server", "--listen", "unix://"],- PidCommandKind::UpdateLoop => vec!["app-server", "daemon", "pid-update-loop"],+ PidCommandKind::UpdateLoop { restore_release } => {+ let mut args = vec!["app-server", "daemon", "pid-update-loop"];+ if let Some(release) = restore_release {+ args.extend(["--restore-release", release.as_str()]);+ }+ args+ }}}@@ -379,7 +389,7 @@ impl PidBackend {PidCommandKind::AppServer {remote_control_enabled: true,}- | PidCommandKind::UpdateLoop => None,+ | PidCommandKind::UpdateLoop { .. } => None,}}@@ -387,9 +397,9 @@ impl PidBackend {match self.command_kind {PidCommandKind::AppServer { .. } => terminate_process(pid),#[cfg(unix)]- PidCommandKind::UpdateLoop => terminate_process_group(pid),+ PidCommandKind::UpdateLoop { .. } => terminate_process_group(pid),#[cfg(not(unix))]- PidCommandKind::UpdateLoop => terminate_process(pid),+ PidCommandKind::UpdateLoop { .. } => terminate_process(pid),}}@@ -397,7 +407,7 @@ impl PidBackend {fn force_terminate_process(&self, pid: u32) -> Result<()> {match self.command_kind {PidCommandKind::AppServer { .. } => force_terminate_process(pid),- PidCommandKind::UpdateLoop => force_terminate_process_group(pid),+ PidCommandKind::UpdateLoop { .. } => force_terminate_process_group(pid),}}diff --git a/codex-rs/app-server-daemon/src/backend/pid_start.rs b/codex-rs/app-server-daemon/src/backend/pid_start.rsindex 35248a7fd1..e0bcba1e11 100644--- a/codex-rs/app-server-daemon/src/backend/pid_start.rs+++ b/codex-rs/app-server-daemon/src/backend/pid_start.rs@@ -205,7 +205,7 @@ impl PidBackend {// Never retry inside the parent's Job Object: that would report a// successful launch that dies when the terminal/SSH session closes.command.creation_flags(DETACHED_PROCESS | CREATE_BREAKAWAY_FROM_JOB);- if matches!(self.command_kind, PidCommandKind::UpdateLoop) {+ if matches!(self.command_kind, PidCommandKind::UpdateLoop { .. }) {match fs::remove_file(self.pid_file.with_extension("ready")).await {Ok(()) => {}Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}@@ -216,7 +216,7 @@ impl PidBackend {PidCommandKind::AppServer { .. } => {command.env(codex_app_server_transport::DAEMON_SHUTDOWN_SOCKET_ENV, "1");}- PidCommandKind::UpdateLoop => {+ PidCommandKind::UpdateLoop { .. } => {let shutdown_file = self.pid_file.with_extension("shutdown");match fs::remove_file(&shutdown_file).await {Ok(()) => {}@@ -311,7 +311,7 @@ impl PidBackend {});}#[cfg(windows)]- if matches!(self.command_kind, PidCommandKind::UpdateLoop) {+ if matches!(self.command_kind, PidCommandKind::UpdateLoop { .. }) {self.finish_updater_start(&record, replacement.as_ref()).await?;}diff --git a/codex-rs/app-server-daemon/src/backend/pid_tests.rs b/codex-rs/app-server-daemon/src/backend/pid_tests.rsindex 5924495f64..35c4d59ea4 100644--- a/codex-rs/app-server-daemon/src/backend/pid_tests.rs+++ b/codex-rs/app-server-daemon/src/backend/pid_tests.rs@@ -434,7 +434,11 @@ async fn shutdown_grace_handles_process_exit() {/*remote_control_enabled*/ false,);#[cfg(windows)]- let backend = PidBackend::new_update_loop(temp.path().join("codex"), pid_file);+ let backend = PidBackend::new_update_loop(+ temp.path().join("codex"),+ pid_file,+ /*restore_release*/ None,+ );let result = tokio::time::timeout(Duration::from_secs(3),backend.stop_with_grace(grace_seconds),@@ -503,7 +507,11 @@ async fn stopping_updater_signals_its_installer_process_group() {).await.expect("write pid file");- let backend = PidBackend::new_update_loop(temp.path().join("codex"), pid_file);+ let backend = PidBackend::new_update_loop(+ temp.path().join("codex"),+ pid_file,+ /*restore_release*/ None,+ );backend.stop().await.expect("stop updater");// The backend normally reaps the shim, so a second wait may return ECHILD.let _ = child.wait();@@ -542,8 +550,11 @@ async fn exited_unreaped_updater_is_reaped() {process_identity,executable_identity: None,};- let backend =- PidBackend::new_update_loop(temp.path().join("codex"), temp.path().join("updater.pid"));+ let backend = PidBackend::new_update_loop(+ temp.path().join("codex"),+ temp.path().join("updater.pid"),+ /*restore_release*/ None,+ );child.kill().expect("terminate updater shim");let deadline = tokio::time::Instant::now() + Duration::from_secs(5);let result = loop {@@ -569,7 +580,9 @@ fn update_loop_uses_hidden_app_server_subcommand() {codex_bin: "codex".into(),pid_file: "updater.pid".into(),lock_file: "updater.pid.lock".into(),- command_kind: PidCommandKind::UpdateLoop,+ command_kind: PidCommandKind::UpdateLoop {+ restore_release: None,+ },};assert_eq!(@@ -692,6 +705,7 @@ async fn failed_updater_handoff_preserves_predecessor_record() {let backend = PidBackend::new_update_loop(temp.path().join("missing-codex.exe"),state_dir.join("updater.pid"),+ /*restore_release*/ None,);let record = PidRecord {pid: std::process::id(),@@ -738,6 +752,7 @@ async fn updater_readiness_and_post_publication_failure_preserve_ownership() {let backend = PidBackend::new_update_loop(temp.path().join("codex.exe"),temp.path().join("updater.pid"),+ /*restore_release*/ None,);let _lock = backend.acquire_reservation_lock()diff --git a/codex-rs/app-server-daemon/src/lib.rs b/codex-rs/app-server-daemon/src/lib.rsindex fdfed6eaa8..8294ad656a 100644--- a/codex-rs/app-server-daemon/src/lib.rs+++ b/codex-rs/app-server-daemon/src/lib.rs@@ -268,11 +268,12 @@ pub async fn set_remote_control(mode: RemoteControlMode) -> Result<RemoteControlpub async fn run_pid_update_loop(http_client_factory: codex_http_client::HttpClientFactory,+ restore_release: Option<String>,) -> Result<()> {ensure_supported_platform()?;#[cfg(windows)]backend::windows::ensure_not_elevated()?;- update_loop::run(http_client_factory).await+ update_loop::run(http_client_factory, restore_release).await}pub async fn update(diff --git a/codex-rs/app-server-daemon/src/manual_update.rs b/codex-rs/app-server-daemon/src/manual_update.rsindex e822e51d52..640c5bc1f6 100644--- a/codex-rs/app-server-daemon/src/manual_update.rs+++ b/codex-rs/app-server-daemon/src/manual_update.rs@@ -60,7 +60,7 @@ pub(crate) async fn request(daemon: &Daemon) -> Result<UpdateOutput> {connection} else {let settings = daemon.load_settings().await?;- if !daemon.is_stable_standalone_release()?+ if !supported(daemon)?|| (daemon.running_backend_instance(&settings).await?.is_none()&& client::probe(&daemon.socket_path).await.is_ok()){@@ -70,8 +70,16 @@ pub(crate) async fn request(daemon: &Daemon) -> Result<UpdateOutput> {.stop().await?;let current_exe = std::env::current_exe()?;- let worker = crate::backend::pid_update_loop_backend(- daemon.backend_paths_with_bin(&settings, ¤t_exe),+ let paths = daemon.backend_paths_with_bin(&settings, ¤t_exe);+ let restore_release = if daemon.is_stable_standalone_release()? {+ None+ } else {+ Some(selected_release(daemon)?.2)+ };+ let worker = crate::backend::PidBackend::new_update_loop(+ paths.codex_bin,+ paths.update_pid_file,+ restore_release,);worker.start().await?;let deadline = tokio::time::Instant::now() + Duration::from_secs(30);@@ -120,11 +128,38 @@ pub(crate) async fn request(daemon: &Daemon) -> Result<UpdateOutput> {transport?;let outcome: std::result::Result<UpdateOutput, String> =serde_json::from_slice(&response).context("invalid response from daemon updater")?;- return outcome.map_err(anyhow::Error::msg);+ let outcome = outcome.map_err(anyhow::Error::msg)?;+ if outcome.status == UpdateStatus::Unsupported && supported(daemon)? {+ // A scheduled or older updater cannot authorize restoring a pin.+ // Replace it under the writable operation lock, even with identical bytes.+ let _operation_lock = daemon.acquire_operation_lock().await?;+ let settings = daemon.load_settings().await?;+ let worker = crate::backend::pid_update_loop_backend(daemon.backend_paths(&settings));+ if !daemon.is_stable_standalone_release()? {+ worker.stop().await?;+ continue 'request;+ }+ }+ return Ok(outcome);+ }+}++pub(super) fn supported(daemon: &Daemon) -> Result<bool> {+ if daemon.is_stable_standalone_release()? {+ return Ok(true);}+ let Ok((root, release, _)) = selected_release(daemon) else {+ return Ok(false);+ };+ let bin = daemon.current_managed_codex_bin()?;+ Ok(std::fs::canonicalize(root.join("releases"))+ .is_ok_and(|releases| release.parent() == Some(releases.as_path()))+ && bin.is_file()+ && std::fs::canonicalize(bin).is_ok_and(|bin| bin.starts_with(&release)))}-const UNSUPPORTED_MESSAGE: &str = "This command requires a CLI-managed daemon and a stable latest-channel standalone install; update this installation with its owning installer.";+const UNSUPPORTED_MESSAGE: &str =+ "This command requires a daemon package selected from its managed releases directory.";pub(super) async fn unsupported(daemon: &Daemon) -> Result<UpdateOutput> {let managed_codex_path = daemon.current_managed_codex_bin()?;@@ -146,6 +181,7 @@ pub(super) async fn handle_request(daemon: &Daemon,running_updater_identity: &crate::managed_install::ExecutableIdentity,terminate: &mut Signal,+ trigger: UpdateTrigger<'_>,) -> Result<RequestDisposition> {#[cfg(windows)]if connection.ensure_non_elevated_peer().is_err() {@@ -159,7 +195,7 @@ pub(super) async fn handle_request({return Ok(RequestDisposition::Unchanged);}- let result = run(http, daemon, running_updater_identity, terminate).await;+ let result = run(http, daemon, running_updater_identity, terminate, trigger).await;let interrupted = result.as_ref().err().is_some_and(|err| {err.downcast_ref::<std::io::Error>().is_some_and(|err| err.kind() == std::io::ErrorKind::Interrupted)@@ -192,10 +228,12 @@ pub(super) async fn run(daemon: &Daemon,running_updater_identity: &crate::managed_install::ExecutableIdentity,terminate: &mut Signal,+ trigger: UpdateTrigger<'_>,) -> Result<UpdateOutput> {let settings = daemon.load_settings().await?;let managed_running = daemon.running_backend_instance(&settings).await?.is_some();- if !daemon.is_stable_standalone_release()?+ if !(daemon.is_stable_standalone_release()?+ || matches!(trigger, UpdateTrigger::RestoreProduction(_)) && supported(daemon)?)|| (!managed_running && client::probe(&daemon.socket_path).await.is_ok()){return unsupported(daemon).await;@@ -204,14 +242,8 @@ pub(super) async fn run(let managed_codex_path = daemon.current_managed_codex_bin()?;let (_, previous_release, _) = selected_release(daemon)?;let previous_identity = executable_identity(&managed_codex_path).await?;- let (control, restart) = update_once(- http,- daemon,- running_updater_identity,- terminate,- UpdateTrigger::Manual,- )- .await?;+ let (control, restart) =+ update_once(http, daemon, running_updater_identity, terminate, trigger).await?;if matches!(control, UpdateLoopControl::Stop) {return Err(std::io::Error::from(std::io::ErrorKind::Interrupted).into());}diff --git a/codex-rs/app-server-daemon/src/migration.rs b/codex-rs/app-server-daemon/src/migration.rsindex e250f6df52..b73dff0d6a 100644--- a/codex-rs/app-server-daemon/src/migration.rs+++ b/codex-rs/app-server-daemon/src/migration.rs@@ -24,7 +24,7 @@ pub(super) async fn run(http: &impl InstallerHttp, legacy: &Daemon) -> Result<Uplet _operation_lock = legacy.acquire_operation_lock().await?;let previous = selected_release(legacy)?;anyhow::ensure!(- previous.0.ends_with("standalone") && legacy.is_stable_standalone_release()?,+ previous.0.ends_with("standalone") && super::manual_update::supported(legacy)?,"daemon selection changed; retry the update");let home = previousdiff --git a/codex-rs/app-server-daemon/src/prepare_install.rs b/codex-rs/app-server-daemon/src/prepare_install.rsindex 23325ae827..290ceae25d 100644--- a/codex-rs/app-server-daemon/src/prepare_install.rs+++ b/codex-rs/app-server-daemon/src/prepare_install.rs@@ -72,7 +72,7 @@ pub async fn update_from_cli(.ok().map(|info| info.app_server_version),managed_codex_path,- message: "The CLI package is selected and pinned.".to_string(),+ message: "The CLI package is selected and pinned. Run `codex app-server daemon update` to return to production updates.".to_string(),}))}diff --git a/codex-rs/app-server-daemon/src/update_loop.rs b/codex-rs/app-server-daemon/src/update_loop.rsindex e8a248f6a5..8f55126878 100644--- a/codex-rs/app-server-daemon/src/update_loop.rs+++ b/codex-rs/app-server-daemon/src/update_loop.rs@@ -49,7 +49,7 @@ pub(crate) async fn request_manual_update(.pid_file.file_name().is_some_and(|name| name == crate::LEGACY_PID_FILE_NAME)- && daemon.is_stable_standalone_release()?+ && manual_update::supported(daemon)?{let http = RouteAwareClientPool::new_without_request_logging(http_client_factory,@@ -67,7 +67,10 @@ const INSTALL_URL: &str = "https://chatgpt.com/codex/install.sh";#[cfg(windows)]const INSTALL_URL: &str = "https://chatgpt.com/codex/install.ps1";-pub(crate) async fn run(http_client_factory: HttpClientFactory) -> Result<()> {+pub(crate) async fn run(+ http_client_factory: HttpClientFactory,+ restore_release: Option<String>,+) -> Result<()> {let http = RouteAwareClientPool::new_without_request_logging(http_client_factory,ClientRouteClass::Other,@@ -76,6 +79,7 @@ pub(crate) async fn run(http_client_factory: HttpClientFactory) -> Result<()> {&http,&Daemon::from_environment()?,¤t_updater_identity().await?,+ restore_release,).await}@@ -84,6 +88,7 @@ async fn run_with_http(http: &impl InstallerHttp,daemon: &Daemon,running_updater_identity: &ExecutableIdentity,+ mut restore_release: Option<String>,) -> Result<()> {#[cfg(unix)]let mut terminate =@@ -136,7 +141,7 @@ async fn run_with_http(.map(|settings| settings.auto_update_enabled).unwrap_or(true);let mut next_check = Instant::now()- + if needs_managed_handoff || !auto_update_enabled {+ + if restore_release.is_some() || needs_managed_handoff || !auto_update_enabled {Duration::from_secs(15)} else {INITIAL_UPDATE_DELAY@@ -148,7 +153,11 @@ async fn run_with_http(_ = terminate.recv() => return Ok(()),connection = listener.as_mut().context("updater listener closed")?.accept() => {let connection = connection.context("failed to accept updater request")?;- let disposition = match manual_update::handle_request(connection, http, daemon, running_updater_identity, &mut terminate).await {+ // Only a manual CLI launch under the operation lock supplies this+ // single-use authority. Ordinary socket requests cannot undo a pin.+ let restoration = restore_release.take();+ let trigger = restoration.as_deref().map_or(UpdateTrigger::Manual, UpdateTrigger::RestoreProduction);+ let disposition = match manual_update::handle_request(connection, http, daemon, running_updater_identity, &mut terminate, trigger).await {Ok(manual_update::RequestDisposition::Stop) => return Ok(()),Ok(disposition) => disposition,Err(_) => manual_update::RequestDisposition::Continue,@@ -168,6 +177,10 @@ async fn run_with_http(next_check = Instant::now();}_ = sleep_until(next_check) => {+ // The authorizing CLI may have exited before sending its request.+ if restore_release.is_some() {+ return Ok(());+ }match UpdaterSettings::load(&daemon.settings_file).await {Ok(settings) if !settings.auto_update_enabled => return Ok(()),Err(_) => {@@ -284,9 +297,10 @@ enum UpdateLoopControl {}#[derive(Clone, Copy, PartialEq, Eq)]-enum UpdateTrigger {+enum UpdateTrigger<'a> {Scheduled,Manual,+ RestoreProduction(&'a str),}async fn update_once(@@ -294,7 +308,7 @@ async fn update_once(daemon: &Daemon,running_updater_identity: &ExecutableIdentity,terminate: &mut Signal,- trigger: UpdateTrigger,+ trigger: UpdateTrigger<'_>,) -> Result<(UpdateLoopControl, Option<RestartIfRunningOutcome>)> {if trigger == UpdateTrigger::Scheduled&& !UpdaterSettings::load(&daemon.settings_file)@@ -308,20 +322,36 @@ async fn update_once(// latest-channel marker. Retry after the interval instead of exiting.return Ok((UpdateLoopControl::Continue, None));}- let (package_root, _, previous_release) = selected_release(daemon)?;+ let (package_root, previous_selection, previous_release) = selected_release(daemon)?;let codex_home = package_root.parent().and_then(Path::parent).context("daemon package root has no Codex home")?;+ let (installer_mode, installer_guard) =+ if let UpdateTrigger::RestoreProduction(expected) = trigger {+ anyhow::ensure!(+ previous_release == expected,+ "daemon selection changed; retry the update"+ );+ (+ InstallerMode::RestoreProduction(&previous_release),+ "CODEX_INSTALL_IF_CURRENT",+ )+ } else {+ (+ InstallerMode::Update(&previous_release),+ "CODEX_INSTALL_IF_LATEST",+ )+ };let script = tokio::select! {result = fetch_installer_script(http) => result?,_ = terminate.recv() => return Ok((UpdateLoopControl::Stop, None)),};anyhow::ensure!(script- .windows(b"CODEX_INSTALL_IF_LATEST".len())- .any(|window| window == b"CODEX_INSTALL_IF_LATEST"),- "standalone installer does not support guarded updates"+ .windows(installer_guard.len())+ .any(|window| window == installer_guard.as_bytes()),+ "standalone installer does not support {installer_guard} guarded updates");if package_root.ends_with("app-server-daemon") {anyhow::ensure!(@@ -347,22 +377,20 @@ async fn update_once();#[cfg(unix)]if matches!(- run_installer_script(- &script,- InstallerMode::Update(&previous_release),- &package_root,- terminate.recv()- )- .await?,+ run_installer_script(&script, installer_mode, &package_root, terminate.recv()).await?,UpdateLoopControl::Stop) {return Ok((UpdateLoopControl::Stop, None));}#[cfg(windows)]tokio::select! {- result = run_installer_script(&script, InstallerMode::Update(&previous_release), &package_root) => { result?; },+ result = run_installer_script(&script, installer_mode, &package_root) => { result?; },_ = terminate.recv() => return Ok((UpdateLoopControl::Stop, None)),}+ anyhow::ensure!(+ trigger == UpdateTrigger::Scheduled || daemon.is_stable_standalone_release()?,+ "installer did not select a stable latest release; retry the update"+ );if release_selection_unstable(daemon, trigger)? {return Ok((UpdateLoopControl::Continue, None));}@@ -370,7 +398,16 @@ async fn update_once(let managed_codex_bin =resolved_managed_codex_bin(&daemon.current_managed_codex_bin()?).await?;let restart_mode = match trigger {- UpdateTrigger::Manual => RestartMode::IfBinaryOrVersionChanged,+ // The package can contain different resources even when its CLI binary+ // is identical. A release change must also replace the running process.+ UpdateTrigger::Manual | UpdateTrigger::RestoreProduction(_)+ if selected_release(daemon)?.1 != previous_selection =>+ {+ RestartMode::Always+ }+ UpdateTrigger::Manual | UpdateTrigger::RestoreProduction(_) => {+ RestartMode::IfBinaryOrVersionChanged+ }UpdateTrigger::Scheduledif executable_identity(&managed_codex_bin).await? != *running_updater_identity =>{@@ -405,7 +442,7 @@ async fn update_once());}RestartIfRunningOutcome::AlreadyCurrent- if trigger == UpdateTrigger::Manual+ if trigger != UpdateTrigger::Scheduled&& restart_mode == RestartMode::IfBinaryOrVersionChanged =>{anyhow::ensure!(@@ -421,7 +458,7 @@ async fn update_once(}RestartIfRunningOutcome::NotReady | RestartIfRunningOutcome::AlreadyCurrent => {anyhow::ensure!(- trigger != UpdateTrigger::Manual,+ trigger == UpdateTrigger::Scheduled,"managed daemon could not restart; retry when it is ready");return Ok((@@ -437,12 +474,15 @@ async fn update_once(}}-fn release_selection_unstable(daemon: &Daemon, trigger: UpdateTrigger) -> Result<bool> {- if daemon.is_stable_standalone_release()? {+fn release_selection_unstable(daemon: &Daemon, trigger: UpdateTrigger<'_>) -> Result<bool> {+ if daemon.is_stable_standalone_release()?+ || matches!(trigger, UpdateTrigger::RestoreProduction(_))+ && manual_update::supported(daemon)?+ {return Ok(false);}anyhow::ensure!(- trigger != UpdateTrigger::Manual,+ trigger == UpdateTrigger::Scheduled,"standalone install selection changed during the update");Ok(true)@@ -485,6 +525,7 @@ pub(crate) fn reexec_managed_updater(managed_codex_bin: &std::path::Path) -> Resenum InstallerMode<'a> {Update(&'a str),+ RestoreProduction(&'a str),Migration,}@@ -509,9 +550,10 @@ async fn run_installer_script(.kill_on_drop(true);command};- let (guard, previous_release, defer_selection) = match mode {- InstallerMode::Update(release) => ("1", release, "0"),- InstallerMode::Migration => ("0", "", "1"),+ let (latest_guard, current_guard, previous_release, defer_selection) = match mode {+ InstallerMode::Update(release) => ("1", "0", release, "0"),+ InstallerMode::RestoreProduction(release) => ("0", "1", release, "0"),+ InstallerMode::Migration => ("0", "0", "", "1"),};let mut child = command.env(@@ -532,7 +574,8 @@ async fn run_installer_script().env("CODEX_RELEASE", "latest").env("CODEX_NON_INTERACTIVE", "1")- .env("CODEX_INSTALL_IF_LATEST", guard)+ .env("CODEX_INSTALL_IF_LATEST", latest_guard)+ .env("CODEX_INSTALL_IF_CURRENT", current_guard).env("CODEX_UPDATE_FROM_RELEASE", previous_release).kill_on_drop(true).stdin(Stdio::piped())diff --git a/codex-rs/app-server-daemon/src/update_loop_tests.rs b/codex-rs/app-server-daemon/src/update_loop_tests.rsindex 2dfd3c40a1..77f16c8249 100644--- a/codex-rs/app-server-daemon/src/update_loop_tests.rs+++ b/codex-rs/app-server-daemon/src/update_loop_tests.rs@@ -57,9 +57,19 @@ struct FakeInstallerHttp {#[cfg(unix)]#[tokio::test]async fn explicit_update_migrates_running_and_stopped_installations() {- for running in [false, true] {+ for (running, local) in [(false, false), (true, false), (false, true), (true, true)] {let home = TempDir::new().unwrap();let (legacy, release) = manual_update_daemon(&home);+ let root = home.path().join("packages/standalone");+ if local {+ let package = root.join("releases/local-development");+ std::fs::create_dir(&package).unwrap();+ std::fs::copy(&legacy.managed_codex_bin, package.join("codex")).unwrap();+ std::fs::remove_file(root.join("current")).unwrap();+ std::os::unix::fs::symlink(&package, root.join("current")).unwrap();+ std::fs::remove_file(root.join("auto-update-version")).unwrap();+ }+ let previous = root.join("current").canonicalize().unwrap();let scheduled = FakeInstallerHttp::new(InstallerResponse::Success(b"# CODEX_INSTALL_IF_LATEST\ntest \"$CODEX_INSTALL_DEFER_SELECTION\" = 0 && test \"$CODEX_INSTALL_DAEMON_ONLY\" = 0\n".to_vec(),));@@ -74,7 +84,14 @@ async fn explicit_update_migrates_running_and_stopped_installations() {).await.unwrap();- assert_eq!(scheduled.requested_urls(), vec![INSTALL_URL.to_string()]);+ assert_eq!(+ scheduled.requested_urls(),+ if local {+ vec![]+ } else {+ vec![INSTALL_URL.to_string()]+ }+ );assert_eq!(crate::managed_install::package_root(home.path()),home.path().join("packages/standalone")@@ -109,6 +126,7 @@ async fn explicit_update_migrates_running_and_stopped_installations() {r#"# CODEX_INSTALL_DEFER_SELECTIONset -eutest "$CODEX_INSTALL_DEFER_SELECTION" = 1+test "$CODEX_INSTALL_IF_CURRENT" = 0test "$CODEX_INSTALL_DAEMON_ONLY" = 1test "$CODEX_INSTALL_IF_LATEST" = 0root="$CODEX_HOME/packages/app-server-daemon"@@ -152,6 +170,7 @@ printf '{release}' > "$root/auto-update-version"dedicated.clone());assert!(!dedicated.join(".migration-current").exists());+ assert_eq!(root.join("current").canonicalize().unwrap(), previous);assert_eq!(std::fs::read(&legacy.managed_codex_bin).unwrap(),legacy_bin@@ -377,10 +396,9 @@ async fn manual_request_recovers_when_one_shot_updater_exits() {.await.expect("remove exited updater socket");});- // Without the marker, the ordinary startup path reports unsupported. A+ // Without the selected executable, the startup path reports unsupported. A// retry that only waits for a successor would time out instead.- std::fs::remove_file(home.path().join("packages/standalone/auto-update-version"))- .expect("remove latest marker");+ std::fs::remove_file(&daemon.managed_codex_bin).expect("remove selected binary");let result = tokio::time::timeout(Duration::from_secs(5),super::manual_update::request(&daemon),@@ -407,8 +425,15 @@ async fn unsupported_request_preserves_updater_schedule() {let socket_path = daemon.manual_update_socket_path();let http = FakeInstallerHttp::new(InstallerResponse::Success(Vec::new()));let updater_daemon = std::sync::Arc::clone(&daemon);- let worker =- tokio::spawn(async move { super::run_with_http(&http, &updater_daemon, &identity).await });+ let worker = tokio::spawn(async move {+ super::run_with_http(+ &http,+ &updater_daemon,+ &identity,+ /*restore_release*/ None,+ )+ .await+ });let deadline = tokio::time::Instant::now() + Duration::from_secs(5);while !socket_path.exists() {assert!(@@ -417,8 +442,23 @@ async fn unsupported_request_preserves_updater_schedule() {);tokio::time::sleep(Duration::from_millis(20)).await;}- std::fs::remove_file(home.path().join("packages/standalone/auto-update-version"))- .expect("remove latest selection");+ // An external installer can pin while this ordinary worker still listens.+ // Raw IPC must not gain the manual CLI's authority to restore production.+ let marker = super::selected_release(&daemon)+ .unwrap()+ .0+ .join("auto-update-version");+ let previous_marker = std::fs::read(&marker).unwrap();+ std::fs::remove_file(&marker).unwrap();+ let mut pinned = codex_uds::UnixStream::connect(&socket_path).await.unwrap();+ pinned.write_all(b"update\n").await.unwrap();+ let mut response = Vec::new();+ pinned.read_to_end(&mut response).await.unwrap();+ let response: Result<UpdateOutput, String> = serde_json::from_slice(&response).unwrap();+ assert_eq!(response.unwrap().status, UpdateStatus::Unsupported);+ assert!(!marker.exists());+ std::fs::write(&marker, previous_marker).unwrap();+ std::fs::remove_file(&daemon.managed_codex_bin).expect("remove selected binary");let mut malformed = codex_uds::UnixStream::connect(&socket_path).await.expect("connect malformed request");@@ -473,7 +513,7 @@ async fn test_control_server(let version = if std::fs::read_to_string(crate::managed_install::package_root(&codex_home).join("auto-update-version"),)- .expect("selected release")+ .unwrap_or_default().starts_with("1.1.0"){"1.1.0"@@ -498,11 +538,39 @@ async fn test_control_server(#[cfg(unix)]#[tokio::test]async fn manual_update_restarts_managed_daemon_with_automatic_updates_disabled() {+ check_manual_update_restart("standalone").await;+}++#[cfg(unix)]+#[tokio::test]+async fn manual_update_restarts_local_daemon_with_automatic_updates_disabled() {+ check_manual_update_restart("app-server-daemon").await;+}++#[cfg(unix)]+async fn check_manual_update_restart(package_directory: &str) {use tokio::io::AsyncReadExt;use tokio::io::AsyncWriteExt;+ let local_package = package_directory == "app-server-daemon";let home = TempDir::new().expect("home");- let (daemon, release) = manual_update_daemon(&home);+ let (mut daemon, mut release) = manual_update_daemon(&home);+ let standalone = home.path().join("packages").join(package_directory);+ if local_package {+ std::fs::rename(home.path().join("packages/standalone"), &standalone).unwrap();+ let local = format!("local-development-{release}");+ std::fs::rename(+ standalone.join("releases").join(&release),+ standalone.join("releases").join(&local),+ )+ .unwrap();+ std::fs::remove_file(standalone.join("current")).unwrap();+ std::os::unix::fs::symlink(format!("releases/{local}"), standalone.join("current"))+ .unwrap();+ std::fs::remove_file(standalone.join("auto-update-version")).unwrap();+ daemon.managed_codex_bin = standalone.join("current/codex");+ release = local;+ }let daemon = std::sync::Arc::new(daemon);std::fs::create_dir_all(daemon.settings_file.parent().expect("state directory")).expect("state directory");@@ -524,23 +592,44 @@ async fn manual_update_restarts_managed_daemon_with_automatic_updates_disabled().expect("PID")};let before = current_pid();- let next = release.replacen("1.0.0", "1.1.0", 1);- let standalone = home.path().join("packages/standalone");+ let version = if local_package { "1.0.0" } else { "1.1.0" };+ let next = release+ .trim_start_matches("local-development-")+ .replacen("1.0.0", version, 1);+ let guard = if local_package {+ "CODEX_INSTALL_IF_CURRENT"+ } else {+ "CODEX_INSTALL_IF_LATEST"+ };+ let install_binary = if local_package {+ // Same binary and version, but a different package: it must still restart.+ format!(+ "cp '{root}/releases/{release}/codex' '{root}/releases/{next}/bin/codex'",+ root = standalone.display()+ )+ } else {+ format!(+ r#"printf '#!/bin/sh\nif [ "$1" = --version ]; then echo codex 1.1.0; else exec sleep 30; fi\n' > '{root}/releases/{next}/bin/codex'"#,+ root = standalone.display()+ )+ };let ready = home.path().join("installer-ready");let proceed = home.path().join("installer-proceed");let script = format!(- "#!/bin/sh\n# CODEX_INSTALL_IF_LATEST\ntest \"$CODEX_INSTALL_IF_LATEST\" = 1 || exit 4\nif [ \"$CODEX_UPDATE_FROM_RELEASE\" = '{next}' ]; then exit 0; fi\ntest \"$CODEX_UPDATE_FROM_RELEASE\" = '{release}' || exit 5\ntouch '{ready}'\nwhile [ ! -e '{proceed}' ]; do sleep .05; done\nmkdir -p '{root}/releases/{next}/bin'\nprintf '#!/bin/sh\\nif [ \"$1\" = --version ]; then echo codex 1.1.0; else exec sleep 30; fi\\n' > '{root}/releases/{next}/bin/codex'\nchmod +x '{root}/releases/{next}/bin/codex'\nln -sfn 'releases/{next}' '{root}/current'\nprintf '{next}' > '{root}/auto-update-version'\n",+ "#!/bin/sh\n# CODEX_INSTALL_IF_LATEST CODEX_INSTALL_IF_CURRENT CODEX_INSTALL_DAEMON_ONLY\nif [ \"$CODEX_UPDATE_FROM_RELEASE\" = '{next}' ]; then exit 0; fi\ntest \"${guard}\" = 1 || exit 4\ntest \"$CODEX_UPDATE_FROM_RELEASE\" = '{release}' || exit 5\ntouch '{ready}'\nwhile [ ! -e '{proceed}' ]; do sleep .05; done\nmkdir -p '{root}/releases/{next}/bin'\n{install_binary}\nchmod +x '{root}/releases/{next}/bin/codex'\nln -sfn 'releases/{next}' '{root}/current'\nprintf '{next}' > '{root}/auto-update-version'\n",root = standalone.display(),ready = ready.display(),proceed = proceed.display(),);let http = FakeInstallerHttp::new(InstallerResponse::Success(script.into_bytes()));let updater_daemon = std::sync::Arc::clone(&daemon);+ let restore_release = local_package.then(|| release.clone());let worker = tokio::spawn(async move {super::run_with_http(&http,&updater_daemon,&executable_identity_from_bytes(b"updater"),+ restore_release,).await});@@ -574,8 +663,8 @@ async fn manual_update_restarts_managed_daemon_with_automatic_updates_disabled().expect("first request task").expect("manual update");assert_eq!(output.status, UpdateStatus::Updated);- assert_eq!(output.installed_version.as_deref(), Some("1.1.0"));- assert_eq!(output.running_version.as_deref(), Some("1.1.0"));+ assert_eq!(output.installed_version.as_deref(), Some(version));+ assert_eq!(output.running_version.as_deref(), Some(version));assert_eq!(output.managed_codex_path,standalone.join("current/bin/codex")@@ -600,7 +689,7 @@ async fn manual_update_restarts_managed_daemon_with_automatic_updates_disabled().expect("updater task").expect("updater loop");let no_op = FakeInstallerHttp::new(InstallerResponse::Success(- b"#!/bin/sh\n# CODEX_INSTALL_IF_LATEST\nexit 0\n".to_vec(),+ b"#!/bin/sh\n# CODEX_INSTALL_IF_LATEST CODEX_INSTALL_DAEMON_ONLY\nexit 0\n".to_vec(),));use std::io::Write;std::fs::OpenOptions::new()@@ -618,6 +707,7 @@ async fn manual_update_restarts_managed_daemon_with_automatic_updates_disabled()&daemon,&executable_identity_from_bytes(b"updater"),&mut test_terminate(),+ super::UpdateTrigger::Manual,).await.expect("retry with stale running binary");@@ -635,6 +725,7 @@ async fn powershell_installer_is_noninteractive_and_reports_script_failure() {function Test-Installer {if ($env:CODEX_NON_INTERACTIVE -ne '1') { throw 'interactive installer' }if ($env:CODEX_INSTALL_DAEMON_ONLY -ne '1') { throw 'wrong package destination' }+ if ($env:CODEX_INSTALL_IF_CURRENT -ne '1' -or $env:CODEX_INSTALL_IF_LATEST -ne '0') { throw 'wrong update guard' }}Test-Installer"#@@ -645,7 +736,7 @@ Test-Installer.expect("fetch installer");super::run_installer_script(&script,- super::InstallerMode::Update("0.150.0-x86_64-pc-windows-msvc"),+ super::InstallerMode::RestoreProduction("0.150.0-x86_64-pc-windows-msvc"),std::path::Path::new("packages/app-server-daemon"),).await@@ -659,7 +750,7 @@ Test-Installerassert!(super::run_installer_script(&script,- super::InstallerMode::Update("0.150.0-x86_64-pc-windows-msvc"),+ super::InstallerMode::RestoreProduction("0.150.0-x86_64-pc-windows-msvc"),std::path::Path::new("packages/app-server-daemon")).await@@ -692,6 +783,7 @@ async fn update_rejects_a_package_root_change_during_download() {&daemon,&identity,&mut test_terminate(),+ super::UpdateTrigger::Manual,).await.unwrap_err();@@ -702,7 +794,7 @@ async fn update_rejects_a_package_root_change_during_download() {#[tokio::test]async fn daemon_owned_updates_require_and_request_an_isolated_installer() {let home = TempDir::new().unwrap();- let (mut daemon, _) = manual_update_daemon(&home);+ let (mut daemon, release) = manual_update_daemon(&home);let root = home.path().join("packages/app-server-daemon");std::fs::rename(home.path().join("packages/standalone"), &root).unwrap();daemon.managed_codex_bin = root.join("current/codex");@@ -712,20 +804,88 @@ async fn daemon_owned_updates_require_and_request_an_isolated_installer() {let old = FakeInstallerHttp::new(InstallerResponse::Success(b"# CODEX_INSTALL_IF_LATEST\nexit 0\n".to_vec(),));- let error = manual_update_once(&old, &daemon, &identity, &mut test_terminate())- .await- .unwrap_err();+ let error = manual_update_once(+ &old,+ &daemon,+ &identity,+ &mut test_terminate(),+ super::UpdateTrigger::Manual,+ )+ .await+ .unwrap_err();assert!(error.to_string().contains("does not support daemon-owned packages"));let current = FakeInstallerHttp::new(InstallerResponse::Success(- b"# CODEX_INSTALL_IF_LATEST\ntest \"$CODEX_INSTALL_DAEMON_ONLY\" = 1\n".to_vec(),+ b"# CODEX_INSTALL_IF_LATEST\ntest \"$CODEX_INSTALL_IF_LATEST\" = 1 && test \"$CODEX_INSTALL_DAEMON_ONLY\" = 1\n".to_vec(),));- let output = manual_update_once(¤t, &daemon, &identity, &mut test_terminate())- .await- .unwrap();+ let output = manual_update_once(+ ¤t,+ &daemon,+ &identity,+ &mut test_terminate(),+ super::UpdateTrigger::Manual,+ )+ .await+ .unwrap();assert_eq!(output.status, UpdateStatus::NoUpdate);assert!(!home.path().join("packages/standalone").exists());++ // Reuse the stopped daemon to verify explicit unpinning with either preference.+ let marker = root.join("auto-update-version");+ let no_op = FakeInstallerHttp::new(InstallerResponse::Success(+ b"# CODEX_INSTALL_IF_CURRENT CODEX_INSTALL_DAEMON_ONLY\nexit 0\n".to_vec(),+ ));+ let script = format!(+ r#"# CODEX_INSTALL_IF_CURRENT CODEX_INSTALL_DAEMON_ONLY+set -eu+test "$CODEX_INSTALL_IF_CURRENT" = 1+test "$CODEX_INSTALL_IF_LATEST" = 0+test "$CODEX_INSTALL_DAEMON_ONLY" = 1+test "$CODEX_RELEASE" = latest+test "$CODEX_UPDATE_FROM_RELEASE" = '{release}'+printf '%s' '{release}' > '{marker}'+"#,+ marker = marker.display()+ );+ let restore = FakeInstallerHttp::new(InstallerResponse::Success(script.into_bytes()));+ for auto_update_enabled in [false, true] {+ let settings = format!(r#"{{"updater":{{"autoUpdateEnabled":{auto_update_enabled}}}}}"#);+ std::fs::write(&daemon.settings_file, &settings).unwrap();+ std::fs::remove_file(&marker).unwrap();+ let error = manual_update_once(+ &no_op,+ &daemon,+ &identity,+ &mut test_terminate(),+ super::UpdateTrigger::RestoreProduction(&release),+ )+ .await+ .unwrap_err();+ assert!(+ error+ .to_string()+ .contains("did not select a stable latest release")+ );+ assert!(!marker.exists());+ let restored = manual_update_once(+ &restore,+ &daemon,+ &identity,+ &mut test_terminate(),+ super::UpdateTrigger::RestoreProduction(&release),+ )+ .await+ .unwrap();+ // Restoring eligibility for the same package still reports noUpdate.+ assert_eq!(restored, output);+ assert!(!daemon.pid_file.exists());+ assert!(daemon.is_stable_standalone_release().unwrap());+ assert_eq!(+ std::fs::read_to_string(&daemon.settings_file).unwrap(),+ settings+ );+ }}diff --git a/codex-rs/cli/src/daemon_install.rs b/codex-rs/cli/src/daemon_install.rsindex dad14777a0..cf1b450b0c 100644--- a/codex-rs/cli/src/daemon_install.rs+++ b/codex-rs/cli/src/daemon_install.rs@@ -23,7 +23,7 @@ pub(crate) fn confirm_install(request: &InstallRequest, yes: bool) -> Result<boofn describe_install(request: &InstallRequest) -> String {let mut message = format!(- "Replace installed daemon version {} with CLI version {} from {}.\nThe daemon package will be installed in {}.\nThe selected package will be pinned.",+ "Replace installed daemon version {} with CLI version {} from {}.\nThe daemon package will be installed in {}.\nThe selected package will be pinned. Run `codex app-server daemon update` to return to production updates.",request.installed_version.as_deref().unwrap_or("unknown"),request.version,request.source.display(),diff --git a/codex-rs/cli/src/daemon_install_tests.rs b/codex-rs/cli/src/daemon_install_tests.rsindex c48c85cb1b..700c23784e 100644--- a/codex-rs/cli/src/daemon_install_tests.rs+++ b/codex-rs/cli/src/daemon_install_tests.rs@@ -12,7 +12,7 @@ fn running_daemon_replacement_prompt() {insta::assert_snapshot!(describe_install(&request), @r"Replace installed daemon version 0.152.0 with CLI version 0.0.0 from /cli/package.The daemon package will be installed in /home/packages/app-server-daemon.- The selected package will be pinned.+ The selected package will be pinned. Run `codex app-server daemon update` to return to production updates.The running daemon will restart; active or queued work may be interrupted.");}diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rsindex 4789190142..108701e58f 100644--- a/codex-rs/cli/src/main.rs+++ b/codex-rs/cli/src/main.rs@@ -821,6 +821,9 @@ enum AppServerDaemonSubcommand {/// Check support for daemon-owned packages without starting the updater.#[arg(long, hide = true)]check_package_ownership: bool,+ /// Authorize one production restoration of this selected release.+ #[arg(long, hide = true)]+ restore_release: Option<String>,},}@@ -1434,12 +1437,14 @@ async fn cli_main(}AppServerDaemonSubcommand::PidUpdateLoop {check_package_ownership: true,+ ..} => return Ok(()),AppServerDaemonSubcommand::Update {from_cli: false, ..}| AppServerDaemonSubcommand::PidUpdateLoop {check_package_ownership: false,+ ..} => {let cli_overrides = root_config_overrides.parse_overrides()@@ -1458,8 +1463,17 @@ async fn cli_main(codex_app_server_daemon::update(http_client_factory).await?;println!("{}", serde_json::to_string(&output)?);} else {- codex_app_server_daemon::run_pid_update_loop(http_client_factory)- .await?;+ let AppServerDaemonSubcommand::PidUpdateLoop {+ restore_release, ..+ } = daemon_cli.subcommand+ else {+ unreachable!()+ };+ codex_app_server_daemon::run_pid_update_loop(+ http_client_factory,+ restore_release,+ )+ .await?;}}},diff --git a/codex-rs/cli/tests/app_server_daemon.rs b/codex-rs/cli/tests/app_server_daemon.rsindex 666791fc05..6ac6de389e 100644--- a/codex-rs/cli/tests/app_server_daemon.rs+++ b/codex-rs/cli/tests/app_server_daemon.rs@@ -353,7 +353,6 @@ fn managed_start_keeps_updater_on_marker_mismatch_but_stops_it_for_pin() -> Resustd::fs::write(&marker, "0.1.0-other-target")?;assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);- assert_eq!(daemon.lifecycle("update")?["status"], "unsupported");std::thread::sleep(Duration::from_millis(250));let updater_state = Command::new("/bin/ps").args(["-p", &updater_pid.to_string(), "-o", "stat="])@@ -457,7 +456,7 @@ fn manual_update_rejects_an_unowned_installation() -> Result<()> {daemon.home.path()- .join("packages/standalone/auto-update-version"),+ .join("packages/standalone/current/bin/codex"),)?;assert_eq!(daemon.lifecycle("update")?["status"], "unsupported");diff --git a/scripts/install/install.ps1 b/scripts/install/install.ps1index 535bcc31f5..cd9c0c7789 100644--- a/scripts/install/install.ps1+++ b/scripts/install/install.ps1@@ -507,7 +507,8 @@ function Move-OldStandaloneBinIfApproved {}function Add-JunctionSupportType {- if (([System.Management.Automation.PSTypeName]'CodexInstaller.Junction').Type) {+ # Older installer types remain loaded when users rerun irm | iex in one session.+ if (([System.Management.Automation.PSTypeName]'CodexInstaller.JunctionV2').Type) {return}@@ -521,7 +522,7 @@ using Microsoft.Win32.SafeHandles;namespace CodexInstaller{- public static class Junction+ public static class JunctionV2{private const uint GENERIC_WRITE = 0x40000000;private const uint FILE_SHARE_READ = 0x00000001;@@ -555,6 +556,25 @@ namespace CodexInstallerout int lpBytesReturned,IntPtr lpOverlapped);+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]+ private static extern uint GetFinalPathNameByHandleW(+ SafeFileHandle file, StringBuilder path, uint length, uint flags);++ public static string ResolveDirectory(string path)+ {+ using (SafeFileHandle handle = CreateFileW(+ path, 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+ IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero))+ {+ if (handle.IsInvalid) { throw new Win32Exception(Marshal.GetLastWin32Error()); }+ StringBuilder resolved = new StringBuilder(32768);+ uint length = GetFinalPathNameByHandleW(handle, resolved, (uint)resolved.Capacity, 0);+ if (length == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); }+ if (length >= resolved.Capacity) { throw new IOException("Resolved path is too long."); }+ return resolved.ToString().TrimEnd('\\');+ }+ }+public static void SetTarget(string linkPath, string targetPath){string substituteName = "\\??\\" + Path.GetFullPath(targetPath);@@ -626,7 +646,7 @@ function Set-JunctionTarget {)Add-JunctionSupportType- [CodexInstaller.Junction]::SetTarget($LinkPath, $TargetPath)+ [CodexInstaller.JunctionV2]::SetTarget($LinkPath, $TargetPath)}function Test-IsJunction {@@ -656,14 +676,15 @@ function Ensure-Junction {$item = Get-Item -LiteralPath $LinkPath -Forceif (Test-IsJunction -Path $LinkPath) {- $existingTarget = [string]$item.Target+ Add-JunctionSupportType+ $existingTarget = [CodexInstaller.JunctionV2]::ResolveDirectory($LinkPath)if (-not [string]::IsNullOrWhiteSpace($InstallerOwnedTargetPrefix)) {- $ownedTargetPrefix = $InstallerOwnedTargetPrefix.TrimEnd("\\")+ $ownedTargetPrefix = [CodexInstaller.JunctionV2]::ResolveDirectory($InstallerOwnedTargetPrefix) + "\"if (-not $existingTarget.StartsWith($ownedTargetPrefix, [System.StringComparison]::OrdinalIgnoreCase)) {throw "Refusing to retarget junction at $LinkPath because it is not managed by this installer."}}- if ($existingTarget.Equals($TargetPath, [System.StringComparison]::OrdinalIgnoreCase)) {+ if ($existingTarget.Equals([CodexInstaller.JunctionV2]::ResolveDirectory($TargetPath), [System.StringComparison]::OrdinalIgnoreCase)) {return}@@ -957,7 +978,7 @@ try {$updaterRecord = Join-Path $codexHome "app-server-daemon\app-server-updater.pid"if ($daemonOnly) { $updaterRecord = Join-Path $codexHome "app-server-daemon\daemon-updater.pid" }$oldUpdaterParent = $false- if ($Release -eq "latest" -and $env:CODEX_INSTALL_IF_LATEST -ne "1" -and (Test-Path -LiteralPath $updaterRecord)) {+ if ($Release -eq "latest" -and $env:CODEX_INSTALL_IF_LATEST -ne "1" -and $env:CODEX_INSTALL_IF_CURRENT -ne "1" -and (Test-Path -LiteralPath $updaterRecord)) {$updaterPid = $null$updaterStartTime = $nulltry {@@ -985,17 +1006,25 @@ try {}}}- if ($env:CODEX_INSTALL_IF_LATEST -eq "1" -or $oldUpdaterParent) {+ if ($env:CODEX_INSTALL_IF_LATEST -eq "1" -or $env:CODEX_INSTALL_IF_CURRENT -eq "1" -or $oldUpdaterParent) {$previousRelease = if ($oldUpdaterParent -and (Test-Path -LiteralPath $autoUpdateVersion)) {[System.IO.File]::ReadAllText($autoUpdateVersion)} else {$env:CODEX_UPDATE_FROM_RELEASE}+ Add-JunctionSupportType$currentTarget = if (Test-Path -LiteralPath $currentDir) { (Get-Item -LiteralPath $currentDir).Target } else { $null }if ($Release -ne "latest" -or [string]::IsNullOrEmpty($previousRelease) -or [string]::IsNullOrEmpty($currentTarget) -or- -not (Test-Path -LiteralPath $autoUpdateVersion) -or- [System.IO.File]::ReadAllText($autoUpdateVersion) -cne $previousRelease -or- [System.IO.Path]::GetFullPath($currentTarget) -ne [System.IO.Path]::GetFullPath((Join-Path $releasesDir $previousRelease))) {+ -not (Test-Path -LiteralPath (Join-Path $releasesDir $previousRelease)) -or+ [CodexInstaller.JunctionV2]::ResolveDirectory($currentDir) -ne [CodexInstaller.JunctionV2]::ResolveDirectory((Join-Path $releasesDir $previousRelease))) {+ if ($env:CODEX_INSTALL_IF_CURRENT -eq "1") { throw "Daemon selection changed; retry the update." }+ $script:guardRejected = $true+ return+ }+ # Explicit daemon updates may leave a local or pinned release.+ if ($env:CODEX_INSTALL_IF_CURRENT -ne "1" -and+ (-not (Test-Path -LiteralPath $autoUpdateVersion) -or+ [System.IO.File]::ReadAllText($autoUpdateVersion) -cne $previousRelease)) {$script:guardRejected = $truereturn}@@ -1069,6 +1098,13 @@ try {if ($deferSelection -and (Get-Item -LiteralPath (Join-Path $standaloneRoot "current") -Force -ErrorAction SilentlyContinue)) {throw "A dedicated daemon is already selected; retry the update."}+ if ($daemonOnly -and -not $deferSelection) {+ $installedCodex = Join-Path $releaseDir $(if ($installLayout -eq "Package") { "bin\codex.exe" } else { "codex.exe" })+ & $installedCodex app-server daemon pid-update-loop --check-package-ownership | Out-Null+ if ($LASTEXITCODE -ne 0) {+ throw "The production release does not support daemon-owned packages; the current selection was left unchanged."+ }+ }Ensure-Junction -LinkPath $currentDir -TargetPath $releaseDir -InstallerOwnedTargetPrefix $releasesDirif ($Release -eq "latest") {$tempMarker = "$autoUpdateVersion.tmp.$PID"diff --git a/scripts/install/install.sh b/scripts/install/install.shindex f230ac0586..58815c797e 100755--- a/scripts/install/install.sh+++ b/scripts/install/install.sh@@ -1177,7 +1177,7 @@ if [ "$DAEMON_ONLY" = "1" ]; thenupdater_record="$CODEX_HOME_DIR/app-server-daemon/daemon-updater.pid"fiold_updater_parent="false"-if [ "${CODEX_INSTALL_IF_LATEST:-}" != "1" ] && [ -f "$updater_record" ]; then+if [ "${CODEX_INSTALL_IF_LATEST:-}" != "1" ] && [ "${CODEX_INSTALL_IF_CURRENT:-}" != "1" ] && [ -f "$updater_record" ]; thenupdater_pid="$(sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$updater_record" | head -n 1)"recorded_start="$(sed -n 's/.*"processStartTime"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$updater_record" | head -n 1)"if [ -r "/proc/$$/stat" ]; then@@ -1201,7 +1201,7 @@ if [ "${CODEX_INSTALL_IF_LATEST:-}" != "1" ] && [ -f "$updater_record" ]; thenexit 0fifi-if [ "${CODEX_INSTALL_IF_LATEST:-}" = "1" ] || [ "$old_updater_parent" = "true" ]; then+if [ "${CODEX_INSTALL_IF_LATEST:-}" = "1" ] || [ "${CODEX_INSTALL_IF_CURRENT:-}" = "1" ] || [ "$old_updater_parent" = "true" ]; thenguarded_release="${CODEX_UPDATE_FROM_RELEASE:-}"if [ "$old_updater_parent" = "true" ]; thenguarded_release="$(cat "$AUTO_UPDATE_VERSION" 2>/dev/null || true)"@@ -1209,8 +1209,17 @@ if [ "${CODEX_INSTALL_IF_LATEST:-}" = "1" ] || [ "$old_updater_parent" = "true"current_release_dir="$(cd -P "$CURRENT_LINK" 2>/dev/null && pwd)" || exit 0releases_dir="$(cd -P "$RELEASES_DIR" 2>/dev/null && pwd)" || exit 0if [ "$RELEASE" != "latest" ] || [ -z "$guarded_release" ] ||- [ "$(cat "$AUTO_UPDATE_VERSION" 2>/dev/null || true)" != "$guarded_release" ] ||[ "$current_release_dir" != "$releases_dir/$guarded_release" ]; then+ if [ "${CODEX_INSTALL_IF_CURRENT:-}" = "1" ]; then+ echo "Daemon selection changed; retry the update." >&2+ exit 1+ fi+ exit 0+ fi+ # An explicit daemon update may leave a local or pinned release. Scheduled+ # updates still require the selected release to follow the latest channel.+ if [ "${CODEX_INSTALL_IF_CURRENT:-}" != "1" ] &&+ [ "$(cat "$AUTO_UPDATE_VERSION" 2>/dev/null || true)" != "$guarded_release" ]; thenexit 0fifi@@ -1249,6 +1258,16 @@ if ! release_dir_is_complete "$release_dir" "$resolved_version" "$vendor_target"echo "Installed Codex command did not report expected version $resolved_version." >&2exit 1fi+if [ "$DAEMON_ONLY" = "1" ] && [ "${CODEX_INSTALL_DEFER_SELECTION:-0}" != "1" ]; then+ installed_codex="$release_dir/codex"+ if [ "$install_layout" = "package" ]; then+ installed_codex="$release_dir/bin/codex"+ fi+ if ! "$installed_codex" app-server daemon pid-update-loop --check-package-ownership >/dev/null 2>&1; then+ echo "The production release does not support daemon-owned packages; the current selection was left unchanged." >&2+ exit 1+ fi+fiupdate_current_link "$release_dir"if [ "$RELEASE" = "latest" ]; thenprintf '%s' "$release_name" > "$AUTO_UPDATE_VERSION.tmp.$$"diff --git a/scripts/install/test_install_sh.py b/scripts/install/test_install_sh.pyindex 5ac63ce4fa..06465d9372 100644--- a/scripts/install/test_install_sh.py+++ b/scripts/install/test_install_sh.py@@ -183,6 +183,63 @@ class InstallShTest(unittest.TestCase):(daemon / "current").resolve(), daemon / "releases" / release_name)self.assertEqual((daemon / "auto-update-version").read_text(), release_name)+ options["daemon_only"] = True+ local = daemon / "releases/local-development"+ local.mkdir()+ (daemon / "current").unlink()+ (daemon / "current").symlink_to(local)+ marker = daemon / "auto-update-version"+ marker.unlink()++ scheduled, _ = run_installer_in(+ root, "latest", update_guard_from_release=local.name, **options+ )+ self.assertEqual(scheduled.returncode, 0, scheduled.stderr)+ self.assertEqual((daemon / "current").resolve(), local)+ self.assertFalse(marker.exists())++ raced, _ = run_installer_in(+ root,+ "latest",+ update_guard_from_release="a-different-release",+ manual_update=True,+ **options,+ )+ self.assertNotEqual(raced.returncode, 0, raced.stderr)+ self.assertEqual((daemon / "current").resolve(), local)+ self.assertFalse(marker.exists())++ binary = daemon / "releases" / release_name / "bin/codex"+ contents = binary.read_text()+ binary.write_text(+ '#!/bin/sh\n[ "$1" = "--version" ] || exit 2\n'+ f"echo codex-cli {VERSION}\n"+ )+ incompatible, _ = run_installer_in(+ root,+ "latest",+ update_guard_from_release=local.name,+ manual_update=True,+ **options,+ )+ self.assertNotEqual(incompatible.returncode, 0)+ self.assertIn("does not support daemon-owned packages", incompatible.stderr)+ self.assertEqual((daemon / "current").resolve(), local)+ self.assertFalse(marker.exists())+ binary.write_text(contents)++ restored, _ = run_installer_in(+ root,+ "latest",+ update_guard_from_release=local.name,+ manual_update=True,+ **options,+ )+ self.assertEqual(restored.returncode, 0, restored.stderr)+ self.assertEqual(+ (daemon / "current").resolve(), daemon / "releases" / release_name+ )+ self.assertEqual(marker.read_text(), release_name)self.assertEqual(visible.resolve(), original)self.assertTrue(pending.is_symlink())self.assertEqual(profile.read_text(), "unchanged profile\n")@@ -672,6 +729,7 @@ def run_installer_in(old_updater_parent_pid: int | None = None,fail_ps: bool = False,daemon_only: bool = False,+ manual_update: bool = False,) -> tuple[subprocess.CompletedProcess[str], list[str]]:bin_dir = root / "bin"bin_dir.mkdir(exist_ok=True)@@ -831,11 +889,12 @@ def run_installer_in("SHELL": "/bin/sh",})+ env["CODEX_INSTALL_IF_CURRENT"] = "1" if manual_update else "0"if update_guard_from_release is None:env.pop("CODEX_INSTALL_IF_LATEST", None)env.pop("CODEX_UPDATE_FROM_RELEASE", None)else:- env["CODEX_INSTALL_IF_LATEST"] = "1"+ env["CODEX_INSTALL_IF_LATEST"] = "0" if manual_update else "1"env["CODEX_UPDATE_FROM_RELEASE"] = update_guard_from_releaseif old_updater_parent_pid is not None:env["CODEX_TEST_PARENT_PID"] = str(old_updater_parent_pid)