diff --git a/cmd/skillshare/check.go b/cmd/skillshare/check.go index 8645ce04b..394ee5230 100644 --- a/cmd/skillshare/check.go +++ b/cmd/skillshare/check.go @@ -48,6 +48,9 @@ type checkOptions struct { names []string // positional (0+ = all) groups []string // --group/-G json bool + diff bool // --diff: show each skill's changes since install + + parseOpts install.ParseOptions // how --diff parses recorded sources } // collectCheckItems reads metadata and partitions items for parallel checking. @@ -111,6 +114,8 @@ func parseCheckArgs(args []string) (*checkOptions, bool, error) { switch { case arg == "--json": opts.json = true + case arg == "--diff": + opts.diff = true case arg == "--group" || arg == "-G": i++ if i >= len(args) { @@ -125,6 +130,12 @@ func parseCheckArgs(args []string) (*checkOptions, bool, error) { opts.names = append(opts.names, arg) } } + if opts.diff && opts.json { + return nil, false, fmt.Errorf("--diff cannot be combined with --json") + } + if opts.diff && len(opts.names) == 0 && len(opts.groups) == 0 { + return nil, false, fmt.Errorf("--diff needs a skill name or --group") + } return opts, false, nil } @@ -183,6 +194,10 @@ func cmdCheck(args []string) error { return parseErr } + if opts.diff && kind == kindAgents { + return fmt.Errorf("--diff compares skills only") + } + cfgPath := config.ConfigPath() if mode == modeProject { cfgPath = config.ProjectConfigPath(cwd) @@ -223,6 +238,7 @@ func cmdCheck(args []string) error { } // Filtered check: resolve targets then check only those + opts.parseOpts = parseOptsFromConfig(cfg) cmdErr := runCheckFiltered(cfg.EffectiveSkillsSource(), "", opts, cfg.SkillsWalk()) logCheckOp(cfgPath, 0, 0, 0, 0, scope, start, cmdErr) return cmdErr @@ -450,7 +466,8 @@ func renderCheckResults(repoResults []checkRepoResult, skillResults []checkSkill next = append(next, "skillshare update --all --prune", "remove stale skills") } if modified > 0 { - next = append(next, "skillshare update --force", "discard local changes and reinstall") + next = append(next, "skillshare check --diff", "see the local changes", + "skillshare update --force", "discard local changes and reinstall") } if len(next) > 0 { ui.Next(next...) @@ -582,6 +599,14 @@ func runCheckFiltered(sourceDir, projectRoot string, opts *checkOptions, walks . return fmt.Errorf("no skills found") } + var follow *sourcewalk.Follow + if len(walks) > 0 { + follow = walks[0].Follow + } + if opts.diff { + return runCheckDiff(sourceDir, targets, opts.parseOpts, follow) + } + // --- Partition targets for parallel check --- var repoNames []string var skillNames []string @@ -593,10 +618,6 @@ func runCheckFiltered(sourceDir, projectRoot string, opts *checkOptions, walks . } } - var follow *sourcewalk.Follow - if len(walks) > 0 { - follow = walks[0].Follow - } repoInputs, plan := collectCheckItems(sourceDir, projectRoot, repoNames, skillNames, follow) total := len(repoInputs) + plan.RemoteSkills() @@ -706,7 +727,7 @@ func singleCheckStatus(repos []checkRepoResult, skills []checkSkillResult) singl case "stale": return singleCheckResult{ui.MarkWarn, "stale — no longer in the upstream repository", "skillshare update --all --prune", "remove stale skills"} case "modified": - return singleCheckResult{ui.MarkWarn, s.Message, "skillshare update " + s.Name + " --force", "discard local changes and reinstall"} + return singleCheckResult{ui.MarkWarn, s.Message, "skillshare check " + s.Name + " --diff", "see the changes; update --force discards them"} case "local": return singleCheckResult{mark: ui.MarkNone, text: "local source, nothing to compare"} case "error": @@ -836,6 +857,7 @@ func printCheckHelp() { {"-p, --project", "Check project-level skills (.skillshare/)"}, {"-g, --global", "Check global skills (~/.config/skillshare)"}, {"--json", "Output results as JSON"}, + {"--diff", "Show what changed in named skills since install"}, }}, helpExamples( helpRow{"skillshare check", "Check all items"}, @@ -844,6 +866,7 @@ func printCheckHelp() { helpRow{"skillshare check --group frontend", "Check all skills in frontend/"}, helpRow{"skillshare check x -G backend", "Mix names and groups"}, helpRow{"skillshare check --json", "Output as JSON (for CI)"}, + helpRow{"skillshare check my-skill --diff", "Show local edits to a skill"}, helpRow{"skillshare check -p", "Check project skills"}, helpRow{"skillshare check agents", "Check all agents"}, helpRow{"skillshare check agents -G demo", "Check agents in demo/"}, diff --git a/cmd/skillshare/check_diff.go b/cmd/skillshare/check_diff.go new file mode 100644 index 000000000..50aae3712 --- /dev/null +++ b/cmd/skillshare/check_diff.go @@ -0,0 +1,67 @@ +package main + +import ( + "errors" + "fmt" + "strings" + + "skillshare/internal/install" + "skillshare/internal/sourcewalk" + "skillshare/internal/ui" +) + +// runCheckDiff prints what changed in each target skill since it was installed. +func runCheckDiff(sourceDir string, targets []updateTarget, parseOpts install.ParseOptions, follow *sourcewalk.Follow) error { + store := install.LoadMetadataOrNew(sourceDir) + names := make([]string, len(targets)) + for i, t := range targets { + names[i] = t.name + } + width := ui.RowWidth(names...) + indent := strings.Repeat(" ", width+4) + + var changed []string + failed := 0 + for _, t := range targets { + if t.isRepo { + ui.Row(ui.MarkNone, t.name, ui.DimText("tracked repo · run git diff in "+t.path), width) + continue + } + spinner := ui.StartSpinner("Comparing " + t.name + " with its installed version...") + changes, err := install.LocalChanges(store.GetExact(t.name), parseOpts, t.path, follow) + spinner.Stop() + if errors.Is(err, install.ErrNoInstallRecord) { + ui.Row(ui.MarkNone, t.name, ui.DimText(err.Error()), width) + continue + } + if err != nil { + ui.Row(ui.MarkFail, t.name, err.Error(), width) + failed++ + continue + } + if len(changes) == 0 { + ui.Row(ui.MarkOK, t.name, "no local changes since install", width) + continue + } + changed = append(changed, t.name) + ui.Row(ui.MarkWarn, t.name, plural(len(changes), "file")+" changed since install", width) + for _, c := range changes { + fmt.Println(indent + c.Status + " " + c.Path) + for _, line := range strings.Split(strings.TrimRight(colorizePlainDiff(c.Diff), "\n"), "\n") { + fmt.Println(indent + " " + line) + } + } + } + + switch len(changed) { + case 0: + case 1: + ui.Next("skillshare update "+changed[0]+" --force", "discard them and reinstall") + default: + ui.Next("skillshare update --force", "discard a skill's changes and reinstall") + } + if failed > 0 { + return fmt.Errorf("could not compare %s", plural(failed, "skill")) + } + return nil +} diff --git a/cmd/skillshare/check_project.go b/cmd/skillshare/check_project.go index d3c33dd78..52592a760 100644 --- a/cmd/skillshare/check_project.go +++ b/cmd/skillshare/check_project.go @@ -34,5 +34,6 @@ func cmdCheckProject(root string, opts *checkOptions) error { } // Filtered check + opts.parseOpts = parseOptsFromProjectConfig(projectCfg) return runCheckFiltered(sourcePath, root, opts, projectSkillsWalk(root, projectCfg)) } diff --git a/cmd/skillshare/completion_bash.go b/cmd/skillshare/completion_bash.go index e2c5d2bff..634bf9243 100644 --- a/cmd/skillshare/completion_bash.go +++ b/cmd/skillshare/completion_bash.go @@ -55,7 +55,7 @@ _skillshare() { local target_remove_flags="--all -a --dry-run -n" local upgrade_flags="--dry-run -n --force -f --skill --cli --help -h" local update_flags="--all -a --dry-run -n --force -f --skip-audit --audit-threshold --threshold -T --diff --audit-verbose --prune --json --group -G --help -h" - local check_flags="--json --all --group -G --help -h" + local check_flags="--json --diff --all --group -G --help -h" local new_flags="--pattern -P --dry-run -n --help -h" local search_flags="--json --list -l --hub --limit -n --help -h" local trash_flags="--all --no-tui --help -h" diff --git a/cmd/skillshare/completion_fish.go b/cmd/skillshare/completion_fish.go index 7abf02657..2f4903267 100644 --- a/cmd/skillshare/completion_fish.go +++ b/cmd/skillshare/completion_fish.go @@ -317,6 +317,7 @@ complete -c skillshare -n '__fish_skillshare_using_command update' -l help -s h # check complete -c skillshare -n '__fish_skillshare_using_command check' -a agents -d 'Check agents' complete -c skillshare -n '__fish_skillshare_using_command check' -l json -d 'JSON output' +complete -c skillshare -n '__fish_skillshare_using_command check' -l diff -d 'Show changes since install' complete -c skillshare -n '__fish_skillshare_using_command check' -l all -d 'Check all' complete -c skillshare -n '__fish_skillshare_using_command check' -l group -s G -r -d 'Check by group' complete -c skillshare -n '__fish_skillshare_using_command check' -l help -s h -d 'Show help' diff --git a/cmd/skillshare/completion_nushell.go b/cmd/skillshare/completion_nushell.go index 357d12c1e..554b6a455 100644 --- a/cmd/skillshare/completion_nushell.go +++ b/cmd/skillshare/completion_nushell.go @@ -566,6 +566,7 @@ export extern "skillshare update" [ export extern "skillshare check" [ scope?: string@"nu-complete skillshare kind" --json # JSON output + --diff # Show changes since install --all # Check all --group(-G): string # Check by group --project(-p) # Use project-level config diff --git a/cmd/skillshare/completion_powershell.go b/cmd/skillshare/completion_powershell.go index b6b46f91a..7cfa8048a 100644 --- a/cmd/skillshare/completion_powershell.go +++ b/cmd/skillshare/completion_powershell.go @@ -201,7 +201,7 @@ $_skillshareCompleter = { 'target' = '--json', '--no-tui', '--help', '-h', '--mode', '-m', '--agent-mode', '--target-naming', '--add-include', '--add-exclude', '--remove-include', '--remove-exclude', '--add-agent-include', '--add-agent-exclude', '--remove-agent-include', '--remove-agent-exclude', '--agent', '--config-dir', '--cli', '--skills', '--no-skills', '--all', '-a', '--dry-run', '-n', '--project', '-p', '--global', '-g' 'upgrade' = '--dry-run', '-n', '--force', '-f', '--skill', '--cli', '--help', '-h' 'update' = '--all', '-a', '--dry-run', '-n', '--force', '-f', '--skip-audit', '--audit-threshold', '--threshold', '-T', '--diff', '--audit-verbose', '--prune', '--json', '--group', '-G', '--help', '-h', '--project', '-p', '--global', '-g' - 'check' = '--json', '--all', '--group', '-G', '--help', '-h', '--project', '-p', '--global', '-g' + 'check' = '--json', '--diff', '--all', '--group', '-G', '--help', '-h', '--project', '-p', '--global', '-g' 'trash' = '--all', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g' 'audit' = '--init-rules', '--json', '--format', '--quiet', '-q', '--yes', '-y', '--no-tui', '--threshold', '-T', '--group', '-G', '--profile', '--dedupe', '--analyzer', '--pattern', '--severity', '--disabled', '--help', '-h', '--project', '-p', '--global', '-g' 'hub' = '--source', '-s', '--output', '-o', '--full', '--audit', '--label', '-l', '--reset', '--help', '-h', '--project', '-p', '--global', '-g' diff --git a/cmd/skillshare/completion_zsh.go b/cmd/skillshare/completion_zsh.go index 5bd993142..7246336f4 100644 --- a/cmd/skillshare/completion_zsh.go +++ b/cmd/skillshare/completion_zsh.go @@ -468,6 +468,7 @@ _skillshare() { _arguments \ '1:scope:(agents)' \ '--json[JSON output]' \ + '--diff[Show changes since install]' \ '--all[Check all]' \ '--group[Check by group]:group:' \ '-G[Check by group]:group:' \ diff --git a/cmd/skillshare/diff.go b/cmd/skillshare/diff.go index 2fb41738a..c7582ab26 100644 --- a/cmd/skillshare/diff.go +++ b/cmd/skillshare/diff.go @@ -14,6 +14,7 @@ import ( "skillshare/internal/config" "skillshare/internal/oplog" "skillshare/internal/sync" + "skillshare/internal/textdiff" "skillshare/internal/ui" "skillshare/internal/utils" ) @@ -1192,7 +1193,7 @@ func renderDiffGroup(r targetDiffResult, opts diffRenderOpts, next *diffNext, wi if f.Action != "modify" || item.srcDir == "" { continue } - diffText := generateUnifiedDiff(filepath.Join(item.srcDir, f.RelPath), filepath.Join(item.dstDir, f.RelPath)) + diffText := textdiff.Files(filepath.Join(item.dstDir, f.RelPath), filepath.Join(item.srcDir, f.RelPath)) if diffText == "" { continue } diff --git a/cmd/skillshare/diff_file.go b/cmd/skillshare/diff_file.go index 1ab9a7462..1f6d1a5df 100644 --- a/cmd/skillshare/diff_file.go +++ b/cmd/skillshare/diff_file.go @@ -11,7 +11,6 @@ import ( "time" "skillshare/internal/install" - "skillshare/internal/textdiff" ) // fileDiffEntry represents a single file-level difference between source and destination. @@ -149,64 +148,6 @@ func fileContentsEqual(pathA, pathB string) bool { } } -// maxDiffFileSize is the maximum file size for generating unified diffs. -// Files larger than this are skipped to avoid performance issues. -const maxDiffFileSize = 1_000_000 // 1MB - -// generateUnifiedDiff produces a unified diff between two files. -// dstContent is treated as "old", srcContent as "new". -// Returns "(binary file differs)" if either file contains null bytes in the first 8000 chars. -// Returns "(file too large for diff)" if either file exceeds maxDiffFileSize. -func generateUnifiedDiff(srcPath, dstPath string) string { - if fileExceedsSize(srcPath, maxDiffFileSize) || fileExceedsSize(dstPath, maxDiffFileSize) { - return "(file too large for diff)" - } - - srcContent := readFileString(srcPath) - dstContent := readFileString(dstPath) - - if isBinary(srcContent) || isBinary(dstContent) { - return "(binary file differs)" - } - - // dstContent is "old", srcContent is "new" - return textdiff.Lines(dstContent, srcContent) -} - -// readFileString reads a file and returns its content as a string. -// Returns "" on error. -func readFileString(path string) string { - data, err := os.ReadFile(path) - if err != nil { - return "" - } - return string(data) -} - -// fileExceedsSize returns true if the file at path is larger than limit bytes. -// Returns false if the file doesn't exist or can't be stat'd. -func fileExceedsSize(path string, limit int64) bool { - info, err := os.Stat(path) - if err != nil { - return false - } - return info.Size() > limit -} - -// isBinary checks whether a string contains null bytes in the first 8000 characters. -func isBinary(content string) bool { - limit := len(content) - if limit > 8000 { - limit = 8000 - } - for i := 0; i < limit; i++ { - if content[i] == 0 { - return true - } - } - return false -} - // renderFileStat returns a git-style stat summary for file diffs. // // add: " + relpath (N bytes)" diff --git a/cmd/skillshare/diff_file_test.go b/cmd/skillshare/diff_file_test.go index 76b9e4648..49f7367b4 100644 --- a/cmd/skillshare/diff_file_test.go +++ b/cmd/skillshare/diff_file_test.go @@ -118,44 +118,6 @@ func TestDiffSkillFiles_NestedDir(t *testing.T) { } } -func TestGenerateUnifiedDiff(t *testing.T) { - dir := t.TempDir() - oldPath := filepath.Join(dir, "old.txt") - newPath := filepath.Join(dir, "new.txt") - - if err := os.WriteFile(oldPath, []byte("line1\nline2\nline3\n"), 0644); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(newPath, []byte("line1\nmodified\nline3\nextra\n"), 0644); err != nil { - t.Fatal(err) - } - - // newPath is src (new), oldPath is dst (old) - result := generateUnifiedDiff(newPath, oldPath) - - if !strings.Contains(result, "+") && !strings.Contains(result, "-") { - t.Errorf("expected diff output to contain '+' and '-' lines, got:\n%s", result) - } - if !strings.Contains(result, "modified") { - t.Errorf("expected diff to mention 'modified', got:\n%s", result) - } - if !strings.Contains(result, "extra") { - t.Errorf("expected diff to mention 'extra', got:\n%s", result) - } -} - -func TestIsBinary(t *testing.T) { - if !isBinary("hello\x00world") { - t.Error("expected isBinary to return true for string with null byte") - } - if isBinary("hello world, this is normal text") { - t.Error("expected isBinary to return false for normal text") - } - if isBinary("") { - t.Error("expected isBinary to return false for empty string") - } -} - func TestRenderFileStat(t *testing.T) { files := []fileDiffEntry{ {RelPath: "new.md", Action: "add", SrcSize: 100}, diff --git a/cmd/skillshare/diff_tui.go b/cmd/skillshare/diff_tui.go index f00973e12..a76600ffe 100644 --- a/cmd/skillshare/diff_tui.go +++ b/cmd/skillshare/diff_tui.go @@ -8,6 +8,7 @@ import ( "strings" "sync" + "skillshare/internal/textdiff" "skillshare/internal/theme" "github.com/charmbracelet/bubbles/list" @@ -870,7 +871,7 @@ func expandDiffCmd(entry *copyDiffEntry) tea.Cmd { defer wg.Done() src := filepath.Join(entry.srcDir, fe.RelPath) dst := filepath.Join(entry.dstDir, fe.RelPath) - results[idx] = generateUnifiedDiff(src, dst) + results[idx] = textdiff.Files(dst, src) }(i, f) } wg.Wait() diff --git a/cmd/skillshare/update_audit_render.go b/cmd/skillshare/update_audit_render.go index b726529fd..10ca9265a 100644 --- a/cmd/skillshare/update_audit_render.go +++ b/cmd/skillshare/update_audit_render.go @@ -254,7 +254,7 @@ func displayModifiedWarning(modified []string) { for _, name := range modified { ui.Row(ui.MarkWarn, name, modifiedSkillReason, width) } - ui.Note("Run with --force to discard the changes and reinstall") + ui.Note("Run 'skillshare check --diff' to see the changes, or update with --force to discard them and reinstall") } // displayMissingTrackedReposWarning warns about tracked repos declared in diff --git a/cmd/skillshare/update_handlers.go b/cmd/skillshare/update_handlers.go index 7d8c938da..d3db698b4 100644 --- a/cmd/skillshare/update_handlers.go +++ b/cmd/skillshare/update_handlers.go @@ -193,11 +193,13 @@ func updateRegularSkill(uc *updateContext, skillName string) (updateResult, erro // Only a skill named on purpose fails; --all and --group skip it as the batch path does. if uc.opts.all || len(uc.opts.groups) > 0 { printUpdateRow(ui.MarkWarn, skillName, modifiedSkillReason, 0) - ui.Next("skillshare update "+skillName+" --force", "discard them and reinstall") + ui.Next("skillshare check "+skillName+" --diff", "see the changes", + "skillshare update "+skillName+" --force", "discard them and reinstall") return updateResult{skipped: 1}, nil } printUpdateRow(ui.MarkFail, skillName, modifiedSkillReason, 0) - ui.Next("skillshare update "+skillName+" --force", "discard them and reinstall") + ui.Next("skillshare check "+skillName+" --diff", "see the changes", + "skillshare update "+skillName+" --force", "discard them and reinstall") return updateResult{skipped: 1}, fmt.Errorf("local changes in skill") } diff --git a/internal/install/local_changes.go b/internal/install/local_changes.go new file mode 100644 index 000000000..df22d1bf0 --- /dev/null +++ b/internal/install/local_changes.go @@ -0,0 +1,110 @@ +package install + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "sort" + "strings" + + "skillshare/internal/sourcewalk" + "skillshare/internal/textdiff" +) + +// FileChange is a file of an installed skill that differs from the version +// the skill was installed at. +type FileChange struct { + Path string `json:"path"` + Status string `json:"status"` // "modified", "added" or "deleted" + Diff string `json:"diff"` // textdiff.Files from the installed version to the local file +} + +// ErrNoInstallRecord means the skill was not installed from a repository with +// recorded file hashes, so there is nothing to compare it with. +var ErrNoInstallRecord = errors.New("no install record to compare with") + +// LocalChanges lists the files of the skill at dir whose hashes differ from +// the ones entry recorded, and diffs each against the skill's source checked +// out at the recorded commit. It fetches only when a recorded file changed. +func LocalChanges(entry *MetadataEntry, parseOpts ParseOptions, dir string, follow ...*sourcewalk.Follow) ([]FileChange, error) { + if entry == nil || entry.Tracked || entry.RepoURL == "" || len(entry.FileHashes) == 0 { + return nil, ErrNoInstallRecord + } + local, err := ComputeFileHashes(dir, follow...) + if err != nil { + return nil, err + } + var changes []FileChange + for path, hash := range local { + if recorded, ok := entry.FileHashes[path]; !ok { + changes = append(changes, FileChange{Path: path, Status: "added"}) + } else if recorded != hash { + changes = append(changes, FileChange{Path: path, Status: "modified"}) + } + } + for path := range entry.FileHashes { + if _, ok := local[path]; !ok { + changes = append(changes, FileChange{Path: path, Status: "deleted"}) + } + } + if len(changes) == 0 { + return nil, nil + } + sort.Slice(changes, func(i, j int) bool { return changes[i].Path < changes[j].Path }) + + // An added file diffs against nothing, so the installed version is only + // fetched for files it had. + installed := "" + if slices.ContainsFunc(changes, func(c FileChange) bool { return c.Status != "added" }) { + // Upstream HEAD would show its own changes as the user's. + commit := installedCommit(entry) + if commit == "" { + return nil, errors.New("no recorded commit to compare with") + } + source, err := ParseSourceWithOptions(entry.Source, parseOpts) + if err != nil { + return nil, fmt.Errorf("invalid source: %w", err) + } + source.ApplyRecordedBranch(entry.Branch) + source.Commit = commit + tmp, err := os.MkdirTemp("", "skillshare-changes-") + if err != nil { + return nil, err + } + defer os.RemoveAll(tmp) + installed = filepath.Join(tmp, "skill") + // Only read, never used, so the audit gate does not apply. + if _, err := Install(source, installed, InstallOptions{SkipAudit: true}); err != nil { + return nil, fmt.Errorf("fetch the installed version: %w", err) + } + } + if len(follow) > 0 { + if resolved, ok := follow[0].Resolve(dir); ok { + dir = resolved + } + } + for i, c := range changes { + rel := filepath.FromSlash(c.Path) + old := "" // reads as empty + if c.Status != "added" { + old = filepath.Join(installed, rel) + } + changes[i].Diff = textdiff.Files(old, filepath.Join(dir, rel)) + } + return changes, nil +} + +// installedCommit is the commit the skill was installed at: the full SHA when +// it is the same commit as the short Version, since fetching a short SHA falls +// back to downloading the whole history. "" when none was recorded. +func installedCommit(entry *MetadataEntry) string { + if !IsCommitSHA(entry.Version) { + return "" + } + if IsCommitSHA(entry.Commit) && strings.HasPrefix(entry.Commit, entry.Version) { + return entry.Commit + } + return entry.Version +} diff --git a/internal/install/local_changes_test.go b/internal/install/local_changes_test.go new file mode 100644 index 000000000..cd1446149 --- /dev/null +++ b/internal/install/local_changes_test.go @@ -0,0 +1,126 @@ +package install + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestLocalChanges_DiffsAgainstInstalledCommit(t *testing.T) { + repo := initTestRepo(t) + if err := os.WriteFile(filepath.Join(repo, "SKILL.md"), []byte("---\nname: alpha\n---\nv1\n"), 0644); err != nil { + t.Fatal(err) + } + gitAdd(t, repo, ".") + gitCommit(t, repo, "v1") + + sourceDir := t.TempDir() + dest := filepath.Join(sourceDir, "alpha") + source, err := ParseSource("file://" + repo) + if err != nil { + t.Fatal(err) + } + if _, err := Install(source, dest, InstallOptions{SourceDir: sourceDir, SkipAudit: true}); err != nil { + t.Fatal(err) + } + entry := LoadMetadataOrNew(sourceDir).Get("alpha") + + // Upstream moves on; the diff must still be against the installed v1. + if err := os.WriteFile(filepath.Join(repo, "SKILL.md"), []byte("---\nname: alpha\n---\nv2\n"), 0644); err != nil { + t.Fatal(err) + } + gitAdd(t, repo, ".") + gitCommit(t, repo, "v2") + + // Edit in place like an editor would: git may have checked out CRLF on Windows. + installed, err := os.ReadFile(filepath.Join(dest, "SKILL.md")) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dest, "SKILL.md"), []byte(strings.Replace(string(installed), "v1", "mine", 1)), 0644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dest, "notes.md"), []byte("note\n"), 0644); err != nil { + t.Fatal(err) + } + + changes, err := LocalChanges(entry, ParseOptions{}, dest) + if err != nil { + t.Fatal(err) + } + var got []string + for _, c := range changes { + got = append(got, c.Status+" "+c.Path+"\n"+strings.ReplaceAll(c.Diff, "\r", "")) + } + want := []string{ + "modified SKILL.md\n ---\n name: alpha\n ---\n- v1\n+ mine\n", + "added notes.md\n+ note\n", + } + if strings.Join(got, "|") != strings.Join(want, "|") { + t.Errorf("changes =\n%q\nwant\n%q", got, want) + } +} + +func TestLocalChanges_UnchangedSkillDoesNotFetch(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("# a\n"), 0644); err != nil { + t.Fatal(err) + } + hashes, err := ComputeFileHashes(dir) + if err != nil { + t.Fatal(err) + } + changes, err := LocalChanges(&MetadataEntry{Source: "file:///nonexistent/repo", RepoURL: "file:///nonexistent/repo", FileHashes: hashes}, ParseOptions{}, dir) + if err != nil || changes != nil { + t.Errorf("LocalChanges = %v, %v; want nil, nil", changes, err) + } +} + +// Without the installed commit the diff would be against upstream HEAD and +// show upstream changes as the user's. +func TestLocalChanges_NoRecordedCommit(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("# a\n"), 0644); err != nil { + t.Fatal(err) + } + _, err := LocalChanges(&MetadataEntry{Source: "file:///nonexistent/repo", RepoURL: "file:///nonexistent/repo", FileHashes: map[string]string{"SKILL.md": "sha256:old"}}, ParseOptions{}, dir) + if err == nil || !strings.Contains(err.Error(), "no recorded commit") { + t.Errorf("err = %v, want no recorded commit", err) + } +} + +// Added files diff against nothing, so they need neither a commit nor a fetch. +func TestLocalChanges_OnlyAddedFilesDoNotFetch(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("# a\n"), 0644); err != nil { + t.Fatal(err) + } + hashes, err := ComputeFileHashes(dir) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "notes.md"), []byte("mine\n"), 0644); err != nil { + t.Fatal(err) + } + changes, err := LocalChanges(&MetadataEntry{Source: "file:///nonexistent/repo", RepoURL: "file:///nonexistent/repo", FileHashes: hashes}, ParseOptions{}, dir) + if err != nil || len(changes) != 1 || changes[0] != (FileChange{Path: "notes.md", Status: "added", Diff: "+ mine\n"}) { + t.Errorf("LocalChanges = %+v, %v", changes, err) + } +} + +// A short SHA makes git fetch the whole history, so the full recorded commit +// is used when it is the same commit as Version. +func TestInstalledCommit(t *testing.T) { + full := "0123456789abcdef0123456789abcdef01234567" + for _, c := range []struct{ version, commit, want string }{ + {"0123456", full, full}, + {"0123456", "", "0123456"}, + {"89abcde", full, "89abcde"}, // stale Commit from an older install + {"", full, ""}, + } { + if got := installedCommit(&MetadataEntry{Version: c.version, Commit: c.commit}); got != c.want { + t.Errorf("installedCommit(%q, %q) = %q, want %q", c.version, c.commit, got, c.want) + } + } +} diff --git a/internal/install/metadata.go b/internal/install/metadata.go index 86ce2b36f..63ed45edf 100644 --- a/internal/install/metadata.go +++ b/internal/install/metadata.go @@ -96,6 +96,25 @@ func (s *MetadataStore) Has(name string) bool { // It first tries a direct key lookup, then falls back to matching group+basename. // This handles the case where entries are stored with basename keys but have a Group field. func (s *MetadataStore) GetByPath(relPath string) *MetadataEntry { + if e := s.GetExact(relPath); e != nil { + return e + } + if s == nil { + return nil + } + base := filepath.Base(filepath.ToSlash(relPath)) + // Basename-only fallback: tracked repos store metadata with short keys + // (e.g. "agent-browser") but discovery produces full relPaths including + // the repo prefix (e.g. "_repo/agent-browser/agent-browser"). + if e := s.Entries[base]; e != nil && e.Group == "" { + return e + } + return nil +} + +// GetExact is GetByPath without the basename-only fallback for tracked-repo +// members, so a nested path never resolves to a top-level skill's entry. +func (s *MetadataStore) GetExact(relPath string) *MetadataEntry { if s == nil { return nil } @@ -114,12 +133,6 @@ func (s *MetadataStore) GetByPath(relPath string) *MetadataEntry { if e := s.Entries[base]; e != nil && e.Group == group { return e } - // Basename-only fallback: tracked repos store metadata with short keys - // (e.g. "agent-browser") but discovery produces full relPaths including - // the repo prefix (e.g. "_repo/agent-browser/agent-browser"). - if e := s.Entries[base]; e != nil && e.Group == "" { - return e - } return nil } diff --git a/internal/server/handler_local_changes.go b/internal/server/handler_local_changes.go new file mode 100644 index 000000000..530c57951 --- /dev/null +++ b/internal/server/handler_local_changes.go @@ -0,0 +1,39 @@ +package server + +import ( + "errors" + "net/http" + "path/filepath" + + "skillshare/internal/install" +) + +// handleSkillLocalChanges diffs the files of a skill installed from a repo +// against the version it was installed at. name is the skill's relative path. +func (s *Server) handleSkillLocalChanges(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + s.mu.RLock() + source := s.skillsSource() + walk := s.skillsWalk() + parseOpts := s.parseOpts() + var entry *install.MetadataEntry + if e := s.skillsStore.GetExact(name); e != nil && filepath.IsLocal(name) { + copied := *e + entry = &copied + } + s.mu.RUnlock() + + changes, err := install.LocalChanges(entry, parseOpts, filepath.Join(source, filepath.FromSlash(name)), walk.Follow) + if errors.Is(err, install.ErrNoInstallRecord) { + writeError(w, http.StatusNotFound, name+": "+err.Error()) + return + } + if err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + if changes == nil { + changes = []install.FileChange{} + } + writeJSON(w, map[string]any{"files": changes}) +} diff --git a/internal/server/handler_local_changes_test.go b/internal/server/handler_local_changes_test.go new file mode 100644 index 000000000..4e8828de8 --- /dev/null +++ b/internal/server/handler_local_changes_test.go @@ -0,0 +1,67 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "skillshare/internal/install" +) + +func TestHandleSkillLocalChanges_DiffsEditedSkill(t *testing.T) { + s, src := newTestServer(t) + remote := t.TempDir() + initGitRepo(t, remote) + if err := os.WriteFile(filepath.Join(remote, "SKILL.md"), []byte("# v1\n"), 0644); err != nil { + t.Fatal(err) + } + runGit(t, remote, "add", ".") + runGit(t, remote, "commit", "-m", "v1") + source, err := install.ParseSource("file://" + remote) + if err != nil { + t.Fatal(err) + } + dest := filepath.Join(src, "tools", "alpha") + if _, err := install.Install(source, dest, install.InstallOptions{SourceDir: src, SkipAudit: true}); err != nil { + t.Fatal(err) + } + s.skillsStore = install.LoadMetadataOrNew(src) + if err := os.WriteFile(filepath.Join(dest, "SKILL.md"), []byte("# mine\n"), 0644); err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/api/resources/tools%2Falpha/local-changes", nil)) + if rr.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String()) + } + var resp struct{ Files []install.FileChange } + if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + want := []install.FileChange{{Path: "SKILL.md", Status: "modified", Diff: "- # v1\n+ # mine\n"}} + if len(resp.Files) != 1 || resp.Files[0] != want[0] { + t.Errorf("files = %+v, want %+v", resp.Files, want) + } +} + +// A nested or escaping path must not borrow a top-level skill's record. +func TestHandleSkillLocalChanges_OnlyExactRecord(t *testing.T) { + s, _ := newTestServer(t) + s.skillsStore = install.NewMetadataStore() + s.skillsStore.Set("foo", &install.MetadataEntry{Source: "file:///r", RepoURL: "file:///r", Version: "abc1234", FileHashes: map[string]string{"SKILL.md": "sha256:x"}}) + // Each request reloads the store from disk. + if err := s.skillsStore.Save(s.skillsSource()); err != nil { + t.Fatal(err) + } + for _, name := range []string{"nope", "_team%2Ffoo", "x%2F..%2F..%2Ffoo"} { + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/api/resources/"+name+"/local-changes", nil)) + if rr.Code != http.StatusNotFound { + t.Errorf("%s: expected 404, got %d: %s", name, rr.Code, rr.Body.String()) + } + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 77ce8c7f7..5eea84698 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -485,6 +485,7 @@ func (s *Server) registerRoutes() { s.mux.HandleFunc("POST /api/resources", s.handleCreateSkill) s.mux.HandleFunc("GET /api/resources/{name}", s.handleGetSkill) s.mux.HandleFunc("GET /api/resources/{name}/files/{filepath...}", s.handleGetSkillFile) + s.mux.HandleFunc("GET /api/resources/{name}/local-changes", s.handleSkillLocalChanges) s.mux.HandleFunc("PUT /api/resources/{name}/content", s.handlePutSkillContent) s.mux.HandleFunc("PATCH /api/resources/{name}/source", s.handlePatchSkillSource) s.mux.HandleFunc("POST /api/resources/{name}/open-in-editor", s.handleOpenSkillInEditor) diff --git a/internal/sourcefs/testdata/raw_writes.tsv b/internal/sourcefs/testdata/raw_writes.tsv index ab02fafa2..03e5d064e 100644 --- a/internal/sourcefs/testdata/raw_writes.tsv +++ b/internal/sourcefs/testdata/raw_writes.tsv @@ -192,6 +192,8 @@ internal/install/install_update.go handleUpdate os.MkdirTemp "" tmp internal/install/install_update.go handleUpdate os.RemoveAll tempDir tmp internal/install/install_update.go updateRepoRootOrchestrator os.MkdirTemp "" tmp internal/install/install_update.go updateRepoRootOrchestrator os.RemoveAll tempDir tmp +internal/install/local_changes.go LocalChanges os.MkdirTemp "" tmp +internal/install/local_changes.go LocalChanges os.RemoveAll tmp tmp internal/install/lock.go (*Lock).Save os.Remove path project internal/install/lock.go (*Lock).Save os.WriteFile path project internal/install/meta.go WriteMeta os.WriteFile metaPath source-unmigrated diff --git a/internal/textdiff/textdiff.go b/internal/textdiff/textdiff.go index bc10a21f3..8d32718b7 100644 --- a/internal/textdiff/textdiff.go +++ b/internal/textdiff/textdiff.go @@ -2,6 +2,7 @@ package textdiff import ( + "os" "strings" "github.com/sergi/go-diff/diffmatchpatch" @@ -50,3 +51,60 @@ func format(diffs []diffmatchpatch.Diff) string { return b.String() } + +// maxDiffFileSize is the maximum file size for generating unified diffs. +// Files larger than this are skipped to avoid performance issues. +const maxDiffFileSize = 1_000_000 // 1MB + +// Files renders Lines for the files at oldPath and newPath. A missing file +// reads as empty. Returns "(binary file differs)" if either file contains null +// bytes in the first 8000 chars, and "(file too large for diff)" if either +// file exceeds maxDiffFileSize. +func Files(oldPath, newPath string) string { + if fileExceedsSize(oldPath, maxDiffFileSize) || fileExceedsSize(newPath, maxDiffFileSize) { + return "(file too large for diff)" + } + + oldContent := readFileString(oldPath) + newContent := readFileString(newPath) + + if isBinary(oldContent) || isBinary(newContent) { + return "(binary file differs)" + } + + return Lines(oldContent, newContent) +} + +// readFileString reads a file and returns its content as a string. +// Returns "" on error. +func readFileString(path string) string { + data, err := os.ReadFile(path) + if err != nil { + return "" + } + return string(data) +} + +// fileExceedsSize returns true if the file at path is larger than limit bytes. +// Returns false if the file doesn't exist or can't be stat'd. +func fileExceedsSize(path string, limit int64) bool { + info, err := os.Stat(path) + if err != nil { + return false + } + return info.Size() > limit +} + +// isBinary checks whether a string contains null bytes in the first 8000 characters. +func isBinary(content string) bool { + limit := len(content) + if limit > 8000 { + limit = 8000 + } + for i := 0; i < limit; i++ { + if content[i] == 0 { + return true + } + } + return false +} diff --git a/internal/textdiff/textdiff_test.go b/internal/textdiff/textdiff_test.go new file mode 100644 index 000000000..b73b47390 --- /dev/null +++ b/internal/textdiff/textdiff_test.go @@ -0,0 +1,45 @@ +package textdiff + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestFiles(t *testing.T) { + dir := t.TempDir() + oldPath := filepath.Join(dir, "old.txt") + newPath := filepath.Join(dir, "new.txt") + + if err := os.WriteFile(oldPath, []byte("line1\nline2\nline3\n"), 0644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(newPath, []byte("line1\nmodified\nline3\nextra\n"), 0644); err != nil { + t.Fatal(err) + } + + result := Files(oldPath, newPath) + + if !strings.Contains(result, "+") && !strings.Contains(result, "-") { + t.Errorf("expected diff output to contain '+' and '-' lines, got:\n%s", result) + } + if !strings.Contains(result, "modified") { + t.Errorf("expected diff to mention 'modified', got:\n%s", result) + } + if !strings.Contains(result, "extra") { + t.Errorf("expected diff to mention 'extra', got:\n%s", result) + } +} + +func TestIsBinary(t *testing.T) { + if !isBinary("hello\x00world") { + t.Error("expected isBinary to return true for string with null byte") + } + if isBinary("hello world, this is normal text") { + t.Error("expected isBinary to return false for normal text") + } + if isBinary("") { + t.Error("expected isBinary to return false for empty string") + } +} diff --git a/skills/skillshare/references/install.md b/skills/skillshare/references/install.md index ae2990c4c..9fb3f3ed9 100644 --- a/skills/skillshare/references/install.md +++ b/skills/skillshare/references/install.md @@ -161,11 +161,12 @@ Check for available updates and validate skill metadata. skillshare check # Show update status for all repos/skills skillshare check --json # JSON output (CI-friendly) skillshare check -p # Check project skills +skillshare check my-skill --diff # Show local edits vs the installed version ``` - **Tracked repos:** Fetches from origin, shows commits behind - **Remote skills:** Compares installed version with remote HEAD -- **Modified skills:** Remote skills edited since install are `modified`; `update` skips them until `--force` +- **Modified skills:** Remote skills edited since install are `modified`; `update` skips them until `--force`. `check --diff` shows the edits - **Local skills:** Shown as "local source" - **Targets validation:** Warns about unknown target names in skill-level `targets` field diff --git a/tests/integration/completion_test.go b/tests/integration/completion_test.go index ad754390e..7101bf69f 100644 --- a/tests/integration/completion_test.go +++ b/tests/integration/completion_test.go @@ -103,6 +103,23 @@ func TestCompletion_MCPCheck_AllShells(t *testing.T) { } } +func TestCompletion_CheckDiff_AllShells(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + for shell, flag := range map[string]string{ + "bash": `check_flags="--json --diff `, + "zsh": "'--diff[Show changes since install]'", + "fish": "check' -l diff", + "powershell": "'check' = '--json', '--diff'", + "nushell": "--diff # Show changes since install", + } { + result := sb.RunCLI("completion", shell) + result.AssertSuccess(t) + result.AssertOutputContains(t, flag) + } +} + func TestCompletion_TargetCLIFlag_AllShells(t *testing.T) { sb := testutil.NewSandbox(t) defer sb.Cleanup() diff --git a/tests/integration/update_local_changes_test.go b/tests/integration/update_local_changes_test.go index 5f67ab194..0d28cc521 100644 --- a/tests/integration/update_local_changes_test.go +++ b/tests/integration/update_local_changes_test.go @@ -100,3 +100,71 @@ func TestUpdateAll_SingleModifiedSkillIsSkipped(t *testing.T) { t.Fatalf("update --all: got %+v, want 1 skipped", got) } } + +// check --diff shows the edit against the version the skill was installed at, +// even after upstream has moved on. +func TestCheckDiff_ShowsChangesSinceInstall(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + setupGlobalConfig(sb) + _, work := setupGroupedSkills(t, sb, "alpha", "beta") + writeGroupedSkill(t, work, "alpha", "v2") + gitAddCommit(t, work, "upstream v2") + gitPush(t, work) + + edited := "---\nname: alpha\n---\n# my edit\n" + if err := os.WriteFile(filepath.Join(sb.SourcePath, "alpha", "SKILL.md"), []byte(edited), 0644); err != nil { + t.Fatal(err) + } + + result := sb.RunCLI("check", "alpha", "beta", "--diff") + result.AssertSuccess(t) + for _, want := range []string{"1 file changed since install", "modified SKILL.md", "- # alpha v1", "+ # my edit", "no local changes since install"} { + if !strings.Contains(result.Stdout, want) { + t.Errorf("check --diff output lacks %q:\n%s", want, result.Stdout) + } + } + if strings.Contains(result.Stdout, "v2") { + t.Errorf("check --diff compared with upstream HEAD instead of the installed version:\n%s", result.Stdout) + } +} + +func TestCheckDiffProject_ShowsChangesSinceInstall(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + projectRoot := sb.SetupProjectDir("claude") + remote := filepath.Join(sb.Root, "project-grouped.git") + work := filepath.Join(sb.Root, "project-grouped-work") + gitInit(t, remote, true) + gitClone(t, remote, work) + writeGroupedSkill(t, work, "alpha", "v1") + gitAddCommit(t, work, "add skills") + gitPush(t, work) + sb.RunCLIInDir(projectRoot, "install", "file://"+remote+"//skills/alpha", "-p", "--skip-audit").AssertSuccess(t) + + skillFile := filepath.Join(projectRoot, ".skillshare", "skills", "alpha", "SKILL.md") + if err := os.WriteFile(skillFile, []byte("---\nname: alpha\n---\n# my edit\n"), 0644); err != nil { + t.Fatal(err) + } + + result := sb.RunCLIInDir(projectRoot, "check", "alpha", "--diff", "-p") + result.AssertSuccess(t) + result.AssertOutputContains(t, "- # alpha v1") + result.AssertOutputContains(t, "+ # my edit") +} + +func TestCheckDiff_RejectsUnsupportedCombinations(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + setupGlobalConfig(sb) + + for want, args := range map[string][]string{ + "cannot be combined with --json": {"check", "alpha", "--diff", "--json"}, + "needs a skill name or --group": {"check", "--diff"}, + "compares skills only": {"check", "agents", "alpha", "--diff"}, + } { + result := sb.RunCLI(args...) + result.AssertFailure(t) + result.AssertAnyOutputContains(t, want) + } +} diff --git a/ui/src/api/resources.ts b/ui/src/api/resources.ts index 3d1b825d6..67f9e417c 100644 --- a/ui/src/api/resources.ts +++ b/ui/src/api/resources.ts @@ -1,5 +1,5 @@ import { apiFetch, kindQuery } from './http'; -import type { BatchToggleResult, MoveRequest, MoveResult, BatchUninstallRequest, BatchUninstallResult, CollectResult, CollectScanResult, CreateSkillRequest, CreateSkillResponse, Overview, LinkedRepo, Skill, SkillFileContent, SourceLink, SourceLinkRequest, SourceLinkResult, TemplatesResponse } from './types/resources'; +import type { BatchToggleResult, MoveRequest, MoveResult, BatchUninstallRequest, BatchUninstallResult, CollectResult, CollectScanResult, CreateSkillRequest, CreateSkillResponse, Overview, LinkedRepo, LocalFileChange, Skill, SkillFileContent, SourceLink, SourceLinkRequest, SourceLinkResult, TemplatesResponse } from './types/resources'; export const resourcesApi = { createSourceLink: (body: SourceLinkRequest) => @@ -76,6 +76,9 @@ export const resourcesApi = { // Skill file content getSkillFile: (skillName: string, filepath: string) => apiFetch(`/resources/${encodeURIComponent(skillName)}/files/${filepath}`), + // Files changed since install, diffed against the installed version; name is the skill's relPath. + getLocalChanges: (name: string) => + apiFetch<{ files: LocalFileChange[] }>(`/resources/${encodeURIComponent(name)}/local-changes`), // Save SKILL.md / agent markdown. saveSkillContent: (name: string, content: string, kind?: 'skill' | 'agent') => apiFetch<{ diff --git a/ui/src/api/types/resources.ts b/ui/src/api/types/resources.ts index 6a6e6c6a0..16e3cb7c7 100644 --- a/ui/src/api/types/resources.ts +++ b/ui/src/api/types/resources.ts @@ -112,6 +112,14 @@ export interface SkillFileContent { filename: string; } +/** A file of an installed skill that differs from the version it was installed at. */ +export interface LocalFileChange { + path: string; + status: 'modified' | 'added' | 'deleted'; + /** Every line of the file, prefixed "+ ", "- " or " ". */ + diff: string; +} + export interface BatchUninstallRequest { names: string[]; kind?: 'skill' | 'agent'; diff --git a/ui/src/i18n/locales/de.json b/ui/src/i18n/locales/de.json index 1219cc49a..06e396b67 100644 --- a/ui/src/i18n/locales/de.json +++ b/ui/src/i18n/locales/de.json @@ -670,6 +670,10 @@ "resourceDetail.toast.openedIn": "In {editor} geöffnet", "resourceDetail.toast.skipped": "Übersprungen", "resourceDetail.modified.message": "{name} wurde seit der Installation geändert. Beim Aktualisieren werden deine Änderungen durch die Upstream-Version ersetzt; sie wird auch dann installiert, wenn das Sicherheitsaudit sie blockieren würde.", + "resourceDetail.modified.loadFailed": "Änderungen konnten nicht geladen werden: {message}", + "resourceDetail.modified.status.added": "Hinzugefügt", + "resourceDetail.modified.status.deleted": "Gelöscht", + "resourceDetail.modified.status.modified": "Geändert", "resourceDetail.toast.upToDate": "{name} ist bereits aktuell.", "resourceDetail.toast.updateFailed": "Aktualisierung fehlgeschlagen", "resourceDetail.toast.updated": "Aktualisiert: {name} — {message}{auditInfo}", @@ -892,6 +896,7 @@ "update.check.updateAvailable": "Update verfügbar", "update.check.stale": "Upstream gelöscht", "update.check.dirty": "Lokal geändert", + "update.check.viewChanges": "Änderungen ansehen", "update.done.subtitle": "Aktualisierung abgeschlossen.", "update.done.syncHint": "Ziele erhalten die neuen Versionen beim nächsten Sync.", "update.empty.description": "Getrackte Repositories oder GitHub-Skills installieren, um auf Updates zu prüfen.", diff --git a/ui/src/i18n/locales/en.json b/ui/src/i18n/locales/en.json index 1958e5cd8..b08f4d8bd 100644 --- a/ui/src/i18n/locales/en.json +++ b/ui/src/i18n/locales/en.json @@ -664,6 +664,10 @@ "resourceDetail.toast.openedIn": "Opened in {editor}", "resourceDetail.toast.skipped": "Skipped", "resourceDetail.modified.message": "{name} has changed since it was installed. Updating replaces your changes with the upstream version and installs it even if the security audit would block it.", + "resourceDetail.modified.loadFailed": "Could not load the changes: {message}", + "resourceDetail.modified.status.added": "Added", + "resourceDetail.modified.status.deleted": "Deleted", + "resourceDetail.modified.status.modified": "Modified", "resourceDetail.toast.updateFailed": "Update failed", "resourceDetail.toast.updated": "Updated: {name} — {message}{auditInfo}", "resourceDetail.toast.upToDate": "{name} is already up to date.", @@ -814,6 +818,7 @@ "update.check.stale": "Deleted upstream", "update.check.upToDate": "Up to date", "update.check.dirty": "Modified locally", + "update.check.viewChanges": "View changes", "update.done.subtitle": "Update finished.", "update.done.syncHint": "Targets get the new versions on the next sync.", "update.empty.description": "Install tracked repositories or GitHub skills to check for updates.", diff --git a/ui/src/i18n/locales/es.json b/ui/src/i18n/locales/es.json index ddcfd34c5..93ee68b2c 100644 --- a/ui/src/i18n/locales/es.json +++ b/ui/src/i18n/locales/es.json @@ -670,6 +670,10 @@ "resourceDetail.toast.openedIn": "Abierto en {editor}", "resourceDetail.toast.skipped": "Omitido", "resourceDetail.modified.message": "{name} ha cambiado desde que se instaló. Al actualizar, tus cambios se reemplazan por la versión upstream, que se instala aunque la auditoría de seguridad la bloquearía.", + "resourceDetail.modified.loadFailed": "No se pudieron cargar los cambios: {message}", + "resourceDetail.modified.status.added": "Añadido", + "resourceDetail.modified.status.deleted": "Eliminado", + "resourceDetail.modified.status.modified": "Modificado", "resourceDetail.toast.upToDate": "{name} ya está actualizado.", "resourceDetail.toast.updateFailed": "Error al actualizar", "resourceDetail.toast.updated": "Actualizado: {name} — {message}{auditInfo}", @@ -892,6 +896,7 @@ "update.check.updateAvailable": "Actualización disponible", "update.check.stale": "Eliminado en origen", "update.check.dirty": "Modificado localmente", + "update.check.viewChanges": "Ver cambios", "update.done.subtitle": "Actualización completa.", "update.done.syncHint": "Los destinos reciben las nuevas versiones en la próxima sincronización.", "update.empty.description": "Instala repositorios rastreados o skills de GitHub para comprobar actualizaciones.", diff --git a/ui/src/i18n/locales/fa.json b/ui/src/i18n/locales/fa.json index 37ed77317..40267dfe6 100644 --- a/ui/src/i18n/locales/fa.json +++ b/ui/src/i18n/locales/fa.json @@ -670,6 +670,10 @@ "resourceDetail.toast.openedIn": "در {editor} باز شد", "resourceDetail.toast.skipped": "رد شد", "resourceDetail.modified.message": "{name} پس از نصب تغییر کرده است. به‌روزرسانی، تغییرات شما را با نسخهٔ upstream جایگزین می‌کند و آن را حتی اگر ممیزی امنیتی مسدودش کند نصب می‌کند.", + "resourceDetail.modified.loadFailed": "بارگیری تغییرات ممکن نشد: {message}", + "resourceDetail.modified.status.added": "افزوده", + "resourceDetail.modified.status.deleted": "حذف‌شده", + "resourceDetail.modified.status.modified": "تغییرکرده", "resourceDetail.toast.upToDate": "{name} از قبل به‌روز است.", "resourceDetail.toast.updateFailed": "به‌روزرسانی ناموفق بود", "resourceDetail.toast.updated": "به‌روز شد: {name} — {message}{auditInfo}", @@ -892,6 +896,7 @@ "update.check.updateAvailable": "به‌روزرسانی موجود است", "update.check.stale": "در مبدأ حذف شده", "update.check.dirty": "تغییرات محلی", + "update.check.viewChanges": "مشاهدهٔ تغییرات", "update.done.subtitle": "به‌روزرسانی کامل شد.", "update.done.syncHint": "مقصدها نسخه‌های جدید را در همگام‌سازی بعدی دریافت می‌کنند.", "update.empty.description": "مخازن ردیابی‌شده یا اسکیل‌های GitHub نصب کنید تا به‌روزرسانی‌ها بررسی شوند.", diff --git a/ui/src/i18n/locales/fr.json b/ui/src/i18n/locales/fr.json index f3b61aff5..28ae98490 100644 --- a/ui/src/i18n/locales/fr.json +++ b/ui/src/i18n/locales/fr.json @@ -670,6 +670,10 @@ "resourceDetail.toast.openedIn": "Ouvert dans {editor}", "resourceDetail.toast.skipped": "Ignoré", "resourceDetail.modified.message": "{name} a été modifié depuis son installation. La mise à jour remplace vos modifications par la version upstream et l'installe même si l'audit de sécurité la bloquerait.", + "resourceDetail.modified.loadFailed": "Impossible de charger les modifications : {message}", + "resourceDetail.modified.status.added": "Ajouté", + "resourceDetail.modified.status.deleted": "Supprimé", + "resourceDetail.modified.status.modified": "Modifié", "resourceDetail.toast.upToDate": "{name} est déjà à jour.", "resourceDetail.toast.updateFailed": "Échec de la mise à jour", "resourceDetail.toast.updated": "Mis à jour : {name} — {message}{auditInfo}", @@ -892,6 +896,7 @@ "update.check.updateAvailable": "Mise à jour disponible", "update.check.stale": "Supprimé en amont", "update.check.dirty": "Modifié localement", + "update.check.viewChanges": "Voir les modifications", "update.done.subtitle": "Mise à jour terminée.", "update.done.syncHint": "Les cibles reçoivent les nouvelles versions à la prochaine synchronisation.", "update.empty.description": "Installez des dépôts suivis ou des skills GitHub pour vérifier les mises à jour.", diff --git a/ui/src/i18n/locales/id.json b/ui/src/i18n/locales/id.json index f2e800ba6..3d66f158f 100644 --- a/ui/src/i18n/locales/id.json +++ b/ui/src/i18n/locales/id.json @@ -670,6 +670,10 @@ "resourceDetail.toast.openedIn": "Dibuka di {editor}", "resourceDetail.toast.skipped": "Dilewati", "resourceDetail.modified.message": "{name} telah berubah sejak dipasang. Memperbarui akan mengganti perubahan Anda dengan versi upstream dan memasangnya meskipun audit keamanan akan memblokirnya.", + "resourceDetail.modified.loadFailed": "Tidak dapat memuat perubahan: {message}", + "resourceDetail.modified.status.added": "Ditambahkan", + "resourceDetail.modified.status.deleted": "Dihapus", + "resourceDetail.modified.status.modified": "Diubah", "resourceDetail.toast.upToDate": "{name} sudah yang terbaru.", "resourceDetail.toast.updateFailed": "Pembaruan gagal", "resourceDetail.toast.updated": "Diperbarui: {name} — {message}{auditInfo}", @@ -892,6 +896,7 @@ "update.check.updateAvailable": "Pembaruan tersedia", "update.check.stale": "Dihapus di upstream", "update.check.dirty": "Diubah secara lokal", + "update.check.viewChanges": "Lihat perubahan", "update.done.subtitle": "Pembaruan selesai.", "update.done.syncHint": "Target mendapatkan versi baru pada sinkronisasi berikutnya.", "update.empty.description": "Instal repositori yang dilacak atau skill GitHub untuk memeriksa pembaruan.", diff --git a/ui/src/i18n/locales/ja.json b/ui/src/i18n/locales/ja.json index 601e850d3..45e219787 100644 --- a/ui/src/i18n/locales/ja.json +++ b/ui/src/i18n/locales/ja.json @@ -670,6 +670,10 @@ "resourceDetail.toast.openedIn": "{editor} で開きました", "resourceDetail.toast.skipped": "スキップしました", "resourceDetail.modified.message": "{name} はインストール後に変更されています。更新すると、変更は upstream のバージョンで置き換えられ、セキュリティ監査でブロックされる場合でもインストールされます。", + "resourceDetail.modified.loadFailed": "変更内容を読み込めませんでした: {message}", + "resourceDetail.modified.status.added": "追加", + "resourceDetail.modified.status.deleted": "削除", + "resourceDetail.modified.status.modified": "変更", "resourceDetail.toast.upToDate": "{name} はすでに最新です。", "resourceDetail.toast.updateFailed": "更新に失敗しました", "resourceDetail.toast.updated": "更新済み: {name} — {message}{auditInfo}", @@ -892,6 +896,7 @@ "update.check.updateAvailable": "更新あり", "update.check.stale": "上流で削除", "update.check.dirty": "ローカルで変更あり", + "update.check.viewChanges": "変更を表示", "update.done.subtitle": "更新が完了しました。", "update.done.syncHint": "ターゲットには次回の同期で新しいバージョンが反映されます。", "update.empty.description": "追跡リポジトリまたは GitHub スキルをインストールして更新を確認してください。", diff --git a/ui/src/i18n/locales/ko.json b/ui/src/i18n/locales/ko.json index 87c9aac8c..f33eaa3a1 100644 --- a/ui/src/i18n/locales/ko.json +++ b/ui/src/i18n/locales/ko.json @@ -670,6 +670,10 @@ "resourceDetail.toast.openedIn": "{editor}에서 열렸습니다", "resourceDetail.toast.skipped": "건너뜀", "resourceDetail.modified.message": "{name}은(는) 설치 후 변경되었습니다. 업데이트하면 변경 사항이 upstream 버전으로 대체되며, 보안 감사가 차단하더라도 설치됩니다.", + "resourceDetail.modified.loadFailed": "변경 사항을 불러올 수 없습니다: {message}", + "resourceDetail.modified.status.added": "추가됨", + "resourceDetail.modified.status.deleted": "삭제됨", + "resourceDetail.modified.status.modified": "수정됨", "resourceDetail.toast.upToDate": "{name}은(는) 이미 최신 상태입니다.", "resourceDetail.toast.updateFailed": "업데이트 실패", "resourceDetail.toast.updated": "업데이트됨: {name} — {message}{auditInfo}", @@ -892,6 +896,7 @@ "update.check.updateAvailable": "업데이트 가능", "update.check.stale": "업스트림에서 삭제됨", "update.check.dirty": "로컬에서 수정됨", + "update.check.viewChanges": "변경 사항 보기", "update.done.subtitle": "업데이트 완료.", "update.done.syncHint": "대상에는 다음 동기화 때 새 버전이 반영됩니다.", "update.empty.description": "업데이트를 확인하려면 추적 저장소 또는 GitHub skills를 설치하세요.", diff --git a/ui/src/i18n/locales/pt-BR.json b/ui/src/i18n/locales/pt-BR.json index 16e6b43a3..620afc0a4 100644 --- a/ui/src/i18n/locales/pt-BR.json +++ b/ui/src/i18n/locales/pt-BR.json @@ -670,6 +670,10 @@ "resourceDetail.toast.openedIn": "Aberto em {editor}", "resourceDetail.toast.skipped": "Ignorado", "resourceDetail.modified.message": "{name} foi alterado desde a instalação. Atualizar substitui suas alterações pela versão upstream e a instala mesmo que a auditoria de segurança a bloqueie.", + "resourceDetail.modified.loadFailed": "Não foi possível carregar as alterações: {message}", + "resourceDetail.modified.status.added": "Adicionado", + "resourceDetail.modified.status.deleted": "Excluído", + "resourceDetail.modified.status.modified": "Modificado", "resourceDetail.toast.upToDate": "{name} já está atualizado.", "resourceDetail.toast.updateFailed": "Atualização falhou", "resourceDetail.toast.updated": "Atualizado: {name} — {message}{auditInfo}", @@ -892,6 +896,7 @@ "update.check.updateAvailable": "Atualização disponível", "update.check.stale": "Excluído na origem", "update.check.dirty": "Modificado localmente", + "update.check.viewChanges": "Ver alterações", "update.done.subtitle": "Atualização concluída.", "update.done.syncHint": "Os destinos recebem as novas versões na próxima sincronização.", "update.empty.description": "Instale repositórios rastreados ou skills do GitHub para verificar atualizações.", diff --git a/ui/src/i18n/locales/zh-CN.json b/ui/src/i18n/locales/zh-CN.json index 2229f5c28..947fec7e0 100644 --- a/ui/src/i18n/locales/zh-CN.json +++ b/ui/src/i18n/locales/zh-CN.json @@ -670,6 +670,10 @@ "resourceDetail.toast.openedIn": "已在 {editor} 中打开", "resourceDetail.toast.skipped": "已跳过", "resourceDetail.modified.message": "{name} 在安装后已被修改。更新会用 upstream 版本替换你的修改,即使安全审计会阻挡也会安装。", + "resourceDetail.modified.loadFailed": "无法加载修改内容:{message}", + "resourceDetail.modified.status.added": "新增", + "resourceDetail.modified.status.deleted": "已删除", + "resourceDetail.modified.status.modified": "已修改", "resourceDetail.toast.upToDate": "{name} 已是最新版本。", "resourceDetail.toast.updateFailed": "更新失败", "resourceDetail.toast.updated": "已更新:{name} — {message}{auditInfo}", @@ -892,6 +896,7 @@ "update.check.updateAvailable": "有可用更新", "update.check.stale": "上游已删除", "update.check.dirty": "本地有修改", + "update.check.viewChanges": "查看修改", "update.done.subtitle": "更新完成。", "update.done.syncHint": "目标会在下次同步时获得新版本。", "update.empty.description": "安装 tracked 仓库或 GitHub skill 以检查更新。", diff --git a/ui/src/i18n/locales/zh-TW.json b/ui/src/i18n/locales/zh-TW.json index 37520e842..828955188 100644 --- a/ui/src/i18n/locales/zh-TW.json +++ b/ui/src/i18n/locales/zh-TW.json @@ -670,6 +670,10 @@ "resourceDetail.toast.openedIn": "已在 {editor} 中開啟", "resourceDetail.toast.skipped": "已跳過", "resourceDetail.modified.message": "{name} 在安裝後已被修改。更新會以 upstream 版本取代你的修改,即使安全稽核會阻擋也會安裝。", + "resourceDetail.modified.loadFailed": "無法載入修改內容:{message}", + "resourceDetail.modified.status.added": "新增", + "resourceDetail.modified.status.deleted": "已刪除", + "resourceDetail.modified.status.modified": "已修改", "resourceDetail.toast.upToDate": "{name} 已是最新版本。", "resourceDetail.toast.updateFailed": "更新失敗", "resourceDetail.toast.updated": "已更新:{name} — {message}{auditInfo}", @@ -892,6 +896,7 @@ "update.check.updateAvailable": "有可用更新", "update.check.stale": "上游已刪除", "update.check.dirty": "本機有修改", + "update.check.viewChanges": "查看修改", "update.done.subtitle": "更新完成。", "update.done.syncHint": "目標會在下次同步時取得新版本。", "update.empty.description": "安裝追蹤的 repositories 或 GitHub skills 以檢查更新。", diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.ts index 3d43f7c03..2995a85e3 100644 --- a/ui/src/lib/queryKeys.ts +++ b/ui/src/lib/queryKeys.ts @@ -7,6 +7,7 @@ export const queryKeys = { detail: (name: string) => ['skills', name] as const, detailOfKind: (name: string, kind?: string) => ['skills', name, kind] as const, file: (name: string, path: string) => ['skill-file', name, path] as const, + localChanges: (relPath: string) => ['skill-local-changes', relPath] as const, }, /** A dry-run of the move dialog: what a move to `dest` would do. */ diff --git a/ui/src/pages/ResourceDetailPage.tsx b/ui/src/pages/ResourceDetailPage.tsx index 462e74312..909e23e1c 100644 --- a/ui/src/pages/ResourceDetailPage.tsx +++ b/ui/src/pages/ResourceDetailPage.tsx @@ -86,7 +86,8 @@ export default function ResourceDetailPage() { const [updating, setUpdating] = useState(false); const [toggling, setToggling] = useState(false); const [blocked, setBlocked] = useState(null); - const [modified, setModified] = useState(false); + // The Updates tab links a modified skill here with ?changes=1 to show its edits. + const [modified, setModified] = useState(() => searchParams.get('changes') === '1'); const [raw, setRaw] = useState(false); const skillMaps = useMemo(() => { @@ -391,9 +392,10 @@ export default function ResourceDetailPage() { {t('resourceDetail.modified.message', { name: resource.name })}{modified && }} confirmText={t('update.tab.force')} variant="danger" + wide loading={updating} onConfirm={() => runUpdate(false, true).then(() => setModified(false))} onCancel={() => setModified(false)} @@ -889,3 +891,26 @@ function BlockedDialog({ name, message, loading, onSkip, onClose }: { ); } + +/** What a remote skill changed since install, each file diffed against the installed version. */ +function LocalChanges({ relPath }: { relPath: string }) { + const t = useT(); + const { data, error, isPending } = useQuery({ queryKey: queryKeys.skills.localChanges(relPath), queryFn: () => api.getLocalChanges(relPath), staleTime: 0 }); + if (isPending) return
; + if (error) return
{t('resourceDetail.modified.loadFailed', { message: (error as Error).message })}
; + const status = { modified: t('resourceDetail.modified.status.modified'), added: t('resourceDetail.modified.status.added'), deleted: t('resourceDetail.modified.status.deleted') }; + return ( +
+ {data.files.map((f) => ( +
+

{f.path} · {status[f.status]}

+
+            {f.diff.replace(/\n$/, '').split('\n').map((l, i) => (
+              {l || ' '}
+            ))}
+          
+
+ ))} +
+ ); +} diff --git a/ui/src/pages/UpdatePage.tsx b/ui/src/pages/UpdatePage.tsx index 8ec351663..5412b5349 100644 --- a/ui/src/pages/UpdatePage.tsx +++ b/ui/src/pages/UpdatePage.tsx @@ -2,6 +2,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import type { ReactNode } from 'react'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import { Bot, Check, CircleAlert, CircleArrowUp, CircleCheck, Download, FolderX, GitBranch, Link, Loader2, Puzzle, RefreshCw, ShieldAlert, Trash2, X } from 'lucide-react'; +import { Link as RouterLink } from 'react-router-dom'; +import { resourceHref } from '../lib/resourceNames'; import { api } from '../api/client'; import type { CheckResult, LinkedRepo, Skill, UpdateResultItem } from '../api/client'; import { queryKeys } from '../lib/queryKeys'; @@ -437,7 +439,12 @@ export default function UpdatePage({ kind }: { kind: Kind }) { case 'stale': return {t('update.check.stale')}; case 'dirty': - return {t('update.check.dirty')}; + return ( + + {t('update.check.dirty')} + {!unit.isRepo && unit.items[0] && {t('update.check.viewChanges')}} + + ); case 'up-to-date': return {t('update.check.upToDate')}; case 'error': diff --git a/website/docs/reference/commands/check.md b/website/docs/reference/commands/check.md index b4cc0fd4c..954f01713 100644 --- a/website/docs/reference/commands/check.md +++ b/website/docs/reference/commands/check.md @@ -13,6 +13,7 @@ skillshare check a b c # Check multiple skills skillshare check --group frontend # Check all skills in frontend/ skillshare check x -G backend # Mix names and groups skillshare check --json # Machine-readable output +skillshare check my-skill --diff # Show what you changed in a skill since install ``` ## When to Use @@ -124,6 +125,7 @@ Skills without metadata (local-only) are skipped when expanding groups. | `--project`, `-p` | Check project-level skills (`.skillshare/`) | | `--global`, `-g` | Check global skills (`~/.config/skillshare`) | | `--json` | Output as JSON (for scripting/CI) | +| `--diff` | For the named skills, show each file changed since install as a line diff against the installed version. Needs a name or `--group`; cannot be combined with `--json` | | `--help`, `-h` | Show help | :::tip Auto-detection @@ -176,6 +178,18 @@ When a skill's subdirectory was renamed or deleted upstream, `check` reports it :::info Locally modified skills A skill you edited after installing it is reported as **modified**, even when upstream has a newer version; its `message` then ends with `update available upstream`. `update` leaves it alone until you run `skillshare update --force`, which discards your changes and reinstalls it. + +To see the changes first, run `skillshare check --diff`. It fetches the commit the skill was installed at, so the diff shows only your edits even when upstream has moved on: + +``` +! my-skill 2 files changed since install + modified SKILL.md + # My Skill + - Run the tests. + + Run the tests with -race. + added NOTES.md + + my notes +``` ::: :::tip Monorepo awareness diff --git a/website/docs/reference/commands/update.md b/website/docs/reference/commands/update.md index e0d1a5c5b..4be40f4f0 100644 --- a/website/docs/reference/commands/update.md +++ b/website/docs/reference/commands/update.md @@ -379,13 +379,13 @@ skillshare update _team-skills --force If skillshare cannot read the repo's git status, the update fails for that repo with `failed to check git status`; `--force` skips the check. -A skill installed from a repository is protected the same way. When its files no longer match the ones recorded at install time, `update` skips it and reports `local changes since install`; `skillshare check` lists it as modified. Copy your edits elsewhere if you want to keep them, then discard them: +A skill installed from a repository is protected the same way. When its files no longer match the ones recorded at install time, `update` skips it and reports `local changes since install`; `skillshare check` lists it as modified, and `skillshare check --diff` shows what you changed. Copy your edits elsewhere if you want to keep them, then discard them: ```bash skillshare update my-skill --force ``` -On the dashboard's **Updates** tab, the skill shows **Modified locally**; tick **Force overwrite local edits** before updating it, or use **Force Retry** on the skipped row. Updating it from the skill's own page asks before discarding the changes. `update --dry-run` reports the skill as one it would skip. A modified skill that was also deleted upstream is kept until you add `--force`, even with `--prune`. +On the dashboard's **Updates** tab, the skill shows **Modified locally** and a **View changes** button that opens its changes on the skill's page; tick **Force overwrite local edits** before updating it, or use **Force Retry** on the skipped row. Updating it from the skill's own page shows the changes and asks before discarding them. `update --dry-run` reports the skill as one it would skip. A modified skill that was also deleted upstream is kept until you add `--force`, even with `--prune`. ## After Updating diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/check.md b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/check.md index a56492ad5..dddf5b7a0 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/check.md +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/check.md @@ -13,6 +13,7 @@ skillshare check a b c # 複数の Skill を確認 skillshare check --group frontend # frontend/ 配下のすべての Skill を確認 skillshare check x -G backend # 名前とグループを混在させる skillshare check --json # 機械可読な出力 +skillshare check my-skill --diff # インストール後に Skill へ加えた変更を表示 ``` ## 使うタイミング @@ -124,6 +125,7 @@ skillshare check frontend # グループとして自動検出 | `--project`, `-p` | Project レベルの Skill(`.skillshare/`)を確認 | | `--global`, `-g` | グローバルの Skill(`~/.config/skillshare`)を確認 | | `--json` | JSON として出力(スクリプト/CI 向け) | +| `--diff` | 指定した Skill について、インストール後に変更された各ファイルを、インストール済みバージョンとの行 diff で表示します。名前または `--group` が必要で、`--json` とは併用できません | | `--help`, `-h` | ヘルプを表示 | :::tip 自動検出 @@ -176,6 +178,18 @@ Skill のサブディレクトリがアップストリームでリネームま :::info ローカルで変更された Skill インストール後に編集した Skill は、upstream に新しいバージョンがあっても **modified** と報告され、その `message` は `update available upstream` で終わります。`update` は `skillshare update --force` を実行するまで手を付けません。このコマンドは変更を破棄して再インストールします。 + +先に変更内容を確認するには、`skillshare check --diff` を実行します。Skill がインストールされた commit を取得するため、upstream が先に進んでいても diff にはあなたの編集だけが表示されます: + +``` +! my-skill 2 files changed since install + modified SKILL.md + # My Skill + - Run the tests. + + Run the tests with -race. + added NOTES.md + + my notes +``` ::: :::tip モノレポでの挙動 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/update.md b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/update.md index b20a109cf..6cfbb6a0d 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/update.md +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/update.md @@ -379,13 +379,13 @@ skillshare update _team-skills --force skillshare がリポジトリの git status を読み取れない場合、そのリポジトリの更新は `failed to check git status` で失敗します。`--force` を使うとこのチェックをスキップします。 -リポジトリからインストールした skill も同様に保護されます。ファイルがインストール時に記録したものと一致しなくなると、`update` はその skill をスキップして `local changes since install` と報告し、`skillshare check` は modified として一覧表示します。変更を残したい場合は別の場所にコピーしてから、破棄します。 +リポジトリからインストールした skill も同様に保護されます。ファイルがインストール時に記録したものと一致しなくなると、`update` はその skill をスキップして `local changes since install` と報告し、`skillshare check` は modified として一覧表示し、`skillshare check --diff` は加えた変更を表示します。変更を残したい場合は別の場所にコピーしてから、破棄します。 ```bash skillshare update my-skill --force ``` -ダッシュボードの **Updates** タブでは、その skill に **Modified locally** と表示されます。更新する前に **Force overwrite local edits** にチェックを入れるか、スキップされた行の **Force Retry** を使います。skill 自身のページから更新する場合は、変更を破棄する前に確認が表示されます。`update --dry-run` は、その skill をスキップ対象として報告します。upstream で削除された modified の skill も、`--prune` を付けても `--force` を付けるまで保持されます。 +ダッシュボードの **Updates** タブでは、その skill に **Modified locally** と、変更を skill のページで開く **View changes** ボタンが表示されます。更新する前に **Force overwrite local edits** にチェックを入れるか、スキップされた行の **Force Retry** を使います。skill 自身のページから更新する場合は、変更を表示したうえで、破棄する前に確認します。`update --dry-run` は、その skill をスキップ対象として報告します。upstream で削除された modified の skill も、`--prune` を付けても `--force` を付けるまで保持されます。 ## 更新後 diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/check.md b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/check.md index 6886cef09..fc47f30a5 100644 --- a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/check.md +++ b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/check.md @@ -13,6 +13,7 @@ skillshare check a b c # Check multiple skills skillshare check --group frontend # Check all skills in frontend/ skillshare check x -G backend # Mix names and groups skillshare check --json # Machine-readable output +skillshare check my-skill --diff # Show what you changed in a skill since install ``` ## 언제 사용하나요 @@ -124,6 +125,7 @@ skillshare check frontend # Auto-detected as group | `--project`, `-p` | project 수준 skill 확인(`.skillshare/`) | | `--global`, `-g` | global skill 확인(`~/.config/skillshare`) | | `--json` | JSON으로 출력(스크립팅/CI용) | +| `--diff` | 지정한 skill에 대해 설치 이후 변경된 각 파일을 설치된 버전과의 줄 단위 diff로 보여줍니다. 이름 또는 `--group`이 필요하며 `--json`과 함께 사용할 수 없습니다 | | `--help`, `-h` | 도움말 표시 | :::tip Auto-detection @@ -176,6 +178,18 @@ skill의 하위 디렉터리가 업스트림에서 이름이 바뀌거나 삭제 :::info 로컬에서 수정된 skills 설치한 뒤 편집한 skill은 upstream에 더 새로운 버전이 있어도 **modified**로 보고되며, 이때 `message`는 `update available upstream`으로 끝납니다. `update`는 `skillshare update --force`를 실행하기 전까지 이 skill을 건드리지 않습니다. 이 명령은 변경 사항을 버리고 다시 설치합니다. + +먼저 변경 사항을 보려면 `skillshare check --diff`를 실행하세요. skill이 설치된 commit을 가져오므로 upstream이 앞서 나가 있어도 diff에는 직접 수정한 내용만 표시됩니다: + +``` +! my-skill 2 files changed since install + modified SKILL.md + # My Skill + - Run the tests. + + Run the tests with -race. + added NOTES.md + + my notes +``` ::: :::tip Monorepo awareness diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/update.md b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/update.md index 1d998a22e..7e40e64c2 100644 --- a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/update.md +++ b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/update.md @@ -379,13 +379,13 @@ skillshare update _team-skills --force skillshare가 repo의 git status를 읽을 수 없으면 해당 repo의 업데이트는 `failed to check git status`로 실패합니다. `--force`를 사용하면 이 확인을 건너뜁니다. -저장소에서 설치한 skill도 같은 방식으로 보호됩니다. 파일이 설치 시 기록된 파일과 더 이상 일치하지 않으면 `update`는 해당 skill을 건너뛰고 `local changes since install`을 보고하며, `skillshare check`는 이를 modified로 나열합니다. 변경 사항을 보존하려면 다른 곳에 복사해 둔 뒤 버리세요. +저장소에서 설치한 skill도 같은 방식으로 보호됩니다. 파일이 설치 시 기록된 파일과 더 이상 일치하지 않으면 `update`는 해당 skill을 건너뛰고 `local changes since install`을 보고하며, `skillshare check`는 이를 modified로 나열하고, `skillshare check --diff`는 변경한 내용을 보여줍니다. 변경 사항을 보존하려면 다른 곳에 복사해 둔 뒤 버리세요. ```bash skillshare update my-skill --force ``` -대시보드의 **Updates** 탭에서는 해당 skill이 **Modified locally**로 표시됩니다. 업데이트하기 전에 **Force overwrite local edits**를 선택하거나, 건너뛴 행의 **Force Retry**를 사용하세요. skill 자체 페이지에서 업데이트하면 변경 사항을 버리기 전에 확인을 요청합니다. `update --dry-run`은 이 skill을 건너뛸 대상으로 보고합니다. upstream에서도 삭제된 modified skill은 `--prune`을 사용해도 `--force`를 추가하기 전까지 유지됩니다. +대시보드의 **Updates** 탭에서는 해당 skill이 **Modified locally**로 표시되고, 변경 사항을 skill 페이지에서 열어 보는 **View changes** 버튼이 나타납니다. 업데이트하기 전에 **Force overwrite local edits**를 선택하거나, 건너뛴 행의 **Force Retry**를 사용하세요. skill 자체 페이지에서 업데이트하면 변경 사항을 보여 주고 버리기 전에 확인을 요청합니다. `update --dry-run`은 이 skill을 건너뛸 대상으로 보고합니다. upstream에서도 삭제된 modified skill은 `--prune`을 사용해도 `--force`를 추가하기 전까지 유지됩니다. ## 업데이트 후 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/check.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/check.md index ccc39cd4b..2a0c9cb7c 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/check.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/check.md @@ -13,6 +13,7 @@ skillshare check a b c # 检查多个 skills skillshare check --group frontend # 检查 frontend/ 中的所有 skill skillshare check x -G backend # 混合使用名称和 group skillshare check --json # 机器可读输出 +skillshare check my-skill --diff # 显示安装后你对 skill 所做的修改 ``` ## 何时使用 @@ -124,6 +125,7 @@ skillshare check frontend # 自动识别为 group | `--project`, `-p` | 检查 project 级别的 skills(`.skillshare/`) | | `--global`, `-g` | 检查 global skills(`~/.config/skillshare`) | | `--json` | 以 JSON 输出(用于脚本/CI) | +| `--diff` | 针对指定的 skills,以行 diff 的形式显示自安装以来每个被修改的文件(与已安装版本比较)。需要指定名称或 `--group`;不能与 `--json` 同时使用 | | `--help`, `-h` | 显示帮助 | :::tip 自动检测 @@ -176,6 +178,18 @@ skillshare check --json :::info 本地修改过的 skills 安装后被你编辑过的 skill 会被报告为 **modified**,即使 upstream 已有更新版本;此时其 `message` 以 `update available upstream` 结尾。在你运行 `skillshare update --force` 之前,`update` 不会处理它;该命令会丢弃你的更改并重新安装。 + +如需先查看更改内容,请运行 `skillshare check --diff`。它会获取该 skill 安装时所在的 commit,因此即使 upstream 已经前进,diff 也只显示你自己的修改: + +``` +! my-skill 2 files changed since install + modified SKILL.md + # My Skill + - Run the tests. + + Run the tests with -race. + added NOTES.md + + my notes +``` ::: :::tip Monorepo 感知 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/update.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/update.md index b065b8659..16656483e 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/update.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/update.md @@ -379,13 +379,13 @@ skillshare update _team-skills --force 如果 skillshare 无法读取该仓库的 git status,该仓库的更新会以 `failed to check git status` 失败;`--force` 会跳过此检查。 -从仓库安装的 skill 同样受到保护。当它的文件与安装时记录的文件不再一致时,`update` 会跳过它并报告 `local changes since install`;`skillshare check` 会将其列为 modified。如果想保留你的修改,请先复制到别处,然后再丢弃它们: +从仓库安装的 skill 同样受到保护。当它的文件与安装时记录的文件不再一致时,`update` 会跳过它并报告 `local changes since install`;`skillshare check` 会将其列为 modified,`skillshare check --diff` 会显示你改了什么。如果想保留你的修改,请先复制到别处,然后再丢弃它们: ```bash skillshare update my-skill --force ``` -在 dashboard 的 **Updates** 标签页中,该 skill 显示为 **Modified locally**;更新前请勾选 **Force overwrite local edits**,或对被跳过的行使用 **Force Retry**。从该 skill 自己的页面更新时,会在丢弃更改前询问。`update --dry-run` 会将该 skill 报告为将被跳过。若一个 modified 的 skill 同时已在 upstream 被删除,即使使用 `--prune`,在你加上 `--force` 之前也会保留它。 +在 dashboard 的 **Updates** 标签页中,该 skill 显示为 **Modified locally**,并有 **View changes** 按钮,可在该 skill 的页面查看更改;更新前请勾选 **Force overwrite local edits**,或对被跳过的行使用 **Force Retry**。从该 skill 自己的页面更新时,会显示这些更改,并在丢弃前询问。`update --dry-run` 会将该 skill 报告为将被跳过。若一个 modified 的 skill 同时已在 upstream 被删除,即使使用 `--prune`,在你加上 `--force` 之前也会保留它。 ## 更新之后 diff --git a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/check.md b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/check.md index 3abf794e7..9f80253cf 100644 --- a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/check.md +++ b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/check.md @@ -13,6 +13,7 @@ skillshare check a b c # 檢查多個 skills skillshare check --group frontend # 檢查 frontend/ 下所有 skills skillshare check x -G backend # 混用名稱與群組 skillshare check --json # 機器可讀輸出 +skillshare check my-skill --diff # 顯示安裝後你對 skill 所做的修改 ``` ## 使用時機 @@ -124,6 +125,7 @@ skillshare check frontend # 自動偵測為群組 | `--project`, `-p` | 檢查 project 層級的 skills(`.skillshare/`) | | `--global`, `-g` | 檢查 global skills(`~/.config/skillshare`) | | `--json` | 以 JSON 輸出(供 scripting/CI 使用) | +| `--diff` | 針對指定的 skills,以行 diff 的形式顯示自安裝以來每個被修改的檔案(與已安裝版本比較)。需要指定名稱或 `--group`;不能與 `--json` 同時使用 | | `--help`, `-h` | 顯示說明 | :::tip 自動偵測 @@ -176,6 +178,18 @@ skillshare check --json :::info 本機修改過的 skills 安裝後被你編輯過的 skill 會被回報為 **modified**,即使 upstream 已有更新版本;此時其 `message` 以 `update available upstream` 結尾。在你執行 `skillshare update --force` 之前,`update` 不會動它;該指令會捨棄你的變更並重新安裝。 + +如需先查看變更內容,請執行 `skillshare check --diff`。它會取得該 skill 安裝時所在的 commit,因此即使 upstream 已經前進,diff 也只顯示你自己的修改: + +``` +! my-skill 2 files changed since install + modified SKILL.md + # My Skill + - Run the tests. + + Run the tests with -race. + added NOTES.md + + my notes +``` ::: :::tip Monorepo 感知 diff --git a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/update.md b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/update.md index c92af5e10..0c8f74083 100644 --- a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/update.md +++ b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/update.md @@ -379,13 +379,13 @@ skillshare update _team-skills --force 如果 skillshare 無法讀取該儲存庫的 git status,該儲存庫的更新會以 `failed to check git status` 失敗;`--force` 會略過此檢查。 -從儲存庫安裝的 skill 同樣受到保護。當它的檔案與安裝時記錄的檔案不再一致時,`update` 會略過它並回報 `local changes since install`;`skillshare check` 會將其列為 modified。如果想保留你的修改,請先複製到別處,再捨棄它們: +從儲存庫安裝的 skill 同樣受到保護。當它的檔案與安裝時記錄的檔案不再一致時,`update` 會略過它並回報 `local changes since install`;`skillshare check` 會將其列為 modified,`skillshare check --diff` 會顯示你改了什麼。如果想保留你的修改,請先複製到別處,再捨棄它們: ```bash skillshare update my-skill --force ``` -在 dashboard 的 **Updates** 分頁中,該 skill 顯示為 **Modified locally**;更新前請勾選 **Force overwrite local edits**,或對被略過的列使用 **Force Retry**。從該 skill 自己的頁面更新時,會在捨棄變更前詢問。`update --dry-run` 會將該 skill 回報為將被略過。若一個 modified 的 skill 同時已在 upstream 被刪除,即使使用 `--prune`,在你加上 `--force` 之前也會保留它。 +在 dashboard 的 **Updates** 分頁中,該 skill 顯示為 **Modified locally**,並有 **View changes** 按鈕,可於該 skill 的頁面查看變更;更新前請勾選 **Force overwrite local edits**,或對被略過的列使用 **Force Retry**。從該 skill 自己的頁面更新時,會顯示這些變更,並在捨棄前詢問。`update --dry-run` 會將該 skill 回報為將被略過。若一個 modified 的 skill 同時已在 upstream 被刪除,即使使用 `--prune`,在你加上 `--force` 之前也會保留它。 ## 更新後 diff --git a/wiki/audit.md b/wiki/audit.md index 667f9cb5f..96bb83e21 100644 --- a/wiki/audit.md +++ b/wiki/audit.md @@ -45,6 +45,8 @@ Compare routes in `internal/server/server.go`, `handler_*.go` files, handler tes `GET /api/check` and the `done` event of `GET /api/check/stream` return the same `linked_repos` field separately from `tracked_repos`. Linked checkouts are excluded from Git checks and work-unit totals. Dashboard update endpoints return a `skipped` result for them before running Git, including force retries and skills within those checkouts. +`GET /api/resources/{name}/local-changes` (`name` is the skill's relative path) returns `{files: [{path, status, diff}]}` with `status` `modified`, `added` or `deleted`, each diffed against the commit the skill was installed at; it backs the same comparison as `check --diff` through `install.LocalChanges`. Skills without an install record of their own (local, tracked, no recorded hashes) are 404. + Source-link endpoints (skills only, in the dashboard's current global/project mode): | Endpoint | Request | Response |