From 5b249b60fe03b23a2131508010d6346dec883d58 Mon Sep 17 00:00:00 2001 From: Willie Date: Tue, 17 Nov 2026 13:03:42 +0800 Subject: [PATCH] refactor(sync): share one orphan-link rule between prune and the dashboard (#937) The Sync page predicted which orphan links sync would remove with its own copy of prune's rule. The copy had already drifted once (#914), and it still disagreed in two cases: prune treats a link it cannot follow, such as a loop, as broken, while the page only counted a missing destination; and prune keeps a link whose target it cannot read. The decision now lives in sync.OrphanLink. Prune and the dashboard diff both call it, so a later change to the rule reaches both. Prune's results, warnings and dry-run text are unchanged. LinksIntoSource, added for the dashboard's copy, is no longer needed and is removed. --- internal/server/handler_diff_stream.go | 7 +--- internal/server/handler_diff_test.go | 20 +++++++++ internal/sync/manifest.go | 56 +++++++++++++++++++++++--- internal/sync/ownership_test.go | 47 +++++++++++++++++++++ internal/sync/sync.go | 56 +++++--------------------- 5 files changed, 129 insertions(+), 57 deletions(-) diff --git a/internal/server/handler_diff_stream.go b/internal/server/handler_diff_stream.go index 307935a35..22bfff355 100644 --- a/internal/server/handler_diff_stream.go +++ b/internal/server/handler_diff_stream.go @@ -233,13 +233,8 @@ func (s *Server) computeTargetDiff(name string, target config.TargetConfig, disc continue } if utils.IsSymlinkOrJunction(entryPath) { - // As prune does: a link into the source goes once it is broken or - // while the manifest records it; a link to anywhere else only when - // it is both broken and recorded. - _, statErr := os.Stat(entryPath) - broken := os.IsNotExist(statErr) _, inManifest := manifest.Managed[eName] - if inSource := ssync.LinksIntoSource(entryPath, source); (inSource && (broken || inManifest)) || (!inSource && broken && inManifest) { + if ssync.OrphanLink(entryPath, source, inManifest, false).RemoveReason != "" { dt.Items = append(dt.Items, diffItem{Skill: eName, Action: "prune", Reason: "orphan symlink", Kind: kindSkill}) } } else if info.IsDir() { diff --git a/internal/server/handler_diff_test.go b/internal/server/handler_diff_test.go index 0ed266cda..eceaebd9c 100644 --- a/internal/server/handler_diff_test.go +++ b/internal/server/handler_diff_test.go @@ -226,3 +226,23 @@ func TestComputeTargetDiff_KeepsRecordedLinkThatStillResolvesElsewhere(t *testin t.Fatalf("items = %+v, want only the broken link pruned", dt.Items) } } + +// Prune treats a link it cannot follow as broken, not only one whose +// destination is missing. A recorded link that loops is removed by sync, so the +// diff must list it. +func TestComputeTargetDiff_ListsRecordedLinkThatCannotBeFollowed(t *testing.T) { + source, target := t.TempDir(), t.TempDir() + loop := filepath.Join(target, "loop") + if err := os.Symlink(loop, loop); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + if err := sync.WriteManifest(target, &sync.Manifest{Managed: map[string]string{"loop": "symlink"}}); err != nil { + t.Fatal(err) + } + + dt := (&Server{}).computeTargetDiff("claude", config.TargetConfig{Skills: &config.ResourceTargetConfig{Path: target, Mode: "merge"}}, nil, "merge", source, nil) + + if len(dt.Items) != 1 || dt.Items[0].Skill != "loop" || dt.Items[0].Action != "prune" { + t.Fatalf("items = %+v, want the looping link pruned", dt.Items) + } +} diff --git a/internal/sync/manifest.go b/internal/sync/manifest.go index d3a209253..d0f02e46c 100644 --- a/internal/sync/manifest.go +++ b/internal/sync/manifest.go @@ -2,6 +2,7 @@ package sync import ( "encoding/json" + "fmt" "os" "path/filepath" "time" @@ -91,16 +92,59 @@ func (m *Manifest) OwnsLink(name, path, sourcePath string) bool { if m != nil && m.Managed[name] == manifestSymlink { return true } - return LinksIntoSource(path, sourcePath) -} - -// LinksIntoSource reports whether the link at path points at the skills source -// or inside it, however either path is spelled. -func LinksIntoSource(path, sourcePath string) bool { absSource, err := filepath.Abs(sourcePath) return err == nil && linksIntoSource(path, absSource) } +// OrphanLinkVerdict is what prune does with a link in a target that no skill +// in the source maps to. At most one field is set; none means the link is kept +// without comment, as the user's own. +type OrphanLinkVerdict struct { + // RemoveReason says why prune removes the link. + RemoveReason string + // KeptWarning is what sync prints after the entry name when it keeps the + // link and says so. + KeptWarning string +} + +// OrphanLink decides what prune does with the orphan link at path. inManifest +// says whether the manifest records the entry. Prune and the dashboard diff +// both call this, so they cannot disagree. +func OrphanLink(path, sourcePath string, inManifest, force bool) OrphanLinkVerdict { + dest, err := utils.ResolveLinkTarget(path) + if err != nil { + return OrphanLinkVerdict{KeptWarning: "unable to resolve link target, kept"} + } + _, statErr := os.Stat(dest) + broken := statErr != nil + absSource, absErr := filepath.Abs(sourcePath) + + switch { + case absErr == nil && linksIntoSource(path, absSource): + if broken { + return OrphanLinkVerdict{RemoveReason: "broken symlink to source"} + } + if inManifest || force { + return OrphanLinkVerdict{RemoveReason: "orphan symlink to source"} + } + // A live link into the source that skillshare never created is the + // user's own wiring. + return OrphanLinkVerdict{} + case broken: + // The destination is gone, for example after the source moved. Remove + // the link only if skillshare made it: a broken link another tool or the + // user made is theirs to clean up. + if inManifest || force { + return OrphanLinkVerdict{RemoveReason: "broken external symlink"} + } + return OrphanLinkVerdict{KeptWarning: fmt.Sprintf("broken link to %s that skillshare did not create, kept (delete it yourself, or sync with --force)", dest)} + case force: + return OrphanLinkVerdict{RemoveReason: "external symlink (force)"} + default: + return OrphanLinkVerdict{KeptWarning: fmt.Sprintf("symlink to external location (%s), kept", dest)} + } +} + // SkipsHidden reports whether a target scan should skip name. Hidden entries // are skipped unless the manifest records them as managed (e.g. a source skill // under ".system/" synced as ".system__example"). diff --git a/internal/sync/ownership_test.go b/internal/sync/ownership_test.go index 79a36e1cc..271e40544 100644 --- a/internal/sync/ownership_test.go +++ b/internal/sync/ownership_test.go @@ -353,3 +353,50 @@ func TestSyncCopyKeepsLinkThatReplacedARecordedCopy(t *testing.T) { t.Errorf("link was replaced: %q (%v), want a link to %q", got, err, other) } } + +// OrphanLink is the one rule prune and its previews share. Each row is a link +// no skill maps to, with what prune does to it. +func TestOrphanLinkVerdict(t *testing.T) { + src, tgt := setupMergeTest(t, "alpha") + other := t.TempDir() + gone := filepath.Join(other, "gone") + if err := os.MkdirAll(gone, 0o755); err != nil { + t.Fatal(err) + } + dirLink(t, filepath.Join(tgt, "live-in-source"), filepath.Join(src, "alpha")) + dirLink(t, filepath.Join(tgt, "live-external"), other) + dirLink(t, filepath.Join(tgt, "broken-external"), gone) + renamed := filepath.Join(src, "renamed") + if err := os.MkdirAll(renamed, 0o755); err != nil { + t.Fatal(err) + } + dirLink(t, filepath.Join(tgt, "broken-in-source"), renamed) + for _, dir := range []string{gone, renamed} { + if err := os.RemoveAll(dir); err != nil { + t.Fatal(err) + } + } + + cases := []struct { + link string + inManifest, force bool + remove, warn bool + }{ + {link: "live-in-source"}, + {link: "live-in-source", inManifest: true, remove: true}, + {link: "live-in-source", force: true, remove: true}, + {link: "broken-in-source", remove: true}, + {link: "live-external", warn: true}, + {link: "live-external", inManifest: true, warn: true}, + {link: "live-external", force: true, remove: true}, + {link: "broken-external", warn: true}, + {link: "broken-external", inManifest: true, remove: true}, + {link: "broken-external", force: true, remove: true}, + } + for _, c := range cases { + got := OrphanLink(filepath.Join(tgt, c.link), src, c.inManifest, c.force) + if (got.RemoveReason != "") != c.remove || (got.KeptWarning != "") != c.warn { + t.Errorf("%s inManifest=%v force=%v: got %+v, want remove=%v warn=%v", c.link, c.inManifest, c.force, got, c.remove, c.warn) + } + } +} diff --git a/internal/sync/sync.go b/internal/sync/sync.go index 113689052..ded7fdfc2 100644 --- a/internal/sync/sync.go +++ b/internal/sync/sync.go @@ -840,8 +840,6 @@ func PruneOrphanLinksWithSkills(opts PruneOptions) (*PruneResult, error) { return nil, fmt.Errorf("failed to read target directory: %w", err) } - absSource, _ := filepath.Abs(sourcePath) - for _, entry := range entries { name := entry.Name() @@ -870,50 +868,18 @@ func PruneOrphanLinksWithSkills(opts PruneOptions) (*PruneResult, error) { _, inManifest := manifest.Managed[name] if utils.IsSymlinkOrJunction(entryPath) { - absLink, err := utils.ResolveLinkTarget(entryPath) - if err != nil { - result.Warnings = append(result.Warnings, - fmt.Sprintf("%s: unable to resolve link target, kept", name)) - continue - } - - targetExists := false - if _, err := os.Stat(absLink); err == nil { - targetExists = true - } - - if linksIntoSource(entryPath, absSource) { - if !targetExists { - shouldRemove = true - reason = "broken symlink to source" - } else if inManifest || force { - shouldRemove = true - reason = "orphan symlink to source" - } else { - // A live link into the source that skillshare never created is the - // user's own wiring. Keep it, like the directory branch below. - result.LocalDirs = append(result.LocalDirs, name) - continue - } - } else if !targetExists { - // External symlink whose target no longer exists (e.g. after data migration). - // Remove it only if skillshare made it: a broken link another tool or the - // user made is theirs to clean up. - if inManifest || force { - shouldRemove = true - reason = "broken external symlink" - } else { - result.Warnings = append(result.Warnings, - fmt.Sprintf("%s: broken link to %s that skillshare did not create, kept (delete it yourself, or sync with --force)", name, absLink)) - continue - } - } else if force { - // Valid external symlink, but force mode requested + verdict := OrphanLink(entryPath, sourcePath, inManifest, force) + switch { + case verdict.RemoveReason != "": shouldRemove = true - reason = "external symlink (force)" - } else { - result.Warnings = append(result.Warnings, - fmt.Sprintf("%s: symlink to external location (%s), kept", name, absLink)) + reason = verdict.RemoveReason + case verdict.KeptWarning != "": + result.Warnings = append(result.Warnings, name+": "+verdict.KeptWarning) + continue + default: + // Keep it, like the directory branch below. + result.LocalDirs = append(result.LocalDirs, name) + continue } } else if info.IsDir() { // Check manifest first (most reliable)