agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! Separate Git worktree from the shared live Skills library.
//! Callers hold RepoLock across projection, Git operations and publication.
mod files;
#[cfg(test)]
mod tests;
mod user_config;
use super::{central_repo, git_backup, skill_store::SkillStore, sync_metadata};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::{
    collections::{BTreeMap, BTreeSet},
    fs,
    path::{Component, Path, PathBuf},
};

const LAYOUT: &str = ".agent-hub/backup-layout.json";
const LEGACY_README: &str = "# Skills\n\nInstall all or selected skills with:\n\n```sh\nnpx skills@latest add <repository-url>\nnpx skills@latest add <repository-url> --skill <skill-name>\n```\n\nSkills are in `skills/`, each with its original `SKILL.md` and supporting files.\n`.agent-hub/` contains portable AgentHub sync metadata.\nPrivate repositories require Git access on the installing machine.\n";
const README: &str = "# AgentHub backup\n\n- `skills/`: installable Skills with `SKILL.md` and supporting files.\n- `automations/`: installable task directories with `task.json`, scripts and prompts.\n- `user-config/`: portable user configuration, including complete Hosts profiles.\n- `.agent-hub/`: portable sync metadata.\n\nInstall Skills with `npx skills@latest add <repository-url>`. Preview automation packages through AgentHub Discover → Automations → Git install. Restored tasks require local configuration and installation before use.\n\nCredentials, installation receipts, private environments and run history stay on the original device. Private repositories require Git access on the installing machine.\n";

fn write_readme(root: &Path) -> Result<()> {
    let path = root.join("README.md");
    match fs::read_to_string(&path) {
        Ok(contents) if contents == LEGACY_README => fs::write(path, README)?,
        Ok(_) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => fs::write(path, README)?,
        Err(error) => return Err(error.into()),
    }
    Ok(())
}

/// Local backup Git repository; respects isolated app/CLI roots.
pub fn repo_dir() -> PathBuf {
    central_repo::base_dir().join("backup")
}
fn journal_path() -> PathBuf {
    central_repo::base_dir().join("backup-publication.json")
}

#[derive(Serialize, Deserialize)]
struct Journal {
    live_root: PathBuf,
    before: BTreeMap<String, String>,
    #[serde(default)]
    user_config_before: Option<BTreeMap<String, String>>,
    recovery: PathBuf,
}

/// Run a complete desktop or CLI operation under the shared library lock.
pub fn run<T>(
    store: &SkillStore,
    operation: &str,
    f: impl FnOnce(&Path) -> Result<T>,
) -> Result<T> {
    git_backup::with_repo_lock(operation, || run_unlocked(store, f))
}

pub(crate) fn run_unlocked<T>(store: &SkillStore, f: impl FnOnce(&Path) -> Result<T>) -> Result<T> {
    prepare_unlocked(store).context("Cannot prepare backup repository")?;
    let root = repo_dir();
    let result = f(&root);
    // A failed push may follow a successful merge. Publish that coherent local
    // result too, so a subsequent export cannot erase the merge.
    finish_unlocked(store).context("Cannot publish backup result to Skills")?;
    result
}

/// Projection for a read-only status refresh, without changing live content.
pub fn status(store: &SkillStore) -> Result<git_backup::GitBackupStatus> {
    run(store, "backup status", git_backup::get_status)
}

pub fn file_diff(path: &str) -> Result<git_backup::GitBackupFileDiff> {
    let root = repo_dir();
    let path = path.to_string();
    git_backup::with_repo_lock("backup file diff", move || {
        git_backup::get_file_diff(&root, &path)
    })
}

pub fn initialize(store: &SkillStore) -> Result<()> {
    run(store, "backup init", |root| {
        if root.join(".git").exists() {
            commit_if_dirty(root, "Use portable Skills backup layout")
        } else {
            git_backup::init_repo_unlocked(root, &git_backup::default_device_name())
        }
    })
}

pub fn commit(store: &SkillStore, message: &str) -> Result<String> {
    run(store, "backup commit", |root| {
        commit_if_dirty(root, message)?;
        git_backup::create_snapshot_tag_unlocked(root)
    })
}

