Skip to content

Computer use CLI for AI agents

feat: relocate the state root with AGENT_DESKTOP_HOME (#135)

Lahfira336b01e7288
diff --git a/.gitleaks.toml b/.gitleaks.toml
index bf5533f5d..d28d7a86f 100644
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@ -70,7 +70,7 @@ regexes = [
'''S-1-5-21-<[^>]*>''',
# Generic doc examples that teach path shape rather than expose one.
'''(?i)/Users/(name|user|username|you|youruser|me|someone)''',
- '''(?i)/home/(name|user|username|you|youruser|runner|me|someone)''',
+ '''(?i)/home/(name|user|username|you|youruser|runner|me|someone|example-user)''',
'''(?i)[A-Za-z]:\\Users\\(name|user|username|you|youruser|runner)''',
# CI runner home paths are not operator identity.
'''/Users/runner''',
diff --git a/CLAUDE.md b/CLAUDE.md
index 63c05bd44..539ed5ae1 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -338,7 +338,8 @@ The `error` object may also carry optional `details` and `recovery` objects. Ver
- A bare `SetFocus` affordance does not qualify on its own (focusability is not a primary action), so inert focusable containers stay ref-less
- Static text and non-actionable groups/containers do NOT get refs (they remain in tree for context)
- Refs are deterministic within a snapshot but NOT stable across snapshots if UI changed
-- Snapshot refs are stored by snapshot ID under `~/.agent-desktop/snapshots/{snapshot_id}/refmap.json`, with a `latest_snapshot_id` pointer for commands that omit `--snapshot`
+- All persisted state lives under one state root, default `~/.agent-desktop`. `AGENT_DESKTOP_HOME` relocates it (the env value is the root itself, no suffix appended); resolution lives in `crates/core/src/state_root.rs` with precedence test override > env > default, and `status` reports the resolved root as `state_root`
+- Snapshot refs are stored by snapshot ID under `<state root>/snapshots/{snapshot_id}/refmap.json`, with a `latest_snapshot_id` pointer for commands that omit `--snapshot`
- Retention keeps the newest 128 snapshots per namespace and evicts down to 96, so the sort-and-stat pass is amortised instead of running on every save. Refs are invalidated by the next UI change, so retention only has to cover one interaction's drill-downs. Per R7/KTD5 of the session-first trace plan, a `snapshot_id` referenced by an *older* trace event may therefore no longer resolve to a full tree; `ArtifactsMode::Full` is the recorded mitigation because it copies each refmap into `<session>/trace/refmaps/`
- `~/.agent-desktop/last_refmap.json` is written only as a latest-snapshot inspection artifact; command code must use `RefStore`
- Action commands use strict re-identification from platform-neutral `RefEntry` evidence: pid, role, path/source surface, role-conditional stable text identity, and bounds hash. Mutable control values are volatile and must not be treated as stable text identity. Return `STALE_REF` on mismatch and `AMBIGUOUS_TARGET` when multiple plausible live candidates remain.
diff --git a/CONCEPTS.md b/CONCEPTS.md
index c2cd4a70a..9a2976474 100644
--- a/CONCEPTS.md
+++ b/CONCEPTS.md
@@ -49,6 +49,11 @@ Strict ref resolution rejects missing, stale, and ambiguous matches instead of g
## Coordination
+### State Root
+The single on-disk directory that owns everything the CLI persists: sessions, snapshot refmaps and their locks, trace segments, and the latest-snapshot inspection artifact. Default is `~/.agent-desktop`.
+
+`AGENT_DESKTOP_HOME` relocates the state root; the env value is the root itself, with no `.agent-desktop` suffix appended. Resolution lives in core and is identical across platforms. Explicit user-given output paths (`screenshot --out`, `--trace <path>`) are not re-rooted.
+
### Session
An on-disk container under `~/.agent-desktop/sessions/<id>/` that owns snapshot refmaps, an optional trace directory, and a `session.json` manifest.
diff --git a/crates/core/src/commands/status.rs b/crates/core/src/commands/status.rs
index b8d5f990e..cdad7f3e4 100644
--- a/crates/core/src/commands/status.rs
+++ b/crates/core/src/commands/status.rs
@@ -45,6 +45,9 @@ pub fn execute_with_report_with_context(
if let Some(artifacts) = artifacts {
body["artifacts"] = json!(artifacts);
}
+ if let Ok(state_root) = crate::state_root::resolve_configured_state_root() {
+ body["state_root"] = json!(state_root.to_string_lossy());
+ }
Ok(body)
}
diff --git a/crates/core/src/commands/status_tests.rs b/crates/core/src/commands/status_tests.rs
index 1673e5ed8..d1bde133e 100644
--- a/crates/core/src/commands/status_tests.rs
+++ b/crates/core/src/commands/status_tests.rs
@@ -73,6 +73,23 @@ fn status_reports_tracing_false_when_writer_failed() {
);
}
+#[test]
+fn status_reports_resolved_state_root_verbatim() {
+ let guard = crate::refs_test_support::HomeGuard::new();
+ let report = PermissionReport {
+ accessibility: PermissionState::Granted,
+ screen_recording: PermissionState::Granted,
+ automation: PermissionState::NotRequired,
+ };
+
+ let value =
+ execute_with_report_with_context(&DeniedAdapter, &report, &CommandContext::default())
+ .unwrap();
+
+ let expected = guard.path().join(".agent-desktop");
+ assert_eq!(value["state_root"], expected.to_string_lossy().as_ref());
+}
+
#[test]
fn status_surfaces_artifacts_mode_for_active_session() {
let _guard = crate::refs_test_support::HomeGuard::new();
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index d076eb84a..ea03c110a 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -130,6 +130,7 @@ pub mod snapshot_ref;
pub mod snapshot_surface;
pub mod state;
mod state_predicate;
+pub(crate) mod state_root;
pub mod step_mechanism;
mod surface_info;
mod surface_signal;
@@ -252,6 +253,7 @@ pub use signal_filter::SignalFilter;
pub use signals::diff_signals;
pub use snapshot_surface::SnapshotSurface;
pub use state_predicate::StatePredicate;
+pub use state_root::validate_state_root_env;
pub use step_mechanism::StepMechanism;
pub use surface_info::SurfaceInfo;
pub use surface_signal::SurfaceSignal;
diff --git a/crates/core/src/refs.rs b/crates/core/src/refs.rs
index 29e7e1031..d2471eca6 100644
--- a/crates/core/src/refs.rs
+++ b/crates/core/src/refs.rs
@@ -147,8 +147,7 @@ impl Default for RefMap {
}
fn refmap_path() -> Result<PathBuf, AppError> {
- let home = home_dir().ok_or_else(|| AppError::Internal("HOME directory not found".into()))?;
- Ok(home.join(".agent-desktop").join("last_refmap.json"))
+ Ok(crate::state_root::resolve_configured_state_root()?.join("last_refmap.json"))
}
pub(crate) fn new_snapshot_id() -> String {
@@ -269,15 +268,7 @@ fn validate_home_dir(home: &Path) -> bool {
if !meta.is_dir() {
return false;
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- meta.uid() == unsafe { libc::getuid() }
- }
- #[cfg(not(unix))]
- {
- true
- }
+ crate::state_root::is_owned_by_current_user(&meta)
}
#[cfg(test)]
@@ -285,6 +276,10 @@ pub(crate) fn set_home_override(home: Option<PathBuf>) -> Option<PathBuf> {
HOME_OVERRIDE.with(|cell| std::mem::replace(&mut *cell.borrow_mut(), home))
}
+pub(crate) fn home_override_active() -> bool {
+ HOME_OVERRIDE.with(|cell| cell.borrow().is_some())
+}
+
#[cfg(test)]
#[path = "refs_tests.rs"]
mod tests;
diff --git a/crates/core/src/refs_store.rs b/crates/core/src/refs_store.rs
index db3dbf908..ab7bb06eb 100644
--- a/crates/core/src/refs_store.rs
+++ b/crates/core/src/refs_store.rs
@@ -1,7 +1,7 @@
use crate::{
AdapterError, AppError,
context::validate_session_id,
- refs::{RefMap, home_dir, new_snapshot_id, validate_snapshot_id, write_private_file},
+ refs::{RefMap, new_snapshot_id, validate_snapshot_id, write_private_file},
refs_lock::RefStoreLock,
};
use std::io::ErrorKind;
@@ -29,20 +29,16 @@ impl RefStore {
}
pub fn for_session(session_id: Option<&str>) -> Result<Self, AppError> {
- let home =
- home_dir().ok_or_else(|| AppError::Internal("HOME directory not found".into()))?;
+ let state_root = crate::state_root::resolve_configured_state_root()?;
if let Some(session_id) = session_id {
validate_session_id(session_id)?;
return Ok(Self {
- base_dir: home
- .join(".agent-desktop")
- .join("sessions")
- .join(session_id),
+ base_dir: state_root.join("sessions").join(session_id),
allow_legacy_migration: false,
});
}
Ok(Self {
- base_dir: home.join(".agent-desktop"),
+ base_dir: state_root,
allow_legacy_migration: true,
})
}
diff --git a/crates/core/src/refs_test_support.rs b/crates/core/src/refs_test_support.rs
index d3f5f94d0..1dce30ce4 100644
--- a/crates/core/src/refs_test_support.rs
+++ b/crates/core/src/refs_test_support.rs
@@ -29,10 +29,10 @@ impl Drop for HomeGuard {
}
}
-struct TempDir(PathBuf);
+pub(crate) struct TempDir(PathBuf);
impl TempDir {
- fn new() -> Self {
+ pub(crate) fn new() -> Self {
let n = COUNTER.fetch_add(1, Ordering::SeqCst);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -43,7 +43,7 @@ impl TempDir {
Self(path)
}
- fn path(&self) -> &Path {
+ pub(crate) fn path(&self) -> &Path {
&self.0
}
}
diff --git a/crates/core/src/session/mod.rs b/crates/core/src/session/mod.rs
index 185f6a3e3..03c3480f9 100644
--- a/crates/core/src/session/mod.rs
+++ b/crates/core/src/session/mod.rs
@@ -7,10 +7,7 @@ pub use liveness::SessionLivenessLease;
pub use manifest::{ArtifactsMode, SessionManifest, SessionTraceMode};
use crate::{
- AppError,
- context::validate_session_id,
- refs::{home_dir, write_private_file},
- refs_store::RefStore,
+ AppError, context::validate_session_id, refs::write_private_file, refs_store::RefStore,
};
use serde_json;
use std::io::ErrorKind;
@@ -40,8 +37,7 @@ impl Default for StartSessionOptions {
}
pub fn agent_desktop_dir() -> Result<PathBuf, AppError> {
- let home = home_dir().ok_or_else(|| AppError::Internal("HOME directory not found".into()))?;
- Ok(home.join(".agent-desktop"))
+ crate::state_root::resolve_configured_state_root()
}
pub fn session_dir(session_id: &str) -> Result<PathBuf, AppError> {
diff --git a/crates/core/src/state_root.rs b/crates/core/src/state_root.rs
new file mode 100644
index 000000000..9102b40ed
--- /dev/null
+++ b/crates/core/src/state_root.rs
@@ -0,0 +1,353 @@
+use crate::AppError;
+use std::path::{Path, PathBuf};
+
+const AGENT_DESKTOP_HOME_ENV: &str = "AGENT_DESKTOP_HOME";
+const STATE_DIR_NAME: &str = ".agent-desktop";
+
+/// Binary-level preflight: validates `AGENT_DESKTOP_HOME` without touching
+/// `HOME`/`USERPROFILE`. A no-op when the variable is unset, so legacy
+/// behavior (surfacing a missing-HOME error later, at first state touch)
+/// stays byte-identical to today.
+pub fn validate_state_root_env() -> Result<(), AppError> {
+ let override_active = crate::refs::home_override_active();
+ let env_value = std::env::var_os(AGENT_DESKTOP_HOME_ENV).map(PathBuf::from);
+ validate_state_root_env_value(override_active, env_value, is_owned_by_current_user)
+}
+
+fn validate_state_root_env_value(
+ override_active: bool,
+ env_value: Option<PathBuf>,
+ owned_by_current_user: impl Fn(&std::fs::Metadata) -> bool,
+) -> Result<(), AppError> {
+ if override_active {
+ return Ok(());
+ }
+ match env_value {
+ Some(path) => validate_env_root(&path, &owned_by_current_user),
+ None => Ok(()),
+ }
+}
+
+pub(crate) fn resolve_configured_state_root() -> Result<PathBuf, AppError> {
+ let override_active = crate::refs::home_override_active();
+ let env_value = std::env::var_os(AGENT_DESKTOP_HOME_ENV).map(PathBuf::from);
+ let home_fallback = crate::refs::home_dir();
+ resolve_state_root(
+ override_active,
+ env_value,
+ home_fallback,
+ is_owned_by_current_user,
+ )
+}
+
+fn resolve_state_root(
+ override_active: bool,
+ env_value: Option<PathBuf>,
+ home_fallback: Option<PathBuf>,
+ owned_by_current_user: impl Fn(&std::fs::Metadata) -> bool,
+) -> Result<PathBuf, AppError> {
+ if !override_active && let Some(env_path) = env_value {
+ validate_env_root(&env_path, &owned_by_current_user)?;
+ return Ok(env_path);
+ }
+ let home =
+ home_fallback.ok_or_else(|| AppError::Internal("HOME directory not found".into()))?;
+ Ok(home.join(STATE_DIR_NAME))
+}
+
+fn validate_env_root(
+ path: &Path,
+ owned_by_current_user: &dyn Fn(&std::fs::Metadata) -> bool,
+) -> Result<(), AppError> {
+ if path.as_os_str().is_empty() {
+ return Err(AppError::invalid_input_with_suggestion(
+ "AGENT_DESKTOP_HOME must not be empty",
+ "Unset the variable or set it to an absolute directory path.",
+ ));
+ }
+ if !path.is_absolute() {
+ return Err(AppError::invalid_input_with_suggestion(
+ format!(
+ "AGENT_DESKTOP_HOME must be an absolute path, got '{}'",
+ path.display()
+ ),
+ "Set AGENT_DESKTOP_HOME to an absolute directory path.",
+ ));
+ }
+ match std::fs::symlink_metadata(path) {
+ Ok(meta) => {
+ if meta.file_type().is_symlink() {
+ return Err(AppError::invalid_input_with_suggestion(
+ format!(
+ "AGENT_DESKTOP_HOME must not be a symlink: '{}'",
+ path.display()
+ ),
+ "Point AGENT_DESKTOP_HOME at a real directory, not a symlink.",
+ ));
+ }
+ if !meta.is_dir() {
+ return Err(AppError::invalid_input_with_suggestion(
+ format!(
+ "AGENT_DESKTOP_HOME must be a directory: '{}'",
+ path.display()
+ ),
+ "Remove the file at this path or choose a different AGENT_DESKTOP_HOME.",
+ ));
+ }
+ if !owned_by_current_user(&meta) {
+ return Err(AppError::invalid_input_with_suggestion(
+ format!(
+ "AGENT_DESKTOP_HOME is owned by a different user: '{}'",
+ path.display()
+ ),
+ "Choose a directory you own for AGENT_DESKTOP_HOME.",
+ ));
+ }
+ Ok(())
+ }
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(err) => Err(AppError::invalid_input_with_suggestion(
+ format!(
+ "Cannot access AGENT_DESKTOP_HOME '{}': {err}",
+ path.display()
+ ),
+ "Check permissions on the parent directory or choose a different path.",
+ )),
+ }
+}
+
+#[cfg(unix)]
+pub(crate) fn is_owned_by_current_user(meta: &std::fs::Metadata) -> bool {
+ use std::os::unix::fs::MetadataExt;
+ meta.uid() == unsafe { libc::getuid() }
+}
+
+#[cfg(not(unix))]
+pub(crate) fn is_owned_by_current_user(_meta: &std::fs::Metadata) -> bool {
+ true
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::refs_test_support::TempDir;
+ use std::fs;
+
+ fn always_owned(_meta: &std::fs::Metadata) -> bool {
+ true
+ }
+
+ #[test]
+ fn env_set_to_existing_absolute_dir_resolves_exactly() {
+ let dir = TempDir::new();
+ let resolved = resolve_state_root(
+ false,
+ Some(dir.path().to_path_buf()),
+ Some(PathBuf::from("/should/not/be/used")),
+ always_owned,
+ )
+ .expect("resolves");
+ assert_eq!(resolved, dir.path());
+ }
+
+ #[test]
+ fn env_unset_resolves_to_home_fallback_joined_with_dotdir() {
+ let home = PathBuf::from("/home/example-user");
+ let resolved =
+ resolve_state_root(false, None, Some(home.clone()), always_owned).expect("resolves");
+ assert_eq!(resolved, home.join(".agent-desktop"));
+ }
+
+ #[test]
+ fn relative_env_value_is_invalid_args() {
+ let err = resolve_state_root(
+ false,
+ Some(PathBuf::from("relative/path")),
+ Some(PathBuf::from("/home/example-user")),
+ always_owned,
+ )
+ .expect_err("must reject relative path");
+ assert_eq!(err.code(), "INVALID_ARGS");
+ }
+
+ #[test]
+ fn empty_env_value_is_invalid_args() {
+ let err = resolve_state_root(
+ false,
+ Some(PathBuf::from("")),
+ Some(PathBuf::from("/home/example-user")),
+ always_owned,
+ )
+ .expect_err("must reject empty path");
+ assert_eq!(err.code(), "INVALID_ARGS");
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn symlink_leaf_is_invalid_args() {
+ let dir = TempDir::new();
+ let target = dir.path().join("real");
+ let link = dir.path().join("link");
+ fs::create_dir_all(&target).expect("create target dir");
+ std::os::unix::fs::symlink(&target, &link).expect("create symlink");
+
+ let err = resolve_state_root(
+ false,
+ Some(link),
+ Some(PathBuf::from("/home/example-user")),
+ always_owned,
+ )
+ .expect_err("must reject symlink leaf");
+ assert_eq!(err.code(), "INVALID_ARGS");
+ }
+
+ #[test]
+ fn regular_file_leaf_is_invalid_args() {
+ let dir = TempDir::new();
+ let file_path = dir.path().join("not-a-dir");
+ fs::write(&file_path, b"x").expect("write file");
+
+ let err = resolve_state_root(
+ false,
+ Some(file_path),
+ Some(PathBuf::from("/home/example-user")),
+ always_owned,
+ )
+ .expect_err("must reject regular file leaf");
+ assert_eq!(err.code(), "INVALID_ARGS");
+ }
+
+ #[test]
+ fn nonexistent_leaf_is_valid() {
+ let dir = TempDir::new();
+ let missing = dir.path().join("does-not-exist-yet");
+
+ let resolved = resolve_state_root(
+ false,
+ Some(missing.clone()),
+ Some(PathBuf::from("/home/example-user")),
+ always_owned,
+ )
+ .expect("nonexistent leaf is valid, created lazily");
+ assert_eq!(resolved, missing);
+ assert!(!missing.exists());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn leaf_under_symlinked_ancestor_resolves_ok() {
+ let real_parent = TempDir::new();
+ let symlinked_parent_container = TempDir::new();
+ let symlinked_parent = symlinked_parent_container.path().join("ancestor-link");
+ std::os::unix::fs::symlink(real_parent.path(), &symlinked_parent)
+ .expect("create ancestor symlink");
+
+ let leaf = symlinked_parent.join("state-root");
+ fs::create_dir_all(&leaf).expect("create leaf dir through symlinked ancestor");
+
+ let resolved = resolve_state_root(
+ false,
+ Some(leaf.clone()),
+ Some(PathBuf::from("/home/example-user")),
+ always_owned,
+ )
+ .expect("ancestors are never checked, only the leaf");
+ assert_eq!(resolved, leaf);
+ }
+
+ #[test]
+ fn override_active_wins_over_env_value() {
+ let dir = TempDir::new();
+ let home = PathBuf::from("/home/example-user");
+ let resolved = resolve_state_root(
+ true,
+ Some(dir.path().to_path_buf()),
+ Some(home.clone()),
+ always_owned,
+ )
+ .expect("resolves via home fallback, ignoring env");
+ assert_eq!(resolved, home.join(".agent-desktop"));
+ }
+
+ #[test]
+ fn env_set_with_no_home_fallback_still_resolves() {
+ let dir = TempDir::new();
+ let resolved =
+ resolve_state_root(false, Some(dir.path().to_path_buf()), None, always_owned)
+ .expect("env path does not need HOME/USERPROFILE");
+ assert_eq!(resolved, dir.path());
+ }
+
+ #[test]
+ fn leaf_owned_by_different_user_is_invalid_args() {
+ let dir = TempDir::new();
+ let err = resolve_state_root(
+ false,
+ Some(dir.path().to_path_buf()),
+ Some(PathBuf::from("/home/example-user")),
+ |_meta| false,
+ )
+ .expect_err("owner predicate reports mismatch");
+ assert_eq!(err.code(), "INVALID_ARGS");
+ }
+
+ #[test]
+ fn preflight_env_unset_is_a_no_op() {
+ validate_state_root_env_value(false, None, always_owned).expect("unset env is a no-op");
+ }
+
+ #[test]
+ fn preflight_override_active_skips_env_validation() {
+ validate_state_root_env_value(true, Some(PathBuf::from("relative/bad")), always_owned)
+ .expect("test HOME override bypasses env validation, mirroring resolve_state_root");
+ }
+
+ #[test]
+ fn preflight_relative_env_value_is_invalid_args() {
+ let err = validate_state_root_env_value(
+ false,
+ Some(PathBuf::from("relative/path")),
+ always_owned,
+ )
+ .expect_err("must reject relative path");
+ assert_eq!(err.code(), "INVALID_ARGS");
+ }
+
+ #[test]
+ fn preflight_empty_env_value_is_invalid_args() {
+ let err = validate_state_root_env_value(false, Some(PathBuf::from("")), always_owned)
+ .expect_err("must reject empty path");
+ assert_eq!(err.code(), "INVALID_ARGS");
+ }
+
+ #[test]
+ fn preflight_nonexistent_absolute_leaf_does_not_require_home_and_is_valid() {
+ let dir = TempDir::new();
+ let missing = dir.path().join("does-not-exist-yet");
+
+ validate_state_root_env_value(false, Some(missing.clone()), always_owned)
+ .expect("nonexistent absolute leaf is valid without touching HOME");
+ assert!(
+ !missing.exists(),
+ "preflight validation must not create the state root directory"
+ );
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn existing_dir_with_unusual_permissions_is_used_as_is() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = TempDir::new();
+ fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o777))
+ .expect("set permissions");
+
+ let resolved = resolve_state_root(
+ false,
+ Some(dir.path().to_path_buf()),
+ Some(PathBuf::from("/home/example-user")),
+ always_owned,
+ )
+ .expect("existing dir is used as-is regardless of mode bits");
+ assert_eq!(resolved, dir.path());
+ }
+}
diff --git a/docs/plans/2026-08-19-001-feat-agent-desktop-home-state-root-plan.md b/docs/plans/2026-08-19-001-feat-agent-desktop-home-state-root-plan.md
new file mode 100644
index 000000000..ecaafdd55
--- /dev/null
+++ b/docs/plans/2026-08-19-001-feat-agent-desktop-home-state-root-plan.md
@@ -0,0 +1,233 @@
+---
+title: AGENT_DESKTOP_HOME State Root Relocation - Plan
+type: feat
+date: 2026-08-19
+topic: agent-desktop-home-state-root
+artifact_contract: ce-unified-plan/v1
+artifact_readiness: implementation-ready
+product_contract_source: ce-brainstorm
+execution: code
+---
+
+# AGENT_DESKTOP_HOME State Root Relocation - Plan
+
+## Goal Capsule
+
+- **Objective:** Add an `AGENT_DESKTOP_HOME` environment variable that relocates the CLI's entire persisted state root for every subcommand, resolved once in `agent-desktop-core` so behavior is identical on macOS, Windows, and Linux.
+- **Product authority:** The invoking brief (VDA adapter integration design, CARGO_HOME pattern) plus this Product Contract.
+- **Open blockers:** None.
+
+---
+
+## Product Contract
+
+### Summary
+
+An `AGENT_DESKTOP_HOME` environment variable relocates the whole state root. When set, everything the CLI persists — sessions, snapshot refmaps, trace segments, lock files — lives under that path. When unset, the default stays `~/.agent-desktop`, unchanged. The `status` command reports the resolved root so callers can detect the capability.
+
+### Problem Frame
+
+A sandboxed adapter (VDA) spawns `agent-desktop` per task and needs each spawn's state to live inside the task's sandbox root, so the sandbox wipe is the only cleanup. Today the root is fixed: core resolves the home directory in one helper and joins `.agent-desktop` at four call sites, with no override. The adapter side already composes env vars through an allowlist (the `PLAYWRIGHT_BROWSERS_PATH` precedent), so a fixed root is the only missing piece.
+
+### Key Decisions
+
+- KD1. **Environment variable, not a flag** (session-settled: user-directed — chosen over a per-invocation flag: it applies uniformly to every invocation without threading an injected flag through the model's argv space, and it composes with the existing env-allowlist mechanism). Governs R1, R2.
+- KD2. **The env value IS the state root — no `.agent-desktop` suffix appended** (session-settled: user-directed — the acceptance example `/tmp/x/sessions/<id>/` pins this over a prefix-plus-suffix reading). Governs R1.
+- KD3. **A future `--state-root` flag wins over the env; the flag itself is deferred** (session-settled: user-directed — env-only ships now; the precedence rule is recorded so the later flag does not need a breaking change). Governs the Scope Boundaries entry.
+- KD4. **`status` reports the resolved `state_root`** (session-settled: user-approved — gives the adapter a positive capability signal after release instead of relying only on a version floor). Governs R6.
+- KD5. **Validation checks the leaf path only, never ancestors** (session-settled: user-approved — on macOS `/tmp` is itself a symlink to `/private/tmp`, so an ancestor-resolving symlink check would reject the exact acceptance path). Governs R4.
+- KD6. **Resolution precedence: test override, then `AGENT_DESKTOP_HOME`, then default home join.** The existing thread-local test hook must beat the env, or a developer with the variable exported in their shell leaks a real root into the test suite. Governs R3.
+
+### Requirements
+
+```mermaid
+flowchart TB
+ E[AGENT_DESKTOP_HOME] --> ROOT[resolved state root]
+ D[default: home + .agent-desktop] --> ROOT
+ ROOT --> S[sessions/id/ + trace segments]
+ ROOT --> R[snapshots/id/refmap.json + locks]
+ ROOT --> L[last_refmap.json]
+```
+
+**Root resolution**
+
+- R1. When `AGENT_DESKTOP_HOME` is set, that path is the state root itself, and every persisted artifact lives under it: sessions at `$AGENT_DESKTOP_HOME/sessions/<id>/`, snapshot refmaps and their lock files, trace segments, and the latest-snapshot inspection artifact. Nothing is written under `~/.agent-desktop` while the variable is set.
+- R2. The variable applies to every subcommand with no per-command opt-in, including `session start`/`end`/`list`/`gc`, snapshot namespace lookup, and trace output. Explicit user-given output paths (`screenshot --out`, `--trace <path>`) stay verbatim and are not re-rooted.
+- R3. When the variable is unset, path resolution is unchanged from today: home directory (HOME, then USERPROFILE) joined with `.agent-desktop`, behind the existing test override.
+
+**Validation and creation**
+
+- R4. A missing root is created with owner-only permissions where the platform supports it (mode 700 on Unix; default user-profile ACLs on Windows). An existing directory is used as-is with no permission tightening, but on Unix a pre-existing leaf owned by a different uid fails with `INVALID_ARGS`, mirroring the home-directory ownership check. Validation applies to the leaf path only and rejects a leaf that is a symlink or not a directory.
+- R5. A relative or empty value fails with `INVALID_ARGS` before any command work runs, matching the empty-value precedent of `AGENT_DESKTOP_SESSION`.
+
+**Observability**
+
+- R6. `status` output includes the resolved `state_root` (the env value when set, otherwise the default path), so a caller can verify relocation without writing state.
+
+**Platform agnosticism**
+
+- R7. Resolution lives entirely in `agent-desktop-core`; no platform crate participates, and behavior is identical across macOS, Windows, and Linux. Any `#[cfg]` branch this adds to core must be executed by an existing CI lane, per `docs/solutions/best-practices/never-ship-platform-code-that-ci-cannot-execute.md`.
+
+**Documentation**
+
+- R8. User-facing docs that state the `~/.agent-desktop` layout (`skills/agent-desktop/`, `CLAUDE.md` ref-system section) name the variable and its semantics.
+
+### Acceptance Examples
+
+- AE1. **Covers R1, R2, R4.** **Given** `AGENT_DESKTOP_HOME=/tmp/x` on macOS (an ancestor-symlink path, since `/tmp` links to `/private/tmp`), **When** `agent-desktop session start` runs, **Then** `/tmp/x/sessions/<id>/session.json` exists, `/tmp/x` was created with owner-only permissions, and nothing new exists under `~/.agent-desktop`.
+- AE2. **Covers R2.** **Given** the same environment, **When** `agent-desktop session list` runs, **Then** only session ids under `/tmp/x` resolve.
+- AE3. **Covers R5.** **Given** `AGENT_DESKTOP_HOME=relative/path` or an empty value, **When** any command runs, **Then** the command exits 1 with error code `INVALID_ARGS` and writes no state.
+- AE4. **Covers R3.** **Given** the variable unset, **When** any command runs, **Then** every state path is identical to today's behavior.
+- AE5. **Covers R6.** **Given** `AGENT_DESKTOP_HOME=/tmp/x`, **When** `agent-desktop status` runs, **Then** the JSON body contains `"state_root": "/tmp/x"`.
+
+### Scope Boundaries
+
+- No `--state-root` flag now. When one is added later, the flag wins over the env (per KD3).
+- No migration and no dual-root visibility: state under `~/.agent-desktop` is invisible while the variable points elsewhere. That isolation is the goal, not a defect.
+- No new cleanup or GC behavior — the caller's sandbox wipe is the cleanup path.
+- The VDA adapter side (env injection per spawn, version floor, capability detection) is the consumer's work and out of scope here.
+
+### Sources / Research
+
+- `crates/core/src/refs.rs:251` — `home_dir()`: thread-local test override, then HOME, then USERPROFILE; leaf symlink/directory validation.
+- The four `.agent-desktop` join sites, all in core: `crates/core/src/refs_store.rs:38` and `:45` (session-scoped and default `RefStore` constructors), `crates/core/src/refs.rs:151`, `crates/core/src/session/mod.rs:44`.
+- `crates/core/src/refs_lock.rs` and `crates/core/src/trace_artifact_budget.rs` — their `std::env::temp_dir()` uses are test-only; production lock files live next to the state they guard, so they relocate with the root.
+- `crates/core/src/commands/screenshot.rs:21` — a file is written only when an output path is given; there is no home-derived `--out` default to change.
+- `src/cli_args/session.rs` — `start`, `end`, `list`, `gc` all exist.
+- `crates/core/src/commands/status.rs` — the `json!` body where `state_root` lands.
+- `crates/core/src/session/mod.rs:67` — the `AGENT_DESKTOP_SESSION` empty-value error precedent behind R5 (`AppError::invalid_input_with_suggestion` → `INVALID_ARGS`).
+- `crates/core/src/private_file_parent.rs` — `ensure_directory_path()` creates directory chains with mode 700 on Unix and `create_dir_all` on Windows; one of the two creation paths R4 reuses. Session start builds its tree with its own recursive mode-700 `DirBuilder` in `crates/core/src/session/mod.rs` and bypasses this helper.
+- `crates/core/src/refs_test_support.rs` — `HomeGuard` test helper (temp home + thread-local override, auto-restore on drop).
+- `crates/core/src/commands/status_tests.rs` — field-level `json` assertions; the test placement pattern for the new `state_root` field.
+- `crates/core/src/output.rs:7` — envelope version `2.3`; additive `data` fields historically ship without a version bump (`session_id`/`tracing` precedent).
+- `docs/solutions/best-practices/never-ship-platform-code-that-ci-cannot-execute.md` — governs the `cfg(unix)` permissions branch; core already carries CI-executed `cfg` branches in `private_file.rs` and `refs.rs`.
+
+---
+
+## Planning Contract
+
+**Product Contract preservation:** changed: R4 — added the Unix uid-ownership rejection for pre-existing roots (security review); otherwise unchanged.
+
+### Key Technical Decisions
+
+- KTD1. **New core module `crates/core/src/state_root.rs` owns resolution; all four join sites call it.** One file per concern (`refs.rs` is near the 400-LOC limit). Both `RefStore` constructors in `refs_store.rs` (session-scoped and default), `refs.rs` (`last_refmap` path), and `session/mod.rs` (`agent_desktop_dir`) delegate to it. Covers R1, R3, R7.
+- KTD2. **Resolution precedence: `HOME_OVERRIDE` test hook, then `AGENT_DESKTOP_HOME`, then `home_dir()` + `.agent-desktop`.** The env path must not route through `home_dir()` — a minimal sandbox can set the env with no `HOME`/`USERPROFILE` present, and resolution must still succeed. `HOME_OVERRIDE` is a private thread-local in `refs.rs`, so `refs.rs` gains a `pub(crate)` probe (e.g. `home_override_active()`) that the wrapper checks before it reads the env; the pure resolver takes override state, env value, and home fallback as explicit inputs. The env root's leaf validation mirrors `validate_home_dir`'s Unix uid-ownership rejection per R4 but never walks ancestors. Covers R1, R3, R4.
+- KTD3. **The env value is read per invocation with `var_os` (no process-lifetime caching, no UTF-8 requirement).** Resolution stays dynamic; FFI hosts that change the env between calls see the new root on the next state-touching call. Covers R2, R7.
+- KTD4. **Every value-side validation failure maps to `INVALID_ARGS` with a suggestion** (relative, empty, leaf symlink, leaf not a directory, foreign-uid leaf on Unix), following the `AGENT_DESKTOP_SESSION` pattern at `crates/core/src/session/mod.rs:67`. Unexpected IO after validation stays `INTERNAL`. (session-settled: user-approved — chosen over ancestor-resolving validation: macOS `/tmp` is a symlink; governs R4, R5.)
+- KTD5. **The binary validates `AGENT_DESKTOP_HOME` once before command dispatch; creation stays lazy.** A set-but-invalid value fails every command (including `version` and whole batches) before any work, satisfying AE3 with one preflight in `src/main.rs`. The preflight does not create the root; first state write creates it through the existing owner-only creation paths — `ensure_directory_path()` for refmap writes, and session start's own recursive mode-700 `DirBuilder` tree (mode 700 on Unix, default ACLs on Windows). Read-only commands stay side-effect-free. Covers R2, R4, R5.
+- KTD6. **`status` reports `state_root` verbatim — no canonicalization, no trailing-slash edits.** The adapter string-matches the value for capability detection; canonicalizing a symlinked path would break it. When the env is unset, the field carries the default absolute path; when default resolution fails (no HOME), the field is omitted. (session-settled: user-approved — chosen over version-floor-only detection; governs R6.)
+
+### High-Level Technical Design
+
+```mermaid
+flowchart TB
+ A[command starts] --> B{AGENT_DESKTOP_HOME set?}
+ B -->|no| C[home_dir + .agent-desktop\nbyte-identical legacy path]
+ B -->|yes| D{absolute + non-empty?}
+ D -->|no| E[INVALID_ARGS before dispatch]
+ D -->|yes| F{leaf exists?}
+ F -->|yes, dir, not symlink| G[env value is the root]
+ F -->|yes, symlink or file| E
+ F -->|no| H[valid; created lazily\nat first state write, mode 700]
+ H --> G
+```
+
+Directional guidance: the pure resolution function takes the override state, the env value, and a home fallback as explicit inputs so unit tests never touch process-global env vars; a thin wrapper reads the real environment and the override probe.
+
+### Assumptions
+
+Pipeline mode resolved these without a user checkpoint; each is recorded here instead of asked:
+
+- AE3's "any command" is read strictly: `version`, `skills`, and read-only commands also fail on a set-but-invalid value, via the single preflight (KTD5).
+- A batch invocation under an invalid value fails as one envelope before any entry runs.
+- The FFI cdylib has no preflight surface; a bad value surfaces as `INVALID_ARGS` on the first state-touching call. This asymmetry is accepted.
+
+---
+
+## Implementation Units
+
+### U1. Core state-root resolver
+
+**Goal:** One core function resolves the state root; the three hardcoded join sites delegate to it.
+**Requirements:** R1, R2, R3, R4, R5, R7 (KTD1, KTD2, KTD3, KTD4).
+**Dependencies:** none.
+**Files:** `crates/core/src/state_root.rs` (new), `crates/core/src/lib.rs`, `crates/core/src/refs.rs`, `crates/core/src/refs_store.rs`, `crates/core/src/session/mod.rs`.
+**Approach:**
+1. Add `state_root.rs`: a pure resolver (override state + env value + home fallback in, `Result<PathBuf>` out) plus a thin wrapper reading `AGENT_DESKTOP_HOME` via `var_os` and the new `pub(crate)` override probe in `refs.rs` (KTD2).
+2. Validate per KTD4; checks stay leaf-only and include the Unix uid-ownership rejection for pre-existing leaves (R4).
+3. Replace all four `.agent-desktop` joins — `refs_store.rs:38` and `refs_store.rs:45` (both `RefStore` constructors), `refs.rs:151`, `session/mod.rs:44` — with calls to the wrapper.
+4. Leave creation to the existing `ensure_directory_path()` path per KTD5.
+**Patterns to follow:** `home_dir()`/`validate_home_dir` in `crates/core/src/refs.rs`; `HomeGuard` in `refs_test_support.rs`; error construction at `session/mod.rs:64-69`.
+**Test scenarios:**
+- Covers AE1/AE2 (core half). Env set to an absolute temp path: session save and lookup paths land under it; nothing lands under the default root.
+- Covers AE2. A session-scoped `RefStore::for_session` lookup and the session trace directory both resolve under the env root, never under `~/.agent-desktop`.
+- Leaf directory owned by a different uid → `INVALID_ARGS` (Unix).
+- Covers AE4. Env unset: resolved path equals `home_dir()` + `.agent-desktop` exactly.
+- Relative value → `INVALID_ARGS`; empty value → `INVALID_ARGS`.
+- Leaf symlink → `INVALID_ARGS`; leaf is a regular file → `INVALID_ARGS`.
+- Path under a symlinked ancestor (e.g. a temp dir inside a symlinked parent) resolves successfully.
+- `HOME_OVERRIDE` set and env set: override wins.
+- Env set, home fallback absent: resolution still succeeds (pure fn with `None` home).
+- Existing directory with unusual permissions is used as-is (no error, no tightening).
+**Verification:** `cargo test --lib -p agent-desktop-core` green; new module under 400 LOC; no `unwrap()` outside tests.
+
+### U2. Binary preflight and CLI contract
+
+**Goal:** Every CLI invocation with a set-but-invalid `AGENT_DESKTOP_HOME` exits 1 with `INVALID_ARGS` before dispatch.
+**Requirements:** R2, R5 (KTD5); AE3.
+**Dependencies:** U1.
+**Files:** `src/main.rs`, `src/tests/` (existing CLI contract test module).
+**Approach:** After CLI parse and before the command match, call the core validation when the env is set. Convert the error through the existing `AppError` → JSON envelope path. Batch inherits the preflight for free.
+**Patterns to follow:** existing `AGENT_DESKTOP_SESSION` resolution call in `src/main.rs:122`; existing binary-level contract tests under `src/tests/`.
+**Test scenarios:**
+- Covers AE3. Relative value + `version` → exit 1, `INVALID_ARGS`, no state written.
+- Covers AE3. Empty value + `session start` → exit 1, `INVALID_ARGS`.
+- Valid absolute value + `version` → exit 0 (preflight does not create the root).
+- Batch JSON with invalid env → single error envelope, no entries run.
+**Verification:** `cargo test -p agent-desktop` green.
+
+### U3. `state_root` in status output
+
+**Goal:** `status` reports the resolved state root verbatim.
+**Requirements:** R6 (KTD6); AE5.
+**Dependencies:** U1.
+**Files:** `crates/core/src/commands/status.rs`, `crates/core/src/commands/status_tests.rs`.
+**Approach:** Add the field to the `json!` body from the U1 resolver; omit when default resolution fails. No envelope version bump (additive-field precedent).
+**Patterns to follow:** conditional field insertion for `artifacts` in `status.rs`; assertions in `status_tests.rs`.
+**Test scenarios:**
+- Covers AE5. With override/env root set: body contains `state_root` equal to the exact configured path.
+- With defaults: `state_root` equals the default path.
+**Verification:** `cargo test --lib -p agent-desktop-core` green; golden fixtures unaffected or regenerated intentionally.
+
+### U4. Documentation
+
+**Goal:** User-facing docs name the variable and its semantics.
+**Requirements:** R8.
+**Dependencies:** U1-U3 (documents shipped behavior).
+**Files:** `skills/agent-desktop/SKILL.md` and/or `skills/agent-desktop/references/commands-system.md`, `CLAUDE.md` (Ref System section).
+**Approach:** State: the env value is the root itself; applies to every subcommand; relative/empty errors; `status.state_root` is the detection signal. `CONCEPTS.md` already carries the State Root entry — keep terms consistent with it.
+**Test scenarios:** Test expectation: none — documentation only.
+**Verification:** docs mention `AGENT_DESKTOP_HOME` wherever the `~/.agent-desktop` layout is stated.
+
+---
+
+## Verification Contract
+
+| Gate | Command | Applies to |
+|---|---|---|
+| Format | `cargo fmt --all -- --check` | all units |
+| Lint | `cargo clippy --all-targets -- -D warnings` | all units |
+| Tests | `cargo test --workspace` | U1-U3 |
+| Core isolation | `cargo tree -p agent-desktop-core` contains no platform crate names | U1 |
+| Cross-compile | `cargo check -p agent-desktop-core --all-targets --target x86_64-pc-windows-msvc` and `--target x86_64-unknown-linux-gnu` | U1 |
+| Perf baseline | `bash scripts/perf-baseline-compare.sh` — latency deltas explainable | before merge |
+
+---
+
+## Definition of Done
+
+- R1-R8 hold; AE1-AE5 each covered by at least one passing test.
+- All Verification Contract gates green; release binary stays under 15MB.
+- Behavior with the variable unset is unchanged (AE4), including error text.
+- Docs updated per U4; `CONCEPTS.md` State Root entry stays accurate.
+- No abandoned or experimental code remains in the diff.
diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.md
index 593dc0f21..1b0322a21 100644
--- a/skills/agent-desktop/SKILL.md
+++ b/skills/agent-desktop/SKILL.md
@@ -271,4 +271,5 @@ agent-desktop skills get desktop --full # Load this skill + all referenc
12. **Headless by default.** Ref actions use semantic AX paths and block silent focus stealing, cursor movement, keyboard synthesis, and pasteboard insertion. Use `--headed` only when exact-window focus or physical delivery is intended; raw coordinates never imply focus.
13. **Start a session once per run.** `session start` creates the manifest; pass its returned ID through `AGENT_DESKTOP_SESSION` for the run or `--session <id>` for one command. It does not activate later processes implicitly.
14. **Trace hard failures.** With an active trace-enabled session, segments are written automatically. Add `--trace /tmp/agent-desktop.jsonl` only when you need a single override file (CI, one-offs). Check `status` when unsure whether tracing is active.
-15. **Chromium-app strategy.** The accessibility path is the default, and the only option for already-running apps and for native surfaces (menus, dialogs, windows). `launch --cdp` plus a CDP client (agent-browser preferred; any CDP client works) is the opt-in fast path for a Chromium app's web contents, when a fresh launch is acceptable.
+15. **Relocate state with `AGENT_DESKTOP_HOME`.** When set, the env value is the state root itself — sessions, refmaps, traces, and locks all live under it, for every subcommand. Default stays `~/.agent-desktop`. The value must be an absolute path; a relative or empty value fails with `INVALID_ARGS` before any command runs. `status` reports the resolved root as `state_root`. Explicit output paths (`screenshot --out`, `--trace <path>`) are never re-rooted.
+16. **Chromium-app strategy.** The accessibility path is the default, and the only option for already-running apps and for native surfaces (menus, dialogs, windows). `launch --cdp` plus a CDP client (agent-browser preferred; any CDP client works) is the opt-in fast path for a Chromium app's web contents, when a fresh launch is acceptable.
diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.md
index bb1f0c07a..29829455d 100644
--- a/skills/agent-desktop/references/commands-system.md
+++ b/skills/agent-desktop/references/commands-system.md
@@ -453,7 +453,7 @@ Each entry may include `"session": "id"` beside `command` and `args`. If omitted
## Session lifecycle
-Sessions are on-disk containers under `~/.agent-desktop/sessions/<id>/` with a `session.json` manifest, snapshot refmaps, and (when tracing is on) a `trace/` directory. Session selection is explicit; `session start` returns an ID but does not activate it for later processes.
+Sessions are on-disk containers under `<state root>/sessions/<id>/` with a `session.json` manifest, snapshot refmaps, and (when tracing is on) a `trace/` directory. The state root defaults to `~/.agent-desktop`; setting `AGENT_DESKTOP_HOME` relocates it — the env value is the root itself, applied to every subcommand. A relative or empty value fails with `INVALID_ARGS` before dispatch, and `status` reports the resolved root as `state_root`. Session selection is explicit; `session start` returns an ID but does not activate it for later processes.
### session start
```bash
diff --git a/src/cli/help_after.txt b/src/cli/help_after.txt
index 7d67891ca..97c33c131 100644
--- a/src/cli/help_after.txt
+++ b/src/cli/help_after.txt
@@ -76,7 +76,7 @@ WAIT
wait --event <kind> Block on a baseline diff: window/app/focus/surface lifecycle
SYSTEM
- status Adapter health, platform, permission, session, and tracing state
+ status Adapter health, platform, permission, session, tracing, and state_root
permissions Check nested permission states: {state,...}
version Show version, target architecture, and OS
skills Bundled skill docs for AI agents (list, get, path)
@@ -86,6 +86,13 @@ SYSTEM
session list List session manifests
session gc Remove ended or provably-stale sessions
+ENVIRONMENT
+ AGENT_DESKTOP_SESSION Session ID fallback when --session is not passed
+ AGENT_DESKTOP_HOME Relocates the state root; the value is the root itself
+ (absolute path; default ~/.agent-desktop). Applies to every
+ command; an invalid value fails with INVALID_ARGS before
+ dispatch. `status` reports the resolved root as state_root.
+
TRACE
trace show Merge session trace segments into a bounded JSON timeline (--limit defaults to 500; 0 = all)
trace export Export a self-contained HTML trace viewer (--limit defaults to 5000; 0 = all)
diff --git a/src/main.rs b/src/main.rs
index 89c4c87ed..c541dd850 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -93,6 +93,10 @@ fn run() -> ExitCode {
let cmd_name = cmd.name();
+ if let Err(err) = agent_desktop_core::validate_state_root_env() {
+ return finish(cmd_name, Err(pre_dispatch_error(err)));
+ }
+
match cmd {
Commands::Version => finish(
cmd_name,
diff --git a/src/tests/cli_process.rs b/src/tests/cli_process.rs
index 62aa96882..d2a9a1084 100644
--- a/src/tests/cli_process.rs
+++ b/src/tests/cli_process.rs
@@ -44,6 +44,144 @@ fn version_has_exact_package_identity() {
assert_eq!(envelope["data"]["version"], env!("CARGO_PKG_VERSION"));
}
+#[test]
+fn relative_state_root_env_fails_version_before_dispatch() {
+ let output = binary()
+ .arg("version")
+ .env("AGENT_DESKTOP_HOME", "relative/not-absolute")
+ .output()
+ .expect("binary starts");
+ let envelope: serde_json::Value =
+ serde_json::from_slice(&output.stdout).expect("stdout is one JSON envelope");
+
+ assert_eq!(output.status.code(), Some(1));
+ assert_eq!(envelope["ok"], false);
+ assert_eq!(envelope["command"], "version");
+ assert_eq!(envelope["error"]["code"], "INVALID_ARGS");
+}
+
+#[test]
+fn empty_state_root_env_fails_session_start_before_dispatch() {
+ let output = binary()
+ .args(["session", "start"])
+ .env("AGENT_DESKTOP_HOME", "")
+ .output()
+ .expect("binary starts");
+ let envelope: serde_json::Value =
+ serde_json::from_slice(&output.stdout).expect("stdout is one JSON envelope");
+
+ assert_eq!(output.status.code(), Some(1));
+ assert_eq!(envelope["ok"], false);
+ assert_eq!(envelope["command"], "session");
+ assert_eq!(envelope["error"]["code"], "INVALID_ARGS");
+}
+
+#[test]
+fn valid_absolute_state_root_env_allows_version_and_creates_nothing() {
+ let dir = std::env::temp_dir().join(format!(
+ "agent-desktop-cli-process-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0)
+ ));
+ let output = binary()
+ .arg("version")
+ .env("AGENT_DESKTOP_HOME", &dir)
+ .output()
+ .expect("binary starts");
+ let envelope: serde_json::Value =
+ serde_json::from_slice(&output.stdout).expect("stdout is one JSON envelope");
+
+ assert!(output.status.success());
+ assert_eq!(envelope["ok"], true);
+ assert!(
+ !dir.exists(),
+ "preflight validation must not create the state root directory"
+ );
+}
+
+#[test]
+fn state_root_env_redirects_session_start_writes() {
+ let dir = std::env::temp_dir().join(format!(
+ "agent-desktop-cli-state-root-session-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0)
+ ));
+ std::fs::create_dir_all(&dir).expect("create state root");
+ let output = binary()
+ .args(["session", "start"])
+ .env("AGENT_DESKTOP_HOME", &dir)
+ .output()
+ .expect("binary starts");
+ let envelope: serde_json::Value =
+ serde_json::from_slice(&output.stdout).expect("stdout is one JSON envelope");
+
+ assert!(output.status.success());
+ assert_eq!(envelope["ok"], true);
+ let session_id = envelope["data"]["session_id"]
+ .as_str()
+ .expect("session start returns a session id");
+ let manifest = dir.join("sessions").join(session_id).join("session.json");
+ assert!(
+ manifest.is_file(),
+ "session manifest must land under the AGENT_DESKTOP_HOME root"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn status_reports_state_root_env_value_verbatim() {
+ let dir = std::env::temp_dir().join(format!(
+ "agent-desktop-cli-state-root-status-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0)
+ ));
+ std::fs::create_dir_all(&dir).expect("create state root");
+ let output = binary()
+ .arg("status")
+ .env("AGENT_DESKTOP_HOME", &dir)
+ .output()
+ .expect("binary starts");
+ let envelope: serde_json::Value =
+ serde_json::from_slice(&output.stdout).expect("stdout is one JSON envelope");
+
+ assert_eq!(envelope["ok"], true);
+ assert_eq!(
+ envelope["data"]["state_root"],
+ dir.to_string_lossy().as_ref(),
+ "status must report the env value verbatim"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn invalid_state_root_env_fails_batch_as_single_envelope() {
+ let output = binary()
+ .args(["batch", "[]"])
+ .env("AGENT_DESKTOP_HOME", "relative/not-absolute")
+ .output()
+ .expect("binary starts");
+ let envelope: serde_json::Value =
+ serde_json::from_slice(&output.stdout).expect("stdout is one JSON envelope");
+
+ assert_eq!(output.status.code(), Some(1));
+ assert_eq!(envelope["ok"], false);
+ assert_eq!(envelope["command"], "batch");
+ assert_eq!(envelope["error"]["code"], "INVALID_ARGS");
+ assert!(
+ envelope.get("data").is_none(),
+ "batch must fail as one error envelope, no entry results"
+ );
+}
+
#[cfg(target_os = "macos")]
#[test]
fn malformed_permission_helper_invocation_bypasses_clap_and_tracing() {