Skip to main content

agent_hub_runtime/core/automation/
backup.rs

1//! Portable definitions share the existing Git metadata namespace. Runtime
2//! registrations, wrappers, claims, logs and unrelated workspace files stay local.
3//! Customized script contents travel in the portable task definition.
4#[cfg(any(feature = "cloud-sync", test))]
5use super::workspace;
6use super::{
7    definition::{valid_id, AutomationDraft},
8    store,
9};
10use serde::{Deserialize, Serialize};
11use std::{collections::BTreeMap, path::Path};
12
13const PREFIX: &str = "automation-";
14#[cfg(any(feature = "cloud-sync", test))]
15pub(crate) mod repository;
16#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
17#[serde(deny_unknown_fields)]
18pub struct AutomationBackup {
19    pub schema_version: u32,
20    pub id: String,
21    pub shell: String,
22    pub draft: AutomationDraft,
23}
24
25pub fn shell() -> &'static str {
26    if cfg!(windows) {
27        "powershell"
28    } else {
29        "sh"
30    }
31}
32
33fn filename(id: &str) -> Result<String, String> {
34    if !valid_id(id) {
35        return Err("Invalid automation backup ID".into());
36    }
37    Ok(format!(
38        "{PREFIX}{}.json",
39        id.trim_start_matches("agent_hub:")
40    ))
41}
42
43#[cfg(any(feature = "cloud-sync", test))]
44fn portable(id: &str, mut draft: AutomationDraft) -> AutomationBackup {
45    if super::package::is_package_draft(&draft) {
46        draft.script_dir = None;
47        draft.workdir = None;
48    }
49    if let Some(path) = &draft.script_dir {
50        draft.script_dir = if workspace::is_default(path, id) {
51            None
52        } else {
53            Some(portable_path(path))
54        };
55    }
56    if let Some(path) = &draft.workdir {
57        draft.workdir = if draft.script_dir.is_none() && workspace::is_default(path, id) {
58            None
59        } else {
60            dirs::home_dir()
61                .and_then(|home| {
62                    Path::new(path).strip_prefix(home).ok().map(|relative| {
63                        format!("~/{}", relative.to_string_lossy().replace('\\', "/"))
64                    })
65                })
66                .or_else(|| Some(path.clone()))
67        };
68    }
69    AutomationBackup {
70        schema_version: 1,
71        id: id.into(),
72        shell: shell().into(),
73        draft,
74    }
75}
76
77#[cfg(any(feature = "cloud-sync", test))]
78fn portable_path(path: &str) -> String {
79    dirs::home_dir()
80        .and_then(|home| {
81            Path::new(path)
82                .strip_prefix(home)
83                .ok()
84                .map(|relative| format!("~/{}", relative.to_string_lossy().replace('\\', "/")))
85        })
86        .unwrap_or_else(|| path.into())
87}
88
89/// RepoLock is held by backup_workspace; acquire the automation lock second.
90/// Mutations only enqueue in the registry and never take RepoLock, preventing
91/// lock inversion. Clearing pending state happens after every file is durable.
92#[cfg(any(feature = "cloud-sync", test))]
93pub(crate) fn flush(metadata: &Path) -> Result<(), String> {
94    flush_from(&store::root(), metadata)
95}
96#[cfg(any(feature = "cloud-sync", test))]
97fn flush_from(root: &Path, metadata: &Path) -> Result<(), String> {
98    super::script_sync::sync_at(root)?;
99    super::libraries::flush(&super::libraries::root(), metadata)?;
100    let snapshot = store::read_registry(root)?;
101    if snapshot.tasks.is_empty() && snapshot.pending_backup.is_empty() {
102        return Ok(());
103    }
104    let _lock = store::Lock::acquire(root)?;
105    let mut registry = store::read_registry(root)?;
106    if !registry.backup_initialized {
107        for task in &registry.tasks {
108            registry
109                .pending_backup
110                .insert(task.id.clone(), Some(task.draft.clone()));
111        }
112        registry.backup_initialized = true;
113    }
114    if registry.pending_backup.is_empty() {
115        return Ok(());
116    }
117    std::fs::create_dir_all(metadata).map_err(|e| e.to_string())?;
118    if metadata.is_symlink() {
119        return Err("Automation backup metadata must not be a symbolic link".into());
120    }
121    for (id, draft) in &registry.pending_backup {
122        let path = metadata.join(filename(id)?);
123        if let Some(draft) = draft {
124            let bytes =
125                super::super::sync_metadata::canonical_json_bytes(&portable(id, draft.clone()))
126                    .map_err(|e| e.to_string())?;
127            write_changed(&path, &bytes)?;
128        } else if path.symlink_metadata().is_ok() {
129            std::fs::remove_file(path).map_err(|e| e.to_string())?;
130        }
131    }
132    registry.pending_backup.clear();
133    store::write_registry(root, &registry)
134}
135
136pub(crate) fn needs_export() -> bool {
137    super::libraries::backup::pending()
138        || store::read_registry(&store::root()).is_ok_and(|registry| {
139            !registry.pending_backup.is_empty()
140                || (!registry.backup_initialized && !registry.tasks.is_empty())
141        })
142}
143
144pub fn list() -> Result<Vec<AutomationBackup>, String> {
145    Ok(read(&super::super::sync_metadata::metadata_dir())?
146        .into_values()
147        .collect())
148}
149
150pub(super) fn read(metadata: &Path) -> Result<BTreeMap<String, AutomationBackup>, String> {
151    let mut records = BTreeMap::new();
152    if metadata.is_symlink() {
153        return Err("Automation backup metadata must not be a symbolic link".into());
154    }
155    let entries = match std::fs::read_dir(metadata) {
156        Ok(entries) => entries,
157        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(records),
158        Err(e) => return Err(e.to_string()),
159    };
160    for entry in entries {
161        let entry = entry.map_err(|e| e.to_string())?;
162        let name = entry.file_name().to_string_lossy().into_owned();
163        if !name.starts_with(PREFIX) || !name.ends_with(".json") {
164            continue;
165        }
166        if !entry.file_type().map_err(|e| e.to_string())?.is_file()
167            || entry.metadata().map_err(|e| e.to_string())?.len()
168                > super::definition::MAX_TASK_JSON_BYTES as u64
169        {
170            return Err("Invalid automation backup entry".into());
171        }
172        let record: AutomationBackup =
173            serde_json::from_slice(&std::fs::read(entry.path()).map_err(|e| e.to_string())?)
174                .map_err(|e| e.to_string())?;
175        if record.schema_version != 1
176            || filename(&record.id)? != name
177            || !["sh", "powershell"].contains(&record.shell.as_str())
178        {
179            return Err("Unsupported or mismatched automation backup".into());
180        }
181        records.insert(name, record);
182    }
183    Ok(records)
184}
185
186/// Projects only the known definition files. Importing merely stores definitions;
187/// it never registers, edits, deletes, or runs a local scheduler task.
188#[cfg(any(feature = "cloud-sync", test))]
189pub(crate) fn project(source: &Path, target: &Path) -> Result<bool, String> {
190    let records = read(source)?;
191    let changed = project_records(&records, target)?;
192    Ok(super::libraries::project(source, target)? || changed)
193}
194
195#[cfg(any(feature = "cloud-sync", test))]
196fn project_records(
197    records: &BTreeMap<String, AutomationBackup>,
198    target: &Path,
199) -> Result<bool, String> {
200    let previous = read(target)?;
201    let mut changed = false;
202    for (name, record) in records {
203        let bytes =
204            super::super::sync_metadata::canonical_json_bytes(record).map_err(|e| e.to_string())?;
205        changed |= write_changed(&target.join(name), &bytes)?;
206    }
207    for name in previous.keys().filter(|name| !records.contains_key(*name)) {
208        std::fs::remove_file(target.join(name)).map_err(|e| e.to_string())?;
209        changed = true;
210    }
211    Ok(changed)
212}
213
214#[cfg(feature = "cloud-sync")]
215pub(crate) fn differs(source: &Path, target: &Path) -> Result<bool, String> {
216    Ok(read(source)? != read(target)? || super::libraries::differs(source, target)?)
217}
218
219#[cfg(any(feature = "cloud-sync", test))]
220fn write_changed(path: &Path, bytes: &[u8]) -> Result<bool, String> {
221    if std::fs::read(path).is_ok_and(|existing| existing == bytes) {
222        return Ok(false);
223    }
224    store::write(path, bytes)?;
225    Ok(true)
226}
227
228/// Explicit restore creates a paused, usable copy. This never overwrites a local task.
229pub fn restore(id: &str, apply: bool) -> Result<AutomationBackup, String> {
230    let mut record = list()?
231        .into_iter()
232        .find(|record| record.id == id)
233        .ok_or("Automation backup not found")?;
234    record.draft.enabled = false;
235    record.draft.script_dir = None;
236    record.draft.workdir = None;
237    if apply {
238        if record.draft.provider == super::Provider::System && record.shell != shell() {
239            return Err(
240                "This backup uses another shell; edit its command before creating a local task"
241                    .into(),
242            );
243        }
244        record.draft.script_dir = None;
245        if let Some(options) = &record.draft.package_options {
246            for dependency in &options.dependencies {
247                if let super::package::Dependency::Library { name } = dependency {
248                    super::libraries::validate_name(name)?;
249                    if !super::libraries::root().join(name).exists() {
250                        super::libraries::restore(name, None, true)?;
251                    }
252                }
253            }
254        }
255        record.id = super::save(None, None, record.draft.clone())?;
256    }
257    Ok(record)
258}
259
260#[cfg(test)]
261mod tests;