Files
1419b62499 fix(sync): never delete or re-point entries skillshare did not create (#914)
* fix(sync): never delete or re-point entries skillshare did not create

On Windows, a plain `init` followed by `sync` deleted things in
~/.claude/skills that skillshare never created, with no backup and no
prompt. It also re-pointed another tool's junction. Seen in a sandbox
run of v0.30.7:

- prune removed real folders whose names only look like skillshare's
  flat naming (team__shared, _drafts), via the name heuristic
- prune removed a broken link that another tool or the user made
- merge sync deleted and re-created a same-name link that pointed into
  another manager's store
- init's import deleted original folders that matched the source
  byte for byte

The manifest already records what skillshare made, so use it:

- prune keeps a look-alike folder that is not in the manifest and warns
  once per sync; --force still removes it
- prune removes a broken external link only if the manifest records it
  (e.g. after the source moved); otherwise it keeps the link and warns
- merge sync re-points a link only if the manifest records it or it
  already points into the source; otherwise it reports the entry as
  kept local, as it already does for a real folder; --force replaces it
- init's import moves identical copies to the trash under
  replaced-by-init/<target>/ instead of deleting them

Tests: ownership_test.go adds regression tests that use createLink, so
they run on Windows without Developer Mode (junctions). The 4 keep
tests fail without this change. TestSyncTargetMerge_FixesBrokenLink now
records the link in the manifest first, since a same-name link that
skillshare did not make is no longer re-pointed. Existing tests in
internal/sync, internal/trash and cmd/skillshare show the same failures
on a Windows host with and without the change (symlink privilege). The
devcontainer suite has not been run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: say what sync and init keep when skillshare did not create it

The previous commit makes sync and init leave alone entries skillshare
did not create. Update the pages that describe that behaviour:

- sync-modes: merge mode keeps a same-name link from another tool and
  reports it as local; orphan cleanup keeps folders that only look like
  skillshare's flat names, and broken links outside the source that the
  manifest does not record. sync --force still removes them.
- init: identical folders replaced with links during the first sync go
  to the trash first (replaced-by-init/<tool>/, cleaned after 7 days).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(sourcefs): drop the raw-write allowance replaceIdenticalCopies no longer needs

replaceIdenticalCopies now moves an identical copy to the trash instead
of calling os.RemoveAll, so TestRawWriteRatchet reports its allowance as
stale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): apply the ownership rule at every consumer

Review of the first commit found places that still did, or predicted,
the old behaviour. One rule now decides whether a link is skillshare's:
Manifest.OwnsLink (the manifest records a link there, or it points into
the source). It compares canonical paths, so a source reached through an
alias and a relative project link still count as skillshare's.

- copy mode kept re-pointing: it removed any same-name link and wrote a
  copy. It now keeps a link it does not own, like merge mode.
- the dashboard diff predicted a prune for a folder that is only named
  like skillshare's, and an update for another tool's link. It now
  reports them as local and kept. The orphan-link prediction uses the
  same rule as prune.
- `diff` reported a target as in sync while sync printed "kept local"
  for another tool's link. It lists the link as a local override.
- doctor reported a broken link skillshare did not create as an error
  and suggested `skillshare sync`, which now keeps it. It is a warning
  with its own row, and `broken_symlinks` is `warning` in --json.
- `trash restore` put a folder init had replaced into the source as a
  new nested skill. Restore refuses entries under replaced-by-init/ and
  names the trash folder to copy from.
- init reported a folder it could not move to the trash as one that
  differs from the source, and dropped the error. It is reported
  separately, with the error.
- the PruneOptions.ManagedOnly comment still said broken external links
  are skipped; manifest-recorded ones are removed.

Tests cover the states the review listed: a source behind an alias, a
relative project link, ManagedOnly, standard naming, dry run with
--force, and a recorded copy the user replaced with a link.
TestSync_Pruning_RemovesBrokenExternalSymlinks passed without testing
anything, because FileExists follows links; it is now two tests that
use Lstat, one per owner.

Agent merge is unchanged: agents have no link manifest.

* fix(diff): list another tool's link as kept in copy mode too

Copy mode now keeps a same-name link skillshare did not create, but both
diffs read the entry with os.Stat. A broken link showed as a skill to
add on every run, and a live one as a plain local copy, while sync kept
both and said "kept local".

`diff` and the dashboard diff check the link first and report it the way
merge mode does: a local override, kept until --force.