pub fn pull(store: &SkillStore) -> Result<super::merge::MergeSummary> {
    run(store, "backup pull", |root| {
        super::merge::gated_pull_unlocked(store, root)
    })
}

pub fn restore(store: &SkillStore, tag: &str) -> Result<String> {
    run(store, "backup restore", |root| {
        commit_if_dirty(root, "backup before restore")?;
        git_backup::restore_snapshot_version_unlocked(root, tag)
    })
}

fn commit_if_dirty(root: &Path, message: &str) -> Result<()> {
    if git_backup::has_uncommitted_changes(root)? {
        git_backup::commit_all_unlocked(root, message)?;
    }
    Ok(())
}

pub fn clone_repo(store: &SkillStore, url: &str, strict: bool) -> Result<()> {
    git_backup::with_repo_lock("backup clone", || {
        if strict
            && files::names(&central_repo::skills_dir())?
                .iter()
                .any(|name| files::content_name(name))
        {
            bail!("Explicit Skills directory must be empty before cloning");
        }
        run_unlocked(store, |root| clone_unlocked(root, url))
    })
}

/// Complete an interrupted publication before configuration access. Caller holds RepoLock.
pub(crate) fn recover_for_user_config() -> Result<()> {
    if journal_path().try_exists()? {
        let store = SkillStore::new(&central_repo::db_path())?;
        finish_unlocked(&store)?;
    }
    Ok(())
}

pub(crate) fn recover_on_startup(store: &SkillStore) {
    if journal_path().exists() {
        if let Err(error) = git_backup::with_repo_lock("backup recovery", || finish_unlocked(store))
        {
            log::warn!("backup publication recovery: {error:#}");
        }
    }
}

/// Clone first; normalize legacy layout before carrying local-only Skills.
/// The previous repository and its complete history remain in recovery.
pub(crate) fn clone_unlocked(root: &Path, url: &str) -> Result<()> {
    let stage = tempfile::tempdir_in(central_repo::base_dir())?;
    let checkout = stage.path().join("checkout");
    git_backup::clone_into_unlocked(&checkout, url)?;
    normalize_layout(&checkout)?;
    carry_local_only(&root.join("skills"), &checkout.join("skills"))?;
    super::user_config::validate_tree(&root.join("user-config"))?;
    super::user_config::validate_tree(&checkout.join("user-config"))?;
    carry_local_only(&root.join("user-config"), &checkout.join("user-config"))?;
    // Restore does not discard tags/IDs of Skills present only on this device.
    let remote_meta = read_metadata(&checkout.join(".agent-hub/skills"))?;
    for (path, meta) in read_metadata(&root.join(".agent-hub/skills"))? {
        validate_relative(&meta.path)?;
        if checkout.join(&meta.path).is_dir()
            && !remote_meta.iter().any(|(_, other)| {
                other.skill_id == meta.skill_id || other.path_key == meta.path_key
            })
        {
            let target = checkout
                .join(".agent-hub/skills")
                .join(path.file_name().context("Metadata file has no name")?);
            fs::create_dir_all(target.parent().context("Metadata has no parent")?)?;
            fs::copy(path, target)?;
        }
    }
    let recovery = central_repo::base_dir()
        .join("recovery")
        .join(format!("repository-{}", uuid::Uuid::new_v4()));
    fs::create_dir_all(recovery.parent().context("Recovery has no parent")?)?;
    fs::rename(root, &recovery)?;
    if let Err(error) = fs::rename(&checkout, root) {
        fs::rename(recovery, root)?;
        return Err(error.into());
    }
    Ok(())
}

fn carry_local_only(source: &Path, target: &Path) -> Result<()> {
    for name in files::names(source)? {
        let from = source.join(&name);
        let to = target.join(name);
        if to
            .symlink_metadata()
            .is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound)
        {
            files::copy(&from, &to, false)?;
        } else if from.is_dir()
            && to.is_dir()
            && !to.is_symlink()
            && !from.join("SKILL.md").is_file()
            && !to.join("SKILL.md").is_file()
        {
            carry_local_only(&from, &to)?;
        }
    }
    Ok(())
}

