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

171 lines
6.1 KiB
Go

package sync
import (
"errors"
"fmt"
"os"
"skillshare/internal/config"
"skillshare/internal/sourcewalk"
"skillshare/internal/utils"
)
// ErrSymlinkConflict marks a symlink-mode target whose link points somewhere
// other than the source. Force replaces the link.
var ErrSymlinkConflict = errors.New("conflict")
// SkillTarget is one target a skill sync visits.
type SkillTarget struct {
Name string
Target config.TargetConfig
Mode string // resolved skills mode: merge, copy, or anything else for symlink
}
// SkillRunOptions holds what differs between skill sync callers.
type SkillRunOptions struct {
Source string // skills source directory
ProjectRoot string // "" in global mode
IgnorePatterns []string
DryRun bool
Force bool
// SourceIncomplete means a followed source link could not be read, so
// skills are missing from the list without being removed. Nothing is
// pruned; linking and copying still run.
SourceIncomplete bool
// OnProgress reports copy-mode progress; nil reports nothing.
OnProgress func(current, total int, skill string)
}
// SkillTargetResult is the outcome of a skill sync for one target.
type SkillTargetResult struct {
Name string
Mode string
Linked []string // merge: linked; copy: copied
Updated []string
Skipped []string
// KeptLocal are the skipped entries that are a user's folder, or a link
// skillshare did not create, on a skill's name.
KeptLocal []string
Pruned []string // nil when no prune ran or it returned nothing
// LocalDirs are user folders a merge prune kept.
LocalDirs []string
DirCreated string
// SymlinkStatus is the target path's status before a symlink-mode sync.
SymlinkStatus TargetStatus
Warnings []string // prune failure, the prune's own warnings, then the kept user folders
// UnmatchedIncludes are the include patterns that select no skill;
// UnmatchedWarnings renders them for the CLI.
UnmatchedIncludes []UnmatchedInclude
Err error // the target failed to sync; nothing else is set
}
// SyncSkillTarget links, copies, or symlinks skills into one target, then
// prunes orphans left by earlier syncs. It prints nothing and writes no oplog.
func SyncSkillTarget(t SkillTarget, skills []DiscoveredSkill, opts SkillRunOptions) SkillTargetResult {
res := SkillTargetResult{Name: t.Name, Mode: t.Mode}
sc := t.Target.SkillsConfig()
switch t.Mode {
case "merge":
result, err := SyncTargetMergeWithSkills(t.Name, t.Target, skills, opts.Source, opts.DryRun, opts.Force, opts.ProjectRoot)
if err != nil {
res.Err = err
return res
}
res.Linked, res.Updated, res.Skipped, res.DirCreated = result.Linked, result.Updated, result.Skipped, result.DirCreated
res.KeptLocal = result.Skipped // merge skips only entries skillshare did not create
// A partial source may hold what the filter names, so only a full one reports unmatched patterns.
if opts.SourceIncomplete {
break
}
res.UnmatchedIncludes = result.UnmatchedIncludes
prune, err := PruneOrphanLinksWithSkills(PruneOptions{
SharedTargets: sc.SharedTargets,
Agent: sc.Agent,
TargetPath: sc.Path, SourcePath: opts.Source, Skills: skills,
Include: sc.Include, Exclude: sc.Exclude, TargetNaming: sc.TargetNaming, TargetName: t.Name,
DryRun: opts.DryRun, Force: opts.Force,
})
res.addPrune(prune, err)
if prune != nil {
res.LocalDirs = prune.LocalDirs
}
case "copy":
result, err := SyncTargetCopyWithSkillsOptions(t.Name, t.Target, skills, opts.Source, opts.DryRun, opts.Force, opts.OnProgress, CopyOptions{IgnorePatterns: opts.IgnorePatterns})
if err != nil {
res.Err = err
return res
}
res.Linked, res.Updated, res.Skipped, res.DirCreated = result.Copied, result.Updated, result.Skipped, result.DirCreated
res.KeptLocal = result.KeptLocal
// A partial source may hold what the filter names, so only a full one reports unmatched patterns.
if opts.SourceIncomplete {
break
}
res.UnmatchedIncludes = result.UnmatchedIncludes
prune, err := pruneOrphanCopiesWithConfig(t.Name, sc, skills, opts.DryRun)
res.addPrune(prune, err)
default:
res.SymlinkStatus = CheckStatus(sc.Path, opts.Source)
// A symlink pointing elsewhere is replaced only with force.
if res.SymlinkStatus == StatusConflict {
if !opts.Force {
link, err := utils.ResolveLinkTarget(sc.Path)
if err != nil {
link = "(unable to resolve target)"
}
res.Err = fmt.Errorf("%w - symlink points to %s (use --force to override)", ErrSymlinkConflict, link)
return res
}
if !opts.DryRun {
os.Remove(sc.Path)
}
}
res.Err = SyncTarget(t.Name, t.Target, opts.Source, opts.DryRun, opts.ProjectRoot)
}
if len(res.KeptLocal) > 0 {
res.Warnings = append(res.Warnings, fmt.Sprintf("%s: %s", res.Name, keptLocalWarning(res.KeptLocal)))
}
if warning := variantRemovalWarning(t.Name, sc, skills, res.Pruned, opts.DryRun); warning != "" {
res.Warnings = append(res.Warnings, warning)
}
return res
}
// SourceLinkWarnings returns one warning per first-level source link the walk
// did not follow. With pruneSkipped, a warning for an unavailable link also
// says that target entries were kept.
func SourceLinkWarnings(walk sourcewalk.Options, pruneSkipped bool) []string {
var warnings []string
for _, s := range walk.Follow.Skipped() {
w := s.String()
if pruneSkipped && s.Unavailable {
w += "; kept existing target entries, nothing pruned this run"
}
warnings = append(warnings, w)
}
return warnings
}
// UnmatchedWarnings renders the unmatched include patterns, one line each, named by target.
func (res SkillTargetResult) UnmatchedWarnings() []string {
warnings := make([]string, 0, len(res.UnmatchedIncludes))
for _, u := range res.UnmatchedIncludes {
warnings = append(warnings, fmt.Sprintf("%s: %s", res.Name, u.Warning()))
}
return warnings
}
// addPrune records a prune's removals and reports its failure and warnings.
func (res *SkillTargetResult) addPrune(prune *PruneResult, err error) {
if err != nil {
res.Warnings = append(res.Warnings, fmt.Sprintf("%s: prune failed: %v", res.Name, err))
}
if prune != nil {
res.Pruned = prune.Removed
res.Warnings = append(res.Warnings, prune.Warnings...)
}
}