Skip to content

mission control for agent skills

feat: restore missing locked skills

dongdongbh0172490c4abf
diff --git a/README.md b/README.md
index 65a2fe7..e77675b 100644
--- a/README.md
+++ b/README.md
@@ -104,6 +104,25 @@ For agent-friendly registry search without opening the TUI:
lazyskills find --json "browser automation"
```
+### Restore from lock files
+
+Restore skills that are recorded in the project or global lock file but missing from disk:
+
+```bash
+lazyskills restore --global
+lazyskills restore --project
+lazyskills restore --all
+```
+
+Pass skill names to restore only those entries, or `--yes` to accept the preview non-interactively:
+
+```bash
+lazyskills restore --project code-review tdd
+lazyskills restore --global --yes
+```
+
+Without a scope flag, restore checks both scopes. Installed skills are left unchanged.
+
## 🔄 Updates
LazySkills can check for new releases and show the command to update your installation manually.
diff --git a/cmd/lazyskills/main.go b/cmd/lazyskills/main.go
index 9e71776..b9d4001 100644
--- a/cmd/lazyskills/main.go
+++ b/cmd/lazyskills/main.go
@@ -161,6 +161,9 @@ func run(args []string) error {
fmt.Fprintln(os.Stdout, "Already up to date.")
return nil
}
+ if len(args) > 0 && args[0] == "restore" {
+ return runRestore(args[1:])
+ }
if len(args) == 0 {
cwd, err := os.Getwd()
if err != nil {
@@ -176,7 +179,7 @@ func run(args []string) error {
return err
}
if fs.NArg() > 0 {
- return fmt.Errorf("usage: lazyskills [--cwd <path>] | lazyskills scan --json [--cwd <path>] | lazyskills update [--check] [--print-command] | lazyskills find --json <query> | lazyskills version")
+ return fmt.Errorf("usage: lazyskills [--cwd <path>] | lazyskills scan --json [--cwd <path>] | lazyskills restore [--global|--project|--all] [--yes] [skills...] | lazyskills update [--check] [--print-command] | lazyskills find --json <query> | lazyskills version")
}
if *cwd == "" {
var err error
diff --git a/cmd/lazyskills/main_test.go b/cmd/lazyskills/main_test.go
index 4c7d03e..8723be5 100644
--- a/cmd/lazyskills/main_test.go
+++ b/cmd/lazyskills/main_test.go
@@ -30,8 +30,6 @@ func (m *mockFetcher) FetchRelease(ctx context.Context, url string) (*selfupdate
func TestCLIUpdate(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
- oldOut := os.Stdout
- defer func() { os.Stdout = oldOut }()
oldVer := buildinfo.Version
oldCommit := buildinfo.Commit
@@ -51,23 +49,8 @@ func TestCLIUpdate(t *testing.T) {
selfupdate.DefaultPlanFetcher = &mockFetcher{release: mockRel}
defer func() { selfupdate.DefaultPlanFetcher = nil }()
- // Help function to capture stdout during run
- captureStdout := func(args []string) (string, error) {
- r, w, _ := os.Pipe()
- os.Stdout = w
-
- err := run(args)
-
- w.Close()
- var buf bytes.Buffer
- _, _ = io.Copy(&buf, r)
- os.Stdout = oldOut
-
- return buf.String(), err
- }
-
// 1. Check only
- out, err := captureStdout([]string{"update", "--check"})
+ out, err := captureRunStdout(t, []string{"update", "--check"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -76,7 +59,7 @@ func TestCLIUpdate(t *testing.T) {
}
// 2. Print command
- out, err = captureStdout([]string{"update", "--print-command"})
+ out, err = captureRunStdout(t, []string{"update", "--print-command"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -90,7 +73,7 @@ func TestCLIUpdate(t *testing.T) {
}
// 3. Default (no --yes)
- out, err = captureStdout([]string{"update"})
+ out, err = captureRunStdout(t, []string{"update"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -99,7 +82,7 @@ func TestCLIUpdate(t *testing.T) {
}
// 4. Test --yes returns non-zero error before calling Plan
- _, errYes := captureStdout([]string{"update", "--yes"})
+ _, errYes := captureRunStdout(t, []string{"update", "--yes"})
if errYes == nil {
t.Fatal("expected error with --yes, got nil")
}
@@ -110,7 +93,7 @@ func TestCLIUpdate(t *testing.T) {
// 5. Already up-to-date behavior.
buildinfo.Version = "v1.1.0"
- out, err = captureStdout([]string{"update"})
+ out, err = captureRunStdout(t, []string{"update"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -121,7 +104,7 @@ func TestCLIUpdate(t *testing.T) {
// 6. Test LAZYSKILLS_NO_UPDATE_CHECK prints the disable reason instead of Already up to date
os.Setenv("LAZYSKILLS_NO_UPDATE_CHECK", "1")
defer os.Setenv("LAZYSKILLS_NO_UPDATE_CHECK", "")
- out, err = captureStdout([]string{"update"})
+ out, err = captureRunStdout(t, []string{"update"})
if err != nil {
t.Fatalf("unexpected error with env check: %v", err)
}
@@ -146,40 +129,26 @@ func TestCLIFind(t *testing.T) {
t.Setenv("SKILLS_API_URL", server.URL)
- oldOut := os.Stdout
- defer func() { os.Stdout = oldOut }()
-
- captureStdout := func(args []string) (string, error) {
- r, w, _ := os.Pipe()
- os.Stdout = w
- err := run(args)
- w.Close()
- var buf bytes.Buffer
- _, _ = io.Copy(&buf, r)
- os.Stdout = oldOut
- return buf.String(), err
- }
-
// 1. Missing json flag
- _, err := captureStdout([]string{"find", "test-query"})
+ _, err := captureRunStdout(t, []string{"find", "test-query"})
if err == nil || !strings.Contains(err.Error(), "usage: lazyskills find --json <query>") {
t.Fatalf("expected usage error without --json, got: %v", err)
}
// 2. Missing query
- _, err = captureStdout([]string{"find", "--json"})
+ _, err = captureRunStdout(t, []string{"find", "--json"})
if err == nil || !strings.Contains(err.Error(), "usage: lazyskills find --json <query>") {
t.Fatalf("expected usage error without query, got: %v", err)
}
// 3. Multi query or too many args
- _, err = captureStdout([]string{"find", "--json", "q1", "q2"})
+ _, err = captureRunStdout(t, []string{"find", "--json", "q1", "q2"})
if err == nil || !strings.Contains(err.Error(), "usage: lazyskills find --json <query>") {
t.Fatalf("expected usage error with multiple queries, got: %v", err)
}
// 4. Success JSON
- out, err := captureStdout([]string{"find", "--json", "test-query"})
+ out, err := captureRunStdout(t, []string{"find", "--json", "test-query"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -201,3 +170,21 @@ func TestCLIFind(t *testing.T) {
t.Errorf("unexpected results: %+v", res.Results)
}
}
+
+func captureRunStdout(t *testing.T, args []string) (string, error) {
+ t.Helper()
+ oldOut := os.Stdout
+ r, w, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ os.Stdout = w
+ defer func() { os.Stdout = oldOut }()
+
+ runErr := run(args)
+ _ = w.Close()
+ var buf bytes.Buffer
+ _, _ = io.Copy(&buf, r)
+ _ = r.Close()
+ return buf.String(), runErr
+}
diff --git a/cmd/lazyskills/restore.go b/cmd/lazyskills/restore.go
new file mode 100644
index 0000000..adf9a88
--- /dev/null
+++ b/cmd/lazyskills/restore.go
@@ -0,0 +1,130 @@
+package main
+
+import (
+ "bufio"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+
+ "github.com/alvinunreal/lazyskills/internal/actions"
+ "github.com/alvinunreal/lazyskills/internal/model"
+ "github.com/alvinunreal/lazyskills/internal/runner"
+ "github.com/alvinunreal/lazyskills/internal/scan"
+)
+
+var (
+ restoreScan = scan.Run
+ restoreResolveSkillsCommand = actions.ResolveSkillsCommand
+ restoreRunExec = func(spec runner.ExecSpec) runner.Result { return (runner.OSRunner{}).Run(spec) }
+ restoreInput io.Reader = os.Stdin
+)
+
+func runRestore(args []string) error {
+ fs := flag.NewFlagSet("restore", flag.ContinueOnError)
+ fs.SetOutput(os.Stderr)
+ global := fs.Bool("global", false, "restore global skills only")
+ project := fs.Bool("project", false, "restore project skills only")
+ all := fs.Bool("all", false, "restore project and global skills")
+ yes := fs.Bool("yes", false, "skip confirmation")
+ cwd := fs.String("cwd", "", "project working directory")
+ if err := fs.Parse(args); err != nil {
+ return err
+ }
+ selectedScopes := 0
+ for _, selected := range []bool{*global, *project, *all} {
+ if selected {
+ selectedScopes++
+ }
+ }
+ if selectedScopes > 1 {
+ return fmt.Errorf("choose only one restore scope: --global, --project, or --all")
+ }
+ if *cwd == "" {
+ var err error
+ *cwd, err = os.Getwd()
+ if err != nil {
+ return err
+ }
+ }
+
+ result, err := restoreScan(*cwd)
+ if err != nil {
+ return err
+ }
+ names := map[string]bool{}
+ for _, name := range fs.Args() {
+ names[strings.ToLower(name)] = true
+ }
+ candidates := restoreCandidates(result.Skills, *global, *project, names)
+ if len(candidates) == 0 {
+ fmt.Fprintln(os.Stdout, "No missing locked skills.")
+ return nil
+ }
+
+ preview := actions.ForRestoreWithResolver(candidates, restoreResolveSkillsCommand)
+ if !preview.Available {
+ return fmt.Errorf("restore unavailable: %s", preview.Reason)
+ }
+ fmt.Fprintln(os.Stdout, preview.Title)
+ for _, skill := range candidates {
+ fmt.Fprintf(os.Stdout, " [%s] %s\n", skill.Scope, skill.Name)
+ }
+ fmt.Fprintf(os.Stdout, "Command: %s\n", preview.Command)
+ if !*yes {
+ fmt.Fprint(os.Stdout, "Continue? [y/N] ")
+ answer, _ := bufio.NewReader(restoreInput).ReadString('\n')
+ answer = strings.ToLower(strings.TrimSpace(answer))
+ if answer != "y" && answer != "yes" {
+ fmt.Fprintln(os.Stdout, "Restore cancelled.")
+ return nil
+ }
+ }
+
+ latest, err := restoreScan(*cwd)
+ if err != nil {
+ return err
+ }
+ latestPreview := actions.ForRestoreWithResolver(restoreCandidates(latest.Skills, *global, *project, names), restoreResolveSkillsCommand)
+ if !latestPreview.Available || latestPreview.Command != preview.Command {
+ return fmt.Errorf("skill state changed after preview; run restore again")
+ }
+ preview = latestPreview
+
+ for _, spec := range preview.Exec.Batch {
+ result := restoreRunExec(runner.ExecSpec{Program: spec.Program, Args: spec.Args, Cwd: *cwd})
+ if result.ExitCode != 0 || result.Err != "" {
+ if result.Stderr != "" {
+ fmt.Fprintln(os.Stderr, result.Stderr)
+ }
+ detail := result.Err
+ if detail == "" {
+ detail = fmt.Sprintf("exit code %d", result.ExitCode)
+ }
+ return fmt.Errorf("restore command failed: %s", detail)
+ }
+ }
+ fmt.Fprintln(os.Stdout, "Restore complete.")
+ return nil
+}
+
+func restoreCandidates(skills []*model.Skill, globalOnly, projectOnly bool, names map[string]bool) []*model.Skill {
+ candidates := make([]*model.Skill, 0, len(skills))
+ for _, skill := range skills {
+ if !actions.IsMissingLockedSkill(skill) {
+ continue
+ }
+ if globalOnly && skill.Scope != model.ScopeGlobal {
+ continue
+ }
+ if projectOnly && skill.Scope != model.ScopeProject {
+ continue
+ }
+ if len(names) > 0 && !names[strings.ToLower(skill.Name)] {
+ continue
+ }
+ candidates = append(candidates, skill)
+ }
+ return candidates
+}
diff --git a/cmd/lazyskills/restore_test.go b/cmd/lazyskills/restore_test.go
new file mode 100644
index 0000000..70df139
--- /dev/null
+++ b/cmd/lazyskills/restore_test.go
@@ -0,0 +1,142 @@
+package main
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/alvinunreal/lazyskills/internal/model"
+ "github.com/alvinunreal/lazyskills/internal/runner"
+)
+
+func TestRestoreGlobalOnly(t *testing.T) {
+ harness := useRestoreHarness(t, func(cwd string) (model.ScanResult, error) {
+ return model.ScanResult{Cwd: cwd, Skills: []*model.Skill{
+ missingRestoreSkill("Global Missing", model.ScopeGlobal),
+ missingRestoreSkill("Project Missing", model.ScopeProject),
+ }}, nil
+ })
+
+ out, err := captureRunStdout(t, []string{"restore", "--global", "--yes", "--cwd", t.TempDir()})
+ if err != nil {
+ t.Fatalf("restore failed: %v", err)
+ }
+ if len(harness.calls) != 1 {
+ t.Fatalf("expected one global restore command, got %#v", harness.calls)
+ }
+ if !containsRestoreArg(harness.calls[0].Args, "-g") || !containsRestoreArg(harness.calls[0].Args, "Global Missing") {
+ t.Fatalf("unexpected global restore command: %#v", harness.calls[0])
+ }
+ if strings.Contains(strings.Join(harness.calls[0].Args, " "), "Project Missing") {
+ t.Fatalf("project skill leaked into global restore: %#v", harness.calls[0])
+ }
+ if !strings.Contains(out, "Restore 1 missing skill") || !strings.Contains(out, "Global Missing") {
+ t.Fatalf("expected restore preview, got %q", out)
+ }
+}
+
+func TestRestoreConfirmationDefaultsToCancel(t *testing.T) {
+ oldInput := restoreInput
+ t.Cleanup(func() { restoreInput = oldInput })
+ harness := useRestoreHarness(t, func(cwd string) (model.ScanResult, error) {
+ return model.ScanResult{Cwd: cwd, Skills: []*model.Skill{missingRestoreSkill("Project Missing", model.ScopeProject)}}, nil
+ })
+ restoreInput = strings.NewReader("\n")
+
+ out, err := captureRunStdout(t, []string{"restore", "--cwd", t.TempDir()})
+ if err != nil {
+ t.Fatalf("cancelled restore returned an error: %v", err)
+ }
+ if len(harness.calls) != 0 {
+ t.Fatal("restore ran despite default confirmation cancellation")
+ }
+ if !strings.Contains(out, "Continue? [y/N]") || !strings.Contains(out, "Restore cancelled.") {
+ t.Fatalf("expected confirmation and cancellation output, got %q", out)
+ }
+}
+
+func TestRestoreSelectedProjectSkill(t *testing.T) {
+ harness := useRestoreHarness(t, func(cwd string) (model.ScanResult, error) {
+ return model.ScanResult{Cwd: cwd, Skills: []*model.Skill{
+ missingRestoreSkill("Project One", model.ScopeProject),
+ missingRestoreSkill("Project Two", model.ScopeProject),
+ missingRestoreSkill("Project One", model.ScopeGlobal),
+ }}, nil
+ })
+
+ out, err := captureRunStdout(t, []string{"restore", "--project", "--yes", "--cwd", t.TempDir(), "project one"})
+ if err != nil {
+ t.Fatalf("restore failed: %v", err)
+ }
+ if len(harness.calls) != 1 || containsRestoreArg(harness.calls[0].Args, "-g") || !containsRestoreArg(harness.calls[0].Args, "Project One") {
+ t.Fatalf("expected only selected project restore, got %#v", harness.calls)
+ }
+ if strings.Contains(out, "Project Two") || strings.Contains(out, "[global]") {
+ t.Fatalf("unselected skill leaked into preview: %q", out)
+ }
+}
+
+func TestRestoreAbortsWhenMissingStateChanges(t *testing.T) {
+ scans := 0
+ harness := useRestoreHarness(t, func(cwd string) (model.ScanResult, error) {
+ scans++
+ skill := missingRestoreSkill("Global Skill", model.ScopeGlobal)
+ if scans == 1 {
+ } else {
+ skill.HealthIssues = nil
+ skill.CanonicalPath = "/tmp/global-skill"
+ }
+ return model.ScanResult{Cwd: cwd, Skills: []*model.Skill{skill}}, nil
+ })
+
+ _, err := captureRunStdout(t, []string{"restore", "--global", "--yes", "--cwd", t.TempDir()})
+ if err == nil || !strings.Contains(err.Error(), "skill state changed") {
+ t.Fatalf("expected changed-state error, got %v", err)
+ }
+ if len(harness.calls) != 0 {
+ t.Fatal("restore ran after the skill was no longer missing")
+ }
+}
+
+type restoreHarness struct {
+ calls []runner.ExecSpec
+}
+
+func useRestoreHarness(t *testing.T, scanFn func(string) (model.ScanResult, error)) *restoreHarness {
+ t.Helper()
+ oldScan := restoreScan
+ oldResolve := restoreResolveSkillsCommand
+ oldRun := restoreRunExec
+ t.Cleanup(func() {
+ restoreScan = oldScan
+ restoreResolveSkillsCommand = oldResolve
+ restoreRunExec = oldRun
+ })
+
+ harness := &restoreHarness{}
+ restoreScan = scanFn
+ restoreResolveSkillsCommand = func() (string, []string) { return "skills", nil }
+ restoreRunExec = func(spec runner.ExecSpec) runner.Result {
+ harness.calls = append(harness.calls, spec)
+ return runner.Result{Program: spec.Program, Args: spec.Args, Cwd: spec.Cwd, ExitCode: 0}
+ }
+ return harness
+}
+
+func missingRestoreSkill(name string, scope model.Scope) *model.Skill {
+ skill := &model.Skill{Name: name, Scope: scope, HealthIssues: []model.HealthIssue{{Type: "lock_without_files"}}}
+ if scope == model.ScopeGlobal {
+ skill.GlobalLock = &model.GlobalLockEntry{Source: "owner/global"}
+ } else {
+ skill.LocalLock = &model.LocalLockEntry{Source: "owner/project"}
+ }
+ return skill
+}
+
+func containsRestoreArg(args []string, want string) bool {
+ for _, arg := range args {
+ if arg == want {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/actions/actions.go b/internal/actions/actions.go
index ded59f9..a2fa8a3 100644
--- a/internal/actions/actions.go
+++ b/internal/actions/actions.go
@@ -71,6 +71,35 @@ func ForSkillsWithResolver(skills []*model.Skill, resolve SkillsResolver) []Comm
return previews
}
+func ForRestoreWithResolver(skills []*model.Skill, resolve SkillsResolver) CommandPreview {
+ missing := make([]*model.Skill, 0, len(skills))
+ for _, skill := range skills {
+ if IsMissingLockedSkill(skill) {
+ missing = append(missing, skill)
+ }
+ }
+ if len(missing) == 0 {
+ return unavailablePreview("Restore missing skills", "no missing locked skills")
+ }
+ batch, ok, reason := bulkBatch(missing, resolve, "reinstall_update")
+ if !ok {
+ return unavailablePreview("Restore missing skills", reason)
+ }
+ count := len(missing)
+ noun := "skills"
+ if count == 1 {
+ noun = "skill"
+ }
+ return newBatchPreview(
+ "restore_missing",
+ fmt.Sprintf("Restore %d missing %s", count, noun),
+ batch,
+ "Reinstall locked skills whose files are missing.",
+ fmt.Sprintf("restore %d %s", count, noun),
+ false,
+ )
+}
+
func AppLevelActions() []CommandPreview {
return AppLevelActionsWithResolver(ResolveSkillsCommand)
}
@@ -318,7 +347,7 @@ func ForSkillWithResolver(sk *model.Skill, resolve SkillsResolver) []CommandPrev
} else {
previews = append(previews, unavailablePreview("Remove selected skill", reasonRemove))
}
- if hasOrphanedLock(sk) {
+ if IsMissingLockedSkill(sk) {
previews = append(previews, pruneLockPreview(sk))
}
if hasBrokenSymlink(sk) {
@@ -351,9 +380,12 @@ func SharedRootReason(path string) string {
return fmt.Sprintf("skill files are reached through a symlinked skills root (%s); write actions are disabled to protect the shared canonical source", compat.SanitizeMetadata(path))
}
-// hasOrphanedLock reports whether the skill is a lock entry whose files are
+// IsMissingLockedSkill reports whether the skill is a lock entry whose files are
// gone from disk (the scan flags this as lock_without_files).
-func hasOrphanedLock(sk *model.Skill) bool {
+func IsMissingLockedSkill(sk *model.Skill) bool {
+ if sk == nil {
+ return false
+ }
for _, issue := range sk.HealthIssues {
if issue.Type == "lock_without_files" {
return true
diff --git a/internal/actions/actions_test.go b/internal/actions/actions_test.go
index 500f84d..9cea5e5 100644
--- a/internal/actions/actions_test.go
+++ b/internal/actions/actions_test.go
@@ -141,6 +141,58 @@ func TestBulkActionsBuildBatchCommands(t *testing.T) {
}
}
+func TestRestoreBuildsBatchFromMissingLockEntries(t *testing.T) {
+ skills := []*model.Skill{
+ {
+ Name: "Project Missing",
+ Scope: model.ScopeProject,
+ LocalLock: &model.LocalLockEntry{Source: "owner/project"},
+ HealthIssues: []model.HealthIssue{{Type: "lock_without_files"}},
+ },
+ {
+ Name: "Global Missing",
+ Scope: model.ScopeGlobal,
+ GlobalLock: &model.GlobalLockEntry{Source: "owner/global"},
+ HealthIssues: []model.HealthIssue{{Type: "lock_without_files"}},
+ },
+ {
+ Name: "Already Installed",
+ Scope: model.ScopeGlobal,
+ CanonicalPath: "/tmp/already-installed",
+ GlobalLock: &model.GlobalLockEntry{Source: "owner/global"},
+ },
+ }
+
+ preview := ForRestoreWithResolver(skills, func() (string, []string) { return "skills", nil })
+ if !preview.Available || preview.ID != "restore_missing" {
+ t.Fatalf("expected available restore preview, got %#v", preview)
+ }
+ if preview.Title != "Restore 2 missing skills" || preview.ConfirmValue != "restore 2 skills" {
+ t.Fatalf("unexpected restore copy: %#v", preview)
+ }
+ if len(preview.Exec.Batch) != 2 {
+ t.Fatalf("expected only missing skills in restore batch, got %#v", preview.Exec.Batch)
+ }
+ if containsArg(preview.Exec.Batch[0].Args, "-g") {
+ t.Fatalf("project restore must not use global flag: %#v", preview.Exec.Batch[0].Args)
+ }
+ if !containsArg(preview.Exec.Batch[1].Args, "-g") {
+ t.Fatalf("global restore must use global flag: %#v", preview.Exec.Batch[1].Args)
+ }
+}
+
+func TestRestoreUsesSingularCopy(t *testing.T) {
+ preview := ForRestoreWithResolver([]*model.Skill{{
+ Name: "Only One",
+ Scope: model.ScopeProject,
+ LocalLock: &model.LocalLockEntry{Source: "owner/project"},
+ HealthIssues: []model.HealthIssue{{Type: "lock_without_files"}},
+ }}, func() (string, []string) { return "skills", nil })
+ if preview.Title != "Restore 1 missing skill" || preview.ConfirmValue != "restore 1 skill" {
+ t.Fatalf("unexpected singular restore copy: %#v", preview)
+ }
+}
+
func TestSharedRootSkillDisablesReinstallAndRemove(t *testing.T) {
sk := &model.Skill{
Name: "Shared",