fn ensure_repo() -> Result<()> {
    let root = repo_dir();
    let live = central_repo::skills_dir();
    if root.starts_with(&live) || live.starts_with(&root) {
        bail!("Backup and live Skills directories must be independent");
    }
    if root.is_symlink() {
        bail!("Backup directory must not be a symbolic link");
    }
    if live.join(".agent-hub").is_symlink() {
        bail!("Skills metadata directory must not be a symbolic link");
    }
    if !root.exists() && live.join(".git").exists() {
        if !live.join(".git").is_dir() || live.join(".git").is_symlink() {
            bail!("Linked Git worktrees require an independent backup repository");
        }
        git_backup::ensure_no_interrupted_git_operation(&live)?;
        let stage = tempfile::tempdir_in(central_repo::base_dir())?;
        let copy = stage.path().join("repo");
        files::copy(&live, &copy, true)?;
        let mut config = git2::Config::open(&copy.join(".git/config"))?;
        if config.get_string("core.worktree").is_ok() {
            config.remove("core.worktree")?;
        }
        // Preserve all Git refs/history/config; the source is retained intact.
        normalize_layout(&copy)?;
        fs::rename(copy, &root)?;
    }
    fs::create_dir_all(&root)?;
    normalize_layout(&root)
}

/// Accept older flat backups and standard skills/ repositories without
/// rewriting history. The next backup commit records the layout transition.
pub(crate) fn normalize_layout(root: &Path) -> Result<()> {
    if root.join(".agent-hub").is_symlink() || root.join("skills").is_symlink() {
        bail!("Linked backup layout is not supported");
    }
    if root.join(LAYOUT).is_file() {
        write_readme(root)?;
        return Ok(());
    }
    let metadata = root.join(".agent-hub/skills");
    let metas = read_metadata(&metadata)?;
    let nested = root.join("skills").is_dir()
        && !root.join("skills/SKILL.md").is_file()
        && (metas.is_empty()
            || metas
                .iter()
                .all(|(_, meta)| meta.path.starts_with("skills/")));
    if !nested {
        for (_, meta) in &metas {
            validate_relative(&meta.path)?;
        }
        let stage = tempfile::tempdir_in(root.parent().context("Backup has no parent")?)?;
        let content = stage.path().join("skills");
        fs::create_dir(&content)?;
        let names: Vec<_> = files::names(root)?
            .into_iter()
            .filter(|name| name != "automations" && name != "user-config")
            .filter(|name| files::content_name(name))
            .collect();
        for name in &names {
            files::copy_skill(&root.join(name), &content.join(name))?;
        }
        // Persist originals before replacing layout; an error or crash never
        // drops moved content with a temporary directory.
        let recovery = central_repo::base_dir()
            .join("recovery")
            .join(format!("layout-{}", uuid::Uuid::new_v4()));
        for name in &names {
            fs::create_dir_all(&recovery)?;
            fs::rename(root.join(name), recovery.join(name))?;
        }
        fs::rename(content, root.join("skills"))?;
        for (path, mut meta) in metas {
            validate_relative(&meta.path)?;
            meta.path = format!("skills/{}", meta.path);
            meta.path_key = sync_metadata::path_key(&meta.path);
            fs::write(path, sync_metadata::canonical_json_bytes(&meta)?)?;
        }
    }
    fs::create_dir_all(root.join(".agent-hub"))?;
    fs::write(root.join(LAYOUT), b"{\"version\":1}\n")?;
    write_readme(root)?;
    Ok(())
}

fn validate_relative(path: &str) -> Result<()> {
    if path.is_empty()
        || path.contains('\\')
        || path.contains(':')
        || Path::new(path)
            .components()
            .any(|c| !matches!(c, Component::Normal(_)))
    {
        bail!("Invalid backup Skill path");
    }
    Ok(())
}

fn read_metadata(root: &Path) -> Result<Vec<(PathBuf, sync_metadata::SkillMetaFile)>> {
    let mut result = Vec::new();
    for name in files::names(root)? {
        if name.ends_with(".json") {
            let path = root.join(name);
            result.push((path.clone(), serde_json::from_slice(&fs::read(path)?)?));
        }
    }
    Ok(result)
}

