Skip to main content

agent_hub_runtime/core/
sync_engine.rs

1use anyhow::{Context, Result};
2use std::path::{Path, PathBuf};
3
4mod replacement;
5
6/// Refuse to sync when `src` and `dst` overlap in either direction (equal,
7/// dst inside src, or src inside dst). Otherwise the recursive copy walks
8/// into the freshly-created `dst` and produces unbounded nesting (issue #61),
9/// or the pre-copy removal of `dst` deletes the source along with it (#199).
10///
11/// `src` must exist and canonicalize — every caller is about to read from it,
12/// and all destructive steps (remove target / remove destination) happen after
13/// this check, so failing here protects the existing target. A missing `dst`
14/// is the normal case for a fresh install and is judged via its parent.
15///
16/// A `dst` that is itself a link is judged by its own location (parent + name),
17/// never by what it resolves to. Resolving it would report our own deployed
18/// link as "inside the source" and refuse — which is what broke switching an
19/// already-deployed skill from symlink to copy mode. Removing that link cannot
20/// touch the source (links are unlinked, not followed), so its pointee is
21/// irrelevant to both hazards this guard exists for.
22pub(crate) fn ensure_dst_not_inside_src(src: &Path, dst: &Path) -> Result<()> {
23    // Same path, before any link-aware special casing below: if `src` is itself
24    // a link, judging `dst` lexically and `src` canonically would compare a link
25    // against its pointee and miss the equality. Unlinking `dst` would then
26    // destroy `src`, and the copy would "succeed" from the empty directory it
27    // just created in its place.
28    if src == dst {
29        anyhow::bail!(
30            "Source and destination are the same path {:?}; refusing to copy",
31            src
32        );
33    }
34    let src_canon = src
35        .canonicalize()
36        .with_context(|| format!("Source {:?} does not exist or is not accessible", src))?;
37    let dst_is_link = std::fs::symlink_metadata(dst)
38        .map(|meta| meta.file_type().is_symlink())
39        .unwrap_or(false);
40    let lexical_dst = || -> Option<PathBuf> {
41        let parent = dst.parent()?.canonicalize().ok()?;
42        let name = dst.file_name()?;
43        Some(parent.join(name))
44    };
45    let dst_canon: Option<PathBuf> = if dst_is_link {
46        lexical_dst()
47    } else {
48        dst.canonicalize().ok().or_else(lexical_dst)
49    };
50    // The same link reached by two spellings (`./x` vs `x`) is still the same
51    // object, and the lexical/canonical mismatch above would hide it.
52    if dst_is_link {
53        let lexical_src = || -> Option<PathBuf> {
54            let parent = src.parent()?.canonicalize().ok()?;
55            Some(parent.join(src.file_name()?))
56        };
57        if let (Some(a), Some(b)) = (lexical_src(), dst_canon.as_ref()) {
58            if a == *b {
59                anyhow::bail!(
60                    "Source and destination are the same path {:?}; refusing to copy",
61                    src
62                );
63            }
64        }
65    }
66    if let Some(dst_canon) = dst_canon {
67        if dst_canon.starts_with(&src_canon) {
68            anyhow::bail!(
69                "Destination {:?} is inside source {:?}; refusing to copy to avoid infinite recursion",
70                dst,
71                src
72            );
73        }
74        if src_canon.starts_with(&dst_canon) {
75            anyhow::bail!(
76                "Source {:?} is inside destination {:?}; refusing to avoid deleting the source",
77                src,
78                dst
79            );
80        }
81    }
82    Ok(())
83}
84
85/// What is actually sitting at a deployment target right now.
86///
87/// Classified from `symlink_metadata` only — never `is_dir()`, which follows
88/// links and would report a Windows junction or a directory symlink as a real
89/// directory, sending it down the `remove_dir_all` path.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum TargetState {
92    /// Nothing there. Deploying cannot destroy anything.
93    Absent,
94    /// A link that resolves to the source we are about to deploy — ours by
95    /// construction, and unlinking it cannot touch the source.
96    LinkToSource,
97    /// A link pointing somewhere else, or a dangling one. The link itself is
98    /// user configuration even when its pointee is gone.
99    ForeignLink,
100    /// A real directory. Indistinguishable from a copy-mode deployment by
101    /// filesystem inspection alone.
102    RealDir,
103    /// A real file. We never deploy a bare file, so this is always the user's.
104    RealFile,
105}
106
107/// What the caller is authorized to destroy at the target.
108///
109/// This is an enum rather than a bool so that adding it to `sync_skill` breaks
110/// every call site and forces each one to state its intent — the property worth
111/// having in a fix for silent data loss (issue #363).
112#[derive(Debug, Clone, Copy)]
113pub enum ReplacePolicy<'a> {
114    /// Only proceed when nothing of the user's can be lost. Anything we cannot
115    /// prove is ours is refused.
116    NoClobber,
117    /// The caller found a `skill_targets` row claiming exactly this path.
118    ///
119    /// The row is historical intent, not proof of what is on disk now, so it
120    /// only authorizes removing an object whose *current* type matches the
121    /// recorded mode: a row saying `symlink` must never authorize deleting a
122    /// real directory that replaced our link.
123    Recorded { mode: &'a str },
124    /// Explicit user intent: adopt an existing directory into the library,
125    /// `--force`, or "update this copy from center".
126    UserConfirmed,
127}
128
129impl ReplacePolicy<'_> {
130    /// Whether this policy authorizes destroying `state`. See the module tests
131    /// for the full decision table.
132    fn permits(&self, state: TargetState) -> bool {
133        match state {
134            // Nothing to lose either way.
135            TargetState::Absent | TargetState::LinkToSource => true,
136            TargetState::ForeignLink => match self {
137                ReplacePolicy::NoClobber => false,
138                // Our own link can dangle after the library moves, so a
139                // symlink row still authorizes replacing a link. A copy row
140                // does not: something turned our directory into a link.
141                ReplacePolicy::Recorded { mode } => *mode == "symlink",
142                ReplacePolicy::UserConfirmed => true,
143            },
144            TargetState::RealDir => match self {
145                ReplacePolicy::NoClobber => false,
146                ReplacePolicy::Recorded { mode } => *mode == "copy",
147                ReplacePolicy::UserConfirmed => true,
148            },
149            // We never deploy a bare file, so no record can vouch for one.
150            TargetState::RealFile => matches!(self, ReplacePolicy::UserConfirmed),
151        }
152    }
153
154    fn describe(&self) -> &'static str {
155        match self {
156            ReplacePolicy::NoClobber => "不由 AgentHub 管理",
157            ReplacePolicy::Recorded { .. } => "与已记录的部署不一致",
158            ReplacePolicy::UserConfirmed => "无法被替换",
159        }
160    }
161}
162
163/// A write was refused because the target is not ours to destroy.
164///
165/// A distinct type so callers can tell an ownership refusal — where the right
166/// response is to report the conflict to the user — from an ordinary IO error,
167/// which reconcile paths have always tolerated and logged.
168#[derive(Debug)]
169pub struct ReplaceRefused {
170    pub target: PathBuf,
171    pub reason: &'static str,
172}
173
174/// The one place this refusal is worded. `ReplaceRefused` and the
175/// `TargetConflict` that carries it out to callers both render through here so
176/// the two cannot drift apart.
177pub fn refusal_message(target: &Path, reason: &str) -> String {
178    format!(
179        "拒绝替换 {target:?}:该路径{reason}。已有内容未被修改——\
180         请先将其导入技能库或移至其他位置后重试。"
181    )
182}
183
184impl std::fmt::Display for ReplaceRefused {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        f.write_str(&refusal_message(&self.target, self.reason))
187    }
188}
189
190impl std::error::Error for ReplaceRefused {}
191
192/// Classify `target` and check `policy` against it, returning the state that
193/// may then be removed. The single place the refusal decision and its wording
194/// live, so `sync_skill` and [`preflight_replace`] can never disagree.
195fn authorize_replacement(
196    source: &Path,
197    target: &Path,
198    policy: ReplacePolicy<'_>,
199) -> Result<TargetState> {
200    let state = classify_target(target, Some(source))?;
201    if !policy.permits(state) {
202        return Err(ReplaceRefused {
203            target: target.to_path_buf(),
204            reason: policy.describe(),
205        }
206        .into());
207    }
208    Ok(state)
209}
210
211/// Whether [`sync_skill`] would be allowed to write here, without touching
212/// anything. For batch callers that must refuse the whole operation before
213/// mutating any of it (#363, expectation 4).
214///
215/// This is a preflight, not an authorization: `sync_skill` re-checks
216/// immediately before it removes anything, because the filesystem can change
217/// in between.
218pub fn preflight_replace(
219    source: &Path,
220    target: &Path,
221    mode: SyncMode,
222    policy: ReplacePolicy<'_>,
223) -> Result<()> {
224    if is_target_current(source, target, mode, None, None) {
225        return Ok(());
226    }
227    authorize_replacement(source, target, policy).map(|_| ())
228}
229
230/// Classify what is at `target` without following links.
231///
232/// `source` is the deployment source, used only to recognize a link that already
233/// points at it. Pass `None` when there is no source to compare against.
234pub fn classify_target(target: &Path, source: Option<&Path>) -> Result<TargetState> {
235    let metadata = match std::fs::symlink_metadata(target) {
236        Ok(metadata) => metadata,
237        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(TargetState::Absent),
238        // A target we cannot even stat is not evidence that it is ours.
239        Err(err) => {
240            return Err(anyhow::Error::from(err)
241                .context(format!("Cannot inspect existing target {:?}", target)));
242        }
243    };
244
245    if metadata.file_type().is_symlink() {
246        // `LinkToSource` is universally permitted, so it must only be reached
247        // with a real source to compare against. Callers with no source (undeploy
248        // and friends) pass `None`: an empty path would canonicalize to the
249        // process CWD and turn a user's link into "ours".
250        if source.is_some_and(|source| symlink_points_to(target, source)) {
251            return Ok(TargetState::LinkToSource);
252        }
253        return Ok(TargetState::ForeignLink);
254    }
255    if metadata.is_dir() {
256        Ok(TargetState::RealDir)
257    } else {
258        Ok(TargetState::RealFile)
259    }
260}
261
262#[derive(Debug, Clone, Copy)]
263pub enum SyncMode {
264    Symlink,
265    Copy,
266}
267
268impl SyncMode {
269    pub fn as_str(&self) -> &'static str {
270        match self {
271            SyncMode::Symlink => "symlink",
272            SyncMode::Copy => "copy",
273        }
274    }
275}
276
277pub fn sync_mode_for_tool(_tool_key: &str, configured_mode: Option<&str>) -> SyncMode {
278    match configured_mode {
279        Some("copy") => SyncMode::Copy,
280        Some("symlink") => SyncMode::Symlink,
281        _ => SyncMode::Symlink,
282    }
283}
284
285pub fn target_dir_name(central_path: &Path, skill_name: &str) -> String {
286    central_path
287        .file_name()
288        .and_then(|name| name.to_str())
289        .filter(|name| !name.is_empty())
290        .map(ToString::to_string)
291        .unwrap_or_else(|| skill_name.to_string())
292}
293
294pub fn sync_skill(
295    source: &Path,
296    target: &Path,
297    mode: SyncMode,
298    policy: ReplacePolicy<'_>,
299) -> Result<SyncMode> {
300    // Internal self-check uses no hash context, so Copy mode always
301    // proceeds — the caller (e.g. `sync_desired_targets`) is the place
302    // that knows about freshness and can short-circuit.
303    if is_target_current(source, target, mode, None, None) {
304        return Ok(mode);
305    }
306
307    // Decide what we are allowed to destroy before touching anything. This
308    // runs here, immediately before the removal, rather than only in a caller
309    // preflight: a preflight result cannot authorize a later deletion (#363).
310    let state = authorize_replacement(source, target, policy)?;
311
312    // A real write to a watched dir follows: mute the watcher so this
313    // app-initiated change doesn't echo back as a redundant refresh (#248).
314    crate::core::file_watcher::mute_self_writes(target);
315
316    if let Some(parent) = target.parent() {
317        std::fs::create_dir_all(parent)
318            .with_context(|| format!("Failed to create parent dir {:?}", parent))?;
319    }
320
321    ensure_dst_not_inside_src(source, target)?;
322
323    replacement::replace(source, target, mode, policy, state)
324}
325
326/// Decide whether the existing target is already in the desired state.
327///
328/// - **Symlink mode**: the target must be a symlink pointing at `source`.
329/// - **Copy mode**: the target must still exist on disk **and** the
330///   previously synced source hash must equal the current source hash
331///   (both must be `Some`). The existence check protects against a
332///   user manually deleting the synced directory between sessions —
333///   without it a stale hash would cause us to skip a re-copy the
334///   user needs. Callers without hash context should pass `None`,
335///   which preserves the historical "always recopy" behavior. See
336///   `SkillTargetRecord.source_hash` and issue #153 for context.
337pub(crate) fn is_library_entry(path: &Path) -> bool {
338    let root = super::central_repo::skills_dir();
339    let Ok(root) = root.canonicalize() else {
340        return false;
341    };
342    path == root
343        || path
344            .parent()
345            .and_then(|parent| parent.canonicalize().ok())
346            .is_some_and(|parent| parent.starts_with(&root))
347}
348
349pub(crate) fn uses_library_directly(source: &Path, target: &Path) -> bool {
350    is_library_entry(target)
351        && source.is_dir()
352        && source
353            .canonicalize()
354            .ok()
355            .zip(target.canonicalize().ok())
356            .is_some_and(|(a, b)| a == b)
357}
358
359pub fn is_target_current(
360    source: &Path,
361    target: &Path,
362    mode: SyncMode,
363    last_synced_source_hash: Option<&str>,
364    current_source_hash: Option<&str>,
365) -> bool {
366    if uses_library_directly(source, target) {
367        return true;
368    }
369    match mode {
370        SyncMode::Symlink => symlink_points_to(target, source),
371        SyncMode::Copy => match (last_synced_source_hash, current_source_hash) {
372            (Some(stored), Some(current)) if stored == current => {
373                std::fs::symlink_metadata(target).is_ok()
374            }
375            _ => false,
376        },
377    }
378}
379
380fn symlink_points_to(target: &Path, source: &Path) -> bool {
381    let Ok(metadata) = std::fs::symlink_metadata(target) else {
382        return false;
383    };
384    if !metadata.file_type().is_symlink() {
385        return false;
386    }
387
388    let Ok(link_target) = std::fs::read_link(target) else {
389        return false;
390    };
391    let resolved_link_target = if link_target.is_absolute() {
392        link_target
393    } else {
394        target
395            .parent()
396            .unwrap_or_else(|| Path::new(""))
397            .join(link_target)
398    };
399
400    if resolved_link_target == source {
401        return true;
402    }
403
404    match (resolved_link_target.canonicalize(), source.canonicalize()) {
405        (Ok(link), Ok(src)) => link == src,
406        _ => false,
407    }
408}
409
410/// Remove a target that was already classified, using an operation that only
411/// works on that kind of object.
412///
413/// This is the difference between "we checked, then deleted whatever we found"
414/// and "we deleted the thing we checked". If a real directory replaces a link
415/// between the classification and this call, `remove_file` fails with an error
416/// instead of `remove_dir_all` quietly eating it — the exact race that makes a
417/// check-then-`remove_target` sequence still unsafe.
418pub fn remove_classified_target(target: &Path, state: TargetState) -> Result<()> {
419    match state {
420        TargetState::Absent => Ok(()),
421        TargetState::LinkToSource | TargetState::ForeignLink => {
422            crate::core::file_watcher::mute_self_writes(target);
423            remove_link(target)
424        }
425        TargetState::RealFile => {
426            crate::core::file_watcher::mute_self_writes(target);
427            std::fs::remove_file(target).map_err(Into::into)
428        }
429        TargetState::RealDir => {
430            crate::core::file_watcher::mute_self_writes(target);
431            // Only reachable via `Recorded { mode: "copy" }` or UserConfirmed.
432            std::fs::remove_dir_all(target).map_err(Into::into)
433        }
434    }
435}
436
437/// Remove a deployment target only while what is on disk still matches the
438/// deployment we recorded. Returns `false` when the object was preserved
439/// because it no longer does.
440///
441/// Undeploy and cleanup paths reach a path through a `skill_targets` row, and
442/// a row is a statement about the past: if the user replaced our link with a
443/// real directory of their own, the row still points at it. Removing on the
444/// row's word alone deletes that directory (#363, expectation 5).
445///
446/// Link-vs-source identity is irrelevant here — a `symlink` row authorizes
447/// removing a link whether or not it still resolves to the skill we deployed
448/// (the library may have moved) — so no source path is required.
449pub fn remove_recorded_target(target: &Path, recorded_mode: &str) -> Result<bool> {
450    if is_library_entry(target) {
451        return Ok(false);
452    }
453    let state = classify_target(target, None)?;
454    let policy = ReplacePolicy::Recorded {
455        mode: recorded_mode,
456    };
457    if !policy.permits(state) {
458        return Ok(false);
459    }
460    remove_classified_target(target, state)?;
461    Ok(true)
462}
463
464/// Row-driven removal for cleanup paths: remove only while the disk still
465/// matches the record, and report a preserved replacement instead of falling
466/// back to [`remove_target`]. Every caller that deletes what a `skill_targets`
467/// row points at should go through here (or [`remove_recorded_target`]) — a
468/// row is a statement about the past, never proof that whatever is on disk is
469/// ours (#363 expectation 5, #435).
470pub fn remove_recorded_target_or_warn(target: &Path, recorded_mode: &str) -> bool {
471    match remove_recorded_target(target, recorded_mode) {
472        Ok(true) => true,
473        Ok(false) => {
474            log::warn!(
475                "Preserving {}: no longer matches its recorded {recorded_mode} deployment; \
476                 removing the record only",
477                target.display()
478            );
479            false
480        }
481        Err(e) => {
482            log::warn!("Failed to remove sync target {}: {e}", target.display());
483            false
484        }
485    }
486}
487
488/// Whether what is at `target` is still consistent with a deployment recorded
489/// as `recorded_mode`. `false` means something else took the path over, which
490/// is why an undeploy may leave a path behind on purpose.
491pub fn matches_recorded_deployment(target: &Path, recorded_mode: &str) -> Result<bool> {
492    let state = classify_target(target, None)?;
493    if state == TargetState::Absent {
494        return Ok(false);
495    }
496    let policy = ReplacePolicy::Recorded {
497        mode: recorded_mode,
498    };
499    Ok(policy.permits(state))
500}
501
502/// Unlink a symlink (or, on Windows, a directory symlink / junction) without
503/// following it.
504pub(crate) fn remove_link(target: &Path) -> Result<()> {
505    #[cfg(windows)]
506    {
507        use std::os::windows::fs::FileTypeExt;
508        let metadata = match std::fs::symlink_metadata(target) {
509            Ok(metadata) => metadata,
510            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
511            Err(err) => return Err(err.into()),
512        };
513        if !metadata.file_type().is_symlink() {
514            anyhow::bail!(
515                "Refusing to remove {:?}: expected a link but found a real file or directory",
516                target
517            );
518        }
519        // `remove_dir` on a directory link removes the link, not its contents.
520        if metadata.file_type().is_symlink_dir() {
521            std::fs::remove_dir(target)?;
522        } else {
523            std::fs::remove_file(target)?;
524        }
525        Ok(())
526    }
527    #[cfg(not(windows))]
528    {
529        // `remove_file` unlinks a symlink of either kind and refuses a real
530        // directory outright, which is precisely the guarantee wanted here.
531        match std::fs::remove_file(target) {
532            Ok(()) => Ok(()),
533            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
534            Err(err) => Err(err.into()),
535        }
536    }
537}
538
539/// Unconditional removal of whatever is at `target`.
540///
541/// **Unchecked**: this will `remove_dir_all` a real directory regardless of
542/// whose it is. Deployment paths must go through [`remove_classified_target`]
543/// (or [`sync_skill`]) instead; this remains for callers that have already
544/// established ownership another way.
545pub fn remove_target(target: &Path) -> Result<()> {
546    let metadata = match std::fs::symlink_metadata(target) {
547        Ok(metadata) => metadata,
548        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
549        Err(err) => return Err(err.into()),
550    };
551
552    // An actual removal from a watched dir follows: mute the self-write echo.
553    crate::core::file_watcher::mute_self_writes(target);
554
555    if metadata.file_type().is_symlink() {
556        #[cfg(windows)]
557        {
558            use std::os::windows::fs::FileTypeExt;
559            // Decide from the link's own metadata: `target.is_dir()` follows
560            // the link, so a dangling directory symlink/junction would be
561            // misclassified as a file and `remove_file` would fail, leaving
562            // a broken link behind.
563            if metadata.file_type().is_symlink_dir() {
564                std::fs::remove_dir(target)?;
565            } else {
566                std::fs::remove_file(target)?;
567            }
568        }
569        #[cfg(not(windows))]
570        {
571            std::fs::remove_file(target)?;
572        }
573    } else if metadata.is_dir() {
574        std::fs::remove_dir_all(target)?;
575    } else {
576        std::fs::remove_file(target)?;
577    }
578    Ok(())
579}
580
581fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
582    std::fs::create_dir_all(dst)?;
583    for entry in std::fs::read_dir(src)? {
584        let entry = entry?;
585        let ft = entry.file_type()?;
586        let dest_path = dst.join(entry.file_name());
587        if ft.is_dir() {
588            let name = entry.file_name();
589            if name == ".git" {
590                continue;
591            }
592            copy_dir_recursive(&entry.path(), &dest_path)?;
593        } else {
594            std::fs::copy(entry.path(), &dest_path)?;
595        }
596    }
597    Ok(())
598}
599
600#[cfg(test)]
601#[path = "sync_engine/replacement_tests.rs"]
602mod replacement_tests;
603
604#[cfg(test)]
605mod tests;