1use std::path::{Path, PathBuf};
2use std::sync::Arc;
3use std::time::Instant;
4
5use anyhow::{Context, Result};
6
7use super::{
8 central_repo, scenario_service, skill_metadata, skill_store::SkillStore, sync_engine,
9 sync_metadata, tool_adapters, tool_service,
10};
11
12#[derive(Debug, Clone)]
18pub struct StartupTimings {
19 pub ensure_central_repo_ms: u128,
20 pub open_store_ms: u128,
21 pub migrate_legacy_tool_keys_ms: u128,
22 pub skill_count: usize,
23 pub reindex_from_metadata_ms: Option<u128>,
24 pub restore_sync_included_ms: u128,
25 pub restore_sync_included_changed: bool,
26 pub write_all_from_db_ms: Option<u128>,
27 pub apply_scenario_ms: u128,
28 pub apply_scenario_kind: &'static str,
33 pub total_ms: u128,
34}
35
36impl Default for StartupTimings {
37 fn default() -> Self {
38 Self {
39 ensure_central_repo_ms: 0,
40 open_store_ms: 0,
41 migrate_legacy_tool_keys_ms: 0,
42 skill_count: 0,
43 reindex_from_metadata_ms: None,
44 restore_sync_included_ms: 0,
45 restore_sync_included_changed: false,
46 write_all_from_db_ms: None,
47 apply_scenario_ms: 0,
48 apply_scenario_kind: "unknown",
49 total_ms: 0,
50 }
51 }
52}
53
54pub fn initialize_store() -> Result<(Arc<SkillStore>, StartupTimings)> {
55 initialize_store_inner(true, true)
56}
57
58pub fn initialize_cli_store() -> Result<Arc<SkillStore>> {
59 initialize_store_inner(false, false).map(|(store, _)| store)
60}
61
62fn reindex_or_rebuild_metadata(store: &SkillStore) -> Result<()> {
63 let Err(err) = sync_metadata::reindex_from_metadata(store) else {
64 return Ok(());
65 };
66 if err.is::<sync_metadata::EmptySkillMetadata>()
72 && (db_library_is_intact(store) || super::shared_skill_index::is_shared())
73 {
74 central_repo::record_startup_error(format!(
75 "sync metadata: {err}; rebuilt it from the database"
76 ));
77 return sync_metadata::with_repo_lock("rebuild shared skills metadata", || {
78 super::shared_skill_index::refresh(store)?;
79 sync_metadata::write_all_from_db_unlocked(store)
80 })
81 .context("Failed to rebuild sync metadata from the database");
82 }
83 Err(err.context("Failed to reindex from sync metadata"))
84}
85
86fn db_library_is_intact(store: &SkillStore) -> bool {
90 let Ok(skills) = store.get_all_skills() else {
91 return false;
92 };
93 let canon = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
94 let mut recorded = std::collections::HashSet::new();
95 for skill in &skills {
96 let path = Path::new(&skill.central_path);
97 if !path.is_dir() {
98 return false;
99 }
100 recorded.insert(canon(path));
101 }
102 if recorded.is_empty() {
103 return false;
104 }
105 let mut walk = walkdir::WalkDir::new(central_repo::skills_dir())
106 .min_depth(1)
107 .max_depth(6)
108 .into_iter()
109 .filter_entry(|e| {
110 let name = e.file_name().to_string_lossy();
111 name != ".git" && name != ".agent-hub"
112 });
113 while let Some(entry) = walk.next() {
114 let Ok(entry) = entry else {
115 return false;
116 };
117 if entry.file_type().is_dir() && skill_metadata::is_valid_skill_dir(entry.path()) {
118 if !recorded.contains(&canon(entry.path())) {
119 return false;
120 }
121 walk.skip_current_dir();
123 }
124 }
125 true
126}
127
128pub fn initialize_cli_store_moving_repo() -> Result<Arc<SkillStore>> {
131 initialize_store_inner(false, true).map(|(store, _)| store)
132}
133
134fn initialize_store_inner(
135 apply_startup_default: bool,
136 allow_migration: bool,
137) -> Result<(Arc<SkillStore>, StartupTimings)> {
138 let total_start = Instant::now();
139 let mut timings = StartupTimings::default();
140
141 let step = Instant::now();
142 central_repo::ensure_central_repo(allow_migration).context("Failed to create central repo")?;
143 timings.ensure_central_repo_ms = step.elapsed().as_millis();
144
145 let db_path = central_repo::db_path();
146 let step = Instant::now();
147 let store = Arc::new(SkillStore::new(&db_path).context("Failed to initialize database")?);
148 super::git_auth_source::set_preference(
149 store
150 .get_setting(super::git_auth_source::SETTING_USE_GH)?
151 .as_deref(),
152 );
153 timings.open_store_ms = step.elapsed().as_millis();
154
155 let step = Instant::now();
156 tool_service::migrate_legacy_tool_keys(&store)
157 .map_err(|e| anyhow::anyhow!(e.to_string()))
158 .context("Failed to migrate legacy tool keys")?;
159 timings.migrate_legacy_tool_keys_ms = step.elapsed().as_millis();
160
161 if allow_migration {
162 if let Some((from, to)) = central_repo::take_repoint_from() {
163 let done = match repoint_after_move(&store, &from, &to) {
166 Ok(failures) => failures == 0,
167 Err(err) => {
168 central_repo::record_startup_error(format!(
169 "central repo: repointing paths after the move failed ({err:#})"
170 ));
171 false
172 }
173 };
174 if done {
175 if let Err(err) = central_repo::clear_repoint_from() {
176 central_repo::record_startup_error(format!(
177 "central repo: cannot clear the repoint marker ({err:#}); it will rerun"
178 ));
179 }
180 }
181 }
182 }
183
184 if let Some((from, to)) = central_repo::take_shared_repoint_from()? {
185 let failures = sync_metadata::with_repo_lock("repoint shared skills", || {
186 repoint_after_move(&store, &from, &to)
187 })?;
188 if failures == 0 {
189 central_repo::clear_shared_repoint_from()?;
190 }
191 }
192
193 let legacy = central_repo::legacy_default_skills_dir();
200 let current = central_repo::default_skills_dir();
201 if central_repo::skills_dir() == current
202 && legacy != current
203 && legacy.symlink_metadata().is_ok()
204 {
205 match repoint_after_move(&store, &legacy, ¤t) {
206 Ok(failures) if failures > 0 => {
207 log::warn!("startup: could not repair {failures} legacy Agent skill link(s)")
208 }
209 Ok(_) => {}
210 Err(err) => log::warn!("startup: legacy Agent link repair failed: {err:#}"),
211 }
212 }
213
214 timings.skill_count = store.get_all_skills().map(|s| s.len()).unwrap_or(0);
215
216 if sync_metadata::metadata_exists() {
217 let step = Instant::now();
218 reindex_or_rebuild_metadata(&store)?;
219 timings.reindex_from_metadata_ms = Some(step.elapsed().as_millis());
220 }
221
222 let step = Instant::now();
223 let changed = scenario_service::restore_all_skills_sync_included(&store)
224 .map_err(|e| anyhow::anyhow!(e.to_string()))
225 .context("Failed to restore skill sync inclusion")?;
226 let (changed, write_ms) = sync_metadata::with_repo_lock("index shared skills", || {
227 let changed = super::shared_skill_index::refresh(&store)? || changed;
228 let write_start = Instant::now();
229 if changed {
230 sync_metadata::write_all_from_db_unlocked(&store)?;
231 }
232 Ok((changed, changed.then(|| write_start.elapsed().as_millis())))
233 })?;
234 timings.restore_sync_included_ms = step.elapsed().as_millis();
235 timings.restore_sync_included_changed = changed;
236 timings.write_all_from_db_ms = write_ms;
237
238 let step = Instant::now();
239 if apply_startup_default {
240 scenario_service::ensure_default_startup_scenario(&store)
241 .map_err(|e| anyhow::anyhow!(e.to_string()))
242 .context("Failed to initialize startup scenario")?;
243 timings.apply_scenario_kind = "default_startup";
244 } else {
245 scenario_service::ensure_cli_scenario_state(&store)
246 .map_err(|e| anyhow::anyhow!(e.to_string()))
247 .context("Failed to initialize CLI scenario state")?;
248 timings.apply_scenario_kind = "cli";
249 }
250 timings.apply_scenario_ms = step.elapsed().as_millis();
251
252 timings.total_ms = total_start.elapsed().as_millis();
253 Ok((store, timings))
254}
255
256impl StartupTimings {
257 pub fn log(&self) {
262 log::info!(
263 "startup: initialize_store total {} ms (skills={})",
264 self.total_ms,
265 self.skill_count
266 );
267 log::info!(
268 "startup: ensure_central_repo {} ms, open_store {} ms, migrate_legacy_tool_keys {} ms",
269 self.ensure_central_repo_ms,
270 self.open_store_ms,
271 self.migrate_legacy_tool_keys_ms
272 );
273 if let Some(ms) = self.reindex_from_metadata_ms {
274 log::info!(
275 "startup: reindex_from_metadata {} ms (skills={})",
276 ms,
277 self.skill_count
278 );
279 }
280 if self.restore_sync_included_changed {
281 log::info!(
282 "startup: restore_sync_included changed in {} ms, write_all_from_db {} ms",
283 self.restore_sync_included_ms,
284 self.write_all_from_db_ms.unwrap_or(0)
285 );
286 } else {
287 log::info!(
288 "startup: restore_sync_included no-op in {} ms",
289 self.restore_sync_included_ms
290 );
291 }
292 log::info!(
293 "startup: apply_scenario ({}) {} ms (skills={})",
294 self.apply_scenario_kind,
295 self.apply_scenario_ms,
296 self.skill_count
297 );
298 }
299}
300
301fn repoint_after_move(store: &SkillStore, from: &Path, to: &Path) -> Result<usize> {
308 let rebase = |path: &str| -> Option<String> {
309 let rel = Path::new(path).strip_prefix(from).ok()?;
310 Some(to.join(rel).to_string_lossy().to_string())
311 };
312 for mut skill in store.get_all_skills()? {
313 let mut changed = false;
314 if let Some(path) = rebase(&skill.central_path) {
315 skill.central_path = path;
316 changed = true;
317 }
318 for field in [&mut skill.source_ref, &mut skill.source_ref_resolved] {
319 if let Some(path) = field.as_deref().and_then(rebase) {
320 *field = Some(path);
321 changed = true;
322 }
323 }
324 if changed {
325 store.upsert_skill(&skill)?;
326 }
327 }
328
329 let mut links: Vec<PathBuf> = store
333 .get_all_targets()?
334 .into_iter()
335 .filter(|target| target.mode == "symlink")
336 .map(|target| PathBuf::from(target.target_path))
337 .collect();
338 let adapters = tool_adapters::all_tool_adapters(store);
339 let mut roots: Vec<PathBuf> = adapters.iter().map(|a| a.skills_dir()).collect();
340 for project in store.get_all_projects()? {
341 if project.workspace_type == "linked" {
342 roots.push(PathBuf::from(&project.path));
343 roots.extend(project.disabled_path.map(PathBuf::from));
344 continue;
345 }
346 for adapter in &adapters {
347 let dir = adapter.project_relative_skills_dir();
348 if !dir.is_empty() {
349 roots.push(Path::new(&project.path).join(dir));
350 roots.push(Path::new(&project.path).join(format!("{dir}-disabled")));
351 }
352 }
353 }
354 let mut failures = 0;
357 for root in roots {
358 match root.try_exists() {
359 Ok(true) => {}
360 Ok(false) => continue,
361 Err(err) => {
362 failures += 1;
363 central_repo::record_startup_error(format!(
364 "central repo: cannot check {} to repoint links ({err})",
365 root.display()
366 ));
367 continue;
368 }
369 }
370 for entry in walkdir::WalkDir::new(&root).min_depth(1).max_depth(4) {
371 match entry {
372 Ok(entry) if entry.path_is_symlink() => links.push(entry.into_path()),
373 Ok(_) => {}
374 Err(err) => {
375 failures += 1;
376 central_repo::record_startup_error(format!(
377 "central repo: cannot scan {} to repoint links ({err})",
378 root.display()
379 ));
380 }
381 }
382 }
383 }
384 links.sort();
385 links.dedup();
386
387 for link in links {
388 let pointee = match std::fs::symlink_metadata(&link) {
389 Ok(meta) if meta.file_type().is_symlink() => std::fs::read_link(&link),
390 Ok(_) => continue,
391 Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
392 Err(err) => Err(err),
393 };
394 let moved = pointee.and_then(|pointee| {
395 let Ok(rel) = pointee.strip_prefix(from) else {
396 return Ok(None);
397 };
398 let moved = to.join(rel);
399 Ok(moved.try_exists()?.then_some(moved))
400 });
401 let moved = match moved {
402 Ok(Some(moved)) => moved,
403 Ok(None) => continue,
404 Err(err) => {
405 failures += 1;
406 central_repo::record_startup_error(format!(
407 "central repo: cannot inspect {} to repoint it ({err})",
408 link.display()
409 ));
410 continue;
411 }
412 };
413 if let Err(err) = sync_engine::sync_skill(
414 &moved,
415 &link,
416 sync_engine::SyncMode::Symlink,
417 sync_engine::ReplacePolicy::Recorded { mode: "symlink" },
418 ) {
419 failures += 1;
420 central_repo::record_startup_error(format!(
421 "central repo: cannot repoint {} to {} ({err:#})",
422 link.display(),
423 moved.display()
424 ));
425 }
426 }
427 Ok(failures)
428}
429
430#[cfg(test)]
431mod tests;