pub(crate) fn prepare_unlocked(store: &SkillStore) -> Result<()> {
    fs::create_dir_all(central_repo::base_dir())?;
    if journal_path().exists() {
        finish_unlocked(store)?;
    }
    super::hosts::profiles::recover_pending().map_err(anyhow::Error::msg)?;
    ensure_repo()?;
    let root = repo_dir();
    if root.join(".git").exists() {
        git_backup::ensure_no_interrupted_git_operation(&root)?;
    }
    super::shared_skill_index::register_missing(store)?;
    super::automation::backup::flush(&sync_metadata::metadata_dir()).map_err(anyhow::Error::msg)?;
    sync_metadata::write_all_from_db_unlocked(store)?;
    let live = central_repo::skills_dir();
    let before = files::snapshot(&live)?;
    if before != files::snapshot(&root.join("skills"))? {
        let stage = tempfile::tempdir_in(&root)?;
        let content = stage.path().join("skills");
        fs::create_dir(&content)?;
        for name in before.keys() {
            files::copy_skill(&live.join(name), &content.join(name))?;
        }
        if before != files::snapshot(&live)? || before != files::snapshot(&content)? {
            bail!("Skills changed during backup; retry sync");
        }
        files::remove(&root.join("skills"))?;
        fs::rename(content, root.join("skills"))?;
    }
    if before != files::snapshot(&live)? {
        bail!("Skills changed during backup; retry sync");
    }
    project_metadata(&live.join(".agent-hub"), &root.join(".agent-hub"), true)?;
    fs::write(root.join(LAYOUT), b"{\"version\":1}\n")?;
    let user_config_before = Some(user_config::export(&root)?);
    let journal = Journal {
        live_root: live,
        before,
        user_config_before,
        recovery: central_repo::base_dir()
            .join("recovery")
            .join(format!("backup-{}", uuid::Uuid::new_v4())),
    };
    let journal_tmp = central_repo::base_dir().join("backup-publication.tmp");
    fs::write(&journal_tmp, serde_json::to_vec(&journal)?)?;
    fs::rename(journal_tmp, journal_path())?;
    Ok(())
}

fn project_metadata(source: &Path, target: &Path, exporting: bool) -> Result<()> {
    if exporting {
        super::automation::backup::repository::export(
            source,
            target.parent().context("Missing backup root")?,
        )
    } else {
        super::automation::backup::repository::import(
            source.parent().context("Missing backup root")?,
            target,
        )
        .map(|_| ())
    }
    .map_err(anyhow::Error::msg)?;
    // Only portable schema/records, never sync protocol files or local state.
    for name in ["schema.json", "skills", "scenarios", "scenario-skills"] {
        files::remove(&target.join(name))?;
        if source.join(name).exists() {
            files::copy(&source.join(name), &target.join(name), false)?;
        }
    }
    for (path, mut meta) in read_metadata(&target.join("skills"))? {
        validate_relative(&meta.path)?;
        meta.path = if exporting {
            format!("skills/{}", meta.path)
        } else {
            meta.path
                .strip_prefix("skills/")
                .context("Backup Skill is outside skills/")?
                .to_string()
        };
        validate_relative(&meta.path)?;
        meta.path_key = sync_metadata::path_key(&meta.path);
        fs::write(path, sync_metadata::canonical_json_bytes(&meta)?)?;
    }
    Ok(())
}

/// Replayable publication: changed originals remain in recovery. Concurrent
/// external edits stop publication instead of being replaced by remote data.
pub(crate) fn finish_unlocked(store: &SkillStore) -> Result<()> {
    if !journal_path().exists() {
        return Ok(());
    }
    let journal: Journal = serde_json::from_slice(&fs::read(journal_path())?)?;
    let root = repo_dir();
    if journal.live_root != central_repo::skills_dir() {
        bail!("Pending backup belongs to another Skills directory");
    }
    if root.join(".git").exists() {
        git_backup::ensure_no_interrupted_git_operation(&root)?;
    }
    normalize_layout(&root)?;
    let desired = files::snapshot(&root.join("skills"))?;
    let names: BTreeSet<_> = journal.before.keys().chain(desired.keys()).collect();
    let changed: Vec<_> = names
        .into_iter()
        .filter(|name| journal.before.get(*name) != desired.get(*name))
        .collect();
    // Validate the entire restore before moving any live entry, including
    // symlinks from untrusted remotes and metadata traversal.
    let stage = tempfile::tempdir_in(
        journal
            .live_root
            .parent()
            .context("Skills directory has no parent")?,
    )?;
    project_metadata(
        &root.join(".agent-hub"),
        &stage.path().join(".agent-hub"),
        false,
    )?;
    let metadata_changed = super::automation::backup::differs(
        &stage.path().join(".agent-hub"),
        &journal.live_root.join(".agent-hub"),
    )
    .map_err(anyhow::Error::msg)?
        || ["schema.json", "skills", "scenarios", "scenario-skills"]
            .iter()
            .try_fold(false, |changed, name| -> Result<bool> {
                Ok(changed
                    || files::fingerprint(&stage.path().join(".agent-hub").join(name))?
                        != files::fingerprint(&journal.live_root.join(".agent-hub").join(name))?)
            })?;
    let config_changed = user_config::stage(&journal, &root, stage.path())?;
    if changed.is_empty() && !metadata_changed && !config_changed {
        fs::remove_file(journal_path())?;
        return Ok(());
    }
    for name in &changed {
        let current = files::fingerprint(&journal.live_root.join(name))?;
        let original_saved = journal.recovery.join(name).symlink_metadata().is_ok();
        if current.as_ref() != journal.before.get(*name)
            && current.as_ref() != desired.get(*name)
            && !(current.is_none() && original_saved)
        {
            bail!("Skills changed while syncing; backup result retained for recovery, retry after preserving local edits");
        }
        if desired.contains_key(*name) {
            files::copy(
                &root.join("skills").join(name),
                &stage.path().join(name),
                false,
            )?;
        }
    }
    for name in changed {
        let target = journal.live_root.join(name);
        let current = files::fingerprint(&target)?;
        if current.as_ref() == desired.get(name) {
            continue;
        }
        if current.as_ref() != journal.before.get(name)
            && !(current.is_none() && journal.recovery.join(name).symlink_metadata().is_ok())
        {
            bail!("Skills changed during restore; originals and backup retained");
        }
        fs::create_dir_all(&journal.recovery)?;
        if target.symlink_metadata().is_ok() {
            if journal.recovery.join(name).symlink_metadata().is_ok() {
                bail!("Recovery entry already exists; live Skills preserved");
            }
            fs::rename(&target, journal.recovery.join(name))?;
        }
        if desired.contains_key(name) {
            if target.symlink_metadata().is_ok() {
                bail!("Skills recreated during restore; originals retained");
            }
            fs::rename(stage.path().join(name), &target)?;
        }
    }
    for name in ["schema.json", "skills", "scenarios", "scenario-skills"] {
        let target = journal.live_root.join(".agent-hub").join(name);
        files::remove(&target)?;
        let source = stage.path().join(".agent-hub").join(name);
        if source.exists() {
            files::copy(&source, &target, false)?;
        }
    }
    crate::commands::git_backup::reconcile_skills_index_unlocked(store)?;
    super::automation::backup::project(
        &stage.path().join(".agent-hub"),
        &journal.live_root.join(".agent-hub"),
    )
    .map_err(anyhow::Error::msg)?;
    if config_changed {
        user_config::publish(&journal, stage.path())?;
    }
    fs::remove_file(journal_path())?;
    Ok(())
}

/// Legacy low-level callers still project metadata themselves. A separated
/// worktree has already been projected by its enclosing transaction.
pub(crate) fn write_metadata(store: &SkillStore, root: &Path) -> Result<()> {
    if root == repo_dir() {
        Ok(())
    } else {
        sync_metadata::write_all_from_db_unlocked(store)
    }
}

pub(crate) fn reconcile(store: &SkillStore, root: &Path) -> Result<()> {
    if root == repo_dir() {
        Ok(())
    } else {
        crate::commands::git_backup::reconcile_skills_index_unlocked(store)
    }
}