Skip to main content

agent_hub_runtime/core/
sync_metadata.rs

1mod membership;
2pub(crate) use membership::write_scenario_membership_metadata_unlocked;
3
4use anyhow::{anyhow, bail, Context, Result};
5use serde::{Deserialize, Serialize};
6use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
7use std::fs;
8use std::io::Write;
9use std::path::{Path, PathBuf};
10use unicode_normalization::UnicodeNormalization;
11use walkdir::WalkDir;
12
13use super::central_repo;
14use super::repo_lock::RepoLock;
15use super::skill_metadata;
16use super::skill_store::{ScenarioRecord, SkillRecord, SkillStore};
17
18const SCHEMA_VERSION: u32 = 1;
19const APP_MIN_VERSION: &str = "2.0.0";
20
21#[derive(Debug, Serialize, Deserialize)]
22pub struct SchemaFile {
23    pub schema_version: u32,
24    pub app_min_version: String,
25    pub created_by: String,
26}
27
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct SourceMeta {
30    #[serde(rename = "type")]
31    pub source_type: String,
32    #[serde(rename = "ref")]
33    pub ref_: Option<String>,
34    pub subpath: Option<String>,
35    pub branch: Option<String>,
36}
37
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39pub struct SkillMetaFile {
40    pub schema_version: u32,
41    pub skill_id: String,
42    pub path: String,
43    pub path_key: String,
44    pub enabled: bool,
45    pub tags: Vec<String>,
46    pub source: SourceMeta,
47}
48
49#[derive(Debug, Serialize, Deserialize)]
50pub struct ScenarioMetaFile {
51    pub schema_version: u32,
52    pub scenario_id: String,
53    pub name: String,
54    pub description: Option<String>,
55    pub icon: Option<String>,
56    pub sort_order: i32,
57}
58
59#[derive(Debug, Serialize, Deserialize)]
60pub struct ScenarioSkillMetaFile {
61    pub schema_version: u32,
62    pub scenario_id: String,
63    pub skill_id: String,
64    pub sort_order: i32,
65    pub tools: BTreeMap<String, bool>,
66}
67
68/// Reindex refused: the metadata lists no skills while the central repo has
69/// skill directories (applying it would empty the library). Typed so startup
70/// can tell it apart from other failures.
71#[derive(Debug)]
72pub struct EmptySkillMetadata;
73
74impl std::fmt::Display for EmptySkillMetadata {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        f.write_str(
77            "sync metadata contains no skills, but the central repository contains skill directories",
78        )
79    }
80}
81
82impl std::error::Error for EmptySkillMetadata {}
83
84pub fn metadata_dir() -> PathBuf {
85    central_repo::skills_dir().join(".agent-hub")
86}
87
88pub fn metadata_exists() -> bool {
89    metadata_dir().join("schema.json").exists()
90        || metadata_dir().join("skills").is_dir()
91        || metadata_dir().join("scenarios").is_dir()
92}
93
94pub fn has_complete_skill_snapshot() -> bool {
95    metadata_dir().join("schema.json").is_file() && metadata_dir().join("skills").is_dir()
96}
97
98#[allow(dead_code)]
99pub fn write_all_from_db(store: &SkillStore) -> Result<()> {
100    // Foreground wait: this runs at startup and from CLI skill group/enable
101    // commands, which must succeed (startup aborts on error), not skip.
102    let _lock = RepoLock::acquire_foreground("write sync metadata")?;
103    write_all_from_db_unlocked(store)
104}
105
106/// Runs `f` while holding the central-repo lock. Callers are user-initiated
107/// operations (set tags, delete, skill group edits, imports), so we wait out
108/// transient contention with background work instead of failing fast.
109pub fn with_repo_lock<T, F>(operation: &str, f: F) -> Result<T>
110where
111    F: FnOnce() -> Result<T>,
112{
113    let _lock = RepoLock::acquire_foreground(operation)?;
114    f()
115}
116
117pub(crate) fn write_all_from_db_unlocked(store: &SkillStore) -> Result<()> {
118    ensure_metadata_dirs()?;
119    write_schema()?;
120    write_skill_records_from_db(store)?;
121    write_scenario_records_from_db(store)?;
122    remove_stale_metadata_files(store)?;
123    Ok(())
124}
125
126#[allow(dead_code)]
127pub fn reindex_from_metadata(store: &SkillStore) -> Result<()> {
128    // Foreground wait: runs at process startup (GUI and every CLI invocation),
129    // which aborts on error — better to wait out transient contention than fail.
130    let _lock = RepoLock::acquire_foreground("reindex sync metadata")?;
131    reindex_from_metadata_unlocked(store)
132}
133
134pub(crate) fn reindex_from_metadata_unlocked(store: &SkillStore) -> Result<()> {
135    if !metadata_exists() {
136        return Ok(());
137    }
138    if !has_complete_skill_snapshot() {
139        bail!("incomplete sync metadata snapshot: missing schema.json or skills directory");
140    }
141
142    let mut skills = read_skill_files()?;
143    if skills.is_empty() && central_repo_has_valid_skill_dirs()? {
144        return Err(EmptySkillMetadata.into());
145    }
146    dedup_by_path_key(&mut skills)?;
147
148    let has_complete_scenario_snapshot = metadata_has_complete_scenario_snapshot();
149    let scenarios = if has_complete_scenario_snapshot {
150        read_scenario_files()?
151    } else {
152        Vec::new()
153    };
154    let memberships = if has_complete_scenario_snapshot {
155        read_membership_files()?
156    } else {
157        Vec::new()
158    };
159    let now = chrono::Utc::now().timestamp_millis();
160    let skills_root = central_repo::skills_dir();
161
162    let metadata_ids: HashSet<String> = skills.iter().map(|m| m.skill_id.clone()).collect();
163    for existing in store.get_all_skills()? {
164        if !metadata_ids.contains(&existing.id) {
165            store.delete_skill(&existing.id)?;
166        }
167    }
168
169    let existing_by_id: HashMap<String, SkillRecord> = store
170        .get_all_skills()?
171        .into_iter()
172        .map(|skill| (skill.id.clone(), skill))
173        .collect();
174
175    // Every surviving row gets its central_path rewritten below; park them
176    // on placeholders first so path reassignments between skills (renames or
177    // merge collision reshuffles) cannot trip the UNIQUE constraint mid-loop.
178    store.park_central_paths_for_reindex()?;
179
180    for meta in skills {
181        let skill_dir = skills_root.join(&meta.path);
182        if !skill_dir.is_dir() {
183            store.delete_skill(&meta.skill_id)?;
184            continue;
185        }
186
187        let parsed = skill_metadata::parse_skill_md(&skill_dir);
188        let inferred_name = skill_dir
189            .file_name()
190            .map(|n| n.to_string_lossy().to_string())
191            .unwrap_or_else(|| "unknown-skill".to_string());
192        let name = parsed
193            .name
194            .filter(|s| !s.trim().is_empty())
195            .unwrap_or(inferred_name);
196        let previous = existing_by_id.get(&meta.skill_id);
197        let source_ref = if matches!(meta.source.source_type.as_str(), "import" | "local") {
198            previous.and_then(|s| s.source_ref.clone())
199        } else {
200            meta.source.ref_.clone()
201        };
202        let central_path = skill_dir.to_string_lossy().to_string();
203
204        let new_hash = super::content_hash::hash_directory(&skill_dir).ok();
205        let updated_at = match previous {
206            Some(prev) if prev.content_hash == new_hash => prev.updated_at,
207            _ => now,
208        };
209
210        let record = SkillRecord {
211            id: meta.skill_id.clone(),
212            name,
213            description: parsed.description,
214            source_type: meta.source.source_type.clone(),
215            source_ref,
216            source_ref_resolved: previous.and_then(|s| s.source_ref_resolved.clone()),
217            source_subpath: meta.source.subpath.clone(),
218            source_branch: meta.source.branch.clone(),
219            source_revision: previous.and_then(|s| s.source_revision.clone()),
220            source_agent: previous.and_then(|s| s.source_agent.clone()),
221            remote_revision: previous.and_then(|s| s.remote_revision.clone()),
222            central_path,
223            content_hash: new_hash,
224            enabled: meta.enabled,
225            created_at: previous.map(|s| s.created_at).unwrap_or(now),
226            updated_at,
227            status: "ok".to_string(),
228            update_status: previous
229                .map(|s| s.update_status.clone())
230                .unwrap_or_else(|| "unknown".to_string()),
231            last_checked_at: previous.and_then(|s| s.last_checked_at),
232            last_check_error: previous.and_then(|s| s.last_check_error.clone()),
233        };
234        store.upsert_skill(&record)?;
235        store.set_tags_for_skill(&meta.skill_id, &meta.tags)?;
236    }
237
238    if has_complete_scenario_snapshot {
239        store.replace_scenarios_from_metadata(&scenarios)?;
240        store.replace_scenario_memberships_from_metadata(&memberships)?;
241    }
242    Ok(())
243}
244
245#[allow(dead_code)]
246pub fn ensure_skill_metadata(store: &SkillStore, skill_id: &str) -> Result<()> {
247    // Foreground wait: the CLI `tag` commands flush metadata here after a DB
248    // write; they should ride out contention rather than fail fast.
249    let _lock = RepoLock::acquire_foreground("write skill metadata")?;
250    ensure_skill_metadata_unlocked(store, skill_id)
251}
252
253pub(crate) fn ensure_skill_metadata_unlocked(store: &SkillStore, skill_id: &str) -> Result<()> {
254    write_schema()?;
255    let skill = store
256        .get_skill_by_id(skill_id)?
257        .ok_or_else(|| anyhow!("skill not found: {skill_id}"))?;
258    let tags = store.get_tags_map()?.remove(skill_id).unwrap_or_default();
259    let pk = path_key(&relative_skill_path(&skill.central_path)?);
260    write_skill_file(&skill, &tags)?;
261    remove_duplicate_path_key_files(skill_id, &pk)
262}
263
264pub fn cleanup_temporary_files() -> Result<()> {
265    let root = metadata_dir();
266    if !root.exists() {
267        return Ok(());
268    }
269    for entry in WalkDir::new(root).into_iter().flatten() {
270        if entry.file_type().is_file() {
271            let name = entry.file_name().to_string_lossy();
272            if name.contains(".tmp.") {
273                let _ = fs::remove_file(entry.path());
274            }
275        }
276    }
277    Ok(())
278}
279
280fn write_schema() -> Result<()> {
281    let schema = SchemaFile {
282        schema_version: SCHEMA_VERSION,
283        app_min_version: APP_MIN_VERSION.to_string(),
284        created_by: "agent-hub".to_string(),
285    };
286    atomic_write_json(&metadata_dir().join("schema.json"), &schema)
287}
288
289fn ensure_metadata_dirs() -> Result<()> {
290    fs::create_dir_all(metadata_dir().join("skills"))?;
291    fs::create_dir_all(metadata_dir().join("scenarios"))?;
292    fs::create_dir_all(metadata_dir().join("scenario-skills"))?;
293    Ok(())
294}
295
296fn metadata_has_complete_scenario_snapshot() -> bool {
297    metadata_dir().join("schema.json").is_file()
298        && metadata_dir().join("scenarios").is_dir()
299        && metadata_dir().join("scenario-skills").is_dir()
300}
301
302fn write_skill_records_from_db(store: &SkillStore) -> Result<()> {
303    let mut tags = store.get_tags_map()?;
304    for skill in store.get_all_skills()? {
305        write_skill_file(&skill, &tags.remove(&skill.id).unwrap_or_default())?;
306    }
307    Ok(())
308}
309
310fn write_scenario_records_from_db(store: &SkillStore) -> Result<()> {
311    for scenario in store.get_all_scenarios()? {
312        write_scenario_file(&scenario)?;
313        membership::write_membership_records(store, &scenario.id)?;
314    }
315    Ok(())
316}
317
318pub(crate) fn remove_scenario_metadata(scenario_id: &str) -> Result<()> {
319    let scenario_file = metadata_dir()
320        .join("scenarios")
321        .join(format!("{scenario_id}.json"));
322    if scenario_file.exists() {
323        fs::remove_file(&scenario_file)?;
324    }
325    let membership_dir = metadata_dir().join("scenario-skills").join(scenario_id);
326    if membership_dir.exists() {
327        fs::remove_dir_all(&membership_dir)?;
328    }
329    Ok(())
330}
331
332fn remove_stale_metadata_files(store: &SkillStore) -> Result<()> {
333    let skill_ids: HashSet<String> = store
334        .get_all_skills()?
335        .into_iter()
336        .map(|skill| skill.id)
337        .collect();
338    remove_stale_json_files(&metadata_dir().join("skills"), &skill_ids)?;
339
340    let scenario_ids: HashSet<String> = store
341        .get_all_scenarios()?
342        .into_iter()
343        .map(|scenario| scenario.id)
344        .collect();
345    remove_stale_json_files(&metadata_dir().join("scenarios"), &scenario_ids)?;
346
347    let membership_root = metadata_dir().join("scenario-skills");
348    if membership_root.exists() {
349        let mut expected_memberships = HashSet::new();
350        for scenario_id in &scenario_ids {
351            for skill_id in store.get_skill_ids_for_scenario(scenario_id)? {
352                expected_memberships.insert((scenario_id.clone(), skill_id));
353            }
354        }
355
356        for entry in fs::read_dir(&membership_root)? {
357            let entry = entry?;
358            if !entry.file_type()?.is_dir() {
359                continue;
360            }
361            let scenario_id = entry.file_name().to_string_lossy().to_string();
362            if !scenario_ids.contains(&scenario_id) {
363                fs::remove_dir_all(entry.path())?;
364                continue;
365            }
366
367            let mut has_files = false;
368            for member in fs::read_dir(entry.path())? {
369                let member = member?;
370                if !member.file_type()?.is_file() {
371                    continue;
372                }
373                let path = member.path();
374                if path.extension().map(|ext| ext == "json").unwrap_or(false) {
375                    let skill_id = path
376                        .file_stem()
377                        .map(|stem| stem.to_string_lossy().to_string())
378                        .unwrap_or_default();
379                    if !expected_memberships.contains(&(scenario_id.clone(), skill_id)) {
380                        fs::remove_file(&path)?;
381                    } else {
382                        has_files = true;
383                    }
384                }
385            }
386            if !has_files && fs::read_dir(entry.path())?.next().is_none() {
387                fs::remove_dir(entry.path())?;
388            }
389        }
390    }
391
392    Ok(())
393}
394
395fn remove_stale_json_files(dir: &Path, expected_stems: &HashSet<String>) -> Result<bool> {
396    if !dir.exists() {
397        return Ok(false);
398    }
399    let mut removed = false;
400    for entry in fs::read_dir(dir)? {
401        let entry = entry?;
402        if !entry.file_type()?.is_file() {
403            continue;
404        }
405        let path = entry.path();
406        if path.extension().map(|ext| ext == "json").unwrap_or(false) {
407            let stem = path
408                .file_stem()
409                .map(|stem| stem.to_string_lossy().to_string())
410                .unwrap_or_default();
411            if !expected_stems.contains(&stem) {
412                fs::remove_file(&path)?;
413                removed = true;
414            }
415        }
416    }
417    Ok(removed)
418}
419
420fn write_skill_file(skill: &SkillRecord, tags: &[String]) -> Result<()> {
421    let path = relative_skill_path(&skill.central_path)?;
422    let tags = sorted_tags(tags);
423    let source_ref = match skill.source_type.as_str() {
424        "import" | "local" => None,
425        _ => skill.source_ref.clone(),
426    };
427    let meta = SkillMetaFile {
428        schema_version: SCHEMA_VERSION,
429        skill_id: skill.id.clone(),
430        path_key: path_key(&path),
431        path,
432        enabled: skill.enabled,
433        tags,
434        source: SourceMeta {
435            source_type: skill.source_type.clone(),
436            ref_: source_ref,
437            subpath: skill.source_subpath.clone(),
438            branch: skill.source_branch.clone(),
439        },
440    };
441    atomic_write_json(
442        &metadata_dir()
443            .join("skills")
444            .join(format!("{}.json", skill.id)),
445        &meta,
446    )
447}
448
449fn write_scenario_file(scenario: &ScenarioRecord) -> Result<()> {
450    let meta = ScenarioMetaFile {
451        schema_version: SCHEMA_VERSION,
452        scenario_id: scenario.id.clone(),
453        name: scenario.name.clone(),
454        description: scenario.description.clone(),
455        icon: scenario.icon.clone(),
456        sort_order: scenario.sort_order,
457    };
458    atomic_write_json(
459        &metadata_dir()
460            .join("scenarios")
461            .join(format!("{}.json", scenario.id)),
462        &meta,
463    )
464}
465
466fn write_membership_file(member: &ScenarioSkillMetaFile) -> Result<()> {
467    atomic_write_json(
468        &metadata_dir()
469            .join("scenario-skills")
470            .join(&member.scenario_id)
471            .join(format!("{}.json", member.skill_id)),
472        member,
473    )
474}
475
476fn read_skill_files() -> Result<Vec<SkillMetaFile>> {
477    read_json_files(metadata_dir().join("skills"))
478}
479
480fn central_repo_has_valid_skill_dirs() -> Result<bool> {
481    let skills_dir = central_repo::skills_dir();
482    if !skills_dir.exists() {
483        return Ok(false);
484    }
485
486    for entry in WalkDir::new(&skills_dir)
487        .min_depth(1)
488        .max_depth(6)
489        .into_iter()
490        .filter_entry(|entry| {
491            let name = entry.file_name().to_string_lossy();
492            name != ".git" && name != ".agent-hub"
493        })
494    {
495        let entry = entry?;
496        if entry.file_type().is_dir() && skill_metadata::is_valid_skill_dir(entry.path()) {
497            return Ok(true);
498        }
499    }
500
501    Ok(false)
502}
503
504fn read_scenario_files() -> Result<Vec<ScenarioMetaFile>> {
505    read_json_files(metadata_dir().join("scenarios"))
506}
507
508fn read_membership_files() -> Result<Vec<ScenarioSkillMetaFile>> {
509    let root = metadata_dir().join("scenario-skills");
510    if !root.exists() {
511        return Ok(Vec::new());
512    }
513    let mut records = Vec::new();
514    for entry in WalkDir::new(root)
515        .min_depth(2)
516        .max_depth(2)
517        .into_iter()
518        .flatten()
519    {
520        if entry.file_type().is_file() && entry.path().extension().is_some_and(|ext| ext == "json")
521        {
522            let raw = fs::read_to_string(entry.path())?;
523            records.push(serde_json::from_str(&raw).with_context(|| {
524                format!(
525                    "invalid scenario membership metadata {}",
526                    entry.path().display()
527                )
528            })?);
529        }
530    }
531    Ok(records)
532}
533
534fn read_json_files<T: for<'de> Deserialize<'de>>(dir: PathBuf) -> Result<Vec<T>> {
535    if !dir.exists() {
536        return Ok(Vec::new());
537    }
538    let mut records = Vec::new();
539    for entry in fs::read_dir(&dir)? {
540        let entry = entry?;
541        let is_json = entry
542            .path()
543            .extension()
544            .map(|ext| ext == "json")
545            .unwrap_or(false);
546        if !entry.file_type()?.is_file() || !is_json {
547            continue;
548        }
549        let raw = fs::read_to_string(entry.path())?;
550        records.push(
551            serde_json::from_str(&raw)
552                .with_context(|| format!("invalid metadata file {}", entry.path().display()))?,
553        );
554    }
555    Ok(records)
556}
557
558fn dedup_by_path_key(skills: &mut Vec<SkillMetaFile>) -> Result<()> {
559    for skill in skills.iter() {
560        let computed = path_key(&skill.path);
561        if computed != skill.path_key {
562            bail!("path_key mismatch for skill {}", skill.skill_id);
563        }
564    }
565
566    let mut seen: HashMap<String, usize> = HashMap::new();
567    let mut to_remove_indices: Vec<usize> = Vec::new();
568    let skills_dir = metadata_dir().join("skills");
569
570    for (i, skill) in skills.iter().enumerate() {
571        if let Some(&kept) = seen.get(&skill.path_key) {
572            let loser_id = if skills[kept].skill_id < skill.skill_id {
573                &skill.skill_id
574            } else {
575                let winner_idx = i;
576                to_remove_indices.push(kept);
577                seen.insert(skill.path_key.clone(), winner_idx);
578                &skills[kept].skill_id
579            };
580            log::warn!(
581                "duplicate path_key '{}': keeping one entry, removing {}",
582                skill.path_key,
583                loser_id
584            );
585            if loser_id == &skill.skill_id {
586                to_remove_indices.push(i);
587            }
588            let stale = skills_dir.join(format!("{loser_id}.json"));
589            if stale.exists() {
590                let _ = fs::remove_file(&stale);
591            }
592        } else {
593            seen.insert(skill.path_key.clone(), i);
594        }
595    }
596
597    to_remove_indices.sort_unstable();
598    to_remove_indices.dedup();
599    for i in to_remove_indices.into_iter().rev() {
600        skills.swap_remove(i);
601    }
602    Ok(())
603}
604
605fn remove_duplicate_path_key_files(skill_id: &str, target_path_key: &str) -> Result<()> {
606    let dir = metadata_dir().join("skills");
607    if !dir.exists() {
608        return Ok(());
609    }
610    for entry in fs::read_dir(&dir)? {
611        let entry = entry?;
612        let path = entry.path();
613        if !entry.file_type()?.is_file() || path.extension().map(|e| e != "json").unwrap_or(true) {
614            continue;
615        }
616        let stem = path
617            .file_stem()
618            .map(|s| s.to_string_lossy().to_string())
619            .unwrap_or_default();
620        if stem == skill_id {
621            continue;
622        }
623        let raw = match fs::read_to_string(&path) {
624            Ok(r) => r,
625            Err(_) => continue,
626        };
627        let meta: SkillMetaFile = match serde_json::from_str(&raw) {
628            Ok(m) => m,
629            Err(_) => continue,
630        };
631        if meta.path_key == target_path_key {
632            log::warn!(
633                "removing stale metadata {} (same path_key '{}')",
634                stem,
635                target_path_key
636            );
637            let _ = fs::remove_file(&path);
638        }
639    }
640    Ok(())
641}
642
643fn relative_skill_path(central_path: &str) -> Result<String> {
644    let root = central_repo::skills_dir();
645    let path = PathBuf::from(central_path);
646    let relative = path
647        .strip_prefix(&root)
648        .with_context(|| format!("skill path is outside skills root: {}", path.display()))?;
649    let value = relative
650        .components()
651        .map(|component| component.as_os_str().to_string_lossy().to_string())
652        .collect::<Vec<_>>()
653        .join("/");
654    if value.is_empty() || value.starts_with("../") {
655        bail!("invalid relative skill path: {value}");
656    }
657    Ok(value)
658}
659
660/// Case/Unicode-folded key of a relative skill path. Shared with the merge
661/// engine (§2.1): metadata rebuilt during a merge must use the exact same
662/// folding as metadata written from the DB.
663pub(crate) fn path_key(path: &str) -> String {
664    path.split('/')
665        .map(|part| caseless::default_case_fold_str(&part.nfc().collect::<String>()))
666        .collect::<Vec<_>>()
667        .join("/")
668}
669
670fn sorted_tags(tags: &[String]) -> Vec<String> {
671    tags.iter()
672        .map(|tag| tag.trim())
673        .filter(|tag| !tag.is_empty())
674        .map(ToOwned::to_owned)
675        .collect::<BTreeSet<_>>()
676        .into_iter()
677        .collect()
678}
679
680/// Canonical on-disk JSON encoding for metadata files. The merge engine
681/// reuses this to rebuild merged metadata blobs so that two devices merging
682/// the same pair of commits produce byte-identical blobs → identical tree
683/// OIDs (§2.1 / §10).
684pub(crate) fn canonical_json_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>> {
685    let mut bytes = serde_json::to_vec_pretty(value)?;
686    bytes.push(b'\n');
687    Ok(bytes)
688}
689
690fn atomic_write_json<T: Serialize>(path: &Path, value: &T) -> Result<()> {
691    if let Some(parent) = path.parent() {
692        fs::create_dir_all(parent)?;
693    }
694    let bytes = canonical_json_bytes(value)?;
695    if fs::read(path).is_ok_and(|existing| existing == bytes) {
696        return Ok(());
697    }
698    let tmp = path.with_extension(format!("json.tmp.{}", uuid::Uuid::now_v7()));
699    {
700        let mut file = fs::File::create(&tmp)?;
701        file.write_all(&bytes)?;
702        file.sync_all()?;
703    }
704    fs::rename(&tmp, path)?;
705    sync_parent_dir(path)?;
706    Ok(())
707}
708
709fn sync_parent_dir(path: &Path) -> Result<()> {
710    let Some(parent) = path.parent() else {
711        return Ok(());
712    };
713
714    #[cfg(windows)]
715    {
716        use std::os::windows::fs::OpenOptionsExt;
717
718        // Windows requires FILE_FLAG_BACKUP_SEMANTICS to open a directory
719        // handle. std::fs::File::open uses ordinary file semantics and fails
720        // with Access is denied (os error 5) for directories.
721        // FlushFileBuffers also requires a handle opened with write access.
722        const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x02000000;
723
724        let dir = fs::OpenOptions::new()
725            .write(true)
726            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
727            .open(parent)?;
728        dir.sync_all()?;
729        Ok(())
730    }
731
732    #[cfg(not(windows))]
733    {
734        let dir = fs::File::open(parent)?;
735        dir.sync_all()?;
736        Ok(())
737    }
738}
739
740#[cfg(test)]
741mod tests;