* test(sync): make the aliased-source link while its folder exists

TestSyncMergeRepointsUnrecordedLinkIntoAliasedSource failed on Windows:
it linked straight to a missing folder, and a junction cannot be made
to one. It now links first and removes the folder after, like the other
broken-link tests in this file.

* fix(sync): compare a broken link by where it would point

linksIntoSource resolved both paths with EvalSymlinks, which gives up on
a path that does not exist. A broken link is exactly that, so a link
into a source reached through an alias (a symlinked config folder, or a
short 8.3 path on Windows) compared an unresolved path with a resolved
one and was taken for another tool's link. Sync then kept it instead of
repairing or pruning it.

It now uses sourcewalk.Canonical, which resolves the nearest folder that
exists and keeps the missing tail. The test covers both spellings: the
alias in the link, and the alias in the configured source.

* fix(init): report what the first sync kept, and match prune in the diff

Two previews said less, or more, than sync does.

init ran its first sync quietly and printed only "Synced". Sync now keeps
a link another tool put on a skill's name, a folder that is only named
like skillshare's, and a broken link it did not create, so the skill was
reported as synced while the tool still loaded the other copy. firstSync
returns the warnings a plain sync prints, and init shows them. They
already name the folders that differ from the source, so the separate
list of those is gone.

The dashboard diff counted an orphan link as a removal whenever the
manifest recorded it. Prune keeps a recorded link that still resolves
outside the source (the source moved and the old checkout stayed), so
the Sync page showed a removal that never happened. The diff now uses
prune's own rule: a link into the source goes when broken or recorded;
any other link only when broken and recorded.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Willie <egg358358@gmail.com>
2026-11-17 04:15:04 +08:00

480 lines
14 KiB
Go

