Skip to main content

gent_daemon/config/
host_recovery.rs

1//! Node-local opt-in to restore selected native conversations. Never replicated.
2use super::*;
3use serde::{Deserialize, Serialize};
4
5pub const MAX_RECOVERY_AGENTS: usize = 32;
6
7#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(deny_unknown_fields)]
9pub struct HostRecovery {
10    pub version: u8,
11    pub cluster_id: String,
12    pub node_id: String,
13    pub agents: BTreeMap<String, RecoveryAgent>,
14}
15
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
17#[serde(rename_all = "snake_case")]
18pub enum RecoveryHost {
19    #[default]
20    Codex,
21    ClaudeCode,
22}
23impl RecoveryHost {
24    fn is_codex(&self) -> bool {
25        *self == Self::Codex
26    }
27}
28
29#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(deny_unknown_fields)]
31pub struct RecoveryAgent {
32    #[serde(default, skip_serializing_if = "RecoveryHost::is_codex")]
33    pub host: RecoveryHost,
34    pub id: String,
35    pub thread_id: String,
36    pub config_dir: PathBuf,
37    pub host_binary: PathBuf,
38    pub credential_hash: String,
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub working_dir: Option<PathBuf>,
41}
42
43fn identifier(value: &str) -> Result<()> {
44    let id = uuid::Uuid::parse_str(value)?;
45    ensure!(
46        !id.is_nil() && id.to_string() == value,
47        "invalid host recovery identity"
48    );
49    Ok(())
50}
51
52impl HostRecovery {
53    pub fn new(config: &Config) -> Self {
54        Self {
55            version: 1,
56            cluster_id: config.cluster.id.clone(),
57            node_id: config.node.id.clone(),
58            agents: BTreeMap::new(),
59        }
60    }
61
62    fn validate(&self, config: &Config) -> Result<()> {
63        ensure!(
64            matches!(self.version, 1 | 2)
65                && self.cluster_id == config.cluster.id
66                && self.node_id == config.node.id
67                && self.agents.len() <= MAX_RECOVERY_AGENTS,
68            "host recovery belongs to another node, is unsupported or exceeds its limit"
69        );
70        let mut targets = std::collections::BTreeSet::new();
71        for (agent, entry) in &self.agents {
72            ensure!(
73                (entry.host == RecoveryHost::Codex && entry.working_dir.is_none())
74                    || (self.version == 2
75                        && entry.host == RecoveryHost::ClaudeCode
76                        && entry.working_dir.is_some()),
77                "host recovery target has an unsupported host or working directory"
78            );
79            identifier(agent)?;
80            identifier(&entry.id)?;
81            identifier(&entry.thread_id)?;
82            for path in [&entry.config_dir, &entry.host_binary]
83                .into_iter()
84                .chain(entry.working_dir.as_ref())
85            {
86                ensure!(
87                    path.is_absolute()
88                        && path
89                            .to_str()
90                            .is_some_and(|s| !s.chars().any(char::is_control) && s.len() <= 4096),
91                    "host recovery paths must be absolute UTF-8 paths without controls"
92                );
93            }
94            ensure!(
95                entry.credential_hash.len() == 64
96                    && entry
97                        .credential_hash
98                        .bytes()
99                        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
100                "invalid host recovery credential binding"
101            );
102            ensure!(
103                targets.insert((entry.host, &entry.config_dir, &entry.thread_id)),
104                "host recovery has a duplicate conversation"
105            );
106        }
107        Ok(())
108    }
109}
110
111impl Config {
112    pub fn host_recovery(&self) -> Result<Option<HostRecovery>> {
113        self.extra
114            .get("host_recovery")
115            .cloned()
116            .map(|value| {
117                let saved: HostRecovery = value
118                    .try_into()
119                    .context("invalid host recovery configuration")?;
120                saved.validate(self)?;
121                Ok(saved)
122            })
123            .transpose()
124    }
125
126    pub fn set_host_recovery(&mut self, mut value: HostRecovery) -> Result<()> {
127        if value
128            .agents
129            .values()
130            .any(|entry| entry.host == RecoveryHost::ClaudeCode)
131        {
132            value.version = 2;
133        }
134        value.validate(self)?;
135        self.extra
136            .insert("host_recovery".into(), toml::Value::try_from(value)?);
137        self.update_local_version()
138    }
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    fn entry() -> RecoveryAgent {
146        RecoveryAgent {
147            host: RecoveryHost::Codex,
148            working_dir: None,
149            id: uuid::Uuid::new_v4().to_string(),
150            thread_id: uuid::Uuid::new_v4().to_string(),
151            config_dir: "/private/codex".into(),
152            host_binary: "/private/bin/codex".into(),
153            credential_hash: "a".repeat(64),
154        }
155    }
156
157    #[test]
158    fn legacy_codex_entries_round_trip_and_claude_requires_versioned_cwd() {
159        let mut cfg = fresh("test").unwrap();
160        let id = uuid::Uuid::new_v4().to_string();
161        let mut selected = HostRecovery::new(&cfg);
162        selected.agents.insert(id.clone(), entry());
163        let legacy = toml::to_string(&selected).unwrap();
164        assert!(!legacy.contains("host =") && !legacy.contains("working_dir"));
165        assert_eq!(toml::from_str::<HostRecovery>(&legacy).unwrap(), selected);
166        selected.agents.get_mut(&id).unwrap().host = RecoveryHost::ClaudeCode;
167        assert!(cfg.set_host_recovery(selected.clone()).is_err());
168        selected.agents.get_mut(&id).unwrap().working_dir = Some("/work".into());
169        assert!(selected.validate(&cfg).is_err());
170        cfg.set_host_recovery(selected).unwrap();
171        let mut selected = cfg.host_recovery().unwrap().unwrap();
172        assert_eq!(selected.version, 2);
173        assert_eq!(
174            toml::from_str::<HostRecovery>(&toml::to_string(&selected).unwrap()).unwrap(),
175            selected
176        );
177        selected.agents.get_mut(&id).unwrap().working_dir = Some("relative".into());
178        assert!(cfg.set_host_recovery(selected).is_err());
179    }
180
181    #[test]
182    fn projections_preserve_enabled_and_removed_recovery_selections() {
183        let root = tempfile::tempdir().unwrap();
184        std::fs::set_permissions(root.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
185        let original = initialize(root.path(), "local").unwrap();
186        let agent = uuid::Uuid::new_v4().to_string();
187        let mut selected = HostRecovery::new(&original);
188        selected.agents.insert(agent.clone(), entry());
189        edit_local(root.path(), |cfg| cfg.set_host_recovery(selected.clone())).unwrap();
190        save(root.path(), &original).unwrap();
191        let enabled = load(root.path()).unwrap();
192        assert_eq!(enabled.version, 3);
193        assert_eq!(enabled.host_recovery().unwrap(), Some(selected));
194        edit_local(root.path(), |cfg| {
195            let mut selected = cfg.host_recovery()?.unwrap();
196            selected.agents.clear();
197            cfg.set_host_recovery(selected)
198        })
199        .unwrap();
200        save(root.path(), &enabled).unwrap();
201        assert!(
202            load(root.path())
203                .unwrap()
204                .host_recovery()
205                .unwrap()
206                .unwrap()
207                .agents
208                .is_empty()
209        );
210        let mut foreign = fresh("foreign").unwrap();
211        foreign.extra = enabled.extra;
212        foreign.version = 3;
213        assert!(foreign.validate_local().is_err());
214    }
215
216    #[test]
217    fn recovery_scope_paths_duplicates_and_feature_marker_are_validated() {
218        let mut cfg = fresh("test").unwrap();
219        let agent = uuid::Uuid::new_v4().to_string();
220        let mut selected = HostRecovery::new(&cfg);
221        selected.agents.insert(agent.clone(), entry());
222        cfg.set_host_recovery(selected.clone()).unwrap();
223        cfg.validate_local().unwrap();
224        let mut downgrade = cfg.clone();
225        downgrade.extra.remove("local_features");
226        assert!(downgrade.validate_local().is_err());
227        let mut changed = selected.clone();
228        changed.agents.get_mut(&agent).unwrap().host_binary = "relative".into();
229        assert!(cfg.set_host_recovery(changed).is_err());
230        let mut changed = selected.clone();
231        changed.agents.get_mut(&agent).unwrap().credential_hash = "X".repeat(64);
232        assert!(cfg.set_host_recovery(changed).is_err());
233        let mut changed = selected.clone();
234        changed.agents.insert(
235            uuid::Uuid::new_v4().to_string(),
236            selected.agents[&agent].clone(),
237        );
238        assert!(cfg.set_host_recovery(changed).is_err());
239        for _ in 0..MAX_RECOVERY_AGENTS {
240            selected
241                .agents
242                .insert(uuid::Uuid::new_v4().to_string(), entry());
243        }
244        assert!(cfg.set_host_recovery(selected).is_err());
245    }
246}