mission control for agent skills
Go agent-skillsagent-toolsai-agentsai-toolsai-workflowclaude-codeclicoding-agentscommand-line-tooldeveloper-toolsgoopencodeproductivity-toolsskill-discoveryskill-managementskillsterminal-appterminal-uituiworkflow-automation
fix: harden restore against state changes
Alvin Unreal559224599f0f
diff --git a/README.md b/README.mdindex e77675b..238edb6 100644--- a/README.md+++ b/README.md@@ -121,7 +121,7 @@ lazyskills restore --project code-review tddlazyskills restore --global --yes```-Without a scope flag, restore checks both scopes. Installed skills are left unchanged.+Without a scope flag, restore checks both scopes. Before each install it rescans and revalidates that skill’s lock identity and restore command, then aborts without running remaining commands if the skill disappeared, its lock metadata changed, or its command changed—reporting any skills already restored. That narrows races with concurrent installs; it does not make restore fully race-free.## 🔄 Updatesdiff --git a/cmd/lazyskills/restore.go b/cmd/lazyskills/restore.goindex adf9a88..8840231 100644--- a/cmd/lazyskills/restore.go+++ b/cmd/lazyskills/restore.go@@ -6,6 +6,8 @@ import ("fmt""io""os"+ "reflect"+ "slices""strings""github.com/alvinunreal/lazyskills/internal/actions"@@ -21,6 +23,15 @@ var (restoreInput io.Reader = os.Stdin)+type restorePlanItem struct {+ name string+ scope model.Scope+ localLock *model.LocalLockEntry+ globalLock *model.GlobalLockEntry+ program string+ args []string+}+func runRestore(args []string) error {fs := flag.NewFlagSet("restore", flag.ContinueOnError)fs.SetOutput(os.Stderr)@@ -63,6 +74,11 @@ func runRestore(args []string) error {return nil}+ // Immutable plan from the user-visible preview baseline.+ plan, err := restoreBuildPlan(candidates, restoreResolveSkillsCommand)+ if err != nil {+ return err+ }preview := actions.ForRestoreWithResolver(candidates, restoreResolveSkillsCommand)if !preview.Available {return fmt.Errorf("restore unavailable: %s", preview.Reason)@@ -86,24 +102,47 @@ func runRestore(args []string) error {if err != nil {return err}- latestPreview := actions.ForRestoreWithResolver(restoreCandidates(latest.Skills, *global, *project, names), restoreResolveSkillsCommand)- if !latestPreview.Available || latestPreview.Command != preview.Command {+ latestPlan, err := restoreBuildPlan(restoreCandidates(latest.Skills, *global, *project, names), restoreResolveSkillsCommand)+ if err != nil {+ return fmt.Errorf("skill state changed after preview; %w", err)+ }+ if !restorePlansEqual(plan, latestPlan) {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)+ var succeeded []string+ for _, item := range plan {+ current, err := restoreScan(*cwd)+ if err != nil {+ return restorePartialError(succeeded, err)+ }+ skill := restoreLookupMissing(current.Skills, item.name, item.scope)+ if skill == nil {+ return restorePartialError(succeeded, fmt.Errorf("skill state changed after preview; [%s] %s is no longer missing; run restore again", item.scope, item.name))+ }+ if !restoreLockIdentityEqual(skill, item) {+ return restorePartialError(succeeded, fmt.Errorf("skill state changed after preview; [%s] %s lock metadata changed; run restore again", item.scope, item.name))+ }+ program, args, ok, reason := restoreSkillCommand(skill, restoreResolveSkillsCommand)+ if !ok {+ return restorePartialError(succeeded, fmt.Errorf("skill state changed after preview; [%s] %s restore command unavailable: %s; run restore again", item.scope, item.name, reason))+ }+ if program != item.program || !slices.Equal(args, item.args) {+ return restorePartialError(succeeded, fmt.Errorf("skill state changed after preview; [%s] %s restore command changed; run restore again", item.scope, item.name))+ }++ execResult := restoreRunExec(runner.ExecSpec{Program: program, Args: args, Cwd: *cwd})+ if execResult.ExitCode != 0 || execResult.Err != "" {+ if execResult.Stderr != "" {+ fmt.Fprintln(os.Stderr, execResult.Stderr)}- detail := result.Err+ detail := execResult.Errif detail == "" {- detail = fmt.Sprintf("exit code %d", result.ExitCode)+ detail = fmt.Sprintf("exit code %d", execResult.ExitCode)}- return fmt.Errorf("restore command failed: %s", detail)+ return restorePartialError(succeeded, fmt.Errorf("restore command failed for [%s] %s: %s", item.scope, item.name, detail))}+ succeeded = append(succeeded, restoreQualifiedName(item.scope, item.name))}fmt.Fprintln(os.Stdout, "Restore complete.")return nil@@ -128,3 +167,102 @@ func restoreCandidates(skills []*model.Skill, globalOnly, projectOnly bool, name}return candidates}++func restoreBuildPlan(candidates []*model.Skill, resolve actions.SkillsResolver) ([]restorePlanItem, error) {+ plan := make([]restorePlanItem, 0, len(candidates))+ for _, skill := range candidates {+ program, args, ok, reason := restoreSkillCommand(skill, resolve)+ if !ok {+ return nil, fmt.Errorf("restore unavailable: %s", reason)+ }+ plan = append(plan, restorePlanItem{+ name: skill.Name,+ scope: skill.Scope,+ localLock: cloneLocalLock(skill.LocalLock),+ globalLock: cloneGlobalLock(skill.GlobalLock),+ program: program,+ args: args,+ })+ }+ return plan, nil+}++func restorePlansEqual(a, b []restorePlanItem) bool {+ if len(a) != len(b) {+ return false+ }+ for i := range a {+ if a[i].name != b[i].name || a[i].scope != b[i].scope {+ return false+ }+ if !reflect.DeepEqual(a[i].localLock, b[i].localLock) || !reflect.DeepEqual(a[i].globalLock, b[i].globalLock) {+ return false+ }+ if a[i].program != b[i].program || !slices.Equal(a[i].args, b[i].args) {+ return false+ }+ }+ return true+}++func restoreSkillCommand(skill *model.Skill, resolve actions.SkillsResolver) (string, []string, bool, string) {+ preview := actions.ForRestoreWithResolver([]*model.Skill{skill}, resolve)+ if !preview.Available {+ return "", nil, false, preview.Reason+ }+ if len(preview.Exec.Batch) != 1 {+ return "", nil, false, "unexpected restore command batch"+ }+ spec := preview.Exec.Batch[0]+ return spec.Program, append([]string{}, spec.Args...), true, ""+}++func restoreLookupMissing(skills []*model.Skill, name string, scope model.Scope) *model.Skill {+ for _, skill := range skills {+ if skill == nil || skill.Name != name || skill.Scope != scope {+ continue+ }+ if actions.IsMissingLockedSkill(skill) {+ return skill+ }+ return nil+ }+ return nil+}++func restoreLockIdentityEqual(skill *model.Skill, item restorePlanItem) bool {+ if skill == nil {+ return false+ }+ return reflect.DeepEqual(skill.LocalLock, item.localLock) && reflect.DeepEqual(skill.GlobalLock, item.globalLock)+}++func restoreQualifiedName(scope model.Scope, name string) string {+ return fmt.Sprintf("[%s] %s", scope, name)+}++func restorePartialError(succeeded []string, err error) error {+ if err == nil {+ return nil+ }+ if len(succeeded) == 0 {+ return err+ }+ return fmt.Errorf("partial restore; already restored: %s; %w", strings.Join(succeeded, ", "), err)+}++func cloneLocalLock(lock *model.LocalLockEntry) *model.LocalLockEntry {+ if lock == nil {+ return nil+ }+ copy := *lock+ return ©+}++func cloneGlobalLock(lock *model.GlobalLockEntry) *model.GlobalLockEntry {+ if lock == nil {+ return nil+ }+ copy := *lock+ return ©+}diff --git a/cmd/lazyskills/restore_test.go b/cmd/lazyskills/restore_test.goindex 70df139..f1b70e9 100644--- a/cmd/lazyskills/restore_test.go+++ b/cmd/lazyskills/restore_test.go@@ -9,7 +9,9 @@ import ()func TestRestoreGlobalOnly(t *testing.T) {+ scans := 0harness := useRestoreHarness(t, func(cwd string) (model.ScanResult, error) {+ scans++return model.ScanResult{Cwd: cwd, Skills: []*model.Skill{missingRestoreSkill("Global Missing", model.ScopeGlobal),missingRestoreSkill("Project Missing", model.ScopeProject),@@ -32,6 +34,10 @@ func TestRestoreGlobalOnly(t *testing.T) {if !strings.Contains(out, "Restore 1 missing skill") || !strings.Contains(out, "Global Missing") {t.Fatalf("expected restore preview, got %q", out)}+ // initial + post-confirm plan check + one pre-exec recheck+ if scans != 3 {+ t.Fatalf("expected 3 scans for one successful restore, got %d", scans)+ }}func TestRestoreConfirmationDefaultsToCancel(t *testing.T) {@@ -55,7 +61,9 @@ func TestRestoreConfirmationDefaultsToCancel(t *testing.T) {}func TestRestoreSelectedProjectSkill(t *testing.T) {+ scans := 0harness := useRestoreHarness(t, func(cwd string) (model.ScanResult, error) {+ scans++return model.ScanResult{Cwd: cwd, Skills: []*model.Skill{missingRestoreSkill("Project One", model.ScopeProject),missingRestoreSkill("Project Two", model.ScopeProject),@@ -73,6 +81,10 @@ func TestRestoreSelectedProjectSkill(t *testing.T) {if strings.Contains(out, "Project Two") || strings.Contains(out, "[global]") {t.Fatalf("unselected skill leaked into preview: %q", out)}+ // initial + post-confirm plan check + one pre-exec recheck+ if scans != 3 {+ t.Fatalf("expected 3 scans for one successful restore, got %d", scans)+ }}func TestRestoreAbortsWhenMissingStateChanges(t *testing.T) {@@ -97,6 +109,174 @@ func TestRestoreAbortsWhenMissingStateChanges(t *testing.T) {}}+func TestRestoreAbortsWhenInstalledAfterFinalScan(t *testing.T) {+ scans := 0+ harness := useRestoreHarness(t, func(cwd string) (model.ScanResult, error) {+ scans+++ skill := missingRestoreSkill("Global Skill", model.ScopeGlobal)+ // scans 1-2: initial + post-confirm check still missing; scan 3: pre-exec finds it installed+ if scans >= 3 {+ 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(), "no longer missing") {+ t.Fatalf("expected no-longer-missing error, got %v", err)+ }+ if len(harness.calls) != 0 {+ t.Fatal("restore ran after post-final-scan install")+ }+ if scans != 3 {+ t.Fatalf("expected 3 scans, got %d", scans)+ }+}++func TestRestoreAbortsWhenLockMetadataChangesOnPostConfirmScan(t *testing.T) {+ scans := 0+ harness := useRestoreHarness(t, func(cwd string) (model.ScanResult, error) {+ scans+++ skill := missingRestoreSkill("Global Skill", model.ScopeGlobal)+ // scan 2: after preview / before any exec — lock identity diverges from initial plan+ if scans >= 2 {+ skill.GlobalLock = &model.GlobalLockEntry{Source: "owner/changed"}+ }+ 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 state-changed error, got %v", err)+ }+ if len(harness.calls) != 0 {+ t.Fatal("restore ran after lock metadata changed on post-confirm scan")+ }+ if scans != 2 {+ t.Fatalf("expected abort after post-confirm scan only, got %d scans", scans)+ }+}++func TestRestoreAbortsWhenLockMetadataChangesBeforeExec(t *testing.T) {+ scans := 0+ harness := useRestoreHarness(t, func(cwd string) (model.ScanResult, error) {+ scans+++ skill := missingRestoreSkill("Global Skill", model.ScopeGlobal)+ if scans >= 3 {+ skill.GlobalLock = &model.GlobalLockEntry{Source: "owner/changed"}+ }+ 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(), "lock metadata changed") {+ t.Fatalf("expected lock-metadata error, got %v", err)+ }+ if len(harness.calls) != 0 {+ t.Fatal("restore ran after lock metadata changed")+ }+ if scans != 3 {+ t.Fatalf("expected 3 scans, got %d", scans)+ }+}++func TestRestoreAbortsWhenOneOfMultipleInstalledOnPostConfirmScan(t *testing.T) {+ scans := 0+ harness := useRestoreHarness(t, func(cwd string) (model.ScanResult, error) {+ scans+++ first := missingRestoreSkill("First", model.ScopeGlobal)+ second := missingRestoreSkill("Second", model.ScopeGlobal)+ // scan 2: one planned candidate is already installed — must not exec the other+ if scans >= 2 {+ first.HealthIssues = nil+ first.CanonicalPath = "/tmp/first"+ }+ return model.ScanResult{Cwd: cwd, Skills: []*model.Skill{first, second}}, nil+ })++ _, err := captureRunStdout(t, []string{"restore", "--global", "--yes", "--cwd", t.TempDir()})+ if err == nil || !strings.Contains(err.Error(), "skill state changed") {+ t.Fatalf("expected state-changed error, got %v", err)+ }+ if len(harness.calls) != 0 {+ t.Fatalf("expected no exec when post-confirm plan diverges, got %#v", harness.calls)+ }+ if scans != 2 {+ t.Fatalf("expected abort after post-confirm scan only, got %d scans", scans)+ }+}++func TestRestorePartialWhenLaterSkillInstalledAfterFirstSuccess(t *testing.T) {+ scans := 0+ harness := useRestoreHarness(t, func(cwd string) (model.ScanResult, error) {+ scans+++ first := missingRestoreSkill("First", model.ScopeGlobal)+ second := missingRestoreSkill("Second", model.ScopeGlobal)+ // After first success, pre-exec recheck for second (scan 4) sees it installed.+ if scans >= 4 {+ second.HealthIssues = nil+ second.CanonicalPath = "/tmp/second"+ }+ return model.ScanResult{Cwd: cwd, Skills: []*model.Skill{first, second}}, nil+ })++ _, err := captureRunStdout(t, []string{"restore", "--global", "--yes", "--cwd", t.TempDir()})+ if err == nil {+ t.Fatal("expected partial restore error")+ }+ msg := err.Error()+ if !strings.Contains(msg, "partial restore") || !strings.Contains(msg, "[global] First") || !strings.Contains(msg, "no longer missing") {+ t.Fatalf("expected partial success naming First, got %v", err)+ }+ if len(harness.calls) != 1 || !containsRestoreArg(harness.calls[0].Args, "First") {+ t.Fatalf("expected only first restore exec, got %#v", harness.calls)+ }+ if scans != 4 {+ t.Fatalf("expected 4 scans, got %d", scans)+ }+}++func TestRestorePartialWhenExecutorFailsAfterFirstSuccess(t *testing.T) {+ scans := 0+ harness := useRestoreHarness(t, func(cwd string) (model.ScanResult, error) {+ scans+++ return model.ScanResult{Cwd: cwd, Skills: []*model.Skill{+ missingRestoreSkill("First", model.ScopeGlobal),+ missingRestoreSkill("Second", model.ScopeGlobal),+ missingRestoreSkill("Third", model.ScopeGlobal),+ }}, nil+ })+ oldRun := restoreRunExec+ t.Cleanup(func() { restoreRunExec = oldRun })+ restoreRunExec = func(spec runner.ExecSpec) runner.Result {+ harness.calls = append(harness.calls, spec)+ if len(harness.calls) >= 2 {+ return runner.Result{Program: spec.Program, Args: spec.Args, Cwd: spec.Cwd, ExitCode: 2, Err: "installer failed"}+ }+ return runner.Result{Program: spec.Program, Args: spec.Args, Cwd: spec.Cwd, ExitCode: 0}+ }++ _, err := captureRunStdout(t, []string{"restore", "--global", "--yes", "--cwd", t.TempDir()})+ if err == nil {+ t.Fatal("expected partial restore error")+ }+ msg := err.Error()+ if !strings.Contains(msg, "partial restore") || !strings.Contains(msg, "[global] First") || !strings.Contains(msg, "[global] Second") || !strings.Contains(msg, "installer failed") {+ t.Fatalf("expected partial executor failure naming First and Second, got %v", err)+ }+ if len(harness.calls) != 2 {+ t.Fatalf("expected first success and second failure only (third skipped), got %#v", harness.calls)+ }+ if !containsRestoreArg(harness.calls[0].Args, "First") || !containsRestoreArg(harness.calls[1].Args, "Second") {+ t.Fatalf("unexpected exec order: %#v", harness.calls)+ }+ // initial + post-confirm plan check + pre-exec for first and second only+ if scans != 4 {+ t.Fatalf("expected 4 scans, got %d", scans)+ }+}+type restoreHarness struct {calls []runner.ExecSpec}