package trash
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestMoveToTrash(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
srcDir := filepath.Join(tmpDir, "source", "my-skill")
// Create source skill
os.MkdirAll(srcDir, 0755)
os.WriteFile(filepath.Join(srcDir, "SKILL.md"), []byte("# Test"), 0644)
trashPath, err := MoveToTrash(srcDir, "my-skill", trashBase)
if err != nil {
t.Fatalf("MoveToTrash failed: %v", err)
}
// Source should be gone
if _, err := os.Stat(srcDir); !os.IsNotExist(err) {
t.Error("source should be removed after MoveToTrash")
}
// Trash should contain the skill
if _, err := os.Stat(filepath.Join(trashPath, "SKILL.md")); err != nil {
t.Error("trashed skill should contain SKILL.md")
}
// Trash path should be under trashBase
if rel, err := filepath.Rel(trashBase, trashPath); err != nil || rel == "" {
t.Error("trash path should be under trashBase")
}
}
func TestList(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
// Create two trashed items
os.MkdirAll(filepath.Join(trashBase, "skill-a_2026-01-01_10-00-00"), 0755)
os.WriteFile(filepath.Join(trashBase, "skill-a_2026-01-01_10-00-00", "SKILL.md"), []byte("a"), 0644)
os.MkdirAll(filepath.Join(trashBase, "skill-b_2026-01-02_10-00-00"), 0755)
os.WriteFile(filepath.Join(trashBase, "skill-b_2026-01-02_10-00-00", "SKILL.md"), []byte("b"), 0644)
items := List(trashBase)
if len(items) != 2 {
t.Fatalf("expected 2 items, got %d", len(items))
}
// Newest first
if items[0].Name != "skill-b" {
t.Errorf("expected newest first, got %s", items[0].Name)
}
if items[1].Name != "skill-a" {
t.Errorf("expected skill-a second, got %s", items[1].Name)
}
}
func TestList_Empty(t *testing.T) {
items := List("/nonexistent/path")
if len(items) != 0 {
t.Errorf("expected 0 items for nonexistent path, got %d", len(items))
}
}
func TestList_SkillNameWithUnderscore(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
// Tracked repo with _ prefix
os.MkdirAll(filepath.Join(trashBase, "_team-repo_2026-01-01_10-00-00"), 0755)
items := List(trashBase)
if len(items) != 1 {
t.Fatalf("expected 1 item, got %d", len(items))
}
if items[0].Name != "_team-repo" {
t.Errorf("expected _team-repo, got %s", items[0].Name)
}
}
func TestCleanup(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
// Create an old item (8 days ago)
old := time.Now().Add(-8 * 24 * time.Hour).Format("2006-01-02_15-04-05")
os.MkdirAll(filepath.Join(trashBase, "old-skill_"+old), 0755)
// Create a recent item (1 day ago)
recent := time.Now().Add(-1 * 24 * time.Hour).Format("2006-01-02_15-04-05")
os.MkdirAll(filepath.Join(trashBase, "new-skill_"+recent), 0755)
removed, err := Cleanup(trashBase, 7*24*time.Hour)
if err != nil {
t.Fatalf("Cleanup failed: %v", err)
}
if removed != 1 {
t.Errorf("expected 1 removed, got %d", removed)
}
items := List(trashBase)
if len(items) != 1 {
t.Fatalf("expected 1 item remaining, got %d", len(items))
}
if items[0].Name != "new-skill" {
t.Errorf("expected new-skill to remain, got %s", items[0].Name)
}
}
func TestDelete_RemovesSavedMetadata(t *testing.T) {
entry := filepath.Join(t.TempDir(), "foo_2026-01-01_00-00-00")
os.MkdirAll(entry, 0755)
os.WriteFile(MetadataFile(entry), []byte("{}"), 0644)
if err := Delete(entry); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(MetadataFile(entry)); !os.IsNotExist(err) {
t.Errorf("saved metadata should be gone, got %v", err)
}
}
func TestTotalSize(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
os.MkdirAll(filepath.Join(trashBase, "skill_2026-01-01_10-00-00"), 0755)
os.WriteFile(filepath.Join(trashBase, "skill_2026-01-01_10-00-00", "SKILL.md"), []byte("hello"), 0644)
size := TotalSize(trashBase)
if size != 5 {
t.Errorf("expected size 5, got %d", size)
}
}
func TestFindByName(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
os.MkdirAll(filepath.Join(trashBase, "my-skill_2026-01-01_10-00-00"), 0755)
os.MkdirAll(filepath.Join(trashBase, "my-skill_2026-01-02_10-00-00"), 0755)
os.MkdirAll(filepath.Join(trashBase, "other_2026-01-01_10-00-00"), 0755)
// Should return the newest match
entry := FindByName(trashBase, "my-skill")
if entry == nil {
t.Fatal("expected to find my-skill")
}
if entry.Timestamp != "2026-01-02_10-00-00" {
t.Errorf("expected newest entry, got %s", entry.Timestamp)
}
// Not found
if FindByName(trashBase, "nonexistent") != nil {
t.Error("expected nil for nonexistent skill")
}
}
func TestRestore(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
destDir := filepath.Join(tmpDir, "skills")
os.MkdirAll(destDir, 0755)
// Trash a skill first
srcDir := filepath.Join(tmpDir, "src", "restore-me")
os.MkdirAll(srcDir, 0755)
os.WriteFile(filepath.Join(srcDir, "SKILL.md"), []byte("# Restore"), 0644)
MoveToTrash(srcDir, "restore-me", trashBase)
entry := FindByName(trashBase, "restore-me")
if entry == nil {
t.Fatal("expected to find restore-me in trash")
}
if err := Restore(entry, destDir); err != nil {
t.Fatalf("Restore failed: %v", err)
}
// Should be back in dest
restored := filepath.Join(destDir, "restore-me", "SKILL.md")
if _, err := os.Stat(restored); err != nil {
t.Error("restored skill should contain SKILL.md")
}
// Trash entry should be gone
if FindByName(trashBase, "restore-me") != nil {
t.Error("trash entry should be removed after restore")
}
}
func TestRestore_AlreadyExists(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
destDir := filepath.Join(tmpDir, "skills")
// Create existing skill in dest
os.MkdirAll(filepath.Join(destDir, "conflict"), 0755)
// Create trash entry
os.MkdirAll(filepath.Join(trashBase, "conflict_2026-01-01_10-00-00"), 0755)
entry := FindByName(trashBase, "conflict")
if entry == nil {
t.Fatal("expected to find conflict in trash")
}
err := Restore(entry, destDir)
if err == nil {
t.Error("expected error when dest already exists")
}
}
func TestMoveToTrash_NestedName(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
srcDir := filepath.Join(tmpDir, "source", "org", "_team-skills")
os.MkdirAll(srcDir, 0755)
os.WriteFile(filepath.Join(srcDir, "README.md"), []byte("# Team"), 0644)
trashPath, err := MoveToTrash(srcDir, "org/_team-skills", trashBase)
if err != nil {
t.Fatalf("MoveToTrash failed: %v", err)
}
if _, err := os.Stat(srcDir); !os.IsNotExist(err) {
t.Error("source should be removed after MoveToTrash")
}
if _, err := os.Stat(filepath.Join(trashPath, "README.md")); err != nil {
t.Error("trashed repo should contain README.md")
}
// Trash path should be nested under trashBase/org/
rel, err := filepath.Rel(trashBase, trashPath)
if err != nil || strings.HasPrefix(rel, "..") {
t.Errorf("trash path should be under trashBase, rel=%q err=%v", rel, err)
}
if dir := filepath.Dir(rel); dir != "org" {
t.Errorf("expected parent dir 'org', got %q", dir)
}
}
func TestList_NestedEntries(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
// Flat entry
os.MkdirAll(filepath.Join(trashBase, "skill-a_2026-01-01_10-00-00"), 0755)
// Nested entry
os.MkdirAll(filepath.Join(trashBase, "org", "_team-skills_2026-01-02_10-00-00"), 0755)
items := List(trashBase)
if len(items) != 2 {
t.Fatalf("expected 2 items, got %d", len(items))
}
// Newest first
if items[0].Name != "org/_team-skills" {
t.Errorf("expected 'org/_team-skills', got %q", items[0].Name)
}
if items[1].Name != "skill-a" {
t.Errorf("expected 'skill-a', got %q", items[1].Name)
}
}
func TestList_SkipsReservedAgentTrashSubtree(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
os.MkdirAll(filepath.Join(trashBase, "skill-a_2026-01-01_10-00-00"), 0755)
os.MkdirAll(filepath.Join(trashBase, "agents", "demo", "code-archaeologist_2026-01-02_10-00-00"), 0755)
items := List(trashBase)
if len(items) != 1 {
t.Fatalf("expected only skill trash items, got %d", len(items))
}
if items[0].Name != "skill-a" {
t.Fatalf("expected only skill-a, got %q", items[0].Name)
}
}
func TestFindByName_NestedName(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
os.MkdirAll(filepath.Join(trashBase, "org", "_team-skills_2026-01-01_10-00-00"), 0755)
entry := FindByName(trashBase, "org/_team-skills")
if entry == nil {
t.Fatal("expected to find org/_team-skills")
}
if entry.Name != "org/_team-skills" {
t.Errorf("expected Name 'org/_team-skills', got %q", entry.Name)
}
}
func TestFindByName_SkipsReservedAgentTrashSubtree(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
os.MkdirAll(filepath.Join(trashBase, "agents", "demo", "code-archaeologist_2026-01-01_10-00-00"), 0755)
if entry := FindByName(trashBase, "agents/demo/code-archaeologist"); entry != nil {
t.Fatalf("expected reserved agent subtree to be ignored, got %q", entry.Name)
}
}
func TestRestore_NestedName(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
destDir := filepath.Join(tmpDir, "skills")
// Note: destDir/org/ does NOT exist yet — Restore should create it
srcDir := filepath.Join(tmpDir, "src", "org", "_team-skills")
os.MkdirAll(srcDir, 0755)
os.WriteFile(filepath.Join(srcDir, "README.md"), []byte("# Team"), 0644)
MoveToTrash(srcDir, "org/_team-skills", trashBase)
entry := FindByName(trashBase, "org/_team-skills")
if entry == nil {
t.Fatal("expected to find org/_team-skills in trash")
}
if err := Restore(entry, destDir); err != nil {
t.Fatalf("Restore failed: %v", err)
}
restored := filepath.Join(destDir, "org", "_team-skills", "README.md")
if _, err := os.Stat(restored); err != nil {
t.Error("restored repo should contain README.md at nested path")
}
if FindByName(trashBase, "org/_team-skills") != nil {
t.Error("trash entry should be removed after restore")
}
}
func TestCleanup_NestedEntry(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
// Create an expired nested entry (8 days ago)
old := time.Now().Add(-8 * 24 * time.Hour).Format("2006-01-02_15-04-05")
os.MkdirAll(filepath.Join(trashBase, "org", "_team-skills_"+old), 0755)
removed, err := Cleanup(trashBase, 7*24*time.Hour)
if err != nil {
t.Fatalf("Cleanup failed: %v", err)
}
if removed != 1 {
t.Errorf("expected 1 removed, got %d", removed)
}
// Empty parent dir should also be cleaned
if _, err := os.Stat(filepath.Join(trashBase, "org")); !os.IsNotExist(err) {
t.Error("expected empty parent dir 'org' to be cleaned up")
}
}
func TestCleanEmptyParents_MultiLevel(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
// Create a 3-level nested empty structure: trash/a/b/c/
deepDir := filepath.Join(trashBase, "a", "b", "c")
os.MkdirAll(deepDir, 0755)
// cleanEmptyParents starts from Dir(path), so pass a child of deepDir
os.Remove(deepDir) // remove c/ first (simulating the item being deleted)
cleanEmptyParents(deepDir, trashBase)
// All empty dirs should be removed
if _, err := os.Stat(filepath.Join(trashBase, "a")); !os.IsNotExist(err) {
t.Error("expected all empty parent dirs to be removed")
}
// trashBase itself should survive
if _, err := os.Stat(trashBase); os.IsNotExist(err) {
t.Error("trashBase should not be removed")
}
}
func TestCleanEmptyParents_StopsAtNonEmpty(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
// Create: trash/org/keep.txt and trash/org/sub/ (empty)
orgDir := filepath.Join(trashBase, "org")
subDir := filepath.Join(orgDir, "sub")
os.MkdirAll(subDir, 0755)
os.WriteFile(filepath.Join(orgDir, "keep.txt"), []byte("keep"), 0644)
// Remove sub/ then clean parents — org/ has keep.txt so should survive
os.Remove(subDir)
cleanEmptyParents(subDir, trashBase)
if _, err := os.Stat(subDir); !os.IsNotExist(err) {
t.Error("expected empty sub/ to stay removed")
}
if _, err := os.Stat(orgDir); os.IsNotExist(err) {
t.Error("expected org/ to survive (has keep.txt)")
}
}
func TestCleanEmptyParents_StopsAtBoundary(t *testing.T) {
tmpDir := t.TempDir()
trashBase := filepath.Join(tmpDir, "trash")
// Create: trash/level1/ (empty)
level1 := filepath.Join(trashBase, "level1")
os.MkdirAll(level1, 0755)
// Remove level1 then call cleanEmptyParents
os.Remove(level1)
cleanEmptyParents(level1, trashBase)
// trashBase should survive
if _, err := os.Stat(trashBase); os.IsNotExist(err) {
t.Error("trashBase should not be removed")
}
}
func TestParseTrashName(t *testing.T) {
tests := []struct {
input string
wantName string
wantTS string
}{
{"my-skill_2026-01-01_10-00-00", "my-skill", "2026-01-01_10-00-00"},
{"_team-repo_2026-01-01_10-00-00", "_team-repo", "2026-01-01_10-00-00"},
{"a_b_c_2026-12-31_23-59-59", "a_b_c", "2026-12-31_23-59-59"},
{"short", "", ""}, // too short
{"no-timestamp_abc", "", ""}, // invalid timestamp
}
for _, tt := range tests {
name, ts := parseTrashName(tt.input)
if name != tt.wantName || ts != tt.wantTS {
t.Errorf("parseTrashName(%q) = (%q, %q), want (%q, %q)",
tt.input, name, ts, tt.wantName, tt.wantTS)
}
}
}
// A folder init replaced with a link came from a tool. Restoring it would
// plant it in the source as a new nested skill, so restore refuses it.
func TestRestore_RefusesFolderReplacedByInit(t *testing.T) {
base := t.TempDir()
copyDir := filepath.Join(t.TempDir(), "alpha")
if err := os.MkdirAll(copyDir, 0o755); err != nil {
t.Fatal(err)
}
if _, err := MoveToTrash(copyDir, "alpha", filepath.Join(base, ReplacedByInitDir, "claude")); err != nil {
t.Fatal(err)
}
entry := FindByName(base, ReplacedByInitDir+"/claude/alpha")
if entry == nil {
t.Fatalf("entry not listed: %+v", List(base))
}
source := t.TempDir()
err := Restore(entry, source)
if err == nil || !strings.Contains(err.Error(), entry.Path) {
t.Fatalf("want a refusal naming the trash copy, got %v", err)
}
if left, _ := os.ReadDir(source); len(left) != 0 {
t.Errorf("restore wrote into the source: %v", left)
}
}