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
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;

use anyhow::{Context, Result};

use super::{
    central_repo, scenario_service, skill_metadata, skill_store::SkillStore, sync_engine,
    sync_metadata, tool_adapters, tool_service,
};

/// Per-stage timings collected during `initialize_store`. The struct is
/// returned to the caller so the log lines can be emitted once
/// `tauri_plugin_log` is registered — anything logged from inside this
/// function would otherwise be dropped because the logger isn't installed
/// until later in `tauri::Builder::setup`. See issue #153.
#[derive(Debug, Clone)]
pub struct StartupTimings {
    pub ensure_central_repo_ms: u128,
    pub open_store_ms: u128,
    pub migrate_legacy_tool_keys_ms: u128,
    pub skill_count: usize,
    pub reindex_from_metadata_ms: Option<u128>,
    pub restore_sync_included_ms: u128,
    pub restore_sync_included_changed: bool,
    pub write_all_from_db_ms: Option<u128>,
    pub apply_scenario_ms: u128,
    /// "default_startup" (Tauri app) or "cli" (CLI bin). Defaults to
    /// `"unknown"` so a struct that escapes `initialize_store_inner`
    /// without being fully populated still produces an obvious value in
    /// the log instead of an empty string.
    pub apply_scenario_kind: &'static str,
    pub total_ms: u128,
}

impl Default for StartupTimings {
    fn default() -> Self {
        Self {
            ensure_central_repo_ms: 0,
            open_store_ms: 0,
            migrate_legacy_tool_keys_ms: 0,
            skill_count: 0,
            reindex_from_metadata_ms: None,
            restore_sync_included_ms: 0,
            restore_sync_included_changed: false,
            write_all_from_db_ms: None,
            apply_scenario_ms: 0,
            apply_scenario_kind: "unknown",
            total_ms: 0,
        }
    }
}

pub fn initialize_store() -> Result<(Arc<SkillStore>, StartupTimings)> {
    initialize_store_inner(true, true)
}

pub fn initialize_cli_store() -> Result<Arc<SkillStore>> {
    initialize_store_inner(false, false).map(|(store, _)| store)
}

fn reindex_or_rebuild_metadata(store: &SkillStore) -> Result<()> {
    let Err(err) = sync_metadata::reindex_from_metadata(store) else {
        return Ok(());
    };
    // #421: empty skill metadata used to abort every launch. When the
    // database still holds a library whose directories all exist, it is the
    // better record: rebuild the metadata from it. Otherwise keep refusing —
    // starting with an empty library would let the auto backup commit that
    // emptiness.
    if err.is::<sync_metadata::EmptySkillMetadata>()
        && (db_library_is_intact(store) || super::shared_skill_index::is_shared())
    {
        central_repo::record_startup_error(format!(
            "sync metadata: {err}; rebuilt it from the database"
        ));
        return sync_metadata::with_repo_lock("rebuild shared skills metadata", || {
            super::shared_skill_index::refresh(store)?;
            sync_metadata::write_all_from_db_unlocked(store)
        })
        .context("Failed to rebuild sync metadata from the database");
    }
    Err(err.context("Failed to reindex from sync metadata"))
}

/// The database can stand in for empty metadata only if it covers the whole
/// library: non-empty, every record's directory exists, and every skill
/// directory in the central repo has a record.
fn db_library_is_intact(store: &SkillStore) -> bool {
    let Ok(skills) = store.get_all_skills() else {
        return false;
    };
    let canon = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
    let mut recorded = std::collections::HashSet::new();
    for skill in &skills {
        let path = Path::new(&skill.central_path);
        if !path.is_dir() {
            return false;
        }
        recorded.insert(canon(path));
    }
    if recorded.is_empty() {
        return false;
    }
    let mut walk = walkdir::WalkDir::new(central_repo::skills_dir())
        .min_depth(1)
        .max_depth(6)
        .into_iter()
        .filter_entry(|e| {
            let name = e.file_name().to_string_lossy();
            name != ".git" && name != ".agent-hub"
        });
    while let Some(entry) = walk.next() {
        let Ok(entry) = entry else {
            return false;
        };
        if entry.file_type().is_dir() && skill_metadata::is_valid_skill_dir(entry.path()) {
            if !recorded.contains(&canon(entry.path())) {
                return false;
            }
            // A skill's own subfolders are its content, not more skills.
            walk.skip_current_dir();
        }
    }
    true
}

/// For CLI `repo set-path` / `reset-path`: also carry out the move now, unless
/// the app is running (it then moves at its next launch).
pub fn initialize_cli_store_moving_repo() -> Result<Arc<SkillStore>> {
    initialize_store_inner(false, true).map(|(store, _)| store)
}

fn initialize_store_inner(
    apply_startup_default: bool,
    allow_migration: bool,
) -> Result<(Arc<SkillStore>, StartupTimings)> {
    let total_start = Instant::now();
    let mut timings = StartupTimings::default();

    let step = Instant::now();
    central_repo::ensure_central_repo(allow_migration).context("Failed to create central repo")?;
    timings.ensure_central_repo_ms = step.elapsed().as_millis();

    let db_path = central_repo::db_path();
    let step = Instant::now();
    let store = Arc::new(SkillStore::new(&db_path).context("Failed to initialize database")?);
    super::git_auth_source::set_preference(
        store
            .get_setting(super::git_auth_source::SETTING_USE_GH)?
            .as_deref(),
    );
    timings.open_store_ms = step.elapsed().as_millis();

    let step = Instant::now();
    tool_service::migrate_legacy_tool_keys(&store)
        .map_err(|e| anyhow::anyhow!(e.to_string()))
        .context("Failed to migrate legacy tool keys")?;
    timings.migrate_legacy_tool_keys_ms = step.elapsed().as_millis();

    if allow_migration {
        if let Some((from, to)) = central_repo::take_repoint_from() {
            // Never fatal: the library itself is intact at `to`. Keep the
            // marker while anything failed, so the next launch retries.
            let done = match repoint_after_move(&store, &from, &to) {
                Ok(failures) => failures == 0,
                Err(err) => {
                    central_repo::record_startup_error(format!(
                        "central repo: repointing paths after the move failed ({err:#})"
                    ));
                    false
                }
            };
            if done {
                if let Err(err) = central_repo::clear_repoint_from() {
                    central_repo::record_startup_error(format!(
                        "central repo: cannot clear the repoint marker ({err:#}); it will rerun"
                    ));
                }
            }
        }
    }

    if let Some((from, to)) = central_repo::take_shared_repoint_from()? {
        let failures = sync_metadata::with_repo_lock("repoint shared skills", || {
            repoint_after_move(&store, &from, &to)
        })?;
        if failures == 0 {
            central_repo::clear_shared_repoint_from()?;
        }
    }

    // The one-time shared-library migration can finish before a skill is
    // imported. In that case an older Agent link still points at the former
    // `~/.agents/skills` root and has no target row to identify it as ours.
    // Re-run the narrow, path-based repair on every startup so those links do
    // not become permanent deployment conflicts. `repoint_after_move` only
    // touches links whose raw target is inside the known legacy root.
    let legacy = central_repo::legacy_default_skills_dir();
    let current = central_repo::default_skills_dir();
    if central_repo::skills_dir() == current
        && legacy != current
        && legacy.symlink_metadata().is_ok()
    {
        match repoint_after_move(&store, &legacy, &current) {
            Ok(failures) if failures > 0 => {
                log::warn!("startup: could not repair {failures} legacy Agent skill link(s)")
            }
            Ok(_) => {}
            Err(err) => log::warn!("startup: legacy Agent link repair failed: {err:#}"),
        }
    }

    timings.skill_count = store.get_all_skills().map(|s| s.len()).unwrap_or(0);

    if sync_metadata::metadata_exists() {
        let step = Instant::now();
        reindex_or_rebuild_metadata(&store)?;
        timings.reindex_from_metadata_ms = Some(step.elapsed().as_millis());
    }

    let step = Instant::now();
    let changed = scenario_service::restore_all_skills_sync_included(&store)
        .map_err(|e| anyhow::anyhow!(e.to_string()))
        .context("Failed to restore skill sync inclusion")?;
    let (changed, write_ms) = sync_metadata::with_repo_lock("index shared skills", || {
        let changed = super::shared_skill_index::refresh(&store)? || changed;
        let write_start = Instant::now();
        if changed {
            sync_metadata::write_all_from_db_unlocked(&store)?;
        }
        Ok((changed, changed.then(|| write_start.elapsed().as_millis())))
    })?;
    timings.restore_sync_included_ms = step.elapsed().as_millis();
    timings.restore_sync_included_changed = changed;
    timings.write_all_from_db_ms = write_ms;

    let step = Instant::now();
    if apply_startup_default {
        scenario_service::ensure_default_startup_scenario(&store)
            .map_err(|e| anyhow::anyhow!(e.to_string()))
            .context("Failed to initialize startup scenario")?;
        timings.apply_scenario_kind = "default_startup";
    } else {
        scenario_service::ensure_cli_scenario_state(&store)
            .map_err(|e| anyhow::anyhow!(e.to_string()))
            .context("Failed to initialize CLI scenario state")?;
        timings.apply_scenario_kind = "cli";
    }
    timings.apply_scenario_ms = step.elapsed().as_millis();

    timings.total_ms = total_start.elapsed().as_millis();
    Ok((store, timings))
}

impl StartupTimings {
    /// Emit a single human-readable log block from the captured timings.
    /// Called from `tauri::Builder::setup` once `tauri_plugin_log` is
    /// installed; calling it before that point would lose the output to
    /// the no-op default logger.
    pub fn log(&self) {
        log::info!(
            "startup: initialize_store total {} ms (skills={})",
            self.total_ms,
            self.skill_count
        );
        log::info!(
            "startup: ensure_central_repo {} ms, open_store {} ms, migrate_legacy_tool_keys {} ms",
            self.ensure_central_repo_ms,
            self.open_store_ms,
            self.migrate_legacy_tool_keys_ms
        );
        if let Some(ms) = self.reindex_from_metadata_ms {
            log::info!(
                "startup: reindex_from_metadata {} ms (skills={})",
                ms,
                self.skill_count
            );
        }
        if self.restore_sync_included_changed {
            log::info!(
                "startup: restore_sync_included changed in {} ms, write_all_from_db {} ms",
                self.restore_sync_included_ms,
                self.write_all_from_db_ms.unwrap_or(0)
            );
        } else {
            log::info!(
                "startup: restore_sync_included no-op in {} ms",
                self.restore_sync_included_ms
            );
        }
        log::info!(
            "startup: apply_scenario ({}) {} ms (skills={})",
            self.apply_scenario_kind,
            self.apply_scenario_ms,
            self.skill_count
        );
    }
}

/// After the library moved, point what still names the old location at the new
/// one: DB paths, and the symlinks deployed into agent and project skills
/// directories. Project deployments have no target records and startup sync
/// only covers the active skill group, so neither heals on its own. Only links that
/// resolve into the old library are touched — never anything else in there.
/// Returns how many links could not be inspected or repointed.
fn repoint_after_move(store: &SkillStore, from: &Path, to: &Path) -> Result<usize> {
    let rebase = |path: &str| -> Option<String> {
        let rel = Path::new(path).strip_prefix(from).ok()?;
        Some(to.join(rel).to_string_lossy().to_string())
    };
    for mut skill in store.get_all_skills()? {
        let mut changed = false;
        if let Some(path) = rebase(&skill.central_path) {
            skill.central_path = path;
            changed = true;
        }
        for field in [&mut skill.source_ref, &mut skill.source_ref_resolved] {
            if let Some(path) = field.as_deref().and_then(rebase) {
                *field = Some(path);
                changed = true;
            }
        }
        if changed {
            store.upsert_skill(&skill)?;
        }
    }

    // Recorded deployments by exact path (nested ones included), then every
    // entry of the agent and project skills roots, which also covers project
    // deployments — those have no records.
    let mut links: Vec<PathBuf> = store
        .get_all_targets()?
        .into_iter()
        .filter(|target| target.mode == "symlink")
        .map(|target| PathBuf::from(target.target_path))
        .collect();
    let adapters = tool_adapters::all_tool_adapters(store);
    let mut roots: Vec<PathBuf> = adapters.iter().map(|a| a.skills_dir()).collect();
    for project in store.get_all_projects()? {
        if project.workspace_type == "linked" {
            roots.push(PathBuf::from(&project.path));
            roots.extend(project.disabled_path.map(PathBuf::from));
            continue;
        }
        for adapter in &adapters {
            let dir = adapter.project_relative_skills_dir();
            if !dir.is_empty() {
                roots.push(Path::new(&project.path).join(dir));
                roots.push(Path::new(&project.path).join(format!("{dir}-disabled")));
            }
        }
    }
    // Skills can sit in category subdirectories (Hermes, and the project
    // scanner recurses too), so walk a few levels without following links.
    let mut failures = 0;
    for root in roots {
        match root.try_exists() {
            Ok(true) => {}
            Ok(false) => continue,
            Err(err) => {
                failures += 1;
                central_repo::record_startup_error(format!(
                    "central repo: cannot check {} to repoint links ({err})",
                    root.display()
                ));
                continue;
            }
        }
        for entry in walkdir::WalkDir::new(&root).min_depth(1).max_depth(4) {
            match entry {
                Ok(entry) if entry.path_is_symlink() => links.push(entry.into_path()),
                Ok(_) => {}
                Err(err) => {
                    failures += 1;
                    central_repo::record_startup_error(format!(
                        "central repo: cannot scan {} to repoint links ({err})",
                        root.display()
                    ));
                }
            }
        }
    }
    links.sort();
    links.dedup();

    for link in links {
        let pointee = match std::fs::symlink_metadata(&link) {
            Ok(meta) if meta.file_type().is_symlink() => std::fs::read_link(&link),
            Ok(_) => continue,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
            Err(err) => Err(err),
        };
        let moved = pointee.and_then(|pointee| {
            let Ok(rel) = pointee.strip_prefix(from) else {
                return Ok(None);
            };
            let moved = to.join(rel);
            Ok(moved.try_exists()?.then_some(moved))
        });
        let moved = match moved {
            Ok(Some(moved)) => moved,
            Ok(None) => continue,
            Err(err) => {
                failures += 1;
                central_repo::record_startup_error(format!(
                    "central repo: cannot inspect {} to repoint it ({err})",
                    link.display()
                ));
                continue;
            }
        };
        if let Err(err) = sync_engine::sync_skill(
            &moved,
            &link,
            sync_engine::SyncMode::Symlink,
            sync_engine::ReplacePolicy::Recorded { mode: "symlink" },
        ) {
            failures += 1;
            central_repo::record_startup_error(format!(
                "central repo: cannot repoint {} to {} ({err:#})",
                link.display(),
                moved.display()
            ));
        }
    }
    Ok(failures)
}

#[cfg(test)]
mod tests;