diff --git a/ai_docs/tests/move_installed_skill_runbook.md b/ai_docs/tests/move_installed_skill_runbook.md new file mode 100644 index 000000000..197d3babf --- /dev/null +++ b/ai_docs/tests/move_installed_skill_runbook.md @@ -0,0 +1,404 @@ +# CLI E2E Runbook: Move Installed Skills and Folders + +Verifies `skillshare move` and `POST /api/resources/batch/move`: installed skills +and whole folders change folder while their install records, audit state and +project lock pins follow, and nothing is downloaded again. + +**Origin**: [#510](https://github.com/runkids/skillshare/issues/510) — moving an +installed skill with `mv` strands its record in `.metadata.json`. + +## Scope + +- Global mode: one local-path skill and one git skill, one edited after install +- Dry run changes nothing; `move` does not sync +- Records (source, commit, group) re-keyed; `doctor` finds no record problem +- `sync` renames the target links; `check` still resolves the source +- Whole-folder move; a folder holding a tracked checkout or a followed link is refused whole +- Project mode: `skills.lock.json` pin, `config.yaml` group and `.gitignore` entry +- Web API against `ss ui` + +## Environment + +Run inside the devcontainer with `ssenv` isolation (`--init`). +Requires `git`, `jq` and `curl`. mdproof replaces `$HOME`, so the source is read +through `$XDG_CONFIG_HOME` and the target path through `ss status --json`. + +## Steps + +### 1. Setup: create a local skill and a local git repo, install both, sync + +```bash +rm -rf /tmp/ss-move-local /tmp/ss-move-git /tmp/ss-move-git.git /tmp/ss-move-linked /tmp/ss-move-proj +mkdir -p /tmp/ss-move-local/local-skill /tmp/ss-move-git/git-skill +printf -- "---\nname: local-skill\n---\n# Local\n" > /tmp/ss-move-local/local-skill/SKILL.md +printf -- "---\nname: git-skill\n---\n# Git\n" > /tmp/ss-move-git/git-skill/SKILL.md +cd /tmp/ss-move-git && git init -q -b main && git add . \ + && git -c user.name=t -c user.email=t@e.c -c commit.gpgsign=false commit -qm seed +git clone -q --bare /tmp/ss-move-git /tmp/ss-move-git.git +ss install /tmp/ss-move-local/local-skill -g +ss install file:///tmp/ss-move-git.git --skill git-skill -g +ss sync -g +CLAUDE=$(ss status -g --json | jq -r '.targets[] | select(.name=="claude") | .path') +ls "$CLAUDE" +``` + +Expected: +- exit_code: 0 +- git-skill +- local-skill + +### 2. Records exist before the move + +```bash +jq -c '.entries | {local: .["local-skill"].type, git: .["git-skill"].type, commit: (.["git-skill"].commit | length)}' $XDG_CONFIG_HOME/skillshare/skills/.metadata.json +``` + +Expected: +- exit_code: 0 +- jq: .local == "local" +- jq: .git == "git-https-subdir" +- jq: .commit == 40 + +### 3. Edit the git skill after install + +```bash +echo "# edited after install" >> $XDG_CONFIG_HOME/skillshare/skills/git-skill/SKILL.md +tail -1 $XDG_CONFIG_HOME/skillshare/skills/git-skill/SKILL.md +``` + +Expected: +- exit_code: 0 +- edited after install + +### 4. Dry run reports the plan + +```bash +ss move local-skill git-skill grp --dry-run --json -g +``` + +Expected: +- exit_code: 0 +- jq: .dry_run == true +- jq: (.moved | length) == 2 +- jq: .moved[0].to == "grp/local-skill" +- jq: (.failed | length) == 0 + +### 5. Dry run changed nothing + +```bash +SRC="$XDG_CONFIG_HOME/skillshare/skills" +jq -n --arg dirs "$(ls "$SRC" | tr '\n' ' ')" --slurpfile m "$SRC/.metadata.json" \ + '{dirs: $dirs, keys: ($m[0].entries | keys)}' +``` + +Expected: +- exit_code: 0 +- jq: (.keys | index("git-skill")) != null +- jq: (.keys | index("local-skill")) != null +- jq: (.keys | index("grp/git-skill")) == null +- jq: (.dirs | contains("grp")) == false + +### 6. Move both into grp + +```bash +ss move local-skill git-skill grp --json -g +``` + +Expected: +- exit_code: 0 +- jq: (.moved | length) == 2 +- jq: .moved[0].record == true +- jq: .moved[1].record == true +- jq: .moved[1].to == "grp/git-skill" +- jq: (.failed | length) == 0 + +### 7. Records moved with their skills + +```bash +SRC="$XDG_CONFIG_HOME/skillshare/skills" +jq -n --arg dirs "$(ls "$SRC/grp" | tr '\n' ' ')" --slurpfile m "$SRC/.metadata.json" '{ + dirs: $dirs, + keys: ($m[0].entries | keys), + group: $m[0].entries["grp/git-skill"].group, + source: $m[0].entries["grp/git-skill"].source, + commit: ($m[0].entries["grp/git-skill"].commit | length), + local_group: $m[0].entries["grp/local-skill"].group +}' +``` + +Expected: +- exit_code: 0 +- jq: (.keys | index("grp/git-skill")) != null +- jq: (.keys | index("grp/local-skill")) != null +- jq: (.keys | index("git-skill")) == null +- jq: (.keys | index("local-skill")) == null +- jq: .group == "grp" +- jq: .local_group == "grp" +- jq: .source == "file:///tmp/ss-move-git.git/git-skill" +- jq: .commit == 40 +- jq: (.dirs | contains("git-skill")) + +### 8. doctor finds no record problem + +The edited skill is the only integrity warning; nothing reports a missing record. + +```bash +ss doctor -g --json || true +``` + +Expected: +- jq: ([.checks[] | select(.message | test("missing on disk"; "i"))] | length) == 0 +- jq: ([.checks[] | select(.name == "skill_integrity")][0].details | length) == 1 +- jq: ([.checks[] | select(.name == "skill_integrity")][0].details[0] | startswith("grp/git-skill")) + +### 9. The old links stay until sync; sync renames them + +```bash +CLAUDE=$(ss status -g --json | jq -r '.targets[] | select(.name=="claude") | .path') +echo "--- before sync"; ls "$CLAUDE" +ss sync -g +echo "--- after sync"; ls "$CLAUDE" +``` + +Expected: +- exit_code: 0 +- --- before sync +- --- after sync +- grp__git-skill +- grp__local-skill + +### 10. check still resolves the source of the moved git skill + +```bash +ss check git-skill --json +``` + +Expected: +- exit_code: 0 +- jq: .skills[0].name == "grp/git-skill" +- jq: .skills[0].source == "file:///tmp/ss-move-git.git/git-skill" + +### 11. Move the whole folder + +```bash +ss move grp archive --json -g +``` + +Expected: +- exit_code: 0 +- jq: .moved[0].to == "archive/grp" +- jq: .moved[0].skills == 2 +- jq: .moved[0].record == true + +### 12. The folder arrived whole, records under the new prefix + +```bash +SRC="$XDG_CONFIG_HOME/skillshare/skills" +jq -n --arg dirs "$(ls "$SRC/archive/grp" | tr '\n' ' ')" --arg top "$(ls "$SRC" | tr '\n' ' ')" --slurpfile m "$SRC/.metadata.json" \ + '{dirs: $dirs, top: $top, keys: ($m[0].entries | keys), group: $m[0].entries["archive/grp/git-skill"].group}' +``` + +Expected: +- exit_code: 0 +- jq: (.dirs | contains("git-skill")) and (.dirs | contains("local-skill")) +- jq: (.top | contains("grp")) == false +- jq: (.keys | index("archive/grp/git-skill")) != null +- jq: .group == "archive/grp" + +### 13. A folder holding a tracked checkout is refused whole + +```bash +SRC="$XDG_CONFIG_HOME/skillshare/skills" +mkdir -p "$SRC/team/pdf" "$SRC/team/_vendor" +printf -- "---\nname: pdf\n---\n# Pdf\n" > "$SRC/team/pdf/SKILL.md" +git -C "$SRC/team/_vendor" init -q +ss move team archive --json -g +``` + +Expected: +- exit_code: 1 +- jq: (.moved | length) == 0 +- jq: .failed[0].code == "inside_tracked_repo" + +### 14. Nothing of the refused folder moved + +```bash +SRC="$XDG_CONFIG_HOME/skillshare/skills" +ls "$SRC/team" +ls "$SRC/archive" +``` + +Expected: +- exit_code: 0 +- pdf +- _vendor +- grp + +### 15. A skill below a followed link is refused + +```bash +mkdir -p /tmp/ss-move-linked/linked-skill +printf -- "---\nname: linked-skill\n---\n# Linked\n" > /tmp/ss-move-linked/linked-skill/SKILL.md +ss link /tmp/ss-move-linked --name dev --enable -g +``` + +Expected: +- exit_code: 0 +- Linked dev + +### 16. The refusal is a linked_folder with exit code 1 + +```bash +ss move dev/linked-skill archive --json -g +``` + +Expected: +- exit_code: 1 +- jq: (.moved | length) == 0 +- jq: .failed[0].code == "linked_folder" + +### 17. A destination that exists is never overwritten, not even with --force + +```bash +SRC="$XDG_CONFIG_HOME/skillshare/skills" +mkdir -p "$SRC/archive/pdf" "$SRC/solo-src/pdf" +printf -- "---\nname: pdf\n---\n# other\n" > "$SRC/archive/pdf/SKILL.md" +printf -- "---\nname: pdf\n---\n# solo\n" > "$SRC/solo-src/pdf/SKILL.md" +ss move solo-src/pdf archive --force --json -g +``` + +Expected: +- exit_code: 1 +- jq: .failed[0].code == "dest_exists" + +### 18. The existing destination is untouched + +```bash +cat "$XDG_CONFIG_HOME/skillshare/skills/archive/pdf/SKILL.md" +``` + +Expected: +- exit_code: 0 +- # other + +### 19. Project mode: initialize and install the git skill + +```bash +mkdir -p /tmp/ss-move-proj && cd /tmp/ss-move-proj +ss init -p --targets claude +ss install file:///tmp/ss-move-git.git --skill git-skill -p +jq -c '{keys: (.skills | keys), commit: (.skills["git-skill"].commit | length)}' .skillshare/skills.lock.json +``` + +Expected: +- exit_code: 0 +- "keys":["git-skill"] +- "commit":40 + +### 20. Project mode: the move keeps the pin, the group and the .gitignore entry + +```bash +cd /tmp/ss-move-proj +PIN=$(jq -r '.skills["git-skill"].commit' .skillshare/skills.lock.json) +ss move git-skill grp -p --json > /tmp/ss-move-proj/move.json || exit 1 +jq -n --arg pin "$PIN" --slurpfile move /tmp/ss-move-proj/move.json --slurpfile lock .skillshare/skills.lock.json \ + --arg cfg "$(grep -A4 '^skills:' .skillshare/config.yaml | tr '\n' ' ')" \ + --arg ign "$(grep 'skills/' .skillshare/.gitignore | tr '\n' ' ')" '{ + moved_to: $move[0].moved[0].to, + record: $move[0].moved[0].record, + lock_keys: ($lock[0].skills | keys), + pin_kept: ($lock[0].skills["grp/git-skill"].commit == $pin), + cfg: $cfg, + ign: $ign + }' +``` + +Expected: +- exit_code: 0 +- jq: .moved_to == "grp/git-skill" +- jq: .record == true +- jq: .lock_keys == ["grp/git-skill"] +- jq: .pin_kept == true +- jq: .cfg | contains("group: grp") +- jq: (.ign | contains("skills/grp/git-skill")) and (.ign | contains("skills/git-skill/") | not) + +### 21. Web API: start the dashboard server + +```bash +cd /tmp +ss ui start --no-open --port 49555 -g +sleep 2 +``` + +Expected: +- exit_code: 0 +- UI running + +### 22. Web API: partial failure is still 200 with a per-item error_code + +```bash +curl -s -X POST localhost:49555/api/resources/batch/move \ + -H "Content-Type: application/json" \ + -d '{"names":["archive/grp/git-skill","ghost"],"dest":"api-dest"}' +``` + +Expected: +- exit_code: 0 +- jq: .summary.succeeded == 1 +- jq: .summary.failed == 1 +- jq: .results[0].to == "api-dest/git-skill" +- jq: .results[0].flatName == "api-dest__git-skill" +- jq: .results[0].record == true +- jq: .results[1].error_code == "skill_not_found" + +### 23. Web API: a malformed destination is 400 + +```bash +curl -s -i -X POST localhost:49555/api/resources/batch/move \ + -H "Content-Type: application/json" -d '{"names":["x"],"dest":"../out"}' | head -1 +``` + +Expected: +- exit_code: 0 +- 400 + +### 24. Web API: agents are not supported + +```bash +curl -s -X POST localhost:49555/api/resources/batch/move \ + -H "Content-Type: application/json" -d '{"names":["x"],"dest":"grp","kind":"agent"}' +``` + +Expected: +- exit_code: 0 +- jq: .error_code == "unsupported_kind" + +### 25. oplog recorded the moves + +```bash +ss log --cmd move --json -g +``` + +Expected: +- exit_code: 0 +- "cmd":"move" + +### 26. Cleanup + +```bash +ss ui stop -g 2>/dev/null || true +ss unlink dev -g 2>/dev/null || true +rm -rf /tmp/ss-move-local /tmp/ss-move-git /tmp/ss-move-git.git /tmp/ss-move-linked /tmp/ss-move-proj +echo cleaned +``` + +Expected: +- exit_code: 0 +- cleaned + +## Pass Criteria + +- Steps 6, 7, 11, 12: records, groups and the commit are present under the new keys, and no download happened +- Steps 13 to 18: refusals exit 1 and leave the source and records untouched +- Step 20: lock pin equals the pin before the move; `config.yaml` has the new group +- Steps 22 to 24: the endpoint answers with the documented codes diff --git a/cmd/skillshare/completion_bash.go b/cmd/skillshare/completion_bash.go index 8735c286e..ddf693ef0 100644 --- a/cmd/skillshare/completion_bash.go +++ b/cmd/skillshare/completion_bash.go @@ -14,7 +14,7 @@ _skillshare() { cword=$COMP_CWORD fi - local commands="init install uninstall link unlink list search sync mcp hooks plugin status diff backup restore collect pull push commit doctor target upgrade update check new trash analyze audit hub log ui tui extras enable disable completion version help" + local commands="init install uninstall link unlink move list search sync mcp hooks plugin status diff backup restore collect pull push commit doctor target upgrade update check new trash analyze audit hub log ui tui extras enable disable completion version help" local global_flags="--project -p --global -g" @@ -36,6 +36,7 @@ _skillshare() { local uninstall_flags="--all --force -f --dry-run -n --json --group -G --help -h" local link_flags="--name --enable --help -h" local unlink_flags="--help -h" + local move_flags="--dry-run -n --force -f --json --help -h" local list_flags="--verbose -v --json -j --no-tui --type -t --status --sort -s --all --help -h" local sync_flags="--all --dry-run -n --force -f --json --quiet -q --help -h" local mcp_flags="--tools-allow --tools-deny --pi-options --url --target --from --file --sync --replace --disabled --keep-files --revision --dry-run -n --json --no-tui --no-dns --live --timeout --http --tls-cert --tls-key --check --help -h" @@ -253,6 +254,7 @@ _skillshare() { uninstall) COMPREPLY=($(compgen -W "${uninstall_flags} ${global_flags}" -- "${cur}")) ;; link) COMPREPLY=($(compgen -W "${link_flags} ${global_flags}" -- "${cur}")) ;; unlink) COMPREPLY=($(compgen -W "${unlink_flags} ${global_flags}" -- "${cur}")) ;; + move) COMPREPLY=($(compgen -W "${move_flags} ${global_flags}" -- "${cur}")) ;; list) COMPREPLY=($(compgen -W "${list_flags} ${global_flags}" -- "${cur}")) ;; sync) COMPREPLY=($(compgen -W "${sync_flags} ${global_flags}" -- "${cur}")) ;; plugin) COMPREPLY=($(compgen -W "add discover import list inspect sync check update enable disable remove --target --from --plugin --name --source-ref --entry --revision --dry-run -n --json --no-tui --help -h ${global_flags}" -- "${cur}")) ;; diff --git a/cmd/skillshare/completion_fish.go b/cmd/skillshare/completion_fish.go index fa6dee939..f10c37fd2 100644 --- a/cmd/skillshare/completion_fish.go +++ b/cmd/skillshare/completion_fish.go @@ -29,6 +29,7 @@ complete -c skillshare -n __fish_skillshare_no_subcommand -a install -d 'Install complete -c skillshare -n __fish_skillshare_no_subcommand -a uninstall -d 'Remove skills/agents from source directory' complete -c skillshare -n __fish_skillshare_no_subcommand -a link -d 'Link a folder of your own skills into the source' complete -c skillshare -n __fish_skillshare_no_subcommand -a unlink -d 'Remove a link from the source' +complete -c skillshare -n __fish_skillshare_no_subcommand -a move -d 'Move skills or folders within the source' complete -c skillshare -n __fish_skillshare_no_subcommand -a list -d 'List installed skills' complete -c skillshare -n __fish_skillshare_no_subcommand -a search -d 'Search or browse GitHub for skills' complete -c skillshare -n __fish_skillshare_no_subcommand -a sync -d 'Sync skills/agents/extras/MCP to targets' @@ -171,6 +172,12 @@ complete -c skillshare -n '__fish_skillshare_using_command link' -l enable -d 'S complete -c skillshare -n '__fish_skillshare_using_command link' -l help -s h -d 'Show help' complete -c skillshare -n '__fish_skillshare_using_command unlink' -l help -s h -d 'Show help' +# move +complete -c skillshare -n '__fish_skillshare_using_command move' -l dry-run -s n -d 'Preview changes' +complete -c skillshare -n '__fish_skillshare_using_command move' -l force -s f -d 'Accept a target name collision' +complete -c skillshare -n '__fish_skillshare_using_command move' -l json -d 'JSON output' +complete -c skillshare -n '__fish_skillshare_using_command move' -l help -s h -d 'Show help' + # list complete -c skillshare -n '__fish_skillshare_using_command list' -a agents -d 'List agents' complete -c skillshare -n '__fish_skillshare_using_command list' -l verbose -s v -d 'Show detailed information' diff --git a/cmd/skillshare/completion_nushell.go b/cmd/skillshare/completion_nushell.go index 34e05fd62..d38ce4883 100644 --- a/cmd/skillshare/completion_nushell.go +++ b/cmd/skillshare/completion_nushell.go @@ -9,6 +9,7 @@ def "nu-complete skillshare commands" [] { { value: "uninstall", description: "Remove skills/agents from source directory" } { value: "link", description: "Link a folder of your own skills into the source" } { value: "unlink", description: "Remove a link from the source" } + { value: "move", description: "Move skills or folders within the source" } { value: "list", description: "List installed skills" } { value: "search", description: "Search or browse GitHub for skills" } { value: "sync", description: "Sync skills/agents/extras/MCP to targets" } @@ -364,6 +365,17 @@ export extern "skillshare unlink" [ --help(-h) # Show help ] +# Move +export extern "skillshare move" [ + ...names: string # Skills or folders, then the destination folder + --dry-run(-n) # Preview changes + --force(-f) # Accept a target name collision + --json # JSON output + --project(-p) # Use project-level config + --global(-g) # Use global config + --help(-h) # Show help +] + # List export extern "skillshare list" [ scope?: string@"nu-complete skillshare kind" diff --git a/cmd/skillshare/completion_powershell.go b/cmd/skillshare/completion_powershell.go index d75f54f08..842b13a78 100644 --- a/cmd/skillshare/completion_powershell.go +++ b/cmd/skillshare/completion_powershell.go @@ -12,6 +12,7 @@ $_skillshareCompleter = { @{ Name = 'uninstall'; Desc = 'Remove skills/agents from source directory' } @{ Name = 'link'; Desc = 'Link a folder of your own skills into the source' } @{ Name = 'unlink'; Desc = 'Remove a link from the source' } + @{ Name = 'move'; Desc = 'Move skills or folders within the source' } @{ Name = 'list'; Desc = 'List installed skills' } @{ Name = 'search'; Desc = 'Search or browse GitHub for skills' } @{ Name = 'sync'; Desc = 'Sync skills/agents/extras/MCP to targets' } @@ -186,6 +187,7 @@ $_skillshareCompleter = { 'uninstall' = '--all', '--force', '-f', '--dry-run', '-n', '--json', '--group', '-G', '--help', '-h', '--project', '-p', '--global', '-g' 'link' = '--name', '--enable', '--help', '-h', '--project', '-p', '--global', '-g' 'unlink' = '--help', '-h', '--project', '-p', '--global', '-g' + 'move' = '--dry-run', '-n', '--force', '-f', '--json', '--help', '-h', '--project', '-p', '--global', '-g' 'list' = '--verbose', '-v', '--json', '-j', '--no-tui', '--type', '-t', '--status', '--sort', '-s', '--all', '--help', '-h', '--project', '-p', '--global', '-g' 'sync' = '--all', '--dry-run', '-n', '--force', '-f', '--json', '--quiet', '-q', '--help', '-h', '--project', '-p', '--global', '-g' 'diff' = '--no-tui', '--patch', '--stat', '--json', '--help', '-h', '--project', '-p', '--global', '-g' diff --git a/cmd/skillshare/completion_zsh.go b/cmd/skillshare/completion_zsh.go index 80c4fc963..559292945 100644 --- a/cmd/skillshare/completion_zsh.go +++ b/cmd/skillshare/completion_zsh.go @@ -10,6 +10,7 @@ _skillshare() { 'uninstall:Remove skills/agents from source directory' 'link:Link a folder of your own skills into the source' 'unlink:Remove a link from the source' + 'move:Move skills or folders within the source' 'list:List installed skills' 'search:Search or browse GitHub for skills' 'sync:Sync skills/agents/extras/MCP to targets' @@ -222,6 +223,18 @@ _skillshare() { '--help[Show help]' \ '-h[Show help]' ;; + move) + _arguments \ + '*:skill, folder or destination:' \ + '--dry-run[Preview changes]' \ + '-n[Preview changes]' \ + '--force[Accept a target name collision]' \ + '-f[Accept a target name collision]' \ + '--json[JSON output]' \ + $global_flags \ + '--help[Show help]' \ + '-h[Show help]' + ;; list) _arguments \ '1:type:(agents)' \ diff --git a/cmd/skillshare/install.go b/cmd/skillshare/install.go index ad165c707..2e39024d1 100644 --- a/cmd/skillshare/install.go +++ b/cmd/skillshare/install.go @@ -10,6 +10,7 @@ import ( "skillshare/internal/config" "skillshare/internal/install" "skillshare/internal/oplog" + "skillshare/internal/skillmove" "skillshare/internal/sourcefs" "skillshare/internal/ui" "skillshare/internal/validate" @@ -50,6 +51,7 @@ type installLogSummary struct { type installBatchSummary struct { InstalledSkills []string FailedSkills []string + Err error // the batch could not start, e.g. a refused --into folder } // parseInstallArgs parses install command arguments @@ -244,14 +246,32 @@ func agentsDirWithInto(agentsDir string, opts install.InstallOptions) string { return agentsDir } -// ensureIntoDirExists creates the Into subdirectory if opts.Into is set. +// ensureIntoDirExists creates the Into subdirectory if opts.Into is set. It +// first refuses a folder an install must not land in: inside a skill or inside +// a tracked checkout. Links are sourcefs's to follow or refuse. func ensureIntoDirExists(sourceDir string, opts install.InstallOptions) error { if opts.Into == "" { return nil } + if err := checkIntoFolder(sourceDir, opts); err != nil { + return err + } return sourcefs.MkdirAllIn(sourceDir, opts.Into, opts.SourceFollow) } +// checkIntoFolder reports why opts.Into is no place for an install, with the +// code move uses for it; nil when it is fine or unset. +func checkIntoFolder(sourceDir string, opts install.InstallOptions) error { + if opts.Into == "" { + return nil + } + _, refusal := skillmove.CheckDest(opts.Into, skillmove.Options{SourceDir: sourceDir, Follow: opts.SourceFollow, Install: true}) + if refusal == nil { + return nil + } + return fmt.Errorf("%s (%s)", refusal.Error(), refusal.Code) +} + // parseOptsFromConfig builds install.ParseOptions from the global config. func parseOptsFromConfig(cfg *config.Config) install.ParseOptions { return install.ParseOptions{ diff --git a/cmd/skillshare/install_handlers.go b/cmd/skillshare/install_handlers.go index 24cd25d26..8adda965b 100644 --- a/cmd/skillshare/install_handlers.go +++ b/cmd/skillshare/install_handlers.go @@ -25,6 +25,8 @@ func handleTrackedRepoInstall(source *install.Source, cfg *config.Config, opts i trackSourceDir := cfg.EffectiveSkillsSource() if trackedKind == "agent" { trackSourceDir = cfg.EffectiveAgentsSource() + } else if err := checkIntoFolder(trackSourceDir, opts); err != nil { + return installLogSummary{}, err } logSummary := installLogSummary{ @@ -334,6 +336,9 @@ func handleGitInstall(source *install.Source, cfg *config.Config, opts install.I } batchSummary := installSelectedSkills(selected, discovery, cfg, opts) + if batchSummary.Err != nil { + return logSummary, batchSummary.Err + } logSummary.InstalledSkills = append(logSummary.InstalledSkills, batchSummary.InstalledSkills...) logSummary.FailedSkills = append(logSummary.FailedSkills, batchSummary.FailedSkills...) logSummary.SkillCount = len(logSummary.InstalledSkills) @@ -370,6 +375,9 @@ func handleGitInstall(source *install.Source, cfg *config.Config, opts install.I } batchSummary := installSelectedSkills(selected, discovery, cfg, opts) + if batchSummary.Err != nil { + return logSummary, batchSummary.Err + } logSummary.InstalledSkills = append(logSummary.InstalledSkills, batchSummary.InstalledSkills...) logSummary.FailedSkills = append(logSummary.FailedSkills, batchSummary.FailedSkills...) logSummary.SkillCount = len(logSummary.InstalledSkills) @@ -404,9 +412,8 @@ func installSelectedSkills(selected []install.SkillInfo, discovery *install.Disc } if progressBar != nil { progressBar.Stop() - ui.ErrorMsg("Failed to create --into directory") } - return installBatchSummary{} + return installBatchSummary{Err: fmt.Errorf("failed to create --into directory: %w", err)} } } diff --git a/cmd/skillshare/main.go b/cmd/skillshare/main.go index 868beb909..b1e00d7db 100644 --- a/cmd/skillshare/main.go +++ b/cmd/skillshare/main.go @@ -59,6 +59,7 @@ var commands = map[string]func([]string) error{ "plugin": cmdPlugin, "enable": cmdEnable, "disable": cmdDisable, + "move": cmdMove, "completion": cmdCompletion, } @@ -210,6 +211,7 @@ func printUsage() { helpGroup{title: "Skills and agents", rows: []helpRow{ {"install", "Install from a repo or path"}, {"uninstall", "Remove from the source"}, + {"move", "Move skills or folders within the source"}, {"link", "Link a folder of your own skills into the source"}, {"unlink", "Remove a link from the source"}, {"list", "List what is installed"}, diff --git a/cmd/skillshare/move.go b/cmd/skillshare/move.go new file mode 100644 index 000000000..64bba22ca --- /dev/null +++ b/cmd/skillshare/move.go @@ -0,0 +1,114 @@ +package main + +import ( + "fmt" + "os" + "strings" + "time" +) + +// moveOptions holds the parsed arguments of `skillshare move`. +type moveOptions struct { + names []string // skills or folders; at least one + dest string // last positional, relative to the skills source + force bool + dryRun bool + json bool +} + +// parseMoveArgs parses the arguments left after the mode flags. The second +// result asks for the help page. +func parseMoveArgs(args []string) (*moveOptions, bool, error) { + opts := &moveOptions{} + var positional []string + for i, arg := range args { + if arg == "--" { + positional = append(positional, args[i+1:]...) + break + } + switch { + case arg == "--force" || arg == "-f": + opts.force = true + case arg == "--dry-run" || arg == "-n": + opts.dryRun = true + case arg == "--json": + opts.json = true + case arg == "--help" || arg == "-h": + return nil, true, nil + case strings.HasPrefix(arg, "-") && arg != "-": + return nil, false, fmt.Errorf("unknown option: %s", arg) + default: + positional = append(positional, arg) + } + } + if len(positional) < 2 { + return nil, true, fmt.Errorf("usage: skillshare move ... ") + } + opts.names, opts.dest = positional[:len(positional)-1], positional[len(positional)-1] + return opts, false, nil +} + +func cmdMove(args []string) error { + start := time.Now() + mode, rest, err := parseModeArgs(args) + if err != nil { + return err + } + opts, showHelp, err := parseMoveArgs(rest) + if showHelp { + printMoveHelp() + return err + } + if err != nil { + return err + } + + cwd, err := os.Getwd() + if err != nil { + return fmt.Errorf("cannot determine working directory: %w", err) + } + mode = resolveAutoMode(mode, cwd) + applyModeLabel(mode) + + // Auto-initializing a project prints; --json stdout must stay the payload. + quiet := newJSONUISuppressor(opts.json) + var m *moveMode + if mode == modeProject { + m, err = projectMoveMode(cwd) + } else { + m, err = globalMoveMode() + } + quiet.Flush() + if err != nil { + if opts.json { + return writeJSONError(err) + } + return err + } + return runMove(opts, m, start) +} + +func printMoveHelp() { + printHelp("skillshare move ... [options]", + "Move installed skills, or whole folders, to another folder of the source.\nTheir install records, audit acceptances and (project mode) lockfile pin move with them,\nso nothing is downloaded again. Run 'skillshare sync' afterwards to rename the Target links.", + helpGroup{title: "Arguments", rows: []helpRow{ + {"", "Skill path, flat name or unique base name, or a folder of the source"}, + {"", "Folder relative to the source; created when missing, \".\" for the root"}, + }}, + helpGroup{title: "Options", rows: []helpRow{ + {"-n, --dry-run", "Preview without making changes"}, + {"-f, --force", "Move even when a Target would get two skills with one name"}, + {"--json", "Machine-readable output"}, + {"-p, --project", "Use project-level config in current directory"}, + {"-g, --global", "Use global config (~/.config/skillshare)"}, + }}, + helpExamples( + helpRow{"skillshare move react-best-practices frontend", "Move one skill into frontend/"}, + helpRow{"skillshare move a b c grp", "Move several skills"}, + helpRow{"skillshare move frontend archive", "Move a folder: it becomes archive/frontend"}, + helpRow{"skillshare move grp/demo .", "Move a skill back to the source root"}, + helpRow{"skillshare move demo grp -n", "Preview the move"}, + ), + helpNotes("Not moved", "Skills of a tracked repo (_name) and anything at or below a followed source link.", "A folder holding a tracked repo is refused whole; nothing in it moves."), + ) +} diff --git a/cmd/skillshare/move_handlers.go b/cmd/skillshare/move_handlers.go new file mode 100644 index 000000000..772cf4728 --- /dev/null +++ b/cmd/skillshare/move_handlers.go @@ -0,0 +1,218 @@ +package main + +import ( + "fmt" + "time" + + "skillshare/internal/config" + "skillshare/internal/install" + "skillshare/internal/oplog" + "skillshare/internal/skillmove" + "skillshare/internal/sourcewalk" + ssync "skillshare/internal/sync" + "skillshare/internal/ui" +) + +// moveMode is what differs between global and project mode. +type moveMode struct { + sourceDir string + walk sourcewalk.Options + store *install.MetadataStore + targets map[string]config.TargetConfig + cfgPath string // the config the oplog entry is written next to + + projectRoot string // "" in global mode + gitignoreDir, gitignorePrefix string + reconcile func() error +} + +// options returns the core's view of the mode. +func (m *moveMode) options(o *moveOptions) skillmove.Options { + return skillmove.Options{ + SourceDir: m.sourceDir, + Follow: m.walk.Follow, + Store: m.store, + Targets: skillmove.EnabledTargets(m.targets), + Force: o.force, + DryRun: o.dryRun, + ProjectRoot: m.projectRoot, + GitignoreDir: m.gitignoreDir, + GitignorePrefix: m.gitignorePrefix, + Reconcile: m.reconcile, + } +} + +// globalMoveMode loads what a move in the global source needs. +func globalMoveMode() (*moveMode, error) { + cfg, err := config.Load() + if err != nil { + return nil, fmt.Errorf("failed to load config: %w", err) + } + sourceDir := cfg.EffectiveSkillsSource() + store, err := loadMoveStore(sourceDir) + if err != nil { + return nil, err + } + return &moveMode{ + sourceDir: sourceDir, + walk: cfg.SkillsWalk(), + store: store, + targets: cfg.Targets, + cfgPath: config.ConfigPath(), + reconcile: func() error { return config.ReconcileGlobalSkills(cfg, store) }, + }, nil +} + +// loadMoveStore reads the install records. An unreadable file stops the move: +// saving an empty store over it would lose every record the move must keep. +func loadMoveStore(sourceDir string) (*install.MetadataStore, error) { + store, err := install.LoadMetadataWithMigration(sourceDir, "") + if err != nil { + return nil, fmt.Errorf("cannot read install records in %s: %w", install.MetadataPath(sourceDir), err) + } + return store, nil +} + +// moveJSONOutput is the shape of `move --json`. +type moveJSONOutput struct { + Moved []moveJSONMoved `json:"moved"` + Failed []moveJSONFailed `json:"failed"` + Skipped int `json:"skipped"` // already in the destination + Warnings []string `json:"warnings"` + DryRun bool `json:"dry_run"` + Duration string `json:"duration"` +} + +type moveJSONMoved struct { + Name string `json:"name"` + From string `json:"from"` + To string `json:"to"` + Record bool `json:"record"` // an install record moved along + Skills int `json:"skills"` // 1 for a skill, the count below a folder +} + +type moveJSONFailed struct { + Name string `json:"name"` + Code string `json:"code"` + Error string `json:"error"` +} + +// runMove resolves the names, applies the move and reports it. +func runMove(opts *moveOptions, m *moveMode, start time.Time) error { + discovered, err := ssync.DiscoverSourceSkillsAll(m.sourceDir, m.walk) + if err != nil { + err = fmt.Errorf("failed to discover skills: %w", err) + if opts.json { + return writeJSONError(err) + } + return err + } + printSkippedSourceLinkWarnings(m.walk, opts.json) + + o := m.options(opts) + out := skillmove.Run(skillmove.Plan(discovered, opts.names, opts.dest, o), o) + + report := moveJSONOutput{DryRun: opts.dryRun} + skills := 0 + for _, item := range out.Items { + switch { + case item.Moved(): + report.Moved = append(report.Moved, moveJSONMoved{Name: item.Name, From: item.From, To: item.To, Record: item.Records > 0, Skills: len(item.Skills)}) + skills += len(item.Skills) + case item.Skipped(): + report.Skipped++ + default: + report.Failed = append(report.Failed, moveJSONFailed{Name: item.Name, Code: string(item.Err.Code), Error: item.Err.Error()}) + } + report.Warnings = append(report.Warnings, item.Warnings...) + } + report.Duration = formatDuration(start) + + var cmdErr error + switch { + case out.Err != nil: + cmdErr = fmt.Errorf("moved, but a follow-up step failed: %w", out.Err) + case len(report.Failed) > 0: + cmdErr = fmt.Errorf("%d of %d could not be moved", len(report.Failed), len(opts.names)) + } + if !opts.dryRun { + logMoveOp(m.cfgPath, opts, m.modeName(), len(report.Moved), start, cmdErr) + } + if opts.json { + return writeJSONResult(&report, cmdErr) + } + renderMove(out.Items, &report, skills, start) + return cmdErr +} + +// modeName is the mode as the oplog records it. +func (m *moveMode) modeName() string { + if m.projectRoot != "" { + return "project" + } + return "global" +} + +// renderMove prints one row per requested name, the warnings, and the closing +// line with the next step. +func renderMove(items []skillmove.Planned, report *moveJSONOutput, skills int, start time.Time) { + labels := make([]string, len(items)) + for i, item := range items { + labels[i] = item.Name + } + width := ui.RowWidth(labels...) + for _, item := range items { + switch { + case item.Moved() && report.DryRun: + ui.Row(ui.MarkNone, item.Name, "would move to "+moveTarget(item), width) + case item.Moved(): + ui.Row(ui.MarkOK, item.Name, "→ "+moveTarget(item), width) + case item.Skipped(): + ui.Row(ui.MarkNone, item.Name, item.Err.Error(), width) + default: + ui.Row(ui.MarkFail, item.Name, fmt.Sprintf("%s (%s)", item.Err.Error(), item.Err.Code), width) + } + } + for _, w := range report.Warnings { + ui.Warning("%s", w) + } + + fmt.Println() + switch { + case report.DryRun: + ui.DryRun() + case skills == 0 && len(report.Failed) == 0: + ui.Done(ui.MarkNone, "Already in place", time.Since(start)) + case skills == 0: + ui.Done(ui.MarkFail, "Nothing moved", time.Since(start)) + case len(report.Failed) > 0: + ui.Done(ui.MarkWarn, "Moved "+plural(skills, "skill"), time.Since(start)) + default: + ui.Done(ui.MarkOK, "Moved "+plural(skills, "skill"), time.Since(start)) + } + if !report.DryRun && skills > 0 { + ui.Next("skillshare sync", "rename the links in your targets") + } +} + +// moveTarget is the destination, with the number of skills of a folder or of a +// skill that carries nested ones. +func moveTarget(item skillmove.Planned) string { + if len(item.Skills) > 1 { + return fmt.Sprintf("%s (%s)", item.To, plural(len(item.Skills), "skill")) + } + return item.To +} + +func logMoveOp(cfgPath string, opts *moveOptions, mode string, moved int, start time.Time, cmdErr error) { + status := statusFromErr(cmdErr) + if moved > 0 && cmdErr != nil { + status = "partial" + } + e := oplog.NewEntry("move", status, time.Since(start)) + e.Args = map[string]any{"names": opts.names, "dest": opts.dest, "force": opts.force, "mode": mode} + if cmdErr != nil { + e.Message = cmdErr.Error() + } + oplog.WriteWithLimit(cfgPath, oplog.OpsFile, e, logMaxEntries()) //nolint:errcheck +} diff --git a/cmd/skillshare/move_project.go b/cmd/skillshare/move_project.go new file mode 100644 index 000000000..32c0ed1dc --- /dev/null +++ b/cmd/skillshare/move_project.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + + "skillshare/internal/config" +) + +// projectMoveMode is the project counterpart: the source, targets, lockfile +// and .gitignore come from the project, and reconcile also rewrites config.yaml. +func projectMoveMode(root string) (*moveMode, error) { + if err := ensureProjectConfig(root); err != nil { + return nil, err + } + cfg, err := config.LoadProject(root) + if err != nil { + return nil, fmt.Errorf("failed to load project config: %w", err) + } + sourceDir := cfg.EffectiveSkillsSource(root) + store, err := loadMoveStore(sourceDir) + if err != nil { + return nil, err + } + targets, _ := config.ResolveValidProjectTargets(root, cfg) + gitignoreDir, prefix := config.ProjectGitignoreTarget(root, sourceDir) + return &moveMode{ + sourceDir: sourceDir, + walk: config.SkillsWalk(cfg.FollowSourceLinks, sourceDir, targets), + store: store, + targets: targets, + cfgPath: config.ProjectConfigPath(root), + projectRoot: root, + gitignoreDir: gitignoreDir, + gitignorePrefix: prefix, + reconcile: func() error { return config.ReconcileProjectSkills(root, cfg, store, sourceDir) }, + }, nil +} diff --git a/internal/config/project_reconcile_test.go b/internal/config/project_reconcile_test.go index ce2d7decb..fad63ca49 100644 --- a/internal/config/project_reconcile_test.go +++ b/internal/config/project_reconcile_test.go @@ -380,3 +380,53 @@ func TestReconcileProjectSkills_MovesGitignoreRule(t *testing.T) { t.Errorf(".gitignore = %q, want the rule moved from skills/old/demo to skills/new/demo", data) } } + +// TestReconcileProjectSkills_MovedSkillKeepsGroupAndPin follows a move made by +// skillmove: the record and the lock pin are re-keyed, then reconcile runs. The +// config entry must take the new group and the pin must keep the older commit. +func TestReconcileProjectSkills_MovedSkillKeepsGroupAndPin(t *testing.T) { + root := t.TempDir() + skillsDir := filepath.Join(root, ".skillshare", "skills") + moved := filepath.Join(skillsDir, "grp", "demo") + if err := os.MkdirAll(moved, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(moved, "SKILL.md"), []byte("---\nname: demo\n---\n"), 0644); err != nil { + t.Fatal(err) + } + pinned := strings.Repeat("a", 40) + installed := strings.Repeat("b", 40) + dir := filepath.Join(root, ".skillshare") + lock := &install.Lock{Skills: map[string]install.LockEntry{"demo": {Source: "github.com/user/repo/demo", Commit: pinned}}} + if !lock.MovePin("demo", "grp/demo") { + t.Fatal("no pin to move") + } + if err := lock.Save(dir); err != nil { + t.Fatal(err) + } + cfg := &ProjectConfig{ + Targets: []ProjectTargetEntry{{Name: "claude"}}, + Skills: []SkillEntry{{Name: "demo", Source: "github.com/user/repo/demo"}}, + } + store := install.NewMetadataStore() + store.Set("demo", &install.MetadataEntry{Source: "github.com/user/repo/demo", Commit: installed}) + store.MovePath("demo", "grp/demo") + + if err := ReconcileProjectSkills(root, cfg, store, skillsDir); err != nil { + t.Fatal(err) + } + + if len(cfg.Skills) != 1 || cfg.Skills[0].Group != "grp" || cfg.Skills[0].Name != "demo" { + t.Errorf("config skills = %+v, want one entry demo in group grp", cfg.Skills) + } + got, err := install.LoadLock(dir) + if err != nil { + t.Fatal(err) + } + if pin := got.Skills["grp/demo"]; pin.Commit != pinned { + t.Errorf("pin = %+v, want the deliberately older commit kept", pin) + } + if _, stale := got.Skills["demo"]; stale { + t.Error("the pin of the old path was left behind") + } +} diff --git a/internal/config/reconcile_core.go b/internal/config/reconcile_core.go index de89e8250..e4ad6b410 100644 --- a/internal/config/reconcile_core.go +++ b/internal/config/reconcile_core.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "os/exec" + "path" "path/filepath" "strings" @@ -173,6 +174,8 @@ func reconcileSkillsWalk(sourcePath string, walk sourcewalk.Options, store *inst } } + keepNestedRecords(walkRoot, store, result.live) + // A record left waiting on a failed walk must not be pruned as gone. if walkFailed && len(moves) > 0 { result.incomplete = true @@ -186,6 +189,29 @@ func reconcileSkillsWalk(sourcePath string, walk sourcewalk.Options, store *inst return result, err } +// keepNestedRecords marks the records below a live plain install as live while +// their directory still exists. The walk stops at an installed skill, so it +// never reaches a nested record; pruning it would lose its audit acceptances. +// A tracked checkout is left out: its skills are not recorded by path. +func keepNestedRecords(walkRoot string, store *install.MetadataStore, live map[string]bool) { + for _, key := range store.List() { + if live[key] { + continue + } + rel := filepath.ToSlash(install.KeyToRelPath(key, store.Get(key))) + for parent := path.Dir(rel); parent != "."; parent = path.Dir(parent) { + owner := store.Get(parent) + if !live[parent] || owner == nil || owner.Tracked || owner.Source == "" { + continue + } + if info, err := os.Stat(filepath.Join(walkRoot, filepath.FromSlash(rel))); err == nil && info.IsDir() { + live[key], live[rel] = true, true + } + break + } + } +} + // pruneStaleEntries removes store entries not present in the live set. func pruneStaleEntries(store *install.MetadataStore, live map[string]bool) bool { changed := false diff --git a/internal/config/reconcile_test.go b/internal/config/reconcile_test.go index ccc274cae..99b57f330 100644 --- a/internal/config/reconcile_test.go +++ b/internal/config/reconcile_test.go @@ -508,3 +508,58 @@ func TestReconcileGlobalSkills_TracksOnlyPrefixedCheckouts(t *testing.T) { t.Error("org/side: an unprefixed checkout without an entry must not be registered") } } + +// nestedRecordFixture installs "foo" with a nested skill "foo/sub" that has a +// record of its own, as a move leaves them. The walk stops at foo, so the +// nested record is only live through its installed parent. +func nestedRecordFixture(t *testing.T) (*Config, *install.MetadataStore, string) { + t.Helper() + root := t.TempDir() + sourceDir := filepath.Join(root, "skills") + t.Setenv("SKILLSHARE_CONFIG", filepath.Join(root, "config.yaml")) + nested := filepath.Join(sourceDir, "grp", "foo", "sub") + if err := os.MkdirAll(nested, 0755); err != nil { + t.Fatal(err) + } + store := install.NewMetadataStore() + store.Set("grp/foo", &install.MetadataEntry{Source: "github.com/user/repo/foo", Group: "grp"}) + store.Set("grp/foo/sub", &install.MetadataEntry{Source: "github.com/user/repo/sub", Group: "grp/foo"}) + store.AuditAccepted = map[string][]string{"grp/foo/sub": {"accepted-key"}} + return &Config{Source: sourceDir}, store, nested +} + +func TestReconcileGlobalSkills_KeepsNestedRecordBelowInstalledParent(t *testing.T) { + cfg, store, _ := nestedRecordFixture(t) + + if err := ReconcileGlobalSkills(cfg, store); err != nil { + t.Fatal(err) + } + + if !store.Has("grp/foo/sub") { + t.Fatal("nested record was pruned although its directory exists below the installed parent") + } + if got := store.AuditAccepted["grp/foo/sub"]; !reflect.DeepEqual(got, []string{"accepted-key"}) { + t.Errorf("accepted audit findings = %v, want them kept", got) + } +} + +// TestReconcileGlobalSkills_PrunesDeletedNestedRecord is the inverse: a nested +// record whose directory is gone is still pruned, so the keep rule cannot pin +// records of deleted skills for as long as their parent lives. +func TestReconcileGlobalSkills_PrunesDeletedNestedRecord(t *testing.T) { + cfg, store, nested := nestedRecordFixture(t) + if err := os.RemoveAll(nested); err != nil { + t.Fatal(err) + } + + if err := ReconcileGlobalSkills(cfg, store); err != nil { + t.Fatal(err) + } + + if store.Has("grp/foo/sub") { + t.Error("record of a deleted nested skill survived reconcile") + } + if !store.Has("grp/foo") { + t.Error("the installed parent's record must stay") + } +} diff --git a/internal/install/install_git.go b/internal/install/install_git.go index 1bf7dd6c5..a22ee14c4 100644 --- a/internal/install/install_git.go +++ b/internal/install/install_git.go @@ -12,6 +12,7 @@ import ( "strings" "time" + "skillshare/internal/sourcewalk" "skillshare/internal/utils" ) @@ -52,6 +53,21 @@ func IsTrackedCheckout(path string) bool { return utils.IsTrackedRepoDir(filepath.Base(path)) && IsGitRepo(path) } +// TrackedAncestor returns the slash path of the first tracked checkout above +// the last element of rel, a slash path below sourceDir. A checkout behind a +// link the policy follows is the user's own and does not count. +func TrackedAncestor(sourceDir, rel string, follow *sourcewalk.Follow) (string, bool) { + dir := sourceDir + parents := strings.Split(rel, "/") + for i, seg := range parents[:len(parents)-1] { + dir = filepath.Join(dir, seg) + if _, followed := follow.Resolve(dir); utils.IsTrackedRepoDir(seg) && !followed && IsGitRepo(dir) { + return strings.Join(parents[:i+1], "/"), true + } + } + return "", false +} + // gitCommandTimeout is the maximum time for a git network operation. // Remote tracked-repo clones can take longer in constrained CI/Docker networks. const gitCommandTimeout = 180 * time.Second diff --git a/internal/install/install_git_test.go b/internal/install/install_git_test.go index 829597c85..7a9b8bd6d 100644 --- a/internal/install/install_git_test.go +++ b/internal/install/install_git_test.go @@ -155,3 +155,30 @@ func runGit(t *testing.T, dir string, args ...string) { t.Fatalf("git %v failed: %s\n%s", args, err, out) } } + +func TestTrackedAncestor(t *testing.T) { + source := t.TempDir() + repo := filepath.Join(source, "org", "_team") + if err := os.MkdirAll(filepath.Join(repo, ".git"), 0755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(source, "_plain", "skill"), 0755); err != nil { + t.Fatal(err) + } + + cases := []struct { + rel, want string + }{ + {"org/_team/foo", "org/_team"}, + {"org/_team/foo/sub", "org/_team"}, + {"org/_team", ""}, // the last element is not an ancestor + {"_plain/skill", ""}, // _-prefixed but not a git repo + {"org/other/foo", ""}, + } + for _, c := range cases { + got, ok := TrackedAncestor(source, c.rel, nil) + if got != c.want || ok != (c.want != "") { + t.Errorf("TrackedAncestor(%q) = %q, %v; want %q", c.rel, got, ok, c.want) + } + } +} diff --git a/internal/install/lock.go b/internal/install/lock.go index 7695998c4..bc7d82723 100644 --- a/internal/install/lock.go +++ b/internal/install/lock.go @@ -61,6 +61,17 @@ func (l *Lock) CommitFor(name, source string) string { return "" } +// MovePin re-keys the pin of a skill that moved to another path and reports +// whether there was one. +func (l *Lock) MovePin(oldName, newName string) bool { + pin, ok := l.Skills[oldName] + if ok { + delete(l.Skills, oldName) + l.Skills[newName] = pin + } + return ok +} + // Save writes the lockfile, leaving it untouched when nothing changed and // removing it when there is nothing to pin. func (l *Lock) Save(dir string) error { diff --git a/internal/install/lock_test.go b/internal/install/lock_test.go index 9616762fd..5b75c116f 100644 --- a/internal/install/lock_test.go +++ b/internal/install/lock_test.go @@ -20,3 +20,20 @@ func TestLockCommitFor(t *testing.T) { t.Errorf("nil lock returned %q", got) } } + +func TestLockMovePin(t *testing.T) { + lock := &Lock{Skills: map[string]LockEntry{"demo": {Source: "src", Commit: "abc"}}} + + if !lock.MovePin("demo", "grp/demo") { + t.Fatal("MovePin reported no pin for a pinned skill") + } + if _, ok := lock.Skills["demo"]; ok { + t.Error("pin stayed at the old name") + } + if got := lock.Skills["grp/demo"]; got.Commit != "abc" || got.Source != "src" { + t.Errorf("pin at the new name = %+v, want it carried unchanged", got) + } + if lock.MovePin("absent", "grp/absent") { + t.Error("MovePin reported a pin for a skill that has none") + } +} diff --git a/internal/install/metadata.go b/internal/install/metadata.go index 0ade685aa..d0d07fcd8 100644 --- a/internal/install/metadata.go +++ b/internal/install/metadata.go @@ -215,6 +215,48 @@ func (s *MetadataStore) MoveEntry(oldKey, newKey string) { } } +// KeysUnder returns the sorted keys of the entries recorded for relPath or for +// a path below it, whether keyed by full path or by a legacy basename with a +// Group. +func (s *MetadataStore) KeysUnder(relPath string) []string { + var keys []string + for _, key := range s.List() { + rel := filepath.ToSlash(KeyToRelPath(key, s.Entries[key])) + if rel == relPath || strings.HasPrefix(rel, relPath+"/") { + keys = append(keys, key) + } + } + return keys +} + +// MovePath re-keys what the store holds for the directory from, and for +// everything below it, to the same places below to: the entries with their +// Group, and the audit findings accepted for a path without an entry of its +// own. It returns how many entries moved. +func (s *MetadataStore) MovePath(from, to string) int { + keys := s.KeysUnder(from) + for _, key := range keys { + entry := s.Entries[key] + newKey := to + strings.TrimPrefix(filepath.ToSlash(KeyToRelPath(key, entry)), from) + s.MoveEntry(key, newKey) + entry.Group = "" + if idx := strings.LastIndex(newKey, "/"); idx >= 0 { + entry.Group = newKey[:idx] + } + } + var stray []string + for old := range s.AuditAccepted { + if old == from || strings.HasPrefix(old, from+"/") { + stray = append(stray, old) + } + } + for _, old := range stray { + s.AuditAccepted[to+strings.TrimPrefix(old, from)] = s.AuditAccepted[old] + delete(s.AuditAccepted, old) + } + return len(keys) +} + // List returns sorted entry names. func (s *MetadataStore) List() []string { names := make([]string, 0, len(s.Entries)) diff --git a/internal/install/metadata_test.go b/internal/install/metadata_test.go index 21b6775ed..be5c7b64e 100644 --- a/internal/install/metadata_test.go +++ b/internal/install/metadata_test.go @@ -512,3 +512,46 @@ func TestMovedEntryKey_ReportsHashFailure(t *testing.T) { t.Error("MovedEntryKey() hid a candidate it could not hash") } } + +// TestMetadataStore_MovePath re-keys a folder's records whether they are keyed +// by full path or by a legacy basename with a Group, and carries the findings +// accepted for them, with or without an entry of their own. +func TestMetadataStore_MovePath(t *testing.T) { + store := NewMetadataStore() + store.Set("frontend/full", &MetadataEntry{Source: "s/full", Group: "frontend"}) + store.Set("legacy", &MetadataEntry{Source: "s/legacy", Group: "frontend/deep"}) + store.Set("frontend", &MetadataEntry{Source: "s/folder-skill"}) + store.Set("frontend-other", &MetadataEntry{Source: "s/other"}) + store.AuditAccepted = map[string][]string{ + "frontend/full": {"a"}, + "frontend/deep/legacy": {"b"}, + "frontend/local": {"c"}, // accepted for a skill with no entry + } + + if got := store.MovePath("frontend", "archive/frontend"); got != 3 { + t.Fatalf("MovePath moved %d entries, want 3", got) + } + + for _, key := range []string{"archive/frontend/full", "archive/frontend/deep/legacy", "archive/frontend"} { + if !store.Has(key) { + t.Errorf("missing entry %q; keys = %v", key, store.List()) + } + } + if got := store.Get("archive/frontend/deep/legacy"); got.Group != "archive/frontend/deep" { + t.Errorf("legacy entry group = %q, want archive/frontend/deep", got.Group) + } + if got := store.Get("archive/frontend"); got.Group != "archive" { + t.Errorf("folder skill group = %q, want archive", got.Group) + } + if !store.Has("frontend-other") { + t.Error("a sibling that only shares the prefix moved too") + } + for _, key := range []string{"archive/frontend/full", "archive/frontend/deep/legacy", "archive/frontend/local"} { + if len(store.AuditAccepted[key]) != 1 { + t.Errorf("accepted findings for %q = %v, want them carried", key, store.AuditAccepted[key]) + } + } + if len(store.AuditAccepted) != 3 { + t.Errorf("accepted findings left at old paths: %v", store.AuditAccepted) + } +} diff --git a/internal/server/handler_install.go b/internal/server/handler_install.go index bf6ace935..fce1ac8ba 100644 --- a/internal/server/handler_install.go +++ b/internal/server/handler_install.go @@ -11,6 +11,7 @@ import ( "skillshare/internal/config" "skillshare/internal/install" + "skillshare/internal/skillmove" "skillshare/internal/sourcefs" ) @@ -28,17 +29,40 @@ func (s *Server) reloadSkillsStore() { // reconcileSkillsConfig syncs the skills config with the metadata store, // logging failures as warnings so the calling operation still succeeds. func (s *Server) reconcileSkillsConfig(sourceDir string) { - if s.IsProjectMode() { - if rErr := config.ReconcileProjectSkills(s.projectRoot, s.projectCfg, s.skillsStore, sourceDir); rErr != nil { - log.Printf("warning: failed to reconcile project skills config: %v", rErr) - } - } else { - if rErr := config.ReconcileGlobalSkills(s.cfg, s.skillsStore); rErr != nil { - log.Printf("warning: failed to reconcile global skills config: %v", rErr) - } + if err := s.reconcileSkills(sourceDir); err != nil { + log.Printf("warning: failed to reconcile skills config: %v", err) } } +// reconcileSkills is reconcileSkillsConfig for a caller that reports the error. +func (s *Server) reconcileSkills(sourceDir string) error { + if s.IsProjectMode() { + return config.ReconcileProjectSkills(s.projectRoot, s.projectCfg, s.skillsStore, sourceDir) + } + return config.ReconcileGlobalSkills(s.cfg, s.skillsStore) +} + +// checkInstallInto refuses an into folder an install must not land in: inside +// a skill or inside a tracked checkout, with the codes move uses. A path below +// a source link is left to the install, which follows it or refuses it itself. It writes the response and returns false when it refuses. +// Agents install under the agents source, which these rules do not describe. +func (s *Server) checkInstallInto(w http.ResponseWriter, into, kind string) bool { + if into == "" || kind == "agent" { + return true + } + opts := skillmove.Options{SourceDir: s.cfg.EffectiveSkillsSource(), Follow: s.skillsWalk().Follow, Install: true} + _, refusal := skillmove.CheckDest(into, opts) + if refusal == nil { + return true + } + status := http.StatusConflict + if refusal.Code == skillmove.CodeInvalidDest { + status = http.StatusBadRequest + } + writeCodedError(w, status, string(refusal.Code), refusal.Error(), nil) + return false +} + func discoverInstallSource(source *install.Source) (*install.DiscoveryResult, error) { if source.IsGit() { if source.HasSubdir() { @@ -136,6 +160,9 @@ func (s *Server) handleInstallBatch(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "source and skills are required") return } + if !s.checkInstallInto(w, body.Into, body.Kind) { + return + } source, err := install.ParseSourceWithOptions(body.Source, s.parseOpts()) if err != nil { @@ -354,6 +381,10 @@ func (s *Server) handleInstall(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "source is required") return } + // A tracked repo's kind is known only after inspecting it; see below. + if !body.Track && !s.checkInstallInto(w, body.Into, body.Kind) { + return + } source, err := install.ParseSourceWithOptions(body.Source, s.parseOpts()) if err != nil { @@ -396,6 +427,9 @@ func (s *Server) handleInstall(w http.ResponseWriter, r *http.Request) { return } + if !s.checkInstallInto(w, body.Into, trackedKind) { + return + } trackSourceDir, trackFollow := s.cfg.EffectiveSkillsSource(), s.skillsWalk().Follow if trackedKind == "agent" { trackSourceDir, trackFollow = s.agentsSource(), nil diff --git a/internal/server/handler_install_test.go b/internal/server/handler_install_test.go index bb50b0247..4b428021c 100644 --- a/internal/server/handler_install_test.go +++ b/internal/server/handler_install_test.go @@ -382,3 +382,45 @@ func TestHandleInstall_TrackAcceptsLocalGitPath(t *testing.T) { t.Fatalf("expected tracked repo %q in skills source: %v", resp.RepoName, err) } } + +// An into folder inside a skill, inside a tracked checkout or malformed is +// refused with move's codes before anything is created, on both endpoints. +func TestHandleInstall_RefusesUnsafeInto(t *testing.T) { + s, src := newTestServer(t) + addSkill(t, src, "holder") + addTrackedRepo(t, src, "_team") + + for _, endpoint := range []string{"/api/install", "/api/install/batch"} { + for _, tc := range []struct { + into string + status int + code string + }{ + {"holder/sub", http.StatusConflict, "dest_is_skill"}, + {"_team/sub", http.StatusConflict, "dest_inside_tracked_repo"}, + {"../out", http.StatusBadRequest, "invalid_dest"}, + } { + t.Run(endpoint+" "+tc.into, func(t *testing.T) { + payload, _ := json.Marshal(map[string]any{ + "source": "./not-read", "into": tc.into, + "skills": []map[string]string{{"name": "x", "path": "x"}}, + }) + rr := httptest.NewRecorder() + s.mux.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, endpoint, bytes.NewReader(payload))) + + var got struct { + ErrorCode string `json:"error_code"` + } + _ = json.Unmarshal(rr.Body.Bytes(), &got) + if rr.Code != tc.status || got.ErrorCode != tc.code { + t.Fatalf("status = %d, code = %q; want %d %s (%s)", rr.Code, got.ErrorCode, tc.status, tc.code, rr.Body.String()) + } + }) + } + } + for _, rel := range []string{"holder/sub", "_team/sub"} { + if _, err := os.Stat(filepath.Join(src, filepath.FromSlash(rel))); !os.IsNotExist(err) { + t.Errorf("%s was created by a refused install", rel) + } + } +} diff --git a/internal/server/handler_move.go b/internal/server/handler_move.go new file mode 100644 index 000000000..2eee0e411 --- /dev/null +++ b/internal/server/handler_move.go @@ -0,0 +1,146 @@ +package server + +import ( + "errors" + "net/http" + "time" + + "skillshare/internal/skillmove" + ssync "skillshare/internal/sync" +) + +type batchMoveRequest struct { + Names []string `json:"names"` + Dest string `json:"dest"` + Kind string `json:"kind,omitempty"` + Force bool `json:"force"` + DryRun bool `json:"dryRun"` +} + +type batchMoveItemResult struct { + Name string `json:"name"` + Success bool `json:"success"` + From string `json:"from,omitempty"` + To string `json:"to,omitempty"` + FlatName string `json:"flatName,omitempty"` // the new flat name of a skill; the dashboard route is keyed by it + Record bool `json:"record,omitempty"` // an install record moved along + Skills int `json:"skills,omitempty"` // the count below a folder + Error string `json:"error,omitempty"` + ErrorCode string `json:"error_code,omitempty"` +} + +// handleBatchMove moves skills and folders to another folder of the source, +// with their install records. It does not sync: the old target links stay +// until the dashboard runs sync. +func (s *Server) handleBatchMove(w http.ResponseWriter, r *http.Request) { + start := time.Now() + s.mu.Lock() + defer s.mu.Unlock() + + var body batchMoveRequest + if err := decodeJSON(w, r, &body, defaultJSONBodyLimit); err != nil { + if !errors.Is(err, errBodyTooLarge) { + writeCodedError(w, http.StatusBadRequest, "invalid_body", "invalid JSON body", nil) + } + return + } + if len(body.Names) == 0 { + writeCodedError(w, http.StatusBadRequest, "invalid_body", "names array is required and must not be empty", nil) + return + } + if body.Kind == "agent" { + writeCodedError(w, http.StatusBadRequest, "unsupported_kind", "agents cannot be moved", nil) + return + } + if body.Kind != "" && body.Kind != "skill" { + writeCodedError(w, http.StatusBadRequest, "invalid_body", "invalid kind: "+body.Kind, nil) + return + } + + source := s.skillsSource() + walk := s.skillsWalk() + opts := skillmove.Options{ + SourceDir: source, + Follow: walk.Follow, + Store: s.skillsStore, + Targets: skillmove.EnabledTargets(s.cfg.Targets), + Force: body.Force, + DryRun: body.DryRun, + Reconcile: func() error { return s.reconcileSkills(source) }, + } + if s.IsProjectMode() { + opts.ProjectRoot = s.projectRoot + opts.GitignoreDir, opts.GitignorePrefix = s.gitignoreDir(), s.projectGitignorePrefix() + } + // A malformed destination fails the request; the other refusals are per name. + if _, refusal := skillmove.CheckDest(body.Dest, opts); refusal != nil && refusal.Code == skillmove.CodeInvalidDest { + writeCodedError(w, http.StatusBadRequest, string(refusal.Code), refusal.Error(), nil) + return + } + + discovered, err := ssync.DiscoverSourceSkillsAll(source, walk) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to discover skills: "+err.Error()) + return + } + out := skillmove.Run(skillmove.Plan(discovered, body.Names, body.Dest, opts), opts) + + results := make([]batchMoveItemResult, len(out.Items)) + warnings := []string{} + var summary batchUninstallSummary + var firstErr string + for i, item := range out.Items { + res := batchMoveItemResult{Name: item.Name} + if item.Skipped() { + // Already in place: nothing to do and nothing wrong; the code says why. + res.Success, res.From, res.To, res.FlatName = true, item.From, item.To, item.FlatName() + res.Error, res.ErrorCode = item.Err.Error(), string(item.Err.Code) + summary.Succeeded++ + } else if item.Moved() { + res.Success, res.From, res.To = true, item.From, item.To + res.Record, res.FlatName = item.Records > 0, item.FlatName() + if item.Folder || len(item.Skills) > 1 { + res.Skills = len(item.Skills) + } + summary.Succeeded++ + } else { + res.Error, res.ErrorCode = item.Err.Error(), string(item.Err.Code) + summary.Failed++ + if firstErr == "" { + firstErr = res.Error + } + } + warnings = append(warnings, item.Warnings...) + results[i] = res + } + if out.Err != nil { + warnings = append(warnings, "moved, but a follow-up step failed: "+out.Err.Error()) + if firstErr == "" { + firstErr = out.Err.Error() + } + } + + if !body.DryRun { + status := "ok" + switch { + case firstErr != "" && summary.Succeeded > 0: + status = "partial" + case firstErr != "": + status = "error" + } + s.writeOpsLog("move", status, start, map[string]any{ + "names": body.Names, + "dest": body.Dest, + "force": body.Force, + "count": summary.Succeeded, + "scope": "ui", + }, firstErr) + } + + writeJSON(w, map[string]any{ + "results": results, + "summary": summary, + "warnings": warnings, + "dryRun": body.DryRun, + }) +} diff --git a/internal/server/handler_move_test.go b/internal/server/handler_move_test.go new file mode 100644 index 000000000..e17ea1a16 --- /dev/null +++ b/internal/server/handler_move_test.go @@ -0,0 +1,280 @@ +package server + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "skillshare/internal/config" + "skillshare/internal/install" + "skillshare/internal/oplog" + "skillshare/internal/projectdir" +) + +type moveResponse struct { + Results []batchMoveItemResult `json:"results"` + Summary batchUninstallSummary `json:"summary"` + Warns []string `json:"warnings"` + DryRun bool `json:"dryRun"` +} + +func postMove(t *testing.T, s *Server, body any) (*httptest.ResponseRecorder, moveResponse) { + t.Helper() + raw, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/api/resources/batch/move", bytes.NewReader(raw))) + var resp moveResponse + if rr.Code == http.StatusOK { + if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v: %s", err, rr.Body.String()) + } + } + return rr, resp +} + +func TestHandleBatchMove_MovesSkillWithItsRecord(t *testing.T) { + s, src := newTestServer(t) + addSkill(t, src, "demo") + s.skillsStore.Set("demo", &install.MetadataEntry{Source: "github.com/user/repo/demo"}) + s.skillsStore.AuditAccepted = map[string][]string{"demo": {"accepted-key"}} + if err := s.skillsStore.Save(src); err != nil { + t.Fatal(err) + } + + rr, resp := postMove(t, s, map[string]any{"names": []string{"demo"}, "dest": "grp"}) + + if rr.Code != http.StatusOK { + t.Fatalf("status = %d: %s", rr.Code, rr.Body.String()) + } + want := batchMoveItemResult{Name: "demo", Success: true, From: "demo", To: "grp/demo", FlatName: "grp__demo", Record: true} + if len(resp.Results) != 1 || resp.Results[0] != want { + t.Fatalf("results = %+v, want %+v", resp.Results, want) + } + if resp.Summary.Succeeded != 1 || resp.Summary.Failed != 0 { + t.Errorf("summary = %+v", resp.Summary) + } + if _, err := os.Stat(filepath.Join(src, "grp", "demo", "SKILL.md")); err != nil { + t.Errorf("skill not at the new path: %v", err) + } + saved := install.LoadMetadataOrNew(src) + if got := saved.Get("grp/demo"); got == nil || got.Group != "grp" || saved.Has("demo") { + t.Errorf("saved keys = %v, want the record re-keyed with its group", saved.List()) + } + if len(saved.AuditAccepted["grp/demo"]) != 1 { + t.Errorf("accepted findings = %v, want them carried", saved.AuditAccepted) + } + entries, _ := oplog.Read(s.configPath(), oplog.OpsFile, 10) + if len(entries) != 1 || entries[0].Command != "move" || entries[0].Status != "ok" { + t.Errorf("oplog = %+v, want one ok move entry", entries) + } +} + +func TestHandleBatchMove_DryRunChangesNothing(t *testing.T) { + s, src := newTestServer(t) + addSkill(t, src, "demo") + + _, resp := postMove(t, s, map[string]any{"names": []string{"demo"}, "dest": "grp", "dryRun": true}) + + if !resp.DryRun || len(resp.Results) != 1 || !resp.Results[0].Success || resp.Results[0].To != "grp/demo" { + t.Fatalf("response = %+v, want the plan reported as a success", resp) + } + if _, err := os.Stat(filepath.Join(src, "demo", "SKILL.md")); err != nil { + t.Errorf("dry run moved the skill: %v", err) + } + if entries, _ := oplog.Read(s.configPath(), oplog.OpsFile, 10); len(entries) != 0 { + t.Errorf("dry run was logged: %+v", entries) + } +} + +func TestHandleBatchMove_PartialFailureIsStill200(t *testing.T) { + s, src := newTestServer(t) + addSkill(t, src, "demo") + addSkill(t, src, "taken") + addSkill(t, src, "grp/taken") + + rr, resp := postMove(t, s, map[string]any{"names": []string{"demo", "ghost", "taken"}, "dest": "grp"}) + + if rr.Code != http.StatusOK { + t.Fatalf("status = %d", rr.Code) + } + codes := []string{resp.Results[0].ErrorCode, resp.Results[1].ErrorCode, resp.Results[2].ErrorCode} + if want := []string{"", "skill_not_found", "dest_exists"}; strings.Join(codes, ",") != strings.Join(want, ",") { + t.Errorf("error codes = %v, want %v", codes, want) + } + if resp.Summary.Succeeded != 1 || resp.Summary.Failed != 2 { + t.Errorf("summary = %+v", resp.Summary) + } + entries, _ := oplog.Read(s.configPath(), oplog.OpsFile, 10) + if len(entries) != 1 || entries[0].Status != "partial" { + t.Errorf("oplog = %+v, want one partial entry", entries) + } +} + +func TestHandleBatchMove_FolderMovesWithEverythingBelowIt(t *testing.T) { + s, src := newTestServer(t) + addSkill(t, src, "frontend/a") + addSkill(t, src, "frontend/deep/b") + + _, resp := postMove(t, s, map[string]any{"names": []string{"frontend"}, "dest": "archive"}) + + if len(resp.Results) != 1 || !resp.Results[0].Success || resp.Results[0].Skills != 2 || resp.Results[0].To != "archive/frontend" { + t.Fatalf("results = %+v, want one folder result with 2 skills", resp.Results) + } + if _, err := os.Stat(filepath.Join(src, "archive", "frontend", "deep", "b", "SKILL.md")); err != nil { + t.Errorf("nested skill did not move: %v", err) + } +} + +func TestHandleBatchMove_NameCollisionNeedsForce(t *testing.T) { + s, src := newTestServerWithTargets(t, map[string]string{"claude": filepath.Join(t.TempDir(), "claude-skills")}) + addSkill(t, src, "grp__demo") + addSkill(t, src, "demo") + + _, resp := postMove(t, s, map[string]any{"names": []string{"demo"}, "dest": "grp"}) + if resp.Results[0].ErrorCode != "name_collision" { + t.Fatalf("results = %+v, want name_collision", resp.Results) + } + + _, resp = postMove(t, s, map[string]any{"names": []string{"demo"}, "dest": "grp", "force": true}) + if !resp.Results[0].Success || len(resp.Warns) == 0 { + t.Errorf("forced response = %+v, want success with a warning", resp) + } +} + +func TestHandleBatchMove_RejectsMalformedRequests(t *testing.T) { + s, src := newTestServer(t) + addSkill(t, src, "demo") + + cases := []struct { + name string + body any + code string + }{ + {"no names", map[string]any{"names": []string{}, "dest": "grp"}, "invalid_body"}, + {"agent kind", map[string]any{"names": []string{"demo"}, "dest": "grp", "kind": "agent"}, "unsupported_kind"}, + {"empty dest", map[string]any{"names": []string{"demo"}, "dest": ""}, "invalid_dest"}, + {"dest outside the source", map[string]any{"names": []string{"demo"}, "dest": "../out"}, "invalid_dest"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + rr, _ := postMove(t, s, c.body) + var got struct { + ErrorCode string `json:"error_code"` + } + _ = json.Unmarshal(rr.Body.Bytes(), &got) + if rr.Code != http.StatusBadRequest || got.ErrorCode != c.code { + t.Errorf("status = %d, code = %q; want 400 %s (%s)", rr.Code, got.ErrorCode, c.code, rr.Body.String()) + } + }) + } + + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/api/resources/batch/move", strings.NewReader("{"))) + if rr.Code != http.StatusBadRequest || !strings.Contains(rr.Body.String(), "invalid_body") { + t.Errorf("malformed JSON: status = %d, body = %s", rr.Code, rr.Body.String()) + } + if _, err := os.Stat(filepath.Join(src, "demo", "SKILL.md")); err != nil { + t.Errorf("a rejected request moved something: %v", err) + } +} + +func TestHandleBatchMove_ProjectModeCarriesPinAndGroup(t *testing.T) { + s, _ := newTestServer(t) + root := t.TempDir() + skills := filepath.Join(root, ".skillshare", "skills") + s.projectRoot = root + s.projectCfg = &config.ProjectConfig{ + Targets: []config.ProjectTargetEntry{{Name: "claude"}}, + Skills: []config.SkillEntry{{Name: "demo", Source: "github.com/user/repo/demo"}}, + } + s.cfg.Source = skills + if err := s.projectCfg.Save(root); err != nil { + t.Fatal(err) + } + addSkill(t, skills, "demo") + s.skillsStore = install.NewMetadataStore() + s.skillsStore.Set("demo", &install.MetadataEntry{Source: "github.com/user/repo/demo"}) + if err := s.skillsStore.Save(skills); err != nil { + t.Fatal(err) + } + const pinned = "0123456789abcdef0123456789abcdef01234567" + dir := projectdir.Resolve(root) + if err := (&install.Lock{Skills: map[string]install.LockEntry{"demo": {Source: "github.com/user/repo/demo", Commit: pinned}}}).Save(dir); err != nil { + t.Fatal(err) + } + + rr, resp := postMove(t, s, map[string]any{"names": []string{"demo"}, "dest": "grp"}) + + if len(resp.Results) != 1 || !resp.Results[0].Success { + t.Fatalf("status = %d, results = %+v, body = %s", rr.Code, resp.Results, rr.Body.String()) + } + if got, err := install.LoadLock(dir); err != nil || got.Skills["grp/demo"].Commit != pinned || len(got.Skills) != 1 { + t.Errorf("lock = %+v (err %v), want the pin carried to grp/demo", got, err) + } + if len(s.projectCfg.Skills) != 1 || s.projectCfg.Skills[0].Group != "grp" { + t.Errorf("config skills = %+v, want one entry in group grp", s.projectCfg.Skills) + } +} + +// A name that is already in the destination is a no-op, not a failed move. +func TestHandleBatchMove_AlreadyInPlaceIsNotAFailure(t *testing.T) { + s, src := newTestServer(t) + addSkill(t, src, "grp/demo") + + _, resp := postMove(t, s, map[string]any{"names": []string{"grp/demo"}, "dest": "grp"}) + + if len(resp.Results) != 1 || !resp.Results[0].Success || resp.Results[0].ErrorCode != "same_folder" || resp.Summary.Failed != 0 { + t.Fatalf("response = %+v, want a success carrying same_folder", resp) + } + if entries, _ := oplog.Read(s.configPath(), oplog.OpsFile, 10); len(entries) != 1 || entries[0].Status != "ok" { + t.Errorf("oplog = %+v, want one ok entry", entries) + } +} + +// A failed reconcile after the rename is reported in the response and the log, +// not swallowed: the project's recorded state is out of step until fixed. +func TestHandleBatchMove_ReportsReconcileFailure(t *testing.T) { + s, _ := newTestServer(t) + root := t.TempDir() + skills := filepath.Join(root, ".skillshare", "skills") + s.projectRoot = root + s.projectCfg = &config.ProjectConfig{ + Targets: []config.ProjectTargetEntry{{Name: "claude"}}, + Skills: []config.SkillEntry{{Name: "demo", Source: "github.com/user/repo/demo"}}, + } + s.cfg.Source = skills + addSkill(t, skills, "demo") + s.skillsStore = install.NewMetadataStore() + s.skillsStore.Set("demo", &install.MetadataEntry{Source: "github.com/user/repo/demo"}) + // A directory where config.yaml belongs: the group change cannot be saved. + if err := os.MkdirAll(filepath.Join(root, ".skillshare", "config.yaml"), 0o755); err != nil { + t.Fatal(err) + } + + raw, _ := json.Marshal(map[string]any{"names": []string{"demo"}, "dest": "grp"}) + rr := httptest.NewRecorder() + s.handleBatchMove(rr, httptest.NewRequest(http.MethodPost, "/api/resources/batch/move", bytes.NewReader(raw))) + + var resp moveResponse + if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v: %s", err, rr.Body.String()) + } + if len(resp.Results) != 1 || !resp.Results[0].Success { + t.Fatalf("results = %+v, want the rename reported", resp.Results) + } + if len(resp.Warns) != 1 || !strings.Contains(resp.Warns[0], "follow-up step failed") { + t.Errorf("warnings = %v, want the reconcile failure", resp.Warns) + } + entries, _ := oplog.Read(s.configPath(), oplog.OpsFile, 10) + if len(entries) != 1 || entries[0].Status == "ok" { + t.Errorf("oplog = %+v, want a non-ok entry", entries) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index b2f810c87..cfececa83 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -479,6 +479,7 @@ func (s *Server) registerRoutes() { s.mux.HandleFunc("DELETE /api/resources/{name}", s.handleUninstallSkill) s.mux.HandleFunc("POST /api/resources/batch/targets", s.handleBatchSetTargets) s.mux.HandleFunc("POST /api/resources/batch/toggle", s.handleBatchToggleSkills) + s.mux.HandleFunc("POST /api/resources/batch/move", s.handleBatchMove) s.mux.HandleFunc("PATCH /api/resources/{name}/targets", s.handleSetSkillTargets) // Targets diff --git a/internal/skillignore/write.go b/internal/skillignore/write.go index 6328767ff..fa721d7ba 100644 --- a/internal/skillignore/write.go +++ b/internal/skillignore/write.go @@ -67,6 +67,26 @@ func RemovePattern(filePath, pattern string) (bool, error) { return true, os.WriteFile(filePath, []byte(result), 0644) } +// RenamePatterns rewrites every line that is exactly a key of renames, or a +// "!" negation of one, to its value and reports whether any changed. Lines keep +// their place: with negations the last matching rule wins, so a removed and +// re-added line would change what the file means. +func RenamePatterns(content string, renames map[string]string) (string, bool) { + lines := strings.Split(content, "\n") + changed := false + for i, line := range lines { + pattern := strings.TrimRight(line, " \t\r") + negation := strings.HasPrefix(pattern, "!") + if to, ok := renames[strings.TrimPrefix(pattern, "!")]; ok { + if negation { + to = "!" + to + } + lines[i], changed = to, true + } + } + return strings.Join(lines, "\n"), changed +} + // HasPattern returns true if the exact pattern exists in a .skillignore file. func HasPattern(filePath, pattern string) bool { data, err := os.ReadFile(filePath) diff --git a/internal/skillignore/write_test.go b/internal/skillignore/write_test.go index ca6f42931..15e7f7c82 100644 --- a/internal/skillignore/write_test.go +++ b/internal/skillignore/write_test.go @@ -231,3 +231,21 @@ func TestRemovePattern_CRLF(t *testing.T) { t.Error("other patterns must be kept") } } + +func TestRenamePatterns_KeepsLinePlacement(t *testing.T) { + // A negation naming a moved path follows it too, or it would stop undoing + // the rule that disabled its neighbours. + content := "# note\ndemo\n!other \nglob*\ndemo/sub\n" + + got, changed := RenamePatterns(content, map[string]string{"demo": "grp/demo", "other": "grp/other", "demo/sub": "grp/demo/sub"}) + + if want := "# note\ngrp/demo\n!grp/other\nglob*\ngrp/demo/sub\n"; got != want { + t.Errorf("got %q, want %q", got, want) + } + if !changed { + t.Error("changed = false for a file with literal matches") + } + if _, changed := RenamePatterns(content, map[string]string{"absent": "x"}); changed { + t.Error("changed = true without a matching line") + } +} diff --git a/internal/skillmove/skillmove.go b/internal/skillmove/skillmove.go new file mode 100644 index 000000000..abb90ca8c --- /dev/null +++ b/internal/skillmove/skillmove.go @@ -0,0 +1,668 @@ +// Package skillmove moves skills and folders to another folder of the skills +// source and carries what the install recorded about them: the metadata +// records with their audit acceptances, the project lockfile pin, the project +// .gitignore entry and a literal .skillignore line. Callers resolve the mode, +// pass the same discovery they list from and report the per-name results. +package skillmove + +import ( + "errors" + "fmt" + "io/fs" + "maps" + "os" + "path" + "path/filepath" + "slices" + "sort" + "strings" + + "skillshare/internal/config" + "skillshare/internal/install" + "skillshare/internal/projectdir" + "skillshare/internal/skillignore" + "skillshare/internal/sourcefs" + "skillshare/internal/sourcewalk" + "skillshare/internal/sync" + "skillshare/internal/utils" + "skillshare/internal/validate" +) + +// Code names why a move was refused. The values are stable: the CLI prints +// them in --json and the dashboard API sends them as error_code. +type Code string + +const ( + CodeNotFound Code = "skill_not_found" + CodeAmbiguousName Code = "ambiguous_name" + CodeDestExists Code = "dest_exists" + CodeInsideTrackedRepo Code = "inside_tracked_repo" + CodeDestInsideTrackedRepo Code = "dest_inside_tracked_repo" + CodeLinkedFolder Code = "linked_folder" + CodeDestIsSkill Code = "dest_is_skill" + CodeInvalidDest Code = "invalid_dest" + CodeDestInsideSource Code = "dest_inside_source_folder" + CodeDuplicateDest Code = "duplicate_dest" + CodeOverlappingSources Code = "overlapping_sources" + CodeSameFolder Code = "same_folder" + CodeNameCollision Code = "name_collision" + CodeAmbiguousRecord Code = "ambiguous_record" + CodeMoveFailed Code = "move_failed" +) + +// Refusal is why one name was not moved. It is also the error of a rename that +// failed after the checks passed (CodeMoveFailed). +type Refusal struct { + Code Code + Msg string +} + +func (r *Refusal) Error() string { return r.Msg } + +// Target is a sync target as the move needs it: its name, for a skill's +// targets: frontmatter, and the skills config its filters and naming come from. +type Target struct { + Name string + Config config.ResourceTargetConfig +} + +// EnabledTargets lists the skills targets a move is checked against, in name +// order. A symlink-mode target links the whole source, so neither its filters +// nor its naming apply. +func EnabledTargets(targets map[string]config.TargetConfig) []Target { + names := make([]string, 0, len(targets)) + for name := range targets { + names = append(names, name) + } + sort.Strings(names) + var out []Target + for _, name := range names { + target := targets[name] + if sc := target.SkillsConfig(); sc.IsEnabled() && sc.Mode != "symlink" { + out = append(out, Target{Name: name, Config: sc}) + } + } + return out +} + +// Options describes the source the names live in. +type Options struct { + SourceDir string + Follow *sourcewalk.Follow + Store *install.MetadataStore // re-keyed and saved to SourceDir by Run + Targets []Target // enabled skills targets, for collisions and filter warnings + Force bool // accept a name collision + + // DryRun makes Run report the plan's results and change nothing. + DryRun bool + // ProjectRoot is set in project mode: the lockfile pin follows the skill. + ProjectRoot string + // GitignoreDir and GitignorePrefix locate the project .gitignore line of an + // installed skill, "/"; an empty dir skips the cleanup. + GitignoreDir string + GitignorePrefix string + // Install is for CheckDest on an install --into folder: links are left to + // the install, which writes through a followed first-level link or is + // refused by sourcefs, so a path below one is not refused here. + Install bool + // Reconcile runs after the records are saved: it sets groups, prunes and, + // in project mode, rewrites config.yaml and the lockfile. May be nil. + Reconcile func() error +} + +// Skill is one discovered skill that moves with its root. +type Skill struct { + From, To string // source-relative slash paths + FlatFrom, FlatTo string +} + +// Planned is one requested name: what it resolved to, or why it is refused. +type Planned struct { + Name string // as requested + From, To string // the skill or folder being renamed + Folder bool // a folder rather than a skill + Skills []Skill + Records int // metadata entries that move with it + Warnings []string + Err *Refusal // nil: will move (Plan) or moved (Run) +} + +// renames maps each path that moves to where it goes: the root, its skills and +// whatever carries a record below it, so a literal ignore line or a lock pin +// naming any of them follows. +func (p Planned) renames() map[string]string { + m := map[string]string{p.From: p.To} + for _, s := range p.Skills { + m[s.From] = s.To + } + return m +} + +// Moved reports whether the name was moved, or would be. +func (p Planned) Moved() bool { return p.Err == nil } + +// Skipped reports a name that is already in the destination: a no-op, not a +// failure. +func (p Planned) Skipped() bool { return p.Err != nil && p.Err.Code == CodeSameFolder } + +// FlatName is the flat name a moved skill goes by afterwards; "" for a folder. +func (p Planned) FlatName() string { + if !p.Folder { + for _, s := range p.Skills { + if s.From == p.From { + return s.FlatTo + } + } + } + return "" +} + +// Outcome is the result of Run: one entry per planned name in input order, and +// the first failure of a step after the renames, which leaves records, +// lockfile or ignore files out of step until fixed. +type Outcome struct { + Items []Planned + Err error +} + +// Plan resolves names to skills or folders below dest and refuses what cannot +// move, without touching disk. discovered is the source's full discovery, +// disabled skills included. Every refusal is final: a folder is checked as a +// whole, so none of it ends half-moved. +func Plan(discovered []sync.DiscoveredSkill, names []string, dest string, o Options) []Planned { + planned := make([]Planned, len(names)) + destRel, destErr := CheckDest(dest, o) + for i, name := range names { + p := Planned{Name: name} + if destErr != nil { + p.Err = destErr + } else { + resolve(&p, discovered, normalize(name), destRel, o) + } + planned[i] = p + } + if destErr != nil { + return planned + } + refuseBatchConflicts(planned) + checkRecords(planned, o) + checkTargets(planned, discovered, o) + files := readIgnoreFiles(o.SourceDir) + before := files.matcher(nil) + for i := range planned { + if planned[i].Err == nil { + planned[i].Warnings = append(planned[i].Warnings, ignoreWarnings(&planned[i], files, before)...) + } + } + return planned +} + +// normalize turns a typed name into a slash path without a trailing slash. +func normalize(name string) string { + name = strings.ReplaceAll(strings.TrimSpace(name), `\`, "/") + name = strings.TrimRight(name, "/") + return strings.TrimPrefix(name, "./") +} + +// CheckDest validates dest once for the whole batch and returns it as a slash +// path below the source ("" for the source root). Plan applies the same check, +// so a caller that wants a bad destination to fail the request, not each name, +// can ask first. +func CheckDest(dest string, o Options) (string, *Refusal) { + dest = normalize(dest) + if dest == "." { + return "", nil + } + // A _ folder cannot be typed, so look for the checkout before validating: + // the refusal then says what is wrong instead of what is not allowed. + if repo, ok := install.TrackedAncestor(o.SourceDir, dest+"/x", o.Follow); ok { + return "", &Refusal{CodeDestInsideTrackedRepo, fmt.Sprintf("destination %q is inside the tracked repo %s", dest, repo)} + } + if err := validate.IntoPath(dest); err != nil { + return "", &Refusal{CodeInvalidDest, fmt.Sprintf("invalid destination %q: %v", dest, err)} + } + prefix := "" + for _, seg := range strings.Split(dest, "/") { + prefix = path.Join(prefix, seg) + abs := filepath.Join(o.SourceDir, filepath.FromSlash(prefix)) + info, err := os.Lstat(abs) + linked := err == nil && utils.IsLinkMode(abs, info.Mode()) + switch { + case err != nil: + return dest, nil // the rest does not exist yet + case linked && !o.Install: + return "", &Refusal{CodeLinkedFolder, fmt.Sprintf("destination %q is below the source link %s", dest, prefix)} + case linked: + case !info.IsDir(): + return "", &Refusal{CodeInvalidDest, fmt.Sprintf("destination %q: %s is a file", dest, prefix)} + } + if _, err := os.Stat(filepath.Join(abs, "SKILL.md")); err == nil { + return "", &Refusal{CodeDestIsSkill, fmt.Sprintf("destination %q is inside the skill %s", dest, prefix)} + } + } + return dest, nil +} + +// resolve fills p for one typed name. An exact path wins over a flat name or +// a base name, so a short name never moves something other than what it spells. +func resolve(p *Planned, discovered []sync.DiscoveredSkill, name string, destRel string, o Options) { + if name == "" || name == "." || strings.HasPrefix(name, "/") || slices.Contains(strings.Split(name, "/"), "..") { + p.Err = &Refusal{CodeNotFound, fmt.Sprintf("invalid name %q", p.Name)} + return + } + root, folder, err := lookup(discovered, name, o) + if err != nil { + p.Err = err + return + } + p.From, p.Folder = root, folder + p.To = path.Join(destRel, path.Base(root)) + + if r := checkSource(root, o); r != nil { + p.Err = r + return + } + for _, d := range discovered { + if d.RelPath == root || strings.HasPrefix(d.RelPath, root+"/") { + p.Skills = append(p.Skills, Skill{From: d.RelPath, FlatFrom: d.FlatName}) + } + } + if len(p.Skills) == 0 { + p.Err = &Refusal{CodeNotFound, fmt.Sprintf("no skill found in %s", root)} + return + } + switch { + case p.To == p.From: + p.Err = &Refusal{CodeSameFolder, fmt.Sprintf("%s is already in %s", root, folderLabel(destRel))} + case destRel == root || strings.HasPrefix(destRel, root+"/"): + p.Err = &Refusal{CodeDestInsideSource, fmt.Sprintf("cannot move %s into itself", root)} + default: + if _, err := os.Lstat(filepath.Join(o.SourceDir, filepath.FromSlash(p.To))); err == nil { + p.Err = &Refusal{CodeDestExists, fmt.Sprintf("%s already exists", p.To)} + } + } + for i := range p.Skills { + p.Skills[i].To = p.To + strings.TrimPrefix(p.Skills[i].From, root) + p.Skills[i].FlatTo = utils.PathToFlatName(p.Skills[i].To) + } +} + +func folderLabel(rel string) string { + if rel == "" { + return "the source root" + } + return rel +} + +// lookup finds the skill or folder a typed name stands for. +func lookup(discovered []sync.DiscoveredSkill, name string, o Options) (root string, folder bool, err *Refusal) { + for _, d := range discovered { + if d.RelPath == name { + return name, false, nil + } + } + abs := filepath.Join(o.SourceDir, filepath.FromSlash(name)) + if info, statErr := os.Lstat(abs); statErr == nil && (info.IsDir() || utils.IsLinkMode(abs, info.Mode())) { + return name, true, nil + } + var flat, base []string + for _, d := range discovered { + if d.FlatName == name { + flat = append(flat, d.RelPath) + } + if path.Base(d.RelPath) == name { + base = append(base, d.RelPath) + } + } + for _, found := range [][]string{flat, base} { + switch len(found) { + case 0: + case 1: + return found[0], false, nil + default: + sort.Strings(found) + return "", false, &Refusal{CodeAmbiguousName, fmt.Sprintf("%q matches %s: use the full path", name, strings.Join(found, ", "))} + } + } + return "", false, &Refusal{CodeNotFound, fmt.Sprintf("skill %q not found in the source", name)} +} + +// checkSource refuses a root that sits in, is, or holds a tracked checkout or +// a followed source link. The whole tree is walked, so a checkout with no +// skill of its own is found too. +func checkSource(root string, o Options) *Refusal { + if repo, ok := install.TrackedAncestor(o.SourceDir, root+"/x", o.Follow); ok { + if repo == root { + return &Refusal{CodeInsideTrackedRepo, fmt.Sprintf("%s is a tracked repo; uninstall or update it instead", root)} + } + return &Refusal{CodeInsideTrackedRepo, fmt.Sprintf("%s is inside the tracked repo %s; uninstall or update the repo instead", root, repo)} + } + prefix := "" + for _, seg := range strings.Split(root, "/") { + prefix = path.Join(prefix, seg) + abs := filepath.Join(o.SourceDir, filepath.FromSlash(prefix)) + if _, followed := o.Follow.Resolve(abs); followed { + return &Refusal{CodeLinkedFolder, fmt.Sprintf("%s is, or is inside, the source link %s", root, prefix)} + } + if info, err := os.Lstat(abs); err == nil && utils.IsLinkMode(abs, info.Mode()) { + return &Refusal{CodeLinkedFolder, fmt.Sprintf("%s is, or is inside, the link %s", root, prefix)} + } + } + var refusal *Refusal + base := filepath.Join(o.SourceDir, filepath.FromSlash(root)) + // The policy follows only direct children of the source, so a link below + // root is an ordinary entry that moves with its folder (root itself was + // checked above); what is left to find is a checkout with no skill of its own. + _ = sourcewalk.WalkDir(base, sourcewalk.Options{Follow: o.Follow}, func(p string, d fs.DirEntry, err error) error { + if err != nil || refusal != nil || !d.IsDir() { + return nil + } + if d.Name() == ".git" { + return filepath.SkipDir + } + if install.IsTrackedCheckout(p) { + rel, _ := filepath.Rel(o.SourceDir, p) + refusal = &Refusal{CodeInsideTrackedRepo, fmt.Sprintf("%s holds the tracked repo %s; a folder is moved whole or not at all", root, filepath.ToSlash(rel))} + } + return nil + }) + return refusal +} + +// refuseBatchConflicts refuses names that cannot be satisfied together: two +// resolving to one destination, or one root equal to or below another. Both +// sides go, as neither order is clearly what was meant. +func refuseBatchConflicts(planned []Planned) { + for i := range planned { + for j := i + 1; j < len(planned); j++ { + a, b := &planned[i], &planned[j] + if a.From == "" || b.From == "" || (a.Err != nil && a.Err.Code != CodeSameFolder) || (b.Err != nil && b.Err.Code != CodeSameFolder) { + continue + } + switch { + case a.From == b.From || strings.HasPrefix(a.From, b.From+"/") || strings.HasPrefix(b.From, a.From+"/"): + r := &Refusal{CodeOverlappingSources, fmt.Sprintf("%s and %s overlap: the folder already carries what is below it", a.From, b.From)} + a.Err, b.Err = r, r + case a.To == b.To: + r := &Refusal{CodeDuplicateDest, fmt.Sprintf("%s and %s would both become %s", a.From, b.From, a.To)} + a.Err, b.Err = r, r + } + } + } +} + +// checkRecords counts the records each name carries and refuses a name whose +// records cannot be re-keyed one to one: two entries claiming one path would +// merge on the move and drop one with its audit acceptances. +func checkRecords(planned []Planned, o Options) { + for i := range planned { + p := &planned[i] + if p.Err != nil || o.Store == nil { + continue + } + seen := map[string]bool{} + for _, key := range o.Store.KeysUnder(p.From) { + rel := filepath.ToSlash(install.KeyToRelPath(key, o.Store.Get(key))) + if seen[rel] { + p.Err = &Refusal{CodeAmbiguousRecord, fmt.Sprintf("two install records claim %s; remove the stale one from .metadata.json first", rel)} + break + } + seen[rel] = true + p.Records++ + } + } +} + +// checkTargets looks at what the new flat names do to each target: a name +// another skill already has there is a collision (refused unless forced), and +// an include or exclude rule that no longer decides the same is a warning. +func checkTargets(planned []Planned, discovered []sync.DiscoveredSkill, o Options) { + moved := map[string]string{} // old relPath -> new + for _, p := range planned { + if p.Err != nil { + continue + } + for _, s := range p.Skills { + moved[s.From] = s.To + } + } + if len(moved) == 0 || len(o.Targets) == 0 { + return + } + after := make([]sync.DiscoveredSkill, len(discovered)) + copy(after, discovered) + for i, d := range after { + if to, ok := moved[d.RelPath]; ok { + // SourcePath stays: the SKILL.md is read from where it still is. + after[i].RelPath, after[i].FlatName = to, utils.PathToFlatName(to) + } + } + + for _, t := range o.Targets { + var before map[string][]string // what already clashed; read only when something does now + for name, paths := range collisions(t, after) { + if before == nil { + before = collisions(t, discovered) + } + for i := range planned { + p := &planned[i] + if p.Err != nil || !joins(p, paths, before[name]) { + continue + } + msg := fmt.Sprintf("target %s would get two skills named %q (%s)", t.Name, name, strings.Join(paths, ", ")) + if o.Force { + p.Warnings = append(p.Warnings, msg+"; sync skips both until one is renamed") + } else { + p.Err = &Refusal{CodeNameCollision, msg + "; use --force to move anyway"} + } + } + } + for i := range planned { + p := &planned[i] + if p.Err != nil { + continue + } + for _, s := range p.Skills { + was, _ := sync.ShouldSyncFlatName(s.FlatFrom, t.Config.Include, t.Config.Exclude) + now, _ := sync.ShouldSyncFlatName(s.FlatTo, t.Config.Include, t.Config.Exclude) + if was != now { + p.Warnings = append(p.Warnings, fmt.Sprintf("target %s: its include/exclude rules treat %s differently from %s (%s); config.yaml is not changed", + t.Name, s.FlatTo, s.FlatFrom, syncedWord(was))) + } + } + } + } +} + +func syncedWord(was bool) string { + if was { + return "it was synced, it no longer is" + } + return "it was not synced, it now is" +} + +// joins reports whether one of p's skills becomes a member of the collision at +// paths that it was not part of before, where members are the old paths of the +// collision already there. A skill that merely stays in a collision it was in +// is no new problem; one that adds itself to it is. +func joins(p *Planned, paths, members []string) bool { + for _, s := range p.Skills { + if slices.Contains(paths, s.To) && !slices.Contains(members, s.From) { + return true + } + } + return false +} + +// collisions maps each target name two skills share to their relPaths. Flat +// naming returns before sync's own detection, so equal flat names are compared +// here. +func collisions(t Target, skills []sync.DiscoveredSkill) map[string][]string { + out := map[string][]string{} + if config.EffectiveTargetNaming(t.Config.TargetNaming) == "flat" { + selected, err := sync.SelectTargetSkills(skills, t.Name, t.Config) + if err != nil { + return out + } + byName := map[string][]string{} + for _, s := range selected { + byName[s.FlatName] = append(byName[s.FlatName], s.RelPath) + } + for name, paths := range byName { + if len(paths) > 1 { + sort.Strings(paths) + out[name] = paths + } + } + return out + } + resolution, err := sync.ResolveTargetSkillsForTarget(t.Name, t.Config, skills) + if err != nil { + return out + } + for _, c := range resolution.Collisions { + out[c.Name] = c.Paths + } + return out +} + +// ignoreFiles is the source's .skillignore and .skillignore.local, read once +// per Plan. +type ignoreFiles struct{ base, local string } + +func readIgnoreFiles(dir string) ignoreFiles { + base, _ := os.ReadFile(filepath.Join(dir, ".skillignore")) + local, _ := os.ReadFile(filepath.Join(dir, ".skillignore.local")) + return ignoreFiles{string(base), string(local)} +} + +// matcher compiles the files as discovery reads them, with the literal lines +// of .skillignore renamed. The local file is a machine's own and never follows. +func (f ignoreFiles) matcher(renames map[string]string) *skillignore.Matcher { + base, _ := skillignore.RenamePatterns(f.base, renames) + return skillignore.Compile(strings.Split(base+"\n"+f.local, "\n")) +} + +// ignoreWarnings predicts whether the rules still decide the same for each +// moved skill once a literal line has followed it. Glob rules are left alone, +// so they may now match differently. +func ignoreWarnings(p *Planned, files ignoreFiles, before *skillignore.Matcher) []string { + if !before.HasRules() { + return nil + } + after := files.matcher(p.renames()) + var warnings []string + for _, s := range p.Skills { + if was, now := before.Match(s.From, true), after.Match(s.To, true); was != now { + state := "enabled" + if now { + state = "disabled" + } + warnings = append(warnings, fmt.Sprintf("%s becomes %s by the .skillignore rules", s.To, state)) + } + } + return warnings +} + +// Run renames each planned name that has no refusal, then re-keys the records +// of what moved. A failed rename changes nothing for that name; the steps after +// the renames run once for everything that moved, and the first failure is +// returned in Outcome.Err. +func Run(planned []Planned, o Options) Outcome { + out := Outcome{Items: append([]Planned(nil), planned...)} + if o.DryRun { + return out + } + root, err := sourcefs.Create(o.SourceDir, o.Follow) + if err != nil { + for i := range out.Items { + if out.Items[i].Err == nil { + out.Items[i].Err = &Refusal{CodeMoveFailed, fmt.Sprintf("cannot open the skills source: %v", err)} + } + } + return out + } + defer root.Close() + var moved []*Planned + for i := range out.Items { + p := &out.Items[i] + if p.Err != nil { + continue + } + if dir := path.Dir(p.To); dir != "." { + if err := root.MkdirAll(filepath.FromSlash(dir), 0o755); err != nil { + p.Err = &Refusal{CodeMoveFailed, fmt.Sprintf("cannot create %s: %v", dir, err)} + continue + } + } + if err := root.Rename(filepath.FromSlash(p.From), filepath.FromSlash(p.To)); err != nil { + p.Err = &Refusal{CodeMoveFailed, fmt.Sprintf("cannot move %s: %v", p.From, err)} + continue + } + moved = append(moved, p) + } + if len(moved) > 0 { + out.Err = followUp(root, moved, o) + } + return out +} + +// followUp carries everything recorded about the moved names. Each step runs +// even when an earlier one failed, so one bad file does not strand the rest. +func followUp(root *sourcefs.Root, moved []*Planned, o Options) error { + var errs []error + note := func(what string, err error) { + if err != nil { + errs = append(errs, fmt.Errorf("%s: %w", what, err)) + } + } + + pins := map[string]string{} // every old path that follows its root + for _, p := range moved { + maps.Copy(pins, p.renames()) + if o.Store != nil { + // A record below an installed skill may have no skill of its own. + for _, key := range o.Store.KeysUnder(p.From) { + rel := filepath.ToSlash(install.KeyToRelPath(key, o.Store.Get(key))) + pins[rel] = p.To + strings.TrimPrefix(rel, p.From) + } + o.Store.MovePath(p.From, p.To) + } + } + if o.Store != nil { + note("save install records", o.Store.Save(o.SourceDir)) + } + // The gitignore line of an installed skill sits at its old path; reconcile + // adds the new one but never removes the old. + if o.GitignoreDir != "" { + var stale []string + for from := range pins { + stale = append(stale, o.GitignorePrefix+"/"+from) + } + _, err := install.RemoveFromGitIgnoreBatch(o.GitignoreDir, stale) + note("update .gitignore", err) + } + if o.ProjectRoot != "" { + dir := projectdir.Resolve(o.ProjectRoot) + lock, err := install.LoadLock(dir) + if err == nil { + changed := false + for from, to := range pins { + changed = lock.MovePin(from, to) || changed + } + if changed { + err = lock.Save(dir) + } + } + note("move the "+install.LockFileName+" pin", err) + } + if data, err := os.ReadFile(filepath.Join(o.SourceDir, ".skillignore")); err == nil { + if out, changed := skillignore.RenamePatterns(string(data), pins); changed { + note("update .skillignore", root.WriteFileAtomic(".skillignore", []byte(out), 0o644)) + } + } + if o.Reconcile != nil { + note("reconcile install records", o.Reconcile()) + } + return errors.Join(errs...) +} diff --git a/internal/skillmove/skillmove_test.go b/internal/skillmove/skillmove_test.go new file mode 100644 index 000000000..137766c26 --- /dev/null +++ b/internal/skillmove/skillmove_test.go @@ -0,0 +1,801 @@ +package skillmove + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "reflect" + "runtime" + "strings" + "testing" + + "skillshare/internal/config" + "skillshare/internal/install" + "skillshare/internal/projectdir" + "skillshare/internal/sourcewalk" + "skillshare/internal/sync" +) + +type fixture struct { + source string + store *install.MetadataStore + opts Options +} + +func newFixture(t *testing.T) *fixture { + t.Helper() + source := filepath.Join(t.TempDir(), "skills") + if err := os.MkdirAll(source, 0o755); err != nil { + t.Fatal(err) + } + store := install.NewMetadataStore() + return &fixture{source: source, store: store, opts: Options{SourceDir: source, Store: store}} +} + +func (f *fixture) path(rel string) string { return filepath.Join(f.source, filepath.FromSlash(rel)) } + +// skill creates a skill whose SKILL.md name is its folder name. +func (f *fixture) skill(t *testing.T, rel string) { + t.Helper() + f.file(t, rel+"/SKILL.md", "---\nname: "+filepath.Base(rel)+"\n---\n# "+rel+"\n") +} + +func (f *fixture) file(t *testing.T, rel, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(f.path(rel)), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.path(rel), []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +// record stores an install record keyed by the full path, as install writes it. +func (f *fixture) record(rel string) { + group := "" + if i := strings.LastIndex(rel, "/"); i >= 0 { + group = rel[:i] + } + f.store.Set(rel, &install.MetadataEntry{Source: "github.com/user/repo/" + filepath.Base(rel), Group: group}) +} + +// repo makes dir a tracked checkout. +func (f *fixture) repo(t *testing.T, rel string) { + t.Helper() + dir := f.path(rel) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if out, err := exec.Command("git", "-C", dir, "init", "-q").CombinedOutput(); err != nil { + t.Fatalf("git init: %v\n%s", err, out) + } +} + +// link makes rel a link to a folder outside the source and follows it. +func (f *fixture) link(t *testing.T, rel string) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("needs symlink rights") + } + target := filepath.Join(t.TempDir(), "checkout", "linked-skill") + if err := os.MkdirAll(target, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(target, "SKILL.md"), []byte("---\nname: linked-skill\n---\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Dir(target), f.path(rel)); err != nil { + t.Fatal(err) + } + f.opts.Follow = sourcewalk.NewFollow(f.source, nil) +} + +func (f *fixture) discover(t *testing.T) []sync.DiscoveredSkill { + t.Helper() + skills, err := sync.DiscoverSourceSkillsAll(f.source, sourcewalk.Options{Follow: f.opts.Follow}) + if err != nil { + t.Fatal(err) + } + return skills +} + +func (f *fixture) plan(t *testing.T, dest string, names ...string) []Planned { + t.Helper() + return Plan(f.discover(t), names, dest, f.opts) +} + +func (f *fixture) exists(rel string) bool { + _, err := os.Lstat(f.path(rel)) + return err == nil +} + +func wantRefusal(t *testing.T, p Planned, code Code) { + t.Helper() + if p.Err == nil || p.Err.Code != code { + t.Fatalf("%s: err = %v, want code %s", p.Name, p.Err, code) + } +} + +func wantMoved(t *testing.T, p Planned) { + t.Helper() + if p.Err != nil { + t.Fatalf("%s: unexpected refusal %s: %v", p.Name, p.Err.Code, p.Err) + } +} + +func TestRun_SkillWithRecordKeepsRecordAndAcceptances(t *testing.T) { + f := newFixture(t) + f.skill(t, "demo") + f.record("demo") + f.store.AuditAccepted = map[string][]string{"demo": {"accepted-key"}} + + planned := f.plan(t, "grp", "demo") + wantMoved(t, planned[0]) + out := Run(planned, f.opts) + + if out.Err != nil { + t.Fatal(out.Err) + } + wantMoved(t, out.Items[0]) + if f.exists("demo") || !f.exists("grp/demo/SKILL.md") { + t.Fatal("the skill did not move on disk") + } + got := f.store.Get("grp/demo") + if got == nil || got.Source != "github.com/user/repo/demo" || got.Group != "grp" { + t.Errorf("record at the new path = %+v, want the old record with group grp", got) + } + if f.store.Has("demo") { + t.Error("record stayed at the old key") + } + if got := f.store.AuditAccepted["grp/demo"]; !reflect.DeepEqual(got, []string{"accepted-key"}) { + t.Errorf("accepted findings = %v, want them carried", got) + } + saved, err := install.LoadMetadata(f.source) + if err != nil || !saved.Has("grp/demo") || saved.Has("demo") { + t.Errorf("saved store keys = %v (err %v), want only grp/demo", saved.List(), err) + } +} + +func TestRun_SkillWithoutRecordMoves(t *testing.T) { + f := newFixture(t) + f.skill(t, "mine") + + out := Run(f.plan(t, "grp", "mine"), f.opts) + + wantMoved(t, out.Items[0]) + if out.Items[0].Records != 0 || !f.exists("grp/mine/SKILL.md") { + t.Errorf("records = %d, moved = %v; want a record-less skill moved", out.Items[0].Records, f.exists("grp/mine")) + } +} + +func TestRun_RecordWithoutHashesOrWithStaleHashesFollows(t *testing.T) { + f := newFixture(t) + f.skill(t, "edited") + f.skill(t, "bare") + f.store.Set("edited", &install.MetadataEntry{Source: "s/edited", FileHashes: map[string]string{"SKILL.md": "not-the-current-hash"}}) + f.store.Set("bare", &install.MetadataEntry{Source: "s/bare"}) + + out := Run(f.plan(t, "grp", "edited", "bare"), f.opts) + + if out.Err != nil { + t.Fatal(out.Err) + } + for _, key := range []string{"grp/edited", "grp/bare"} { + if !f.store.Has(key) { + t.Errorf("record %q did not follow the move; keys = %v", key, f.store.List()) + } + } +} + +func TestRun_LegacyBasenameKeyIsRekeyedWithGroup(t *testing.T) { + f := newFixture(t) + f.skill(t, "frontend/demo") + f.store.Set("demo", &install.MetadataEntry{Source: "s/demo", Group: "frontend"}) + f.store.AuditAccepted = map[string][]string{"frontend/demo": {"k"}} + + out := Run(f.plan(t, "archive", "frontend/demo"), f.opts) + + wantMoved(t, out.Items[0]) + got := f.store.Get("archive/demo") + if got == nil || got.Group != "archive" || f.store.Has("demo") { + t.Fatalf("keys = %v, entry = %+v; want the legacy key replaced by archive/demo", f.store.List(), got) + } + if len(f.store.AuditAccepted["archive/demo"]) != 1 { + t.Errorf("accepted findings = %v", f.store.AuditAccepted) + } +} + +func TestRun_NestedSkillsMoveWithTheirParent(t *testing.T) { + f := newFixture(t) + f.skill(t, "foo") + f.skill(t, "foo/sub") + f.record("foo") + f.record("foo/sub") + f.store.AuditAccepted = map[string][]string{"foo/sub": {"nested-key"}} + + planned := f.plan(t, "grp", "foo") + wantMoved(t, planned[0]) + if len(planned[0].Skills) != 2 || planned[0].Records != 2 { + t.Fatalf("skills = %d, records = %d; want the parent and its nested skill", len(planned[0].Skills), planned[0].Records) + } + out := Run(planned, f.opts) + + if out.Err != nil { + t.Fatal(out.Err) + } + for _, key := range []string{"grp/foo", "grp/foo/sub"} { + if !f.store.Has(key) { + t.Errorf("missing record %q; keys = %v", key, f.store.List()) + } + } + if len(f.store.AuditAccepted["grp/foo/sub"]) != 1 { + t.Errorf("nested accepted findings = %v", f.store.AuditAccepted) + } +} + +func TestRun_FolderMovesWholeWithEverythingInIt(t *testing.T) { + f := newFixture(t) + f.skill(t, "frontend/a") + f.skill(t, "frontend/deep/b") + f.file(t, "frontend/notes.txt", "keep me") + if err := os.MkdirAll(f.path("frontend/empty"), 0o755); err != nil { + t.Fatal(err) + } + f.record("frontend/a") + f.record("frontend/deep/b") + + planned := f.plan(t, "archive", "frontend") + wantMoved(t, planned[0]) + if !planned[0].Folder || len(planned[0].Skills) != 2 || planned[0].To != "archive/frontend" { + t.Fatalf("plan = %+v, want a folder of two skills going to archive/frontend", planned[0]) + } + out := Run(planned, f.opts) + + if out.Err != nil { + t.Fatal(out.Err) + } + for _, rel := range []string{"archive/frontend/a/SKILL.md", "archive/frontend/deep/b/SKILL.md", "archive/frontend/notes.txt", "archive/frontend/empty"} { + if !f.exists(rel) { + t.Errorf("%s did not move with the folder", rel) + } + } + if f.exists("frontend") { + t.Error("the old folder is still there") + } + for _, key := range []string{"archive/frontend/a", "archive/frontend/deep/b"} { + if got := f.store.Get(key); got == nil || got.Group != groupOf(key) { + t.Errorf("record %q = %+v, want it re-keyed with its group", key, got) + } + } +} + +func groupOf(key string) string { return filepath.ToSlash(filepath.Dir(key)) } + +func TestPlan_FolderWithTrackedRepoIsRefusedWholeBeforeAnyRename(t *testing.T) { + f := newFixture(t) + f.skill(t, "frontend/a") + f.repo(t, "frontend/vendor/_lib") // no skill of its own: discovery cannot see it + f.skill(t, "other") + f.record("frontend/a") + + out := Run(f.plan(t, "archive", "frontend", "other"), f.opts) + + wantRefusal(t, out.Items[0], CodeInsideTrackedRepo) + wantMoved(t, out.Items[1]) // a refused name does not stop the others + if !f.exists("frontend/a/SKILL.md") || f.exists("archive/frontend") { + t.Error("part of the folder moved although the folder was refused") + } + if !f.store.Has("frontend/a") { + t.Error("the refused folder's record was touched") + } + if !f.exists("archive/other") { + t.Error("the unrelated name was not moved") + } +} + +func TestPlan_Refusals(t *testing.T) { + cases := []struct { + name string + setup func(t *testing.T, f *fixture) + dest string + names []string + code Code + }{ + {"skill_not_found", func(t *testing.T, f *fixture) {}, "grp", []string{"ghost"}, CodeNotFound}, + {"folder without skills is not found", func(t *testing.T, f *fixture) { + if err := os.MkdirAll(f.path("empty-folder"), 0o755); err != nil { + t.Fatal(err) + } + }, "grp", []string{"empty-folder"}, CodeNotFound}, + {"parent traversal", func(t *testing.T, f *fixture) { f.skill(t, "demo") }, "grp", []string{"../demo"}, CodeNotFound}, + {"ambiguous_name", func(t *testing.T, f *fixture) { + f.skill(t, "a/demo") + f.skill(t, "b/demo") + }, "grp", []string{"demo"}, CodeAmbiguousName}, + {"dest_exists skill", func(t *testing.T, f *fixture) { + f.skill(t, "demo") + f.skill(t, "grp/demo") + }, "grp", []string{"demo"}, CodeDestExists}, + {"dest_exists folder", func(t *testing.T, f *fixture) { + f.skill(t, "demo") + if err := os.MkdirAll(f.path("grp/demo"), 0o755); err != nil { + t.Fatal(err) + } + }, "grp", []string{"demo"}, CodeDestExists}, + {"inside_tracked_repo", func(t *testing.T, f *fixture) { + f.repo(t, "_team") + f.skill(t, "_team/foo") + }, "grp", []string{"_team__foo"}, CodeInsideTrackedRepo}, + {"tracked repo itself", func(t *testing.T, f *fixture) { + f.repo(t, "_team") + f.skill(t, "_team/foo") + }, "grp", []string{"_team"}, CodeInsideTrackedRepo}, + {"dest_inside_tracked_repo", func(t *testing.T, f *fixture) { + f.repo(t, "_team") + f.skill(t, "demo") + }, "_team/sub", []string{"demo"}, CodeDestInsideTrackedRepo}, + {"dest_is_skill", func(t *testing.T, f *fixture) { + f.skill(t, "demo") + f.skill(t, "grp") + }, "grp/inner", []string{"demo"}, CodeDestIsSkill}, + {"invalid_dest segment", func(t *testing.T, f *fixture) { f.skill(t, "demo") }, "grp/_x", []string{"demo"}, CodeInvalidDest}, + {"invalid_dest dotdot", func(t *testing.T, f *fixture) { f.skill(t, "demo") }, "../out", []string{"demo"}, CodeInvalidDest}, + {"invalid_dest empty", func(t *testing.T, f *fixture) { f.skill(t, "demo") }, "", []string{"demo"}, CodeInvalidDest}, + {"invalid_dest is a file", func(t *testing.T, f *fixture) { + f.skill(t, "demo") + f.file(t, "grp", "plain file") + }, "grp", []string{"demo"}, CodeInvalidDest}, + {"dest_inside_source_folder", func(t *testing.T, f *fixture) { + f.skill(t, "frontend/a") + }, "frontend/sub", []string{"frontend"}, CodeDestInsideSource}, + {"dest_inside_source_folder into itself", func(t *testing.T, f *fixture) { + f.skill(t, "frontend/a") + }, "frontend", []string{"frontend"}, CodeDestInsideSource}, + {"duplicate_dest", func(t *testing.T, f *fixture) { + f.skill(t, "frontend/foo") + f.skill(t, "backend/foo") + }, "archive", []string{"frontend/foo", "backend/foo"}, CodeDuplicateDest}, + {"overlapping_sources child", func(t *testing.T, f *fixture) { + f.skill(t, "foo") + f.skill(t, "foo/sub") + }, "archive", []string{"foo", "foo/sub"}, CodeOverlappingSources}, + {"overlapping_sources same name twice", func(t *testing.T, f *fixture) { + f.skill(t, "foo") + }, "archive", []string{"foo", "foo"}, CodeOverlappingSources}, + {"same_folder", func(t *testing.T, f *fixture) { f.skill(t, "grp/demo") }, "grp", []string{"demo"}, CodeSameFolder}, + {"same_folder at the root", func(t *testing.T, f *fixture) { f.skill(t, "demo") }, ".", []string{"demo"}, CodeSameFolder}, + {"ambiguous_record", func(t *testing.T, f *fixture) { + f.skill(t, "grp/demo") + f.record("grp/demo") + f.store.Set("demo", &install.MetadataEntry{Source: "s/stale", Group: "grp"}) + }, "archive", []string{"grp/demo"}, CodeAmbiguousRecord}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + f := newFixture(t) + c.setup(t, f) + + planned := f.plan(t, c.dest, c.names...) + + wantRefusal(t, planned[len(planned)-1], c.code) + out := Run(planned, f.opts) + for _, item := range out.Items { + if item.Err == nil { + t.Fatalf("Run moved %s that Plan refused", item.Name) + } + } + }) + } +} + +func TestPlan_LinkedFolderRefusals(t *testing.T) { + t.Run("skill below a followed link", func(t *testing.T) { + f := newFixture(t) + f.link(t, "_dev") + f.skill(t, "demo") + + planned := f.plan(t, "grp", "_dev/linked-skill") + + wantRefusal(t, planned[0], CodeLinkedFolder) + }) + t.Run("the link itself", func(t *testing.T) { + f := newFixture(t) + f.link(t, "_dev") + + wantRefusal(t, f.plan(t, "grp", "_dev")[0], CodeLinkedFolder) + }) + t.Run("dest below a link", func(t *testing.T) { + f := newFixture(t) + f.link(t, "dev") + f.skill(t, "demo") + + wantRefusal(t, f.plan(t, "dev/inner", "demo")[0], CodeLinkedFolder) + }) + t.Run("link at the root of a moved folder", func(t *testing.T) { + f := newFixture(t) + f.link(t, "dev") + f.skill(t, "demo") + + planned := f.plan(t, "grp", "dev/linked-skill") + + wantRefusal(t, planned[0], CodeLinkedFolder) + }) +} + +func TestPlan_NameResolution(t *testing.T) { + f := newFixture(t) + f.skill(t, "frontend/react") + f.skill(t, "tools/frontend") // a skill whose base name equals a folder's path + f.skill(t, "solo") + + cases := map[string]string{ + "frontend/react": "frontend/react", // path + "frontend__react": "frontend/react", // flat name + "react": "frontend/react", // unique base name + "frontend/": "frontend", // trailing slash; exact folder wins over a base name + "solo": "solo", + } + for name, want := range cases { + planned := f.plan(t, "archive", name) + wantMoved(t, planned[0]) + if planned[0].From != want { + t.Errorf("%q resolved to %q, want %q", name, planned[0].From, want) + } + } +} + +func TestPlan_FlatNameCollisionIsForceable(t *testing.T) { + f := newFixture(t) + f.skill(t, "grp__demo") // a top-level skill already holds the flat name + f.skill(t, "demo") + f.opts.Targets = []Target{{Name: "claude", Config: config.ResourceTargetConfig{TargetNaming: "flat"}}} + + planned := f.plan(t, "grp", "demo") + wantRefusal(t, planned[0], CodeNameCollision) + + f.opts.Force = true + planned = f.plan(t, "grp", "demo") + wantMoved(t, planned[0]) + if len(planned[0].Warnings) == 0 { + t.Error("an accepted collision left no warning") + } +} + +// TestPlan_StandardNamingCollisionExistedBeforeTheMove: standard naming names +// an entry by the skill's own name, which a move never changes, so a collision +// there was there before and does not block the move. +func TestPlan_StandardNamingCollisionExistedBeforeTheMove(t *testing.T) { + f := newFixture(t) + f.skill(t, "a/demo") + f.skill(t, "b/demo") + f.opts.Targets = []Target{{Name: "claude", Config: config.ResourceTargetConfig{TargetNaming: "standard"}}} + + planned := f.plan(t, "c", "a/demo") + + wantMoved(t, planned[0]) +} + +func TestPlan_FilterWarningsInBothDirections(t *testing.T) { + f := newFixture(t) + f.skill(t, "demo") + f.skill(t, "other") + f.opts.Targets = []Target{ + {Name: "named", Config: config.ResourceTargetConfig{Include: []string{"demo"}}}, // synced before, not after + {Name: "dropped", Config: config.ResourceTargetConfig{Exclude: []string{"grp__*"}}}, // synced before, excluded after + {Name: "added", Config: config.ResourceTargetConfig{Include: []string{"grp__*"}}}, // not synced before, synced after + {Name: "same", Config: config.ResourceTargetConfig{}}, + } + + planned := f.plan(t, "grp", "demo") + + wantMoved(t, planned[0]) + joined := strings.Join(planned[0].Warnings, "\n") + for _, target := range []string{"target named", "target dropped", "target added"} { + if !strings.Contains(joined, target) { + t.Errorf("no warning for %q in:\n%s", target, joined) + } + } + if strings.Contains(joined, "target same") { + t.Errorf("a target whose filters decide the same got a warning:\n%s", joined) + } +} + +func TestPlan_SkillignoreWarningsAndLiteralRewrite(t *testing.T) { + f := newFixture(t) + f.skill(t, "demo") + f.skill(t, "globbed") + f.file(t, ".skillignore", "# keep\ndemo\n!other\n/globbed\n") + f.skill(t, "other") + + planned := f.plan(t, "grp", "demo", "globbed") + wantMoved(t, planned[0]) + wantMoved(t, planned[1]) + if len(planned[0].Warnings) != 0 { + t.Errorf("a literal rule follows the skill, yet warned: %v", planned[0].Warnings) + } + if got := strings.Join(planned[1].Warnings, "\n"); !strings.Contains(got, "grp/globbed becomes enabled") { + t.Errorf("warnings = %q, want the glob that no longer matches", got) + } + Run(planned, f.opts) + + data, err := os.ReadFile(f.path(".skillignore")) + if err != nil { + t.Fatal(err) + } + if want := "# keep\ngrp/demo\n!other\n/globbed\n"; string(data) != want { + t.Errorf(".skillignore = %q, want the literal rewritten in place: %q", data, want) + } +} + +func TestRun_DryRunChangesNothing(t *testing.T) { + f := newFixture(t) + f.skill(t, "demo") + f.record("demo") + f.opts.DryRun = true + + out := Run(f.plan(t, "grp", "demo"), f.opts) + + wantMoved(t, out.Items[0]) + if !f.exists("demo/SKILL.md") || f.exists("grp") { + t.Error("dry run moved files") + } + if !f.store.Has("demo") || f.store.Has("grp/demo") { + t.Error("dry run re-keyed the store") + } + if _, err := os.Stat(filepath.Join(f.source, install.MetadataFileName)); err == nil { + t.Error("dry run wrote .metadata.json") + } +} + +func TestRun_FailedRenameChangesNothingForThatName(t *testing.T) { + f := newFixture(t) + f.skill(t, "demo") + f.skill(t, "ok") + f.record("demo") + f.record("ok") + planned := f.plan(t, "grp", "demo", "ok") + // A file where the destination folder should go: the plan was made before. + f.file(t, "grp", "in the way") + + out := Run(planned, f.opts) + + wantRefusal(t, out.Items[0], CodeMoveFailed) + wantRefusal(t, out.Items[1], CodeMoveFailed) + if !f.exists("demo/SKILL.md") || !f.store.Has("demo") || f.store.Has("grp/demo") { + t.Error("a failed move left the skill or its record half-moved") + } +} + +func TestRun_ReconcileRunsAfterRecordsAreSaved(t *testing.T) { + f := newFixture(t) + f.skill(t, "demo") + f.record("demo") + calls := 0 + f.opts.Reconcile = func() error { + calls++ + saved, err := install.LoadMetadata(f.source) + if err != nil || !saved.Has("grp/demo") { + t.Errorf("reconcile saw keys %v (err %v), want the re-keyed store already on disk", saved.List(), err) + } + return errors.New("reconcile failed") + } + + out := Run(f.plan(t, "grp", "demo"), f.opts) + + if calls != 1 { + t.Errorf("reconcile ran %d times, want once", calls) + } + wantMoved(t, out.Items[0]) + if out.Err == nil || !strings.Contains(out.Err.Error(), "reconcile") { + t.Errorf("Err = %v, want the reconcile failure reported without undoing the move", out.Err) + } +} + +func TestRun_ProjectModeCarriesPinGroupAndGitignore(t *testing.T) { + root := t.TempDir() + source := filepath.Join(root, ".skillshare", "skills") + skill := filepath.Join(source, "demo") + if err := os.MkdirAll(skill, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(skill, "SKILL.md"), []byte("---\nname: demo\n---\n"), 0o644); err != nil { + t.Fatal(err) + } + dir := projectdir.Resolve(root) + const pinned = "0123456789abcdef0123456789abcdef01234567" + lock := &install.Lock{Skills: map[string]install.LockEntry{"demo": {Source: "github.com/user/repo/demo", Commit: pinned}}} + if err := lock.Save(dir); err != nil { + t.Fatal(err) + } + gitignore := filepath.Join(dir, ".gitignore") + if err := os.WriteFile(gitignore, []byte("# BEGIN SKILLSHARE MANAGED - DO NOT EDIT\nskills/demo/\n# END SKILLSHARE MANAGED\n"), 0o644); err != nil { + t.Fatal(err) + } + cfg := &config.ProjectConfig{ + Targets: []config.ProjectTargetEntry{{Name: "claude"}}, + Skills: []config.SkillEntry{{Name: "demo", Source: "github.com/user/repo/demo"}}, + } + store := install.NewMetadataStore() + store.Set("demo", &install.MetadataEntry{Source: "github.com/user/repo/demo", Commit: strings.Repeat("b", 40)}) + gitDir, prefix := config.ProjectGitignoreTarget(root, source) + o := Options{ + SourceDir: source, Store: store, ProjectRoot: root, + GitignoreDir: gitDir, GitignorePrefix: prefix, + Reconcile: func() error { return config.ReconcileProjectSkills(root, cfg, store, source) }, + } + discovered, err := sync.DiscoverSourceSkillsAll(source) + if err != nil { + t.Fatal(err) + } + + out := Run(Plan(discovered, []string{"demo"}, "grp", o), o) + + if out.Err != nil { + t.Fatal(out.Err) + } + if len(cfg.Skills) != 1 || cfg.Skills[0].Group != "grp" { + t.Errorf("config skills = %+v, want one entry in group grp", cfg.Skills) + } + got, err := install.LoadLock(dir) + if err != nil { + t.Fatal(err) + } + if got.Skills["grp/demo"].Commit != pinned || len(got.Skills) != 1 { + t.Errorf("lock = %+v, want the older pin carried to grp/demo", got.Skills) + } + data, _ := os.ReadFile(gitignore) + if strings.Contains(string(data), "skills/demo/") || !strings.Contains(string(data), "skills/grp/demo/") { + t.Errorf(".gitignore = %q, want the entry swapped", data) + } +} + +// TestRun_NestedRecordsSurviveReconcileUnderMovedParent is the end-to-end +// scenario of the reconcile change: after the move reconcile walks, stops at +// the installed parent and must not prune the nested record with its findings. +func TestRun_NestedRecordsSurviveReconcileUnderMovedParent(t *testing.T) { + f := newFixture(t) + f.skill(t, "foo") + f.skill(t, "foo/sub") + f.record("foo") + f.record("foo/sub") + f.store.AuditAccepted = map[string][]string{"foo/sub": {"nested-key"}} + t.Setenv("SKILLSHARE_CONFIG", filepath.Join(t.TempDir(), "config.yaml")) + f.opts.Reconcile = func() error { + return config.ReconcileGlobalSkills(&config.Config{Source: f.source}, f.store) + } + + out := Run(f.plan(t, "grp", "foo"), f.opts) + + if out.Err != nil { + t.Fatal(out.Err) + } + if !f.store.Has("grp/foo/sub") || len(f.store.AuditAccepted["grp/foo/sub"]) != 1 { + t.Errorf("keys = %v, accepted = %v; want the nested record and its findings kept", f.store.List(), f.store.AuditAccepted) + } +} + +// Force only accepts a name collision: it never turns a refused destination or +// batch conflict into a move. +func TestPlan_ForceDoesNotAcceptOtherRefusals(t *testing.T) { + f := newFixture(t) + f.skill(t, "frontend/foo") + f.skill(t, "backend/foo") + f.skill(t, "taken") + f.skill(t, "archive/taken") + f.opts.Force = true + + dup := f.plan(t, "archive", "frontend/foo", "backend/foo") + wantRefusal(t, dup[0], CodeDuplicateDest) + wantRefusal(t, dup[1], CodeDuplicateDest) + + wantRefusal(t, f.plan(t, "archive", "taken")[0], CodeDestExists) +} + +// An install --into folder below a source link is the install's business: it +// writes through a followed link, or sourcefs refuses it. A skill folder is +// refused either way. +func TestCheckDest_InstallLeavesLinksToTheInstall(t *testing.T) { + f := newFixture(t) + f.link(t, "dev") + f.skill(t, "holder") + + if _, r := CheckDest("dev/inner", f.opts); r == nil || r.Code != CodeLinkedFolder { + t.Fatalf("move: refusal = %v, want linked_folder", r) + } + f.opts.Install = true + if _, r := CheckDest("dev/inner", f.opts); r != nil { + t.Errorf("install: refusal = %v, want none", r) + } + if _, r := CheckDest("holder/inner", f.opts); r == nil || r.Code != CodeDestIsSkill { + t.Errorf("install into a skill: refusal = %v, want dest_is_skill", r) + } +} + +// An absolute destination or name is refused, not read as a path in the source. +func TestPlan_AbsolutePathsAreNotRelativeToTheSource(t *testing.T) { + f := newFixture(t) + f.skill(t, "demo") + f.skill(t, "tmp/x") + + wantRefusal(t, f.plan(t, "/etc/ssh", "demo")[0], CodeInvalidDest) + wantRefusal(t, f.plan(t, "grp", "/tmp/x")[0], CodeNotFound) +} + +// A literal line follows its skill and its folder, and so does a negation that +// keeps one skill of a disabled folder on. +func TestRun_SkillignoreFollowsNegationAndFolder(t *testing.T) { + f := newFixture(t) + f.skill(t, "legacy/tools/a") + f.skill(t, "grp/demo") + f.file(t, ".skillignore", "legacy/tools\ngrp/*\n!grp/demo\n") + + planned := f.plan(t, "archive", "legacy/tools", "grp/demo") + wantMoved(t, planned[0]) + wantMoved(t, planned[1]) + out := Run(planned, f.opts) + + if out.Err != nil { + t.Fatal(out.Err) + } + data, _ := os.ReadFile(f.path(".skillignore")) + if want := "archive/tools\ngrp/*\n!archive/demo\n"; string(data) != want { + t.Errorf(".skillignore = %q, want %q", data, want) + } +} + +// A record below an installed skill that has no SKILL.md of its own is no +// discovered skill, yet its lock pin must follow the move. +func TestRun_PinOfRecordWithoutSkillFollows(t *testing.T) { + root := t.TempDir() + source := filepath.Join(root, ".skillshare", "skills") + for _, rel := range []string{"foo", "foo/data"} { + if err := os.MkdirAll(filepath.Join(source, rel), 0o755); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(source, "foo", "SKILL.md"), []byte("---\nname: foo\n---\n"), 0o644); err != nil { + t.Fatal(err) + } + store := install.NewMetadataStore() + store.Set("foo", &install.MetadataEntry{Source: "s/foo"}) + store.Set("foo/data", &install.MetadataEntry{Source: "s/data", Group: "foo"}) + dir := projectdir.Resolve(root) + const pinned = "0123456789abcdef0123456789abcdef01234567" + lock := &install.Lock{Skills: map[string]install.LockEntry{"foo/data": {Source: "s/data", Commit: pinned}}} + if err := lock.Save(dir); err != nil { + t.Fatal(err) + } + o := Options{SourceDir: source, Store: store, ProjectRoot: root} + discovered, err := sync.DiscoverSourceSkillsAll(source) + if err != nil { + t.Fatal(err) + } + + out := Run(Plan(discovered, []string{"foo"}, "grp", o), o) + + if out.Err != nil { + t.Fatal(out.Err) + } + got, _ := install.LoadLock(dir) + if got.Skills["grp/foo/data"].Commit != pinned || len(got.Skills) != 1 { + t.Errorf("lock = %+v, want the pin under grp/foo/data", got.Skills) + } +} + +// A move that adds a skill to a collision that already exists makes it worse: +// sync skips every member, so the move needs --force like a new collision. +func TestPlan_MoveJoiningAnExistingCollisionIsRefused(t *testing.T) { + f := newFixture(t) + f.skill(t, "a/b__c") // flat name a__b__c + f.skill(t, "a__b/c") // flat name a__b__c + f.skill(t, "x/a__b__c") // flat name x__a__b__c, becomes a__b__c at the root + f.skill(t, "x/other") + f.opts.Targets = []Target{{Name: "claude", Config: config.ResourceTargetConfig{TargetNaming: "flat"}}} + + wantRefusal(t, f.plan(t, ".", "x/a__b__c")[0], CodeNameCollision) + // Moving a member of the collision elsewhere does not add to it. + wantMoved(t, f.plan(t, "elsewhere", "a/b__c")[0]) + // An unrelated skill never joins it. + wantMoved(t, f.plan(t, "elsewhere", "x/other")[0]) +} diff --git a/internal/uninstall/uninstall.go b/internal/uninstall/uninstall.go index 71f5e5fd4..6fdeef7cd 100644 --- a/internal/uninstall/uninstall.go +++ b/internal/uninstall/uninstall.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "path/filepath" - "strings" gosync "sync" "skillshare/internal/git" @@ -15,7 +14,6 @@ import ( "skillshare/internal/sourcefs" "skillshare/internal/sourcewalk" "skillshare/internal/trash" - "skillshare/internal/utils" ) // Item is one resolved skill, group directory or tracked repo. @@ -149,13 +147,8 @@ func checkMoveOut(item Item, o Options) error { // A tracked repo is a _-prefixed git checkout; removing part of it would // leave it dirty for update. A followed source link is the user's own // checkout, whose skills may go one at a time. - dir := o.SourceDir - parents := strings.Split(filepath.ToSlash(rel), "/") - for _, seg := range parents[:len(parents)-1] { - dir = filepath.Join(dir, seg) - if _, followed := o.Follow.Resolve(dir); utils.IsTrackedRepoDir(seg) && !followed && install.IsGitRepo(dir) { - return ErrInsideRepo - } + if _, inside := install.TrackedAncestor(o.SourceDir, filepath.ToSlash(rel), o.Follow); inside { + return ErrInsideRepo } return nil } diff --git a/skills/skillshare/SKILL.md b/skills/skillshare/SKILL.md index fae62bf17..cdc46d88e 100644 --- a/skills/skillshare/SKILL.md +++ b/skills/skillshare/SKILL.md @@ -111,6 +111,18 @@ skillshare sync Run the requested operation, not this entire example sequence. Quote glob patterns so Skillshare receives them unchanged. Disabling uses ignore rules; uninstall uses trash. +### Move skills into folders + +```bash +skillshare move my-skill frontend --dry-run +skillshare move my-skill other-skill frontend +skillshare sync +``` + +Use `move` instead of `mv` for installed skills: it keeps their install records, so +nothing is downloaded again. It does not sync; run `sync` afterwards. Read +[install.md](references/install.md) for refusals and project mode. + ### MCP settings ```bash @@ -166,7 +178,7 @@ references for a single task. | Complete plugins, native lifecycle, and sync selection | [plugins.md](references/plugins.md) | | Init flags | [init.md](references/init.md) | | Sync/collect/commit/push/pull | [sync.md](references/sync.md) | -| Install/update/uninstall/new | [install.md](references/install.md) | +| Install/update/uninstall/move/new | [install.md](references/install.md) | | Status/diff/list/search/check | [status.md](references/status.md) | | Security audit | [audit.md](references/audit.md) | | Trash | [trash.md](references/trash.md) | diff --git a/skills/skillshare/references/install.md b/skills/skillshare/references/install.md index 633404d47..becaab667 100644 --- a/skills/skillshare/references/install.md +++ b/skills/skillshare/references/install.md @@ -1,4 +1,4 @@ -# Install, Update, Uninstall & New +# Install, Update, Uninstall, Move & New Use `-p` for project resources or `-g` for global resources. For native agent workflows, see [native-agents.md](native-agents.md). These examples use skills unless specified otherwise. @@ -208,6 +208,43 @@ skillshare uninstall my-skill --json **After uninstall:** `skillshare sync` +## move + +Move installed skills, or whole folders, to another folder of the source, keeping install +records, audit acceptances and (project mode) the lock pin and config group. Nothing is +downloaded again. Use it instead of `mv` for installed skills. + +```bash +skillshare move react-best-practices frontend # Skill -> frontend/react-best-practices +skillshare move pdf docx office # Several skills into office/ +skillshare move frontend archive # Folder -> archive/frontend/ +skillshare move archive/old-skill . # Back to the source root +skillshare move my-skill frontend --dry-run # Preview +skillshare move my-skill frontend -p --json # Project mode, JSON output +``` + +The last argument is the destination folder relative to the skills source; `.` is the source +root. A name resolves as exact skill path, exact folder path, flat name (`grp__demo`), then +unique skill base name. A skill with nested skills moves with them. + +| Flag | Description | +|------|-------------| +| `--dry-run, -n` | Preview, change nothing | +| `--force, -f` | Accept a target-name collision only; never overwrites or moves tracked or linked content | +| `--json` | JSON output: `moved`, `failed` (with `code`), `skipped`, `warnings`, `dry_run`, `duration` | +| `--project, -p` / `--global, -g` | Select mode | + +Agents are not supported (no `--kind`). Refusals use stable codes in `failed[].code`: +`skill_not_found`, `ambiguous_name`, `dest_exists` (never overwritten), `inside_tracked_repo`, +`dest_inside_tracked_repo`, `linked_folder`, `dest_is_skill`, `invalid_dest`, +`dest_inside_source_folder`, `duplicate_dest`, `overlapping_sources`, `same_folder` (no-op), +`name_collision`, `ambiguous_record`. A folder holding a tracked repo is refused as a whole before anything is renamed. +The exit code is non-zero when `failed` is not empty. + +**After move:** `skillshare sync`. Move does not sync, so old target links dangle until then. +Target `include`/`exclude` filters match flat names and are not rewritten; `move` warns when a +filter result changes. + ## new Create a new skill template. diff --git a/tests/integration/completion_test.go b/tests/integration/completion_test.go index f14125467..4773d5d56 100644 --- a/tests/integration/completion_test.go +++ b/tests/integration/completion_test.go @@ -389,3 +389,22 @@ func TestCompletion_LinkUnlink_AllShells(t *testing.T) { } } } + +func TestCompletion_Move_AllShells(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + for shell, want := range map[string][]string{ + "bash": {"unlink move list", `move_flags="--dry-run -n --force -f --json`}, + "zsh": {"'move:", "'--force[Accept a target name collision]'"}, + "fish": {"-a move ", "using_command move' -l force"}, + "powershell": {"Name = 'move'", "'move' = '--dry-run', '-n', '--force', '-f', '--json'"}, + "nushell": {`export extern "skillshare move"`, "--force(-f)"}, + } { + result := sb.RunCLI("completion", shell) + result.AssertSuccess(t) + for _, s := range want { + result.AssertOutputContains(t, s) + } + } +} diff --git a/tests/integration/move_test.go b/tests/integration/move_test.go new file mode 100644 index 000000000..59c9e995c --- /dev/null +++ b/tests/integration/move_test.go @@ -0,0 +1,309 @@ +//go:build !online + +package integration + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "skillshare/internal/install" + "skillshare/internal/testutil" +) + +type moveJSON struct { + Moved []struct { + Name string `json:"name"` + From string `json:"from"` + To string `json:"to"` + Record bool `json:"record"` + Skills int `json:"skills"` + } `json:"moved"` + Failed []struct { + Name string `json:"name"` + Code string `json:"code"` + } `json:"failed"` + Skipped int `json:"skipped"` + Warnings []string `json:"warnings"` + DryRun bool `json:"dry_run"` +} + +func parseMoveJSON(t *testing.T, r *testutil.Result) moveJSON { + t.Helper() + var out moveJSON + if err := json.Unmarshal([]byte(r.Stdout), &out); err != nil { + t.Fatalf("stdout is not the move JSON: %v\n%s", err, r.Stdout) + } + return out +} + +// movedSandbox holds an installed skill "demo" (with a record and an accepted +// finding) next to a plain local skill, and one target. +func movedSandbox(t *testing.T) (*testutil.Sandbox, string) { + t.Helper() + sb := testutil.NewSandbox(t) + target := sb.CreateTarget("claude") + sb.WriteConfig("source: " + sb.SourcePath + "\ntargets:\n claude:\n path: " + target + "\n") + sb.CreateSkill("demo", map[string]string{"SKILL.md": "---\nname: demo\n---\n# Demo"}) + sb.CreateSkill("mine", map[string]string{"SKILL.md": "---\nname: mine\n---\n# Mine"}) + store := install.NewMetadataStore() + store.Set("demo", &install.MetadataEntry{Source: "github.com/user/repo/demo"}) + store.AuditAccepted = map[string][]string{"demo": {"accepted-key"}} + if err := store.Save(sb.SourcePath); err != nil { + t.Fatal(err) + } + return sb, target +} + +func TestMove_MovesSkillKeepsRecordAndSuggestsSync(t *testing.T) { + sb, target := movedSandbox(t) + defer sb.Cleanup() + + result := sb.RunCLI("move", "demo", "grp") + + result.AssertSuccess(t) + result.AssertRowContains(t, "demo", "→ grp/demo") + result.AssertAnyOutputContains(t, "skillshare sync") + if !sb.FileExists(filepath.Join(sb.SourcePath, "grp", "demo", "SKILL.md")) || sb.FileExists(filepath.Join(sb.SourcePath, "demo")) { + t.Fatal("skill did not move on disk") + } + store, err := install.LoadMetadata(sb.SourcePath) + if err != nil { + t.Fatal(err) + } + if got := store.Get("grp/demo"); got == nil || got.Source != "github.com/user/repo/demo" || got.Group != "grp" || store.Has("demo") { + t.Errorf("store keys = %v, want the record under grp/demo", store.List()) + } + if len(store.AuditAccepted["grp/demo"]) != 1 { + t.Errorf("accepted findings = %v, want them carried", store.AuditAccepted) + } + + // move never syncs; after sync the target holds the new flat name only. + sb.RunCLI("sync").AssertSuccess(t) + if !sb.FileExists(filepath.Join(target, "grp__demo")) || sb.FileExists(filepath.Join(target, "demo")) { + t.Errorf("target entries = %v, want grp__demo and no demo", sb.ListDir(target)) + } +} + +func TestMove_DryRunChangesNothing(t *testing.T) { + sb, _ := movedSandbox(t) + defer sb.Cleanup() + + result := sb.RunCLI("move", "demo", "grp", "--dry-run") + + result.AssertSuccess(t) + result.AssertOutputContains(t, "would move to grp/demo") + result.AssertAnyOutputContains(t, "Dry run") + if !sb.FileExists(filepath.Join(sb.SourcePath, "demo", "SKILL.md")) || sb.FileExists(filepath.Join(sb.SourcePath, "grp")) { + t.Error("dry run changed the source") + } + if store, _ := install.LoadMetadata(sb.SourcePath); !store.Has("demo") { + t.Error("dry run re-keyed the store") + } +} + +func TestMove_JSON(t *testing.T) { + sb, _ := movedSandbox(t) + defer sb.Cleanup() + sb.CreateNestedSkill("frontend/a", map[string]string{"SKILL.md": "---\nname: a\n---\n"}) + sb.CreateNestedSkill("frontend/b", map[string]string{"SKILL.md": "---\nname: b\n---\n"}) + + result := sb.RunCLI("move", "demo", "frontend", "ghost", "archive", "--json") + + result.AssertFailure(t) // one name failed + out := parseMoveJSON(t, result) + if len(out.Moved) != 2 || out.Moved[0].To != "archive/demo" || !out.Moved[0].Record || out.Moved[0].Skills != 1 { + t.Errorf("moved = %+v, want demo with its record", out.Moved) + } + if out.Moved[1].To != "archive/frontend" || out.Moved[1].Skills != 2 || out.Moved[1].Record { + t.Errorf("moved folder = %+v, want 2 skills and no record", out.Moved[1]) + } + if len(out.Failed) != 1 || out.Failed[0].Name != "ghost" || out.Failed[0].Code != "skill_not_found" { + t.Errorf("failed = %+v, want ghost: skill_not_found", out.Failed) + } +} + +func TestMove_RefusesWithoutChangingAnything(t *testing.T) { + sb, _ := movedSandbox(t) + defer sb.Cleanup() + sb.CreateNestedSkill("grp/demo", map[string]string{"SKILL.md": "---\nname: demo\n---\n"}) + + result := sb.RunCLI("move", "demo", "grp", "--json") + + result.AssertFailure(t) + out := parseMoveJSON(t, result) + if len(out.Moved) != 0 || len(out.Failed) != 1 || out.Failed[0].Code != "dest_exists" { + t.Fatalf("output = %+v, want one dest_exists failure", out) + } + if !sb.FileExists(filepath.Join(sb.SourcePath, "demo", "SKILL.md")) { + t.Error("a refused move touched the skill") + } +} + +func TestMove_FolderWithTrackedRepoIsRefusedWhole(t *testing.T) { + sb, _ := movedSandbox(t) + defer sb.Cleanup() + sb.CreateNestedSkill("frontend/a", map[string]string{"SKILL.md": "---\nname: a\n---\n"}) + if err := os.MkdirAll(filepath.Join(sb.SourcePath, "frontend", "_vendor", ".git"), 0o755); err != nil { + t.Fatal(err) + } + + result := sb.RunCLI("move", "frontend", "archive", "--json") + + result.AssertFailure(t) + out := parseMoveJSON(t, result) + if len(out.Failed) != 1 || out.Failed[0].Code != "inside_tracked_repo" { + t.Fatalf("failed = %+v, want inside_tracked_repo", out.Failed) + } + if !sb.FileExists(filepath.Join(sb.SourcePath, "frontend", "a", "SKILL.md")) || sb.FileExists(filepath.Join(sb.SourcePath, "archive")) { + t.Error("part of the refused folder moved") + } +} + +func TestMove_RequiresNameAndDestination(t *testing.T) { + sb, _ := movedSandbox(t) + defer sb.Cleanup() + + result := sb.RunCLI("move", "demo") + + result.AssertFailure(t) + result.AssertAnyOutputContains(t, "skillshare move ... ") +} + +func TestMoveProject_CarriesPinGroupAndGitignore(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + root := sb.SetupProjectDir("claude") + const pinned = "0123456789abcdef0123456789abcdef01234567" + sb.WriteProjectConfig(root, "targets:\n - claude\nskills:\n - name: demo\n source: github.com/user/repo/demo\n") + sb.CreateProjectSkill(root, "demo", map[string]string{"SKILL.md": "---\nname: demo\n---\n# Demo"}) + skills := filepath.Join(root, ".skillshare", "skills") + store := install.NewMetadataStore() + store.Set("demo", &install.MetadataEntry{Source: "github.com/user/repo/demo", Commit: strings.Repeat("b", 40)}) + if err := store.Save(skills); err != nil { + t.Fatal(err) + } + sb.WriteFile(filepath.Join(root, ".skillshare", "skills.lock.json"), + `{"version":1,"skills":{"demo":{"source":"github.com/user/repo/demo","commit":"`+pinned+`"}}}`) + sb.WriteFile(filepath.Join(root, ".skillshare", ".gitignore"), + "# BEGIN SKILLSHARE MANAGED - DO NOT EDIT\nskills/demo/\n# END SKILLSHARE MANAGED\n") + + result := sb.RunCLIInDir(root, "move", "demo", "grp", "-p", "--json") + + result.AssertSuccess(t) + out := parseMoveJSON(t, result) + if len(out.Moved) != 1 || out.Moved[0].To != "grp/demo" || !out.Moved[0].Record { + t.Fatalf("moved = %+v", out.Moved) + } + lock := sb.ReadFile(filepath.Join(root, ".skillshare", "skills.lock.json")) + if !strings.Contains(lock, `"grp/demo"`) || !strings.Contains(lock, pinned) || strings.Contains(lock, `"demo": {`) { + t.Errorf("skills.lock.json = %s, want the older pin under grp/demo only", lock) + } + cfg := sb.ReadFile(filepath.Join(root, ".skillshare", "config.yaml")) + if !strings.Contains(cfg, "group: grp") { + t.Errorf("config.yaml = %s, want the skill in group grp", cfg) + } + ignore := sb.ReadFile(filepath.Join(root, ".skillshare", ".gitignore")) + if strings.Contains(ignore, "skills/demo/") || !strings.Contains(ignore, "skills/grp/demo/") { + t.Errorf(".gitignore = %s, want the entry moved", ignore) + } +} + +// install --into shares move's destination preflight: it must not put a skill +// inside another skill. +func TestInstallInto_RefusesFolderInsideSkill(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + sb.WriteConfig("source: " + sb.SourcePath + "\ntargets: {}\n") + sb.CreateSkill("holder", map[string]string{"SKILL.md": "---\nname: holder\n---\n# Holder"}) + src := filepath.Join(sb.Root, "incoming", "new-skill") + if err := os.MkdirAll(src, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(src, "SKILL.md"), []byte("---\nname: new-skill\n---\n# New"), 0o644); err != nil { + t.Fatal(err) + } + + result := sb.RunCLI("install", src, "--into", "holder/sub") + + result.AssertFailure(t) + result.AssertAnyOutputContains(t, "dest_is_skill") + if sb.FileExists(filepath.Join(sb.SourcePath, "holder", "sub")) { + t.Error("a refused install created the folder") + } +} + +// An unreadable .metadata.json stops the move before anything is renamed: +// saving an empty store over it would lose every record. +func TestMove_RefusesWhenRecordsCannotBeRead(t *testing.T) { + sb, _ := movedSandbox(t) + defer sb.Cleanup() + meta := filepath.Join(sb.SourcePath, install.MetadataFileName) + sb.WriteFile(meta, "{ not json") + + result := sb.RunCLI("move", "demo", "grp") + + result.AssertFailure(t) + result.AssertAnyOutputContains(t, "cannot read install records") + if !sb.FileExists(filepath.Join(sb.SourcePath, "demo", "SKILL.md")) { + t.Error("the skill moved although its records could not be read") + } + if got := sb.ReadFile(meta); got != "{ not json" { + t.Errorf(".metadata.json was rewritten: %q", got) + } +} + +func TestMove_AlreadyInPlaceIsNotAFailure(t *testing.T) { + sb, _ := movedSandbox(t) + defer sb.Cleanup() + sb.CreateNestedSkill("grp/stay", map[string]string{"SKILL.md": "---\nname: stay\n---\n"}) + + result := sb.RunCLI("move", "grp/stay", "grp") + + result.AssertSuccess(t) + result.AssertOutputContains(t, "Already in place") + result.AssertOutputNotContains(t, "Nothing moved") +} + +// install --track shares move's destination preflight, like a plain install. +func TestInstallTrackInto_RefusesFolderInsideSkill(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + sb.WriteConfig("source: " + sb.SourcePath + "\ntargets: {}\n") + sb.CreateSkill("holder", map[string]string{"SKILL.md": "---\nname: holder\n---\n# Holder"}) + repo := filepath.Join(sb.Root, "incoming", "team-repo") + sb.WriteFile(filepath.Join(repo, "pdf", "SKILL.md"), "---\nname: pdf\n---\n# Pdf") + for _, args := range [][]string{{"init", "-q"}, {"add", "."}, {"-c", "user.name=t", "-c", "user.email=t@e.c", "-c", "commit.gpgsign=false", "commit", "-qm", "seed"}} { + if out, err := exec.Command("git", append([]string{"-C", repo}, args...)...).CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + + result := sb.RunCLI("install", repo, "--track", "--into", "holder/sub") + + result.AssertFailure(t) + result.AssertAnyOutputContains(t, "dest_is_skill") + if sb.FileExists(filepath.Join(sb.SourcePath, "holder", "sub")) { + t.Error("a refused tracked install created the folder") + } +} + +// A batch install (--all) refused at its --into folder exits non-zero, as the +// single-skill path does, so automation can see it. +func TestInstallInto_BatchRefusalExitsNonZero(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + sb.WriteConfig("source: " + sb.SourcePath + "\ntargets: {}\n") + sb.CreateSkill("holder", map[string]string{"SKILL.md": "---\nname: holder\n---\n# Holder"}) + repo := filepath.Join(sb.Root, "incoming", "pair") + sb.WriteFile(filepath.Join(repo, "one", "SKILL.md"), "---\nname: one\n---\n# One") + sb.WriteFile(filepath.Join(repo, "two", "SKILL.md"), "---\nname: two\n---\n# Two") + + result := sb.RunCLI("install", repo, "--all", "--into", "holder/sub") + + result.AssertFailure(t) + result.AssertAnyOutputContains(t, "dest_is_skill") +} diff --git a/website/docs/getting-started/quick-reference.md b/website/docs/getting-started/quick-reference.md index 46e7c7e35..e907a7375 100644 --- a/website/docs/getting-started/quick-reference.md +++ b/website/docs/getting-started/quick-reference.md @@ -30,6 +30,7 @@ Command cheat sheet for skillshare. | `check` | Check for skill updates | | `check --json` | Check for updates (JSON output) | | `upgrade` | Upgrade CLI and built-in skill | +| `move ... ` | Move installed skills or folders into another folder, keeping install records | | `hub list` | List configured skill hubs | | `hub add ` | Add a skill hub | diff --git a/website/docs/how-to/daily-tasks/organizing-skills.md b/website/docs/how-to/daily-tasks/organizing-skills.md index 7a00d2814..bbe7d305c 100644 --- a/website/docs/how-to/daily-tasks/organizing-skills.md +++ b/website/docs/how-to/daily-tasks/organizing-skills.md @@ -290,16 +290,14 @@ skillshare sync After `sync`, targets are updated automatically — old flat symlinks are cleaned up and new flattened names are created. :::warning Skills installed with `skillshare install` -Do not move an installed skill with `mv`. Its install record in `.metadata.json` is keyed by its path, so the moved copy loses its source link and the record still points at the old location. Reinstall it into the folder instead: +Do not move an installed skill with `mv`. Its install record in `.metadata.json` is keyed by its path, so the moved copy loses its source link and the record still points at the old location. Use [`skillshare move`](/docs/reference/commands/move) instead. It moves the skill together with its install record, so nothing is downloaded again: ```bash -skillshare list -v react-best-practices # note the Source -skillshare uninstall react-best-practices -skillshare install --into frontend/react +skillshare move react-best-practices frontend/react skillshare sync ``` -Repeat any flags from the original install, such as `--track`. +`move` also takes several skills and whole folders (`skillshare move frontend archive`). Add `--dry-run` to preview. Like `mv`, it does not update your targets until you run `skillshare sync`. ::: --- diff --git a/website/docs/reference/commands/index.md b/website/docs/reference/commands/index.md index 54df25060..07d66ca0c 100644 --- a/website/docs/reference/commands/index.md +++ b/website/docs/reference/commands/index.md @@ -18,6 +18,7 @@ Complete reference for all skillshare commands. | Search for community skills | [`search`](./search.md) | | Update installed skills | [`check`](./check.md) then [`update`](./update.md) | | Temporarily hide a skill without removing it | [`enable` / `disable`](./enable.md) | +| Move installed skills into folders | [`move`](./move.md) | | Save or sync changes with git | [`commit`](./commit.md) / [`push`](./push.md) / [`pull`](./pull.md) | | Set up an MCP server once for every tool | [`mcp`](./mcp.md) | | Manage native hooks across tools | [`hooks`](./hooks.md) | @@ -36,7 +37,7 @@ Complete reference for all skillshare commands. | Category | Commands | |----------|----------| | **Core** | `init`, `install`, `uninstall`, `link`, `unlink`, `list`, `search`, `sync`, `status` | -| **Skill Management** | `new`, `check`, `update`, `upgrade`, `enable`, `disable` | +| **Skill Management** | `new`, `check`, `update`, `upgrade`, `enable`, `disable`, `move` | | **MCP Connections** | `mcp` (`add`, `edit`, `import`, `list`, `remove`, `restore`), `sync mcp` | | **Hooks** | `hooks` (`list`, `add`, `edit`, `import`, `enable`, `disable`, `remove`, `sync`, `restore`) | | **Plugin Management** | `plugin` (`list`, `discover`, `add`, `import`, `inspect`, `sync`, `check`, `update`, `enable`, `disable`, `remove`) | @@ -70,6 +71,7 @@ Complete reference for all skillshare commands. | [update](./update.md) | Update a skill or tracked repo | | [upgrade](./upgrade.md) | Upgrade CLI or built-in skill | | [enable / disable](./enable.md) | Temporarily enable or disable skills | +| [move](./move.md) | Move installed skills or folders without losing install records | ## Target Management diff --git a/website/docs/reference/commands/list.md b/website/docs/reference/commands/list.md index e5e032bfc..59766c52f 100644 --- a/website/docs/reference/commands/list.md +++ b/website/docs/reference/commands/list.md @@ -251,7 +251,7 @@ Project list uses the same visual format as global list, with `· project` label ## Directory Grouping -When skills are organized into folders (via [`--into`](/docs/reference/commands/install) during install or manual `mv` + `sync`), `list` automatically groups them by directory: +When skills are organized into folders (via [`--into`](/docs/reference/commands/install) during install or [`move`](/docs/reference/commands/move) + `sync`), `list` automatically groups them by directory: ``` frontend/ diff --git a/website/docs/reference/commands/move.md b/website/docs/reference/commands/move.md new file mode 100644 index 000000000..304a52d5c --- /dev/null +++ b/website/docs/reference/commands/move.md @@ -0,0 +1,206 @@ +--- +sidebar_position: 6 +--- + +# move + +Move installed skills, or whole folders of skills, to another folder of the source. Install records move with them, so nothing is re-downloaded. + +```bash +skillshare move react-best-practices frontend # Skill into frontend/ +skillshare move pdf docx office # Several skills into office/ +skillshare move frontend archive # Whole folder -> archive/frontend/ +skillshare move archive/old-skill . # Back to the source root +skillshare move react-best-practices frontend -n # Preview +skillshare move react-best-practices frontend -p # Project mode +``` + +## When to Use + +- Organize a flat collection into folders after you installed the skills +- Rename a group by moving its folder +- Keep the source link, audit acceptance and project lock pin of a skill that you reorganize + +For skills you created yourself with `skillshare new`, a plain `mv` + `sync` works as well. Installed skills should always go through `move`: their install record is keyed by path, and `mv` would leave it behind. See [Organizing Skills](/docs/how-to/daily-tasks/organizing-skills#migrating-from-flat-to-folders). + +## How It Works + +```mermaid +flowchart TD + TITLE["skillshare move"] + S1["1. Resolve names to skills and folders"] + S2["2. Check every source and destination"] + S3["3. Rename the folders"] + S4["4. Carry the records along"] + TITLE --> S1 --> S2 --> S3 --> S4 +``` + +Step 2 checks everything before anything is renamed. One refusal stops that skill or folder as a whole, so a folder is never left half moved. + +What moves along with a skill or folder: + +| Item | Where it lives | +|------|----------------| +| Install record | `.metadata.json` | +| Audit acceptances | `.metadata.json` | +| Literal `.skillignore` line (disabled skills) | `.skillignore` | +| Commit pin (project mode) | `.skillshare/skills.lock.json` | +| Skill group (project mode) | `.skillshare/config.yaml` | +| Ignore entry (project mode) | `.skillshare/.gitignore` | + +## Arguments + +``` +skillshare move ... [options] +``` + +- The **last** argument is the destination folder, relative to the skills source. `.` is the source root. At least two arguments are required. +- A folder keeps its base name under the destination: `move frontend archive` produces `archive/frontend/...`. A trailing `/` is accepted. +- A name is resolved in this order: exact skill path, exact folder path, flat name (`grp__demo`), then a unique skill base name. A base name that matches several skills is refused with `ambiguous_name`; use the full path. +- A skill that has nested skills below it moves together with them. A folder moves with every skill under it; empty subfolders and non-skill files move along. + +## Options + +| Flag | Description | +|------|-------------| +| `--dry-run, -n` | Preview without changing anything | +| `--force, -f` | Accept a target-name collision (`name_collision`). Never overwrites a destination, never moves tracked or linked content | +| `--json` | Output JSON | +| `--project, -p` | Use project-level config in current directory | +| `--global, -g` | Use global config (`~/.config/skillshare`) | +| `--help, -h` | Show help | + +There is no `--kind` flag: agents are not supported. + +## Examples + +```text +$ skillshare move react-best-practices pdf frontend +✓ react-best-practices → frontend/react-best-practices +✓ pdf → frontend/pdf + +✓ Moved 2 skills + +Next + skillshare sync rename the links in your targets +``` + +```text +$ skillshare move frontend archive -n + frontend would move to archive/frontend (3 skills) + +Dry run — nothing was written +``` + +## Run sync afterwards + +`move` does not sync. Until you run `skillshare sync`, the old link in each target is dangling, the same as after `uninstall`. `sync` removes the old flat name and creates the new one (`react-best-practices` becomes `frontend__react-best-practices`). + +:::tip +`move` only touches the source. Run `skillshare sync` (or `sync -p`) when you are happy with the result. +::: + +## Refusals + +Each refusal has a stable code. It appears in `--json` output (`failed[].code`) and as `error_code` in the Web API. + +| Code | Case | +|------|------| +| `skill_not_found` | The name matches no skill, and no folder with a skill below it | +| `ambiguous_name` | The base name matches several skills. Use the full path | +| `dest_exists` | `/` already exists, as a skill or a folder. Never overwritten or merged; `--force` does not change it | +| `inside_tracked_repo` | The skill is under a `_`-prefixed tracked repo checkout, which `update` pulls into. A folder that is or contains a tracked checkout, even one with no skill of its own, is refused as a whole | +| `dest_inside_tracked_repo` | The destination is inside a tracked repo | +| `linked_folder` | The skill or folder is, or sits below, a followed source link ([`follow_source_links`](../targets/configuration.md#follow_source_links)), or the destination is below one. Other symlinks inside a folder are ordinary entries and move with it | +| `dest_is_skill` | The destination, or one of its ancestors, is itself a skill | +| `invalid_dest` | Not a valid folder path: use letters, numbers, `_` and `-`, and no segment starting with `_` | +| `dest_inside_source_folder` | A folder is moved into itself or one of its descendants | +| `duplicate_dest` | Two names in one command resolve to the same destination. `--force` does not change it | +| `overlapping_sources` | One name equals or is below another, such as `move foo foo/sub archive` | +| `same_folder` | Already in that folder. A no-op, exit code 0 | +| `name_collision` | The new flat or target name equals another skill's name in a sync target. `--force` accepts it; sync skips both entries until one is renamed | +| `ambiguous_record` | Two install records in `.metadata.json` claim the same path below the moved name (a legacy basename key and a full-path key), so moving would drop one with its audit acceptances. Remove the stale one from `.metadata.json` by hand, then retry | + +## Target filters + +Target `include` and `exclude` filters are not rewritten. They match flat names (`grp__demo`), not the old `demo`. `move` prints a warning when a target's filter result differs between the old and the new flat name, in either direction. Edit `config.yaml` yourself if a filter should follow the skill. See [Filtering Skills](/docs/how-to/daily-tasks/filtering-skills). + +## JSON Output + +```bash +skillshare move demo grp --json +``` + +```json +{ + "moved": [ + {"name": "demo", "from": "demo", "to": "grp/demo", "record": true, "skills": 1} + ], + "failed": [ + {"name": "x", "code": "dest_exists", "error": "..."} + ], + "skipped": 0, + "warnings": [], + "dry_run": false, + "duration": "1.2s" +} +``` + +| Field | Meaning | +|-------|---------| +| `moved[].record` | Whether an install record moved along | +| `moved[].skills` | `1` for a skill, or the number of skills below a folder | +| `failed[].code` | One of the refusal codes above | + +The exit code is non-zero when `failed` is not empty. `--json` works in global and project mode. + +## Project Mode + +```bash +skillshare move react-best-practices frontend -p +skillshare sync -p +``` + +In project mode `move` also updates the files that describe the skill: + +- `.skillshare/skills.lock.json`: the commit pin follows the skill to its new path +- `.skillshare/config.yaml`: the skill's `group` is rewritten to the new folder +- `.skillshare/.gitignore`: the ignore entry follows the skill + +Commit these files together, so teammates running `skillshare install -p` get the new layout. See [Project Skills](/docs/understand/project-skills#lockfile). + +## Dashboard / API + +The Web API exposes the same operation. It does not sync. + +```http +POST /api/resources/batch/move +``` + +```json +{"names": ["demo"], "dest": "grp", "force": false, "dryRun": false} +``` + +The response is `200` with one result per name, also when some names failed. A folder result carries `skills: n`. `same_folder` is reported as a successful item with `from` equal to `to` and that `error_code`, since nothing is wrong. A malformed request is `400` with `error_code` `invalid_body`, `invalid_dest` or `unsupported_kind` (a `kind` of `agent`). + +```json +{ + "results": [ + {"name": "demo", "success": true, "from": "demo", "to": "grp/demo", + "flatName": "grp__demo", "record": true}, + {"name": "x", "success": false, "error": "grp/x already exists", + "error_code": "dest_exists"} + ], + "summary": {"succeeded": 1, "failed": 1}, + "warnings": [], + "dryRun": false +} +``` + +## See Also + +- [Organizing Skills](/docs/how-to/daily-tasks/organizing-skills) — Folder layouts and migration from a flat source +- [install](./install.md) — `--into` installs straight into a folder +- [uninstall](./uninstall.md) — Remove a skill or group +- [sync](./sync.md) — Rename the links in your targets after a move +- [Project Skills](/docs/understand/project-skills) — Lockfile and project config diff --git a/website/docs/understand/declarative-manifest.md b/website/docs/understand/declarative-manifest.md index 17d9c5a16..291e0c98e 100644 --- a/website/docs/understand/declarative-manifest.md +++ b/website/docs/understand/declarative-manifest.md @@ -75,6 +75,7 @@ The manifest stays in sync with your actual skill collection: - **`skillshare install `** — adds the installed skill to the manifest automatically - **`skillshare uninstall ...`** — removes the entry from the manifest automatically +- **`skillshare move ... `** — updates the entry's `group` (project mode) or moves its `.metadata.json` record (global mode) In project mode, `config.yaml` and `skills.lock.json` are updated. In global mode, `.metadata.json` is updated. You never need to edit the manifest manually (though you can). diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md b/website/i18n/ja/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md index 3d4abd000..4d31e610b 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md @@ -290,16 +290,14 @@ skillshare sync `sync` の後、Target は自動的に更新されます — 古いフラットなシンボリックリンクはクリーンアップされ、新しいフラット化された名前が作成されます。 :::warning `skillshare install` でインストールした Skill -インストール済みの Skill は `mv` で移動しないでください。`.metadata.json` のインストール記録はパスをキーにしているため、移動したコピーはソースとのリンクを失い、記録は古い場所を指したままになります。代わりにフォルダへ再インストールしてください: +インストール済みの Skill は `mv` で移動しないでください。`.metadata.json` のインストール記録はパスをキーにしているため、移動したコピーはソースとのリンクを失い、記録は古い場所を指したままになります。代わりに [`skillshare move`](/docs/reference/commands/move) を使ってください。Skill とインストール記録を一緒に移動するため、再ダウンロードは行われません: ```bash -skillshare list -v react-best-practices # Source を確認 -skillshare uninstall react-best-practices -skillshare install --into frontend/react +skillshare move react-best-practices frontend/react skillshare sync ``` -`--track` など、元のインストール時のフラグも同じように指定してください。 +`move` は複数の Skill やフォルダ全体も受け付けます(`skillshare move frontend archive`)。`--dry-run` でプレビューできます。`mv` と同様、`skillshare sync` を実行するまで Target は更新されません。 ::: --- diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md b/website/i18n/ko/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md index d7b96d80e..c20af3440 100644 --- a/website/i18n/ko/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md +++ b/website/i18n/ko/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md @@ -290,16 +290,14 @@ skillshare sync `sync` 후에는 Target이 자동으로 업데이트됩니다 — 이전의 평면 심볼릭 링크는 정리되고 새로운 평탄화된 이름이 생성됩니다. :::warning `skillshare install`로 설치한 Skill -설치한 Skill은 `mv`로 옮기지 마세요. `.metadata.json`의 설치 기록은 경로를 키로 사용하므로, 옮긴 복사본은 소스 연결을 잃고 기록은 계속 이전 위치를 가리킵니다. 대신 폴더에 다시 설치하세요: +설치한 Skill은 `mv`로 옮기지 마세요. `.metadata.json`의 설치 기록은 경로를 키로 사용하므로, 옮긴 복사본은 소스 연결을 잃고 기록은 계속 이전 위치를 가리킵니다. 대신 [`skillshare move`](/docs/reference/commands/move)를 사용하세요. Skill과 설치 기록을 함께 옮기므로 다시 다운로드하지 않습니다: ```bash -skillshare list -v react-best-practices # Source 확인 -skillshare uninstall react-best-practices -skillshare install --into frontend/react +skillshare move react-best-practices frontend/react skillshare sync ``` -`--track` 등 처음 설치할 때 사용한 플래그도 똑같이 지정하세요. +`move`는 여러 Skill과 폴더 전체도 받을 수 있습니다(`skillshare move frontend archive`). `--dry-run`으로 미리 볼 수 있습니다. `mv`와 마찬가지로 `skillshare sync`를 실행하기 전까지 Target은 업데이트되지 않습니다. ::: --- diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md index 14c597cf4..43989d06b 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md @@ -290,16 +290,14 @@ skillshare sync 执行 `sync` 后,Target 会自动更新——旧的扁平符号链接会被清理,并创建新的扁平化名称。 :::warning 通过 `skillshare install` 安装的 Skill -不要用 `mv` 移动已安装的 Skill。`.metadata.json` 里的安装记录以路径为键,移动后的副本会失去来源链接,记录仍指向旧位置。请改为重新安装到文件夹中: +不要用 `mv` 移动已安装的 Skill。`.metadata.json` 里的安装记录以路径为键,移动后的副本会失去来源链接,记录仍指向旧位置。请改用 [`skillshare move`](/docs/reference/commands/move)。它会把 Skill 和安装记录一起移动,不会重新下载: ```bash -skillshare list -v react-best-practices # 记下 Source -skillshare uninstall react-best-practices -skillshare install --into frontend/react +skillshare move react-best-practices frontend/react skillshare sync ``` -原本安装时用过的参数(例如 `--track`)也要一并加上。 +`move` 也可以一次移动多个 Skill 或整个文件夹(`skillshare move frontend archive`)。加上 `--dry-run` 可以先预览。和 `mv` 一样,执行 `skillshare sync` 之前 Target 不会更新。 ::: --- diff --git a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md index bf71a1de2..ac1934b60 100644 --- a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md +++ b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/how-to/daily-tasks/organizing-skills.md @@ -290,16 +290,14 @@ skillshare sync 執行 `sync` 後,Targets 會自動更新 — 舊的平面 symlink 會被清除,並建立新的攤平後名稱。 :::warning 透過 `skillshare install` 安裝的 Skill -不要用 `mv` 移動已安裝的 Skill。`.metadata.json` 裡的安裝紀錄以路徑為 key,移動後的副本會失去來源連結,紀錄仍指向舊位置。請改為重新安裝到資料夾中: +不要用 `mv` 移動已安裝的 Skill。`.metadata.json` 裡的安裝紀錄以路徑為 key,移動後的副本會失去來源連結,紀錄仍指向舊位置。請改用 [`skillshare move`](/docs/reference/commands/move)。它會把 Skill 和安裝紀錄一起移動,不會重新下載: ```bash -skillshare list -v react-best-practices # 記下 Source -skillshare uninstall react-best-practices -skillshare install --into frontend/react +skillshare move react-best-practices frontend/react skillshare sync ``` -原本安裝時用過的參數(例如 `--track`)也要一併加上。 +`move` 也可以一次移動多個 Skill 或整個資料夾(`skillshare move frontend archive`)。加上 `--dry-run` 可以先預覽。和 `mv` 一樣,執行 `skillshare sync` 之前 Targets 不會更新。 ::: --- diff --git a/website/sidebars.ts b/website/sidebars.ts index 734873d63..9d3d695b1 100644 --- a/website/sidebars.ts +++ b/website/sidebars.ts @@ -154,6 +154,7 @@ const sidebars: SidebarsConfig = { 'reference/commands/update', 'reference/commands/upgrade', 'reference/commands/enable', + 'reference/commands/move', ], }, { diff --git a/website/src/data/featureMap.ts b/website/src/data/featureMap.ts index c10847362..48e44f619 100644 --- a/website/src/data/featureMap.ts +++ b/website/src/data/featureMap.ts @@ -21,7 +21,7 @@ export type FeatureGroup = { const C = '/docs/reference/commands/'; const D = '/docs/'; -export const COMMAND_COUNT = 37; +export const COMMAND_COUNT = 38; export const TARGET_COUNT = 79; export const FEATURE_GROUPS: FeatureGroup[] = [ @@ -133,6 +133,7 @@ export const FEATURE_GROUPS: FeatureGroup[] = [ items: [ {cmd: 'new', what: 'Scaffold a skill with a valid SKILL.md', kw: 'create author scaffold template', href: C + 'new'}, {cmd: 'analyze', what: 'Context window usage and skill quality per target', kw: 'tokens size budget quality', href: C + 'analyze'}, + {cmd: 'move', what: 'Move skills and folders without losing install records', kw: 'organize folder rename relocate group mv', href: C + 'move'}, {cmd: 'enable / disable', what: 'Turn skills off without removing them', kw: 'toggle off pause', href: C + 'enable'}, {cmd: 'extras', what: 'Sync rules, commands and prompts alongside skills', kw: 'rules prompts agents non-skill', href: C + 'extras'}, {cmd: 'mcp', what: 'Define an MCP server once, write it into each tool\'s own config', kw: 'model context protocol server connection json toml import', href: C + 'mcp'},