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,
};
#[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,
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(());
};
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"))
}
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;
}
walk.skip_current_dir();
}
}
true
}
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() {
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()?;
}
}
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, ¤t) {
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 {
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
);
}
}
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)?;
}
}
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")));
}
}
}
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;