You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/10/22 16:16:38 UTC

(maka) branch rust-preview updated: fix(cli): update bundled applications automatically on startup

This is an automated email from the ASF dual-hosted git repository.

M4n5ter pushed a commit to branch rust-preview
in repository https://gitbox.apache.org/repos/asf/maka.git


The following commit(s) were added to refs/heads/rust-preview by this push:
     new 4f78e3c1ad fix(cli): update bundled applications automatically on startup
4f78e3c1ad is described below

commit 4f78e3c1ad20e340fc0938b331893f23f1232f8b
Author: Wang <m4...@gmail.com>
AuthorDate: Fri Oct 23 00:16:20 2026 +0800

    fix(cli): update bundled applications automatically on startup
    
    Apply compatible selected-package updates before Host admission while retaining
    source composition, configuration, identities and grants. Retire an outdated
    live Host only when its exact epoch is idle, then reconnect automatically.
    Bound recovery and preserve diagnostics for busy or unsuccessful updates.
    
    Generated-by: Codex
---
 products/maka/cli/README.md                        |    4 +-
 products/maka/cli/README.zh-CN.md                  |    4 +-
 products/maka/cli/src/application.rs               |    4 +-
 products/maka/cli/src/application/product.rs       |    1 +
 .../maka/cli/src/application/product/headless.rs   |  148 ++-
 .../cli/src/application/product/headless/update.rs |  149 ++-
 products/maka/cli/src/deployment/activation.rs     |    2 +-
 products/maka/cli/src/deployment/local.rs          | 1024 +++++++++++++++++++-
 8 files changed, 1278 insertions(+), 58 deletions(-)

diff --git a/products/maka/cli/README.md b/products/maka/cli/README.md
index e6d177e854..273fd492e8 100644
--- a/products/maka/cli/README.md
+++ b/products/maka/cli/README.md
@@ -41,7 +41,9 @@ Dedicated Host processes capture stderr in their Root's private control-cache fi
 
 Composition commands read complete JSON source and remote-export files. The Plugins composition editor loads an exact source revision in UTF-8 pages of at most 64 KiB and saves the confirmed native editor snapshot against that revision. Whole documents have no separate byte ceiling; typed validation, package checks, Host permissions, revision conflicts and actual resource admission still apply. Committed revisions retain the complete source for subsequent reads and reopening the Root.
 
-To update a standalone Host's selected bundled plugins, stop that Host and use its State Root:
+Before a Host starts, it automatically updates selected bundled plugins using the same validation and recovery as `update-defaults --apply`. When opening the interface, a running product Host is checked through its management endpoint and automatically restarted for an available update only when no other session or active work remains. Busy Hosts keep serving their existing clients and startup explains that they must become idle before retrying. A startup with current packages does not c [...]
+
+To preview or explicitly apply an update while a standalone Host is stopped, use its State Root:
 
 ```sh
 maka application update-defaults --root /path/to/host
diff --git a/products/maka/cli/README.zh-CN.md b/products/maka/cli/README.zh-CN.md
index ff011024fa..36eca486a8 100644
--- a/products/maka/cli/README.zh-CN.md
+++ b/products/maka/cli/README.zh-CN.md
@@ -41,7 +41,9 @@
 
 组合命令读取完整的 JSON 来源和远程导出文件。插件组合编辑器按最多 64 KiB 的 UTF-8 分页加载指定来源版本,并基于该版本保存已确认的原生编辑器快照。整份文档没有独立字节上限;类型校验、包校验、Host 权限、版本冲突和实际资源准入仍然生效。已提交版本保留完整来源,供后续读取和重新打开 Root 使用。
 
-更新独立 Host 已选的内置插件时,先停止该 Host,再指定它的 State Root:
+Host 启动前会自动更新已选的内置插件,复用 `update-defaults --apply` 的校验和恢复流程。打开界面时会通过管理端点检查已运行的产品 Host;有可用更新且没有其他会话或活跃工作时,会自动重启并更新。忙碌的 Host 继续服务已有客户端,启动会提示等待其空闲后重试。包已是当前版本时不会新增来源修订。更新与已保存配置不兼容时,启动会报告错误并保留原来源,修正配置后可重新启动。
+
+要预览或显式更新已停止的独立 Host,请指定它的 State Root:
 
 ```sh
 maka application update-defaults --root /path/to/host
diff --git a/products/maka/cli/src/application.rs b/products/maka/cli/src/application.rs
index 264ba472f2..41504283c3 100644
--- a/products/maka/cli/src/application.rs
+++ b/products/maka/cli/src/application.rs
@@ -21,7 +21,9 @@ mod install;
 mod product;
 mod serve;
 
-pub(crate) use product::{ProductHost, Roots, open_host, select_committed_host};
+pub(crate) use product::{
+    ProductHost, Roots, live_update_available, open_host, select_committed_host,
+};
 
 use std::path::{Path, PathBuf};
 
diff --git a/products/maka/cli/src/application/product.rs b/products/maka/cli/src/application/product.rs
index bbed87c564..db0343d74a 100644
--- a/products/maka/cli/src/application/product.rs
+++ b/products/maka/cli/src/application/product.rs
@@ -28,6 +28,7 @@ use std::{collections::BTreeMap, io::Write, path::PathBuf};
 mod headless;
 mod launch;
 mod update;
+pub(crate) use headless::update::live_update_available;
 pub(crate) use headless::{ProductHost, Roots, open_host, select_committed_host};
 pub(super) use update::Update;
 
diff --git a/products/maka/cli/src/application/product/headless.rs b/products/maka/cli/src/application/product/headless.rs
index cdcb52658f..b55695e65b 100644
--- a/products/maka/cli/src/application/product/headless.rs
+++ b/products/maka/cli/src/application/product/headless.rs
@@ -172,6 +172,45 @@ pub(crate) async fn open_host(
 async fn prepare(
     store: &EventLog,
     roots: Roots,
+) -> Result<(LoadedDeployment, Selection), HostError> {
+    // A fresh Host is already authored from the current bundle.
+    if store.application_launch().await?.is_none() {
+        return prepare_saved(store, roots).await;
+    }
+    // Recover a frozen operation before considering the executing bundle. The
+    // updater uses prepare_saved too, so applying a replacement cannot recurse.
+    let (loaded, selection) = prepare_saved(store, Roots::Saved).await?;
+    let root = store.owned_root()?.canonical_path().to_owned();
+    let outcome = update::synchronize(store, true).await.map_err(|error| {
+        HostError::from(format!(
+            "Automatic bundled application update failed: {error}. Resolve the reported error and retry starting the Host; application update-defaults --root {} previews the update.",
+            root.display()
+        ))
+    })?;
+    let configured = matches!(roots, Roots::Configured(_));
+    if let Roots::Configured(roots) = roots {
+        apply_directories(
+            store,
+            loaded.source().reference.deployment,
+            directories(roots)?,
+        )
+        .await?;
+    }
+    if outcome.applied || configured {
+        let loaded = store
+            .load_application(loaded.source().reference.deployment)
+            .await?
+            .ok_or("public Host source missing")?;
+        return Ok((loaded, selection));
+    }
+    Ok((loaded, selection))
+}
+
+// Explicit update recovery must finish only its frozen target, without starting
+// another update from a potentially newer bundle.
+async fn prepare_saved(
+    store: &EventLog,
+    roots: Roots,
 ) -> Result<(LoadedDeployment, Selection), HostError> {
     if store.application_launch().await?.is_none() {
         let initial = match &roots {
@@ -210,9 +249,6 @@ async fn prepare(
         }
         store.complete_application_launch(record.deployment).await?;
     }
-    if let Roots::Configured(roots) = roots {
-        apply_directories(store, record.deployment, directories(roots)?).await?;
-    }
     let loaded = store
         .load_application(record.deployment)
         .await?
@@ -380,6 +416,112 @@ fn configuration_values<'a>(
 #[cfg(test)]
 mod tests {
     use super::*;
+    #[tokio::test]
+    async fn startup_updates_old_selected_packages_and_retries_after_incompatible_configuration() {
+        let directory = tempfile::tempdir().unwrap();
+        let store = launch::create(directory.path().join("host")).await.unwrap();
+        let (initial, _) = prepare(&store, Roots::Configured(Some(vec![])))
+            .await
+            .unwrap();
+        let deployment = initial.source().reference.deployment;
+        let selection = store
+            .application_launch()
+            .await
+            .unwrap()
+            .unwrap()
+            .configuration;
+        let current = initial
+            .packages()
+            .iter()
+            .find(|package| package.application_ref().id == "maka.agent.settings")
+            .unwrap();
+        // Model an older, valid settings package whose configuration accepted a
+        // setting removed by the current bundled revision.
+        let mut files = current.files().clone();
+        let mut manifest: Value = serde_json::from_slice(&files["maka.extension.json"]).unwrap();
+        manifest["application"]["entries"]["host"]["configuration"]["properties"]["legacySetting"] =
+            json!({"type":"boolean"});
+        files.insert(
+            "maka.extension.json".into(),
+            serde_json::to_vec(&manifest).unwrap(),
+        );
+        let previous = super::super::Package::new(files).unwrap();
+        let mut input = initial.source().input.clone();
+        let settings = input.instances.get_mut("settings").unwrap();
+        settings.package = previous.application_ref().into();
+        settings
+            .configuration
+            .values
+            .insert("legacySetting".into(), json!(true));
+        settings
+            .configuration
+            .values
+            .insert("locale".into(), json!("zh-CN"));
+        let packages: Vec<_> = initial
+            .packages()
+            .iter()
+            .map(|package| {
+                if package.application_ref() == current.application_ref() {
+                    previous.clone()
+                } else {
+                    package.clone()
+                }
+            })
+            .collect();
+        let old = store
+            .commit_application(
+                deployment,
+                initial.source().reference.revision,
+                input.clone(),
+                vec![],
+                packages.clone(),
+            )
+            .await
+            .unwrap();
+        let error = prepare(&store, Roots::Saved).await.err().unwrap();
+        assert!(
+            error
+                .to_string()
+                .contains("Automatic bundled application update failed"),
+            "{error}"
+        );
+        assert!(error.to_string().contains("configuration"), "{error}");
+        let unchanged = store.load_application(deployment).await.unwrap().unwrap();
+        assert_eq!(unchanged.source().reference, old);
+        assert_eq!(unchanged.source().input, input);
+        assert!(
+            store
+                .application_launch()
+                .await
+                .unwrap()
+                .unwrap()
+                .pending
+                .is_none()
+        );
+        // Fix the reported user configuration and retry the exact startup path.
+        input
+            .instances
+            .get_mut("settings")
+            .unwrap()
+            .configuration
+            .values
+            .remove("legacySetting");
+        let fixed = store
+            .commit_application(deployment, old.revision, input.clone(), vec![], packages)
+            .await
+            .unwrap();
+        let (updated, _) = prepare(&store, Roots::Saved).await.unwrap();
+        input.instances.get_mut("settings").unwrap().package = current.application_ref().into();
+        assert_eq!(updated.source().input, input);
+        assert_eq!(updated.source().reference.revision, fixed.revision + 1);
+        let record = store.application_launch().await.unwrap().unwrap();
+        assert_eq!(record.configuration, selection);
+        assert!(record.pending.is_none());
+        let (again, _) = prepare(&store, Roots::Saved).await.unwrap();
+        assert_eq!(again.source().reference, updated.source().reference);
+        store.drain().await;
+    }
+
     #[tokio::test]
     async fn public_host_resumes_original_source_and_starts_with_read_only_permissions() {
         let directory = tempfile::tempdir().unwrap();
diff --git a/products/maka/cli/src/application/product/headless/update.rs b/products/maka/cli/src/application/product/headless/update.rs
index 9fc27429b0..d86530b404 100644
--- a/products/maka/cli/src/application/product/headless/update.rs
+++ b/products/maka/cli/src/application/product/headless/update.rs
@@ -63,7 +63,7 @@ pub(in super::super) async fn synchronize(
         };
         if apply {
             // Recover only this frozen operation, even under a newer executable.
-            super::prepare(store, Roots::Saved).await?;
+            super::prepare_saved(store, Roots::Saved).await?;
             outcome.applied = true;
         }
         return Ok(outcome);
@@ -75,6 +75,124 @@ pub(in super::super) async fn synchronize(
     synchronize_packages(store, record, apply, packages).await
 }
 
+/// Read the ordinary management query through the live Host, never its database.
+/// Generic Hosts that do not expose product management remain independently owned.
+pub(crate) async fn live_update_available(
+    client: &maka_host_runtime::application::host::Client,
+) -> Result<bool, HostError> {
+    use maka_plugin_core::contract::{Interface, MethodMode};
+    let Ok(description) = client.catalogue().describe("management") else {
+        return Ok(false);
+    };
+    let expected = maka_plugin_core::deployment::management::deployment_manager_contract();
+    if description.contract.name != expected.name
+        || description.contract.version != expected.version
+    {
+        return Ok(false);
+    }
+    let Interface::Service { methods } = &description.contract.interface else {
+        return Ok(false);
+    };
+    if !matches!(methods.get("read"), Some(method) if method.mode == MethodMode::Query) {
+        return Ok(false);
+    }
+    let metadata: maka_plugin_core::deployment::management::ManagedDeployment =
+        serde_json::from_value(query_management(client, "read", serde_json::json!({})).await?)?;
+    if metadata.source.reference.state_domain != client.source().state_domain
+        || metadata.source.reference.deployment != client.source().deployment
+    {
+        return Err("Host management read returned another deployment".into());
+    }
+    let version = tokio::task::spawn_blocking(super::super::bundle_fingerprint).await??;
+    let packages = tokio::task::spawn_blocking(super::super::packages).await??;
+    let authoring = super::super::authoring()?;
+    super::super::verified_fingerprint(&authoring, &packages, &version)?;
+    let replacements = bundled_replacements(&packages)?;
+    let needs_update = |input: &Input| {
+        pins(input).values().any(|package| {
+            replacements
+                .get(&package.id)
+                .is_some_and(|replacement| replacement != *package)
+        })
+    };
+    if needs_update(&metadata.source.input) {
+        return Ok(true);
+    }
+    if metadata.source.reference == *client.source() {
+        return Ok(false);
+    }
+    // Management reads the desired head; this incarnation's initial source may
+    // still select older bundled pins while asynchronous adoption is pending.
+    // A revision change by itself never authorizes a restart.
+    let initial = read_initial_document(client).await?;
+    Ok(needs_update(&initial.input))
+}
+
+async fn query_management(
+    client: &maka_host_runtime::application::host::Client,
+    method: &str,
+    input: serde_json::Value,
+) -> Result<serde_json::Value, HostError> {
+    use maka_host_runtime::application::transport::Reply;
+    use maka_plugin_core::contract::{Interface, MethodMode};
+    let description = client.catalogue().describe("management")?;
+    if !matches!(&description.contract.interface, Interface::Service { methods } if matches!(methods.get(method), Some(declaration) if declaration.mode == MethodMode::Query))
+    {
+        return Err(format!("Host management {method} is not a query").into());
+    }
+    let mut call = client
+        .call("management", method.into(), input, Default::default())
+        .await?;
+    let result = async {
+        call.start().await?;
+        match call.receive().await? {
+            Reply::Finished { result, cleanup } => {
+                cleanup?;
+                Ok::<_, HostError>(result?)
+            }
+            _ => Err(format!("Host management {method} returned an unexpected reply").into()),
+        }
+    }
+    .await;
+    let cleanup = call.close().await;
+    let value = result?;
+    cleanup?;
+    Ok(value)
+}
+
+async fn read_initial_document(
+    client: &maka_host_runtime::application::host::Client,
+) -> Result<maka_plugin_core::deployment::management::DeploymentDocument, HostError> {
+    use maka_plugin_core::deployment::management::DeploymentDocumentChunk;
+    let mut text = String::new();
+    let mut total = None;
+    loop {
+        let offset = text.len();
+        let chunk: DeploymentDocumentChunk = serde_json::from_value(
+            query_management(
+                client,
+                "readDocument",
+                serde_json::json!({"source": client.source(), "offset": offset}),
+            )
+            .await?,
+        )?;
+        if chunk.source != *client.source()
+            || chunk.offset != offset
+            || total.is_some_and(|total| total != chunk.total_bytes)
+        {
+            return Err("Host initial source document changed during paging".into());
+        }
+        total = Some(chunk.total_bytes);
+        text.push_str(&chunk.text);
+        match chunk.next {
+            Some(next) if next == text.len() && next > offset && next < chunk.total_bytes => {}
+            None if text.len() == chunk.total_bytes => break,
+            _ => return Err("Host initial source document returned an invalid page".into()),
+        }
+    }
+    Ok(serde_json::from_str(&text)?)
+}
+
 async fn synchronize_packages(
     store: &EventLog,
     record: Launch,
@@ -89,16 +207,7 @@ async fn synchronize_packages(
         return Err("public Host source cannot use remote observations".into());
     }
     validate_target(&loaded.source().input, loaded.packages())?;
-    let mut replacements = BTreeMap::new();
-    for package in bundled.values() {
-        let reference = package.application_ref();
-        if replacements
-            .insert(reference.id.clone(), reference)
-            .is_some()
-        {
-            return Err("current bundle contains duplicate package IDs".into());
-        }
-    }
+    let replacements = bundled_replacements(&bundled)?;
     let mut next = loaded.source().input.clone();
     for node in next.instances.values_mut() {
         if let PackageSelection::Pinned { package } = &mut node.package {
@@ -159,7 +268,7 @@ async fn synchronize_packages(
         store
             .begin_application_restore(record.deployment, serde_json::to_vec(&preparation)?)
             .await?;
-        super::prepare(store, Roots::Saved).await?;
+        super::prepare_saved(store, Roots::Saved).await?;
         outcome.applied = true;
     }
     Ok(outcome)
@@ -173,6 +282,22 @@ pub(super) fn validate_target(input: &Input, packages: &[Package]) -> Result<(),
     Ok(())
 }
 
+fn bundled_replacements(
+    bundled: &BTreeMap<String, Package>,
+) -> Result<BTreeMap<String, PackageRef>, HostError> {
+    let mut replacements = BTreeMap::new();
+    for package in bundled.values() {
+        let reference = package.application_ref();
+        if replacements
+            .insert(reference.id.clone(), reference)
+            .is_some()
+        {
+            return Err("current bundle contains duplicate package IDs".into());
+        }
+    }
+    Ok(replacements)
+}
+
 fn replace(package: &mut PackageRef, replacements: &BTreeMap<String, PackageRef>) {
     if let Some(next) = replacements.get(&package.id) {
         *package = next.clone();
diff --git a/products/maka/cli/src/deployment/activation.rs b/products/maka/cli/src/deployment/activation.rs
index 0df99ea276..0d5dd3ff0f 100644
--- a/products/maka/cli/src/deployment/activation.rs
+++ b/products/maka/cli/src/deployment/activation.rs
@@ -211,7 +211,7 @@ pub(super) async fn connect_or_launch(
             }
             if let Some(child) = &mut child {
                 if let Some(status) = child.try_wait()? {
-                    return Err(format!("Host candidate exited before Ready: {status}").into());
+                    return Err(format!("Host candidate exited before Ready: {status}. Read the startup error with maka host logs --root-id {}, resolve it, and retry opening Maka.", deployment.root_id).into());
                 }
             } else if !service_started {
                 match RootOwner::open(
diff --git a/products/maka/cli/src/deployment/local.rs b/products/maka/cli/src/deployment/local.rs
index f4debd531e..3fffffaf83 100644
--- a/products/maka/cli/src/deployment/local.rs
+++ b/products/maka/cli/src/deployment/local.rs
@@ -31,24 +31,40 @@ use tokio::io::AsyncWriteExt;
 
 type Connection = Client;
 
-/// Interactive startup does not install, update, repair or take over a Host.
+#[derive(Default)]
+struct UpdateAttempt {
+    restarted: bool,
+    startup_error: Option<String>,
+}
+
+/// Interactive startup connects to a live Host or starts one. A newly started
+/// Host synchronizes its selected bundled application packages before Ready.
 /// The UI calls this only after terminal validation, in a cancellable background job.
 pub async fn connect(path: PathBuf) -> Result<Connection, HostError> {
-    crate::operation::without_progress(connect_inner(path, None)).await
+    let launcher = std::env::current_exe()?;
+    crate::operation::without_progress(connect_inner(path, None, &launcher)).await
 }
 
 pub async fn connect_application(
     request: &maka_host_runtime::application::host::startup::Request,
 ) -> Result<Connection, HostError> {
     request.validate()?;
-    crate::operation::without_progress(connect_inner(request.root.clone(), Some(request))).await
+    let launcher = std::env::current_exe()?;
+    crate::operation::without_progress(connect_inner(
+        request.root.clone(),
+        Some(request),
+        &launcher,
+    ))
+    .await
 }
 
 async fn connect_inner(
     path: PathBuf,
     selection: Option<&maka_host_runtime::application::host::startup::Request>,
+    launcher: &std::path::Path,
 ) -> Result<Connection, HostError> {
     let mut child = None;
+    let mut update_attempt = UpdateAttempt::default();
     let result = tokio::time::timeout(Duration::from_secs(30), async {
         let (_launch, root_id) = loop {
             let root_path = path.clone();
@@ -81,7 +97,7 @@ async fn connect_inner(
         {
             return Err("State Root differs from the selected application Host".into());
         }
-        if let Some(connection) = live(&path, &root_id, selection).await? {
+        if let Some(connection) = live(&path, &root_id, selection, &mut update_attempt).await? {
             return Ok(connection);
         }
         let directory = directory(&root_id)?;
@@ -90,7 +106,9 @@ async fn connect_inner(
             match FileLease::acquire(&directory.join("executor.lock")) {
                 Ok(lease) => break Arc::new(lease),
                 Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
-                    if let Some(connection) = live(&path, &root_id, selection).await? {
+                    if let Some(connection) =
+                        live(&path, &root_id, selection, &mut update_attempt).await?
+                    {
                         return Ok(connection);
                     }
                     pause().await;
@@ -99,7 +117,7 @@ async fn connect_inner(
             }
         };
         lease.validate()?;
-        if let Some(connection) = live(&path, &root_id, selection).await? {
+        if let Some(connection) = live(&path, &root_id, selection, &mut update_attempt).await? {
             return Ok(connection);
         }
         match store::read(&directory).await? {
@@ -107,34 +125,48 @@ async fn connect_inner(
                 let root = root::resolve(&path)?;
                 deployment.validate(&root, &directory)?;
                 deployment.require_active()?;
-                prepare_application(&path, &root_id, selection).await?;
-                // Keep its probe resident until the actual interactive handshake.
-                let (probe, _) = activation::connect_or_launch(&deployment, lease.clone()).await?;
-                let anchor = probe.anchor().await?;
-                let connection = live(&path, &root_id, selection)
-                    .await?
-                    .ok_or("Activated Host is unavailable")?;
-                lease.validate()?;
-                drop(anchor);
-                return Ok(connection);
+                prepare_application(&path, &root_id, selection, &mut update_attempt).await?;
+                loop {
+                    let (probe, _) = activation::connect_or_launch(&deployment, lease.clone()).await?;
+                    // Reuse this launcher's residency session for admission, so
+                    // it cannot block its own idle retirement as another client.
+                    let anchor = probe.anchor().await?;
+                    match observe_live(&path, &root_id, selection, &mut update_attempt, Some(anchor)).await? {
+                        Live::Ready(connection) => {
+                            lease.validate()?;
+                            return Ok(*connection);
+                        }
+                        Live::Retired => continue,
+                        Live::Missing => return Err("Activated Host is unavailable".into()),
+                    }
+                }
             }
             store::Installation::Incomplete => {
                 return Err("Host deployment installation is incomplete".into());
             }
             store::Installation::Missing => {}
         }
-        prepare_application(&path, &root_id, selection).await?;
+        prepare_application(&path, &root_id, selection, &mut update_attempt).await?;
         loop {
             lease.validate()?;
-            if let Some(connection) = live(&path, &root_id, selection).await? {
-                if let Some(child) = &mut child {
-                    release(child).await?;
+            match observe_live(&path, &root_id, selection, &mut update_attempt, None).await? {
+                Live::Ready(connection) => {
+                    if let Some(child) = &mut child {
+                        release(child).await?;
+                    }
+                    return Ok(*connection);
+                }
+                Live::Retired => {
+                    if let Some(mut retired) = child.take() {
+                        activation::stop_failed_candidate(&mut retired, Duration::from_secs(5)).await?;
+                    }
+                    continue;
                 }
-                return Ok(connection);
+                Live::Missing => {},
             }
             if let Some(child) = &mut child {
                 if let Some(status) = child.try_wait()? {
-                    return Err(format!("Host candidate exited before Ready: {status}").into());
+                    return Err(format!("Host candidate exited before Ready: {status}. Read the startup error with maka host logs --root-id {root_id}, resolve it, and retry opening Maka.").into());
                 }
             } else {
                 match RootOwner::open(&path, &RootNamespaces::for_current_account()?) {
@@ -148,7 +180,7 @@ async fn connect_inner(
                         drop(owner);
                         child = Some(
                             detached::spawn(
-                                &std::env::current_exe()?,
+                                launcher,
                                 &[
                                     "host",
                                     "candidate",
@@ -184,19 +216,28 @@ async fn connect_inner(
     {
         return Err(format!("{}; candidate cleanup: {cleanup}", result.err().unwrap()).into());
     }
-    result
+    result.map_err(|error| match &update_attempt.startup_error {
+        Some(original) => {
+            HostError::from(format!("{error}; original Host startup error: {original}"))
+        }
+        None => error,
+    })
 }
 
 async fn prepare_application(
     path: &std::path::Path,
     root_id: &str,
     selection: Option<&maka_host_runtime::application::host::startup::Request>,
+    update_attempt: &mut UpdateAttempt,
 ) -> Result<(), HostError> {
     let Some(selection) = selection else {
         return Ok(());
     };
     loop {
-        if live(path, root_id, Some(selection)).await?.is_some() {
+        if live(path, root_id, Some(selection), update_attempt)
+            .await?
+            .is_some()
+        {
             return Ok(());
         }
         let root = match RootOwner::open(path, &RootNamespaces::for_current_account()?) {
@@ -231,11 +272,33 @@ async fn release(child: &mut Child) -> Result<(), HostError> {
     Ok(())
 }
 
+enum Live {
+    Missing,
+    Ready(Box<Connection>),
+    Retired,
+}
+
 async fn live(
     path: &std::path::Path,
     expected_root: &str,
     selection: Option<&maka_host_runtime::application::host::startup::Request>,
+    update_attempt: &mut UpdateAttempt,
 ) -> Result<Option<Connection>, HostError> {
+    Ok(
+        match observe_live(path, expected_root, selection, update_attempt, None).await? {
+            Live::Ready(connection) => Some(*connection),
+            Live::Missing | Live::Retired => None,
+        },
+    )
+}
+
+async fn observe_live(
+    path: &std::path::Path,
+    expected_root: &str,
+    selection: Option<&maka_host_runtime::application::host::startup::Request>,
+    update_attempt: &mut UpdateAttempt,
+    anchor: Option<Connection>,
+) -> Result<Live, HostError> {
     // A candidate has not published discovery until database initialization is
     // complete. Do not inspect its transient SQLite startup files as a live root.
     if !RootNamespaces::for_current_account()?
@@ -244,14 +307,15 @@ async fn live(
         .join("registration.json")
         .try_exists()?
     {
-        return Ok(None);
+        return Ok(Live::Missing);
     }
-    let path = path.to_owned();
-    let discovery = match tokio::task::spawn_blocking(move || discovery::read(&path)).await? {
-        Ok(discovery) => discovery,
-        Err(error) if absent(&error) => return Ok(None),
-        Err(error) => return Err(error.into()),
-    };
+    let discovery_path = path.to_owned();
+    let discovery =
+        match tokio::task::spawn_blocking(move || discovery::read(&discovery_path)).await? {
+            Ok(discovery) => discovery,
+            Err(error) if absent(&error) => return Ok(Live::Missing),
+            Err(error) => return Err(error.into()),
+        };
     if discovery.root_id != expected_root {
         return Err("State Root changed during startup".into());
     }
@@ -259,14 +323,86 @@ async fn live(
         return Err("live Host belongs to another application deployment".into());
     }
 
-    let stream = match ipc::connect(&discovery.endpoint).await {
-        Ok(stream) => stream,
-        Err(error) if error.downcast_ref::<io::Error>().is_some_and(absent) => return Ok(None),
-        Err(error) => return Err(error),
+    let mut client = if let Some(mut client) = anchor {
+        if client.epoch() != discovery.host_epoch || client.source() != &discovery.source {
+            client.close().await?;
+            return Err("Host changed during activation admission".into());
+        }
+        client
+    } else {
+        let stream = match ipc::connect(&discovery.endpoint).await {
+            Ok(stream) => stream,
+            Err(error) if error.downcast_ref::<io::Error>().is_some_and(absent) => {
+                return Ok(Live::Missing);
+            }
+            Err(error) => return Err(error),
+        };
+        Client::connect_stream(&discovery.endpoint, Some(discovery.host_epoch), stream).await?
     };
-    Ok(Some(
-        Client::connect_stream(&discovery.endpoint, Some(discovery.host_epoch), stream).await?,
-    ))
+    let startup_error = client.catalogue().startup_error().map(str::to_owned);
+    let available = if startup_error.is_some() {
+        // A failed Application may have no callable management endpoint. Retry
+        // its startup once under the same idle retirement fence, preserving the
+        // diagnostic if recovery fails.
+        Ok(true)
+    } else {
+        crate::application::live_update_available(&client).await
+    };
+    let available = match available {
+        Ok(available) => available,
+        Err(error) => {
+            client.close().await?;
+            return Err(error);
+        }
+    };
+    if !available {
+        return Ok(Live::Ready(Box::new(client)));
+    }
+    if update_attempt.restarted {
+        client.close().await?;
+        if let Some(error) = startup_error {
+            return Err(format!("Host startup failed after automatic recovery: {error}").into());
+        }
+        return Err("The restarted Host still uses older bundled applications. Update the managed Host executable, then retry opening Maka.".into());
+    }
+    update_attempt.restarted = true;
+    update_attempt.startup_error = startup_error;
+    // Release only this launcher's session. Retirement atomically refuses other
+    // sessions or accepted work; a stale status observation cannot authorize it.
+    client.close().await?;
+    match Client::retire_with_options(&discovery.endpoint, discovery.host_epoch, false, false).await
+    {
+        Ok(true) => {}
+        Ok(false) => {
+            let action = if update_attempt.startup_error.is_some() {
+                "Automatic Host recovery"
+            } else {
+                "Automatic bundled application updating"
+            };
+            return Err(format!("{action} cannot proceed while another Host session or active task remains. Close the other sessions or wait for their work to finish, then retry opening Maka; no manual update command is needed.").into());
+        }
+        Err(error) => {
+            // Closing our session can race the ephemeral Host's idle exit. Only
+            // acquiring its writer lease confirms that this is a safe retry.
+            match RootOwner::open(path, &RootNamespaces::for_current_account()?) {
+                Ok(owner) if owner.root_id() == expected_root => return Ok(Live::Retired),
+                _ => return Err(error.into()),
+            }
+        }
+    }
+    // A retirement acknowledgement is not proof that its writer lease is free.
+    loop {
+        match RootOwner::open(path, &RootNamespaces::for_current_account()?) {
+            Ok(owner) => {
+                if owner.root_id() != expected_root {
+                    return Err("State Root changed during automatic application update".into());
+                }
+                return Ok(Live::Retired);
+            }
+            Err(error) if error.kind() == io::ErrorKind::WouldBlock => pause().await,
+            Err(error) => return Err(error.into()),
+        }
+    }
 }
 
 fn absent(error: &io::Error) -> bool {
@@ -275,3 +411,813 @@ fn absent(error: &io::Error) -> bool {
         io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused
     )
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::application::ProductHost;
+    use maka_host_runtime::application::host::{Configuration, Host, Options};
+    use maka_packages::Package;
+    use tokio_util::sync::CancellationToken;
+
+    fn catalog_transport() -> std::sync::Arc<dyn maka_agent_ports::model::Transport> {
+        struct Unavailable;
+        impl maka_agent_ports::model::Transport for Unavailable {
+            fn identity(&self) -> u64 {
+                0
+            }
+            fn request(
+                &self,
+                _: maka_capabilities::http::Request,
+            ) -> futures_util::future::BoxFuture<
+                '_,
+                Result<maka_capabilities::http::Response, maka_agent_ports::model::Error>,
+            > {
+                Box::pin(async {
+                    Err(maka_agent_ports::model::Error::Adapter(
+                        "public catalog network is not part of this fixture".into(),
+                    ))
+                })
+            }
+            fn connect(
+                &self,
+                _: maka_agent_ports::model::Connect,
+            ) -> futures_util::future::BoxFuture<
+                '_,
+                Result<
+                    std::sync::Arc<dyn maka_agent_ports::model::Socket>,
+                    maka_agent_ports::model::Error,
+                >,
+            > {
+                Box::pin(async {
+                    Err(maka_agent_ports::model::Error::Adapter(
+                        "public catalog does not use WebSockets".into(),
+                    ))
+                })
+            }
+        }
+        std::sync::Arc::new(Unavailable)
+    }
+
+    async fn serve_fixture(
+        endpoint: crate::endpoint::LocalEndpoint,
+        mut product: ProductHost,
+        stop: CancellationToken,
+        websocket: Option<maka_host_runtime::application::host::websocket::WebSocketListener>,
+    ) -> Result<(), String> {
+        // Retain the socket directory without the process entrypoint's exit
+        // watchdog, since several Hosts share this test process.
+        let result = product
+            .host
+            .clone()
+            .serve(endpoint.listener, websocket, stop)
+            .await;
+        let cleanup = product.shutdown().await.map_err(|error| error.to_string());
+        result.and(cleanup)
+    }
+
+    type ServedProduct = (
+        String,
+        uuid::Uuid,
+        CancellationToken,
+        tokio::task::JoinHandle<()>,
+    );
+
+    enum DesiredRevision {
+        CurrentPackages,
+        ConfigurationOnly,
+    }
+
+    async fn serve_product(
+        root: &std::path::Path,
+        old: bool,
+        broken: bool,
+        generation: Option<String>,
+    ) -> ServedProduct {
+        serve_product_with_desired(root, old, broken, generation, None).await
+    }
+
+    async fn serve_product_with_desired(
+        root: &std::path::Path,
+        old: bool,
+        broken: bool,
+        generation: Option<String>,
+        desired: Option<DesiredRevision>,
+    ) -> ServedProduct {
+        let namespaces = RootNamespaces::for_current_account().unwrap();
+        if !root.exists() {
+            let mut host = crate::application::open_host(
+                RootOwner::create(root, &namespaces).unwrap(),
+                Options::default(),
+                crate::application::Roots::Configured(Some(vec![])),
+                Some(catalog_transport()),
+            )
+            .await
+            .unwrap();
+            host.shutdown().await.unwrap();
+            drop(host);
+        }
+        let store = Arc::new(
+            maka_transport::open_store(Arc::new(RootOwner::open(root, &namespaces).unwrap()))
+                .await
+                .unwrap(),
+        );
+        let record = store.application_launch().await.unwrap().unwrap();
+        let mut loaded = store
+            .load_application(record.deployment)
+            .await
+            .unwrap()
+            .unwrap();
+        if old {
+            let settings = loaded
+                .packages()
+                .iter()
+                .find(|package| package.application_ref().id == "maka.agent.settings")
+                .unwrap();
+            let mut files = settings.files().clone();
+            files.insert(
+                "previous-build.txt".into(),
+                b"Older selected package".to_vec(),
+            );
+            if broken {
+                let mut manifest: serde_json::Value =
+                    serde_json::from_slice(&files["maka.extension.json"]).unwrap();
+                manifest["application"]["entries"]["host"]["implementation"]["implementation"] =
+                    serde_json::json!("example.FailingSettings");
+                files.insert(
+                    "maka.extension.json".into(),
+                    serde_json::to_vec(&manifest).unwrap(),
+                );
+            }
+            let previous = Package::new(files).unwrap();
+            let mut input = loaded.source().input.clone();
+            input.instances.get_mut("settings").unwrap().package =
+                previous.application_ref().into();
+            let packages = loaded
+                .packages()
+                .iter()
+                .map(|package| {
+                    if package.application_ref() == settings.application_ref() {
+                        previous.clone()
+                    } else {
+                        package.clone()
+                    }
+                })
+                .collect();
+            store
+                .commit_application(
+                    record.deployment,
+                    loaded.source().reference.revision,
+                    input,
+                    vec![],
+                    packages,
+                )
+                .await
+                .unwrap();
+            loaded = store
+                .load_application(record.deployment)
+                .await
+                .unwrap()
+                .unwrap();
+        } else {
+            // Merely installed older bytes must not trigger a restart when no
+            // instance or override selects them.
+            let mut files = loaded.packages()[0].files().clone();
+            files.insert(
+                "unselected-build.txt".into(),
+                b"Unselected older package".to_vec(),
+            );
+            let mut packages = loaded.packages().to_vec();
+            packages.push(Package::new(files).unwrap());
+            store
+                .commit_application(
+                    record.deployment,
+                    loaded.source().reference.revision,
+                    loaded.source().input.clone(),
+                    vec![],
+                    packages,
+                )
+                .await
+                .unwrap();
+            loaded = store
+                .load_application(record.deployment)
+                .await
+                .unwrap()
+                .unwrap();
+        }
+        if let Some(desired) = desired {
+            let mut input = loaded.source().input.clone();
+            let mut packages = loaded.packages().to_vec();
+            match desired {
+                DesiredRevision::CurrentPackages => {
+                    let mut reference = loaded.source().reference.clone();
+                    reference.revision = 1;
+                    let initial = store
+                        .load_application_at(&reference)
+                        .await
+                        .unwrap()
+                        .unwrap();
+                    let settings = initial
+                        .packages()
+                        .iter()
+                        .find(|package| package.application_ref().id == "maka.agent.settings")
+                        .unwrap()
+                        .clone();
+                    input.instances.get_mut("settings").unwrap().package =
+                        settings.application_ref().into();
+                    packages.push(settings);
+                }
+                DesiredRevision::ConfigurationOnly => {
+                    input
+                        .instances
+                        .get_mut("settings")
+                        .unwrap()
+                        .configuration
+                        .values
+                        .insert("locale".into(), serde_json::json!("zh-CN"));
+                }
+            }
+            store
+                .commit_application(
+                    record.deployment,
+                    loaded.source().reference.revision,
+                    input,
+                    vec![],
+                    packages,
+                )
+                .await
+                .unwrap();
+            // Start the incarnation from its exact frozen snapshot even though
+            // the desired head is newer. No sleep or adoption timing is needed.
+        }
+        let Configuration::PublicHost { endpoints, native } =
+            serde_json::from_value(record.configuration).unwrap();
+        let configuration = maka_config::ConfigurationStore::for_root(store.owned_root().unwrap())
+            .await
+            .unwrap();
+        let catalog = maka_product_native::catalog::RuntimeCatalog::with_transport(
+            configuration,
+            catalog_transport(),
+        )
+        .await
+        .unwrap();
+        // Deliberately model an already running older Host, bypassing the new
+        // executable's startup synchronization only when building this fixture.
+        let host = Host::open_loaded_with_options(
+            store.clone(),
+            loaded,
+            {
+                let mut native = maka_host_runtime::application::NativeRegistry::default();
+                maka_product_native::provide(&mut native, catalog.catalog()).unwrap();
+                native
+                    .insert(
+                        "example.FailingSettings".into(),
+                        Arc::new(|_, _| {
+                            Box::pin(async {
+                                maka_host_runtime::application::NativeActivation {
+                                    exports: Err(
+                                        "fixture: outdated settings native contract".into()
+                                    ),
+                                    owner: Arc::new(()),
+                                }
+                            })
+                        }),
+                    )
+                    .unwrap();
+                native
+            },
+            Some(maka_host_js::factory(Default::default())),
+            endpoints,
+            native,
+            Options {
+                generation: generation.clone(),
+                ..Options::default()
+            },
+        )
+        .await
+        .unwrap();
+        let host = ProductHost::admitted(host, catalog);
+        drop(store);
+        let endpoint = crate::endpoint::LocalEndpoint::bind().unwrap();
+        let websocket = if generation.is_some() {
+            Some(
+                maka_host_runtime::application::host::websocket::WebSocketListener::bind(
+                    "127.0.0.1:0".parse().unwrap(),
+                    vec![],
+                )
+                .await
+                .unwrap(),
+            )
+        } else {
+            None
+        };
+        let registration = host
+            .host
+            .publish_registration(
+                &endpoint.path,
+                websocket
+                    .as_ref()
+                    .map(|listener| listener.local_addr().unwrap()),
+            )
+            .unwrap();
+        let root_id = host.host.root_id().to_owned();
+        let epoch = host.host.epoch();
+        let stop = CancellationToken::new();
+        let stopped = stop.clone();
+        let server = tokio::spawn(async move {
+            serve_fixture(endpoint, host, stopped, websocket)
+                .await
+                .unwrap();
+            registration.remove().unwrap();
+        });
+        (root_id, epoch, stop, server)
+    }
+
+    #[cfg(unix)]
+    fn watch_fixture_owner(stop: CancellationToken) {
+        std::thread::spawn(move || {
+            use std::io::BufRead;
+            let mut bytes = Vec::new();
+            let read = std::io::stdin().lock().read_until(b'\n', &mut bytes);
+            if read.is_err()
+                || !serde_json::from_slice::<serde_json::Value>(&bytes).is_ok_and(|value| {
+                    value == serde_json::json!({"kind":"runtime-host-launch-owner-release"})
+                })
+            {
+                stop.cancel();
+            }
+        });
+    }
+
+    #[cfg(unix)]
+    #[tokio::test]
+    async fn cold_start_candidate_process_fixture() {
+        let Some(root) = std::env::var_os("MAKA_DEFAULTS_FIXTURE_ROOT") else {
+            return;
+        };
+        let root = PathBuf::from(root);
+        let generation = std::env::var("MAKA_DEFAULTS_FIXTURE_GENERATION")
+            .ok()
+            .filter(|value| !value.is_empty());
+        let attempts = root.with_file_name("fixture-candidate-attempts");
+        let previous = match std::fs::read_to_string(&attempts) {
+            Ok(value) => value.parse::<u32>().unwrap(),
+            Err(error) if error.kind() == io::ErrorKind::NotFound => 0,
+            Err(error) => panic!("candidate counter unavailable: {error}"),
+        };
+        let attempt = previous.checked_add(1).unwrap();
+        std::fs::write(&attempts, attempt.to_string()).unwrap();
+        let first = attempt == 1;
+        let options = Options {
+            generation: generation.clone(),
+            ..Options::default()
+        };
+        let mut host = crate::application::open_host(
+            RootOwner::open(&root, &RootNamespaces::for_current_account().unwrap()).unwrap(),
+            options,
+            crate::application::Roots::Configured(Some(vec![])),
+            Some(catalog_transport()),
+        )
+        .await
+        .unwrap();
+        if first {
+            host.shutdown().await.unwrap();
+            drop(host);
+            let (_, _, stop, mut server) = serve_product(&root, true, true, generation).await;
+            watch_fixture_owner(stop.clone());
+            if tokio::time::timeout(Duration::from_secs(45), &mut server)
+                .await
+                .is_err()
+            {
+                stop.cancel();
+                server.await.unwrap();
+                panic!("launcher did not retire the failed candidate");
+            }
+        } else {
+            let endpoint = crate::endpoint::LocalEndpoint::bind().unwrap();
+            let websocket = if generation.is_some() {
+                Some(
+                    maka_host_runtime::application::host::websocket::WebSocketListener::bind(
+                        "127.0.0.1:0".parse().unwrap(),
+                        vec![],
+                    )
+                    .await
+                    .unwrap(),
+                )
+            } else {
+                None
+            };
+            let registration = host
+                .host
+                .publish_registration(
+                    &endpoint.path,
+                    websocket
+                        .as_ref()
+                        .map(|listener| listener.local_addr().unwrap()),
+                )
+                .unwrap();
+            let stop = CancellationToken::new();
+            watch_fixture_owner(stop.clone());
+            tokio::time::timeout(
+                Duration::from_secs(45),
+                serve_fixture(endpoint, host, stop, websocket),
+            )
+            .await
+            .unwrap()
+            .unwrap();
+            registration.remove().unwrap();
+        }
+    }
+
+    #[cfg(unix)]
+    async fn cold_launcher_recovers_its_candidate(managed: bool) {
+        use std::os::unix::fs::PermissionsExt;
+        let temporary = tempfile::tempdir().unwrap();
+        let root_path = temporary.path().join("host");
+        let owner =
+            RootOwner::create(&root_path, &RootNamespaces::for_current_account().unwrap()).unwrap();
+        let root_path = owner.canonical_path().to_owned();
+        let root_id = owner.root_id().to_owned();
+        let deployment_id = uuid::Uuid::new_v4();
+        let generation = if managed {
+            format!("{deployment_id}:1")
+        } else {
+            String::new()
+        };
+        let executable = std::env::current_exe().unwrap();
+        let quote = |value: &str| format!("'{}'", value.replace('\'', "'\\''"));
+        let script = format!(
+            "#!/bin/sh\nexport MAKA_DEFAULTS_FIXTURE_ROOT=\"$4\"\nexport MAKA_DEFAULTS_FIXTURE_GENERATION={}\nexec {} --exact deployment::local::tests::cold_start_candidate_process_fixture --nocapture\n",
+            quote(&generation),
+            quote(executable.to_str().unwrap())
+        );
+        let launcher = temporary.path().join("launcher");
+        std::fs::write(&launcher, &script).unwrap();
+        std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o700)).unwrap();
+        let deployment_directory = directory(&root_id).unwrap();
+        if managed {
+            root::private_directory(&deployment_directory).unwrap();
+            let lease =
+                Arc::new(FileLease::acquire(&deployment_directory.join("executor.lock")).unwrap());
+            let digest = hex::encode(Sha256::digest(script.as_bytes()));
+            let packaged = super::super::package::path(&deployment_directory, &digest);
+            root::private_directory(packaged.parent().unwrap()).unwrap();
+            std::fs::copy(&launcher, &packaged).unwrap();
+            let deployment = super::super::Deployment {
+                deployment_id,
+                config_revision: 1,
+                root_id: root_id.clone(),
+                root_path: root_path.clone(),
+                executable: packaged,
+                sha256: digest,
+                mode: super::super::Mode::OnDemand,
+                websocket: "127.0.0.1:0".parse().unwrap(),
+                project_directory_roots: Some(vec![]),
+                admission: super::super::Admission::Active,
+            };
+            store::install(&deployment_directory, lease.clone(), owner, deployment)
+                .await
+                .unwrap();
+            drop(lease);
+        } else {
+            drop(owner);
+        }
+        let mut client = connect_inner(root_path.clone(), None, &launcher)
+            .await
+            .unwrap();
+        assert_eq!(
+            std::fs::read_to_string(root_path.with_file_name("fixture-candidate-attempts"))
+                .unwrap(),
+            "2"
+        );
+        assert!(client.catalogue().startup_error().is_none());
+        assert!(
+            client
+                .catalogue()
+                .describe("settings")
+                .unwrap()
+                .registration_epoch
+                .is_some()
+        );
+        assert!(
+            !crate::application::live_update_available(&client)
+                .await
+                .unwrap()
+        );
+        client.quit().await.unwrap();
+        let owner = tokio::time::timeout(Duration::from_secs(5), async {
+            loop {
+                match RootOwner::open(&root_path, &RootNamespaces::for_current_account().unwrap()) {
+                    Ok(owner) => break owner,
+                    Err(error) if error.kind() == io::ErrorKind::WouldBlock => pause().await,
+                    Err(error) => panic!("{error}"),
+                }
+            }
+        })
+        .await
+        .unwrap();
+        assert_eq!(owner.root_id(), root_id);
+        drop(owner);
+        if deployment_directory.exists() {
+            std::fs::remove_dir_all(deployment_directory).unwrap();
+        }
+    }
+
+    #[cfg(unix)]
+    #[tokio::test]
+    async fn cold_standalone_launcher_reaps_and_restarts_its_retired_candidate() {
+        cold_launcher_recovers_its_candidate(false).await;
+    }
+
+    #[cfg(unix)]
+    #[tokio::test]
+    async fn cold_managed_launcher_reuses_its_anchor_and_reactivates() {
+        cold_launcher_recovers_its_candidate(true).await;
+    }
+
+    async fn desired_metadata(
+        client: &Client,
+    ) -> maka_plugin_core::deployment::management::ManagedDeployment {
+        use maka_host_runtime::application::transport::Reply;
+        let mut call = client
+            .call(
+                "management",
+                "read".into(),
+                serde_json::json!({}),
+                Default::default(),
+            )
+            .await
+            .unwrap();
+        call.start().await.unwrap();
+        let Reply::Finished { result, cleanup } = call.receive().await.unwrap() else {
+            panic!("management query did not finish")
+        };
+        cleanup.unwrap();
+        call.close().await.unwrap();
+        serde_json::from_value(result.unwrap()).unwrap()
+    }
+
+    fn bundled_settings() -> maka_plugin_core::package::PackageSelection {
+        #[cfg(maka_embedded_product)]
+        let bundle = PathBuf::from(env!("OUT_DIR")).join("product");
+        #[cfg(not(maka_embedded_product))]
+        let bundle = std::env::var_os("MAKA_PRODUCT_BUNDLE")
+            .map(PathBuf::from)
+            .unwrap_or_else(|| {
+                PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/../bundle/dist"))
+            });
+        Package::read_from(&bundle.join("packages/settings"))
+            .unwrap()
+            .application_ref()
+            .into()
+    }
+
+    #[tokio::test]
+    async fn current_desired_head_does_not_hide_older_incarnation_pins() {
+        let temporary = tempfile::tempdir().unwrap();
+        let root = temporary.path().join("host");
+        let (_, epoch, stop, server) = serve_product_with_desired(
+            &root,
+            true,
+            false,
+            None,
+            Some(DesiredRevision::CurrentPackages),
+        )
+        .await;
+        let discovery = discovery::read(&root).unwrap();
+        let mut client = Client::connect(&discovery.endpoint, Some(epoch))
+            .await
+            .unwrap();
+        let metadata = desired_metadata(&client).await;
+        assert_ne!(metadata.source.reference, *client.source());
+        assert_eq!(
+            metadata.source.input.instances["settings"].package,
+            bundled_settings()
+        );
+        assert!(
+            crate::application::live_update_available(&client)
+                .await
+                .unwrap()
+        );
+        client.close().await.unwrap();
+        stop.cancel();
+        server.await.unwrap();
+    }
+
+    #[tokio::test]
+    async fn configuration_only_desired_revision_keeps_current_incarnation_running() {
+        let temporary = tempfile::tempdir().unwrap();
+        let root = temporary.path().join("host");
+        let (root_id, epoch, stop, server) = serve_product_with_desired(
+            &root,
+            false,
+            false,
+            None,
+            Some(DesiredRevision::ConfigurationOnly),
+        )
+        .await;
+        let mut attempted = UpdateAttempt::default();
+        let mut client = live(&root, &root_id, None, &mut attempted)
+            .await
+            .unwrap()
+            .unwrap();
+        let metadata = desired_metadata(&client).await;
+        assert_ne!(metadata.source.reference, *client.source());
+        assert_eq!(
+            metadata.source.input.instances["settings"].package,
+            bundled_settings()
+        );
+        assert_eq!(
+            metadata.source.input.instances["settings"]
+                .configuration
+                .values["locale"],
+            serde_json::json!("zh-CN")
+        );
+        assert_eq!(client.epoch(), epoch);
+        assert!(!attempted.restarted);
+        client.close().await.unwrap();
+        stop.cancel();
+        server.await.unwrap();
+    }
+
+    #[tokio::test]
+    async fn unavailable_endpoints_recover_before_opening_the_interface() {
+        let directory = tempfile::tempdir().unwrap();
+        let root = directory.path().join("host");
+        let (root_id, epoch, _stop, server) = serve_product(&root, true, true, None).await;
+        let discovery = discovery::read(&root).unwrap();
+        let mut probe = Client::connect(&discovery.endpoint, Some(epoch))
+            .await
+            .unwrap();
+        let original = probe
+            .catalogue()
+            .startup_error()
+            .expect("fixture must fail native initialization")
+            .to_owned();
+        assert!(
+            probe
+                .catalogue()
+                .describe("settings")
+                .unwrap()
+                .registration_epoch
+                .is_none()
+        );
+        probe.close().await.unwrap();
+        let mut attempted = UpdateAttempt::default();
+        assert!(
+            live(&root, &root_id, None, &mut attempted)
+                .await
+                .unwrap()
+                .is_none()
+        );
+        assert_eq!(attempted.startup_error.as_deref(), Some(original.as_str()));
+        server.await.unwrap();
+        // A replacement that still fails must report the real diagnostic and
+        // stay available for inspection, never enter a retirement loop.
+        let (_, failed_epoch, stop, failed_server) = serve_product(&root, false, false, None).await;
+        let error = live(&root, &root_id, None, &mut attempted)
+            .await
+            .err()
+            .unwrap();
+        assert!(
+            error
+                .to_string()
+                .contains("Host startup failed after automatic recovery"),
+            "{error}"
+        );
+        assert!(error.to_string().contains(original.as_str()), "{error}");
+        let failed_discovery = discovery::read(&root).unwrap();
+        assert!(
+            !Client::status(&failed_discovery.endpoint, Some(failed_epoch))
+                .await
+                .unwrap()
+                .closing
+        );
+        stop.cancel();
+        failed_server.await.unwrap();
+        let host = crate::application::open_host(
+            RootOwner::open(&root, &RootNamespaces::for_current_account().unwrap()).unwrap(),
+            Options::default(),
+            crate::application::Roots::Saved,
+            Some(catalog_transport()),
+        )
+        .await
+        .unwrap();
+        let endpoint = crate::endpoint::LocalEndpoint::bind().unwrap();
+        let registration = host
+            .host
+            .publish_registration(&endpoint.path, None)
+            .unwrap();
+        let stop = CancellationToken::new();
+        let stopped = stop.clone();
+        let server = tokio::spawn(async move {
+            serve_fixture(endpoint, host, stopped, None).await.unwrap();
+            registration.remove().unwrap();
+        });
+        let mut client = live(&root, &root_id, None, &mut attempted)
+            .await
+            .unwrap()
+            .unwrap();
+        assert_ne!(client.epoch(), epoch);
+        assert!(client.catalogue().startup_error().is_none());
+        assert!(
+            client
+                .catalogue()
+                .describe("settings")
+                .unwrap()
+                .registration_epoch
+                .is_some()
+        );
+        client.close().await.unwrap();
+        stop.cancel();
+        server.await.unwrap();
+    }
+
+    #[tokio::test]
+    async fn current_live_host_is_reused_without_retirement() {
+        let directory = tempfile::tempdir().unwrap();
+        let root = directory.path().join("host");
+        let (root_id, epoch, stop, server) = serve_product(&root, false, false, None).await;
+        let mut attempted = UpdateAttempt::default();
+        let mut client = live(&root, &root_id, None, &mut attempted)
+            .await
+            .unwrap()
+            .unwrap();
+        assert_eq!(client.epoch(), epoch);
+        assert!(!attempted.restarted);
+        client.close().await.unwrap();
+        stop.cancel();
+        server.await.unwrap();
+    }
+
+    #[tokio::test]
+    async fn old_live_host_refuses_other_sessions_then_updates_on_safe_reconnect() {
+        let directory = tempfile::tempdir().unwrap();
+        let root = directory.path().join("host");
+        let (root_id, epoch, _stop, server) = serve_product(&root, true, false, None).await;
+        let discovery = discovery::read(&root).unwrap();
+        let mut other = Client::connect(&discovery.endpoint, Some(epoch))
+            .await
+            .unwrap();
+        let mut attempted = UpdateAttempt::default();
+        let error = live(&root, &root_id, None, &mut attempted)
+            .await
+            .err()
+            .unwrap();
+        assert!(
+            error
+                .to_string()
+                .contains("another Host session or active task"),
+            "{error}"
+        );
+        let status = Client::status(&discovery.endpoint, Some(epoch))
+            .await
+            .unwrap();
+        assert_eq!(status.epoch, epoch);
+        assert!(!status.closing);
+        assert_eq!(status.sessions, 1);
+        other.close().await.unwrap();
+        let mut attempted = UpdateAttempt::default();
+        assert!(
+            live(&root, &root_id, None, &mut attempted)
+                .await
+                .unwrap()
+                .is_none()
+        );
+        assert!(attempted.restarted);
+        server.await.unwrap();
+        let host = crate::application::open_host(
+            RootOwner::open(&root, &RootNamespaces::for_current_account().unwrap()).unwrap(),
+            Options::default(),
+            crate::application::Roots::Saved,
+            Some(catalog_transport()),
+        )
+        .await
+        .unwrap();
+        assert_ne!(host.host.epoch(), epoch);
+        let endpoint = crate::endpoint::LocalEndpoint::bind().unwrap();
+        let registration = host
+            .host
+            .publish_registration(&endpoint.path, None)
+            .unwrap();
+        let stop = CancellationToken::new();
+        let stopped = stop.clone();
+        let server = tokio::spawn(async move {
+            serve_fixture(endpoint, host, stopped, None).await.unwrap();
+            registration.remove().unwrap();
+        });
+        let mut client = live(&root, &root_id, None, &mut attempted)
+            .await
+            .unwrap()
+            .unwrap();
+        assert_ne!(client.epoch(), epoch);
+        assert!(
+            !crate::application::live_update_available(&client)
+                .await
+                .unwrap()
+        );
+        client.close().await.unwrap();
+        stop.cancel();
+        server.await.unwrap();
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org