//! First-spawn provisioning: ensure the per-agent state / claude-credentials //! dirs (btrfs subvolume when available) exist. use std::path::Path; use anyhow::{Context, Result}; /// Create the per-agent Claude credentials dir if missing. Mode 0755 — hive-core /// needs read+execute to list the directory so `claude_has_session` can detect a /// valid session; credential files inside (`.credentials.json` etc.) are 0600 so /// secrets stay private regardless of the directory mode. Idempotent: existing /// dirs are left untouched (an agent's OAuth tokens survive `destroy`/recreate). pub fn ensure_claude_dir(claude_dir: &Path) -> Result<()> { use std::io; if !claude_dir.exists() { std::fs::create_dir_all(claude_dir) .with_context(|| format!("create {}", claude_dir.display()))?; } // 0755: hive-core (different user from the agent) needs read+execute to // list the directory so `claude_has_session` can detect a valid session. // The credential files inside (`.credentials.json` etc.) are 0600 so the // secrets themselves stay private regardless of the directory mode. // // Best-effort: on the first container boot, `hive-agent-user-migrate` // chowns this dir to the agent user. After that, hive-core (a different // user) cannot chmod it (EPERM) — that's fine because the mode set during // initial creation (0755) is preserved through the chown. Any other error // (ENOENT, I/O error) is unexpected and propagated. #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; match std::fs::set_permissions(claude_dir, std::fs::Permissions::from_mode(0o755)) { Ok(()) => {} Err(e) if e.kind() == io::ErrorKind::PermissionDenied => { tracing::debug!( path = %claude_dir.display(), "ensure_claude_dir: chmod 755 skipped (dir likely owned by agent user after migration)" ); } Err(e) => { return Err(e).with_context(|| format!("chmod 755 {}", claude_dir.display())); } } } Ok(()) } /// Create the per-agent state dir if missing. Also creates the sibling /// `harness/` dir so the first harness startup can write its sqlite files /// immediately, and the sibling `work/` dir. pub fn ensure_state_dir(notes_dir: &Path) -> Result<()> { if !notes_dir.exists() { std::fs::create_dir_all(notes_dir) .with_context(|| format!("create {}", notes_dir.display()))?; } // Harness and work dirs are siblings of the agent-visible state dir. if let Some(parent) = notes_dir.parent() { for sibling in ["harness", crate::paths::WORK_SUBDIR] { let dir = parent.join(sibling); if !dir.exists() { std::fs::create_dir_all(&dir) .with_context(|| format!("create {}", dir.display()))?; } } } Ok(()) } /// Ensure agent `name`'s persistent state root /// (`/var/lib/hyperhive/agents/`) is a btrfs subvolume — when the host /// filesystem supports it — BEFORE the per-agent subdirs (`state/`, `claude/`, /// `harness/`, `work/`) are created by `ensure_state_dir` / `ensure_claude_dir`. /// /// Progressive enhancement: if the root already exists /// (any agent provisioned before this landed, plain dir or subvol) it's left /// exactly as-is — no auto-migration — and the priv round-trip is skipped. On /// a non-btrfs host the priv op no-ops and the root is later created as a /// plain dir by `ensure_*_dir`, identical to the old behaviour. Only a /// brand-new agent on a btrfs host gets a real subvolume. Subvolume creation /// is privileged, so it's delegated to hive-priv. pub async fn ensure_agent_state_subvolume(name: &str) -> Result<()> { let agent = hive_types::Ident::parse(name) .map_err(|e| anyhow::anyhow!("invalid agent name {name:?}: {e}"))?; let root = crate::paths::agent_state_dir(&agent); if root.exists() { return Ok(()); } crate::priv_client::ensure_agent_subvolume(name) .await .with_context(|| format!("ensure btrfs subvolume for agent {name}")) }