fix(sync): fail only the target whose config is invalid

Any per-target config problem, such as a skills path that is a file or
an unknown mode, made `skillshare sync`, `sync -p` and the dashboard
refuse to sync anything. That contradicts the policy that sync runs
every target and reports the ones that failed. Sync now validates the
config as a whole first and still stops on global problems (source,
global mode or naming, git_root, extras); a target whose own settings
are invalid is skipped for skills and agents and reported as failed
("invalid config" in CLI output and --json details, part "config" in
the dashboard's failed list). Config validation on save is unchanged.
This commit is contained in:
Willie
2026-09-30 03:27:20 +08:00
parent d6960e46a7
commit 5dfd63d5e9
16 changed files with 489 additions and 125 deletions
+42 -11
View File
@@ -3,6 +3,7 @@ package main
import (
"fmt"
"io"
"maps"
"os"
"slices"
"strings"
@@ -204,16 +205,16 @@ func cmdSync(args []string) error {
if mode == modeProject {
// Agent-only project sync
if kind == kindAgents {
_, err := syncAgentsProject(cwd, dryRun, force, jsonOutput, start)
_, err := syncAgentsProject(cwd, nil, dryRun, force, jsonOutput, start)
return err
}
stats, results, projIgnoreStats, projCtxCost, err := cmdSyncProject(cwd, dryRun, force, jsonOutput, quiet)
stats, results, projIgnoreStats, projCtxCost, invalid, err := cmdSyncProject(cwd, dryRun, force, jsonOutput, quiet)
stats.ProjectScope = true
// Append agent sync when kind=all or --all
if kind == kindAll || hasAll {
agentFailed, agentErr := syncAgentsProject(cwd, dryRun, force, jsonOutput, start)
agentFailed, agentErr := syncAgentsProject(cwd, invalid, dryRun, force, jsonOutput, start)
if agentErr != nil && err == nil {
err = agentErr
}
@@ -259,8 +260,9 @@ func cmdSync(args []string) error {
return err
}
// Validate config before sync
warnings, validErr := config.ValidateConfig(cfg)
// Validate config before sync. A target with invalid settings fails alone:
// it is reported as failed and skipped, and the other targets still sync.
warnings, invalid, validErr := config.ValidateConfigForSync(cfg)
if validErr != nil {
if jsonOutput {
return writeJSONError(validErr)
@@ -273,12 +275,23 @@ func cmdSync(args []string) error {
}
}
syncCfg := withoutTargets(cfg, invalid)
// Agent-only mode: skip skill discovery/sync entirely
if kind == kindAgents {
agentStats, agentErr := syncAgentsGlobal(cfg, dryRun, force, jsonOutput, start)
invalidNames := slices.Sorted(maps.Keys(invalid))
if !jsonOutput {
for _, name := range invalidNames {
ui.Error("%s: %s", name, invalidConfigMessage(invalid[name]))
}
}
agentStats, agentErr := syncAgentsGlobal(syncCfg, dryRun, force, jsonOutput, start)
if agentErr == nil && len(invalidNames) > 0 {
agentErr = fmt.Errorf("some targets failed to sync")
}
logSyncOp(config.ConfigPath(), syncLogStats{
Targets: len(cfg.Targets),
FailedTargets: mergeFailedTargets(agentStats.failed),
FailedTargets: mergeFailedTargets(agentStats.failed, invalidNames),
DryRun: dryRun,
Force: force,
}, start, agentErr)
@@ -307,7 +320,7 @@ func cmdSync(args []string) error {
// Backup targets before sync (only if not dry-run and there are skills)
if !dryRun && len(discoveredSkills) > 0 && !jsonOutput {
backupTargetsBeforeSync(cfg)
backupTargetsBeforeSync(syncCfg)
}
// Phase 2: Per-target sync (parallel)
@@ -323,7 +336,7 @@ func cmdSync(args []string) error {
var entries []syncTargetEntry
for name, target := range cfg.Targets {
entries = append(entries, syncTargetEntry{name: name, target: target, mode: getTargetMode(target.SkillsConfig().Mode, cfg.Mode)})
entries = append(entries, syncTargetEntry{name: name, target: target, mode: getTargetMode(target.SkillsConfig().Mode, cfg.Mode), configErr: invalid[name]})
}
var results []syncTargetResult
@@ -376,7 +389,7 @@ func cmdSync(args []string) error {
// for installed skills whose files may be missing from disk.
// Compute token cost once — used by both text summary and JSON output
analyzeEntries, analyzeErr := buildAnalyzeEntries(discoveredSkills, cfg.Targets, cfg.Mode, cfg.EffectiveSkillsSource(), "")
analyzeEntries, analyzeErr := buildAnalyzeEntries(discoveredSkills, syncCfg.Targets, cfg.Mode, cfg.EffectiveSkillsSource(), "")
if !jsonOutput && !quiet && analyzeErr == nil && len(analyzeEntries) > 0 {
printTokenSummary(analyzeEntries)
@@ -394,7 +407,7 @@ func cmdSync(args []string) error {
// Agents are included in --all in both human-readable and JSON output.
if kind == kindAll || hasAll {
agentStats, agentErr := syncAgentsGlobal(cfg, dryRun, force, jsonOutput, start)
agentStats, agentErr := syncAgentsGlobal(syncCfg, dryRun, force, jsonOutput, start)
if agentErr != nil && syncErr == nil {
syncErr = agentErr
}
@@ -477,6 +490,24 @@ func logSyncOp(cfgPath string, stats syncLogStats, start time.Time, cmdErr error
oplog.WriteWithLimit(cfgPath, oplog.OpsFile, e, logMaxEntries()) //nolint:errcheck
}
// withoutTargets returns cfg, or a copy of it without the targets in skip.
func withoutTargets(cfg *config.Config, skip map[string]error) *config.Config {
if len(skip) == 0 {
return cfg
}
c := *cfg
c.Targets = maps.Clone(cfg.Targets)
for name := range skip {
delete(c.Targets, name)
}
return &c
}
// invalidConfigMessage is the failure shown for a target with invalid settings.
func invalidConfigMessage(err error) string {
return "invalid config: " + err.Error()
}
// failedSkillTargets returns the targets whose skills sync failed.
func failedSkillTargets(results []syncTargetResult) []string {
var names []string
+6 -3
View File
@@ -121,8 +121,8 @@ func resolveAgentTargetPath(tc config.TargetConfig, builtinAgents map[string]con
// syncAgentsProject syncs agents for project mode using .skillshare/agents/ as source
// and project-level target agent paths.
// Returns the targets that failed and any error.
func syncAgentsProject(projectRoot string, dryRun, force, jsonOutput bool, start time.Time) ([]string, error) {
// Targets in skip are left out. Returns the targets that failed and any error.
func syncAgentsProject(projectRoot string, skip map[string]error, dryRun, force, jsonOutput bool, start time.Time) ([]string, error) {
// Load project config first to resolve agents source path.
projCfg, loadErr := config.LoadProject(projectRoot)
if loadErr != nil {
@@ -170,7 +170,7 @@ func syncAgentsProject(projectRoot string, dryRun, force, jsonOutput bool, start
backedUp := false
for _, entry := range projCfg.Targets {
agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, projectRoot)
if agentPath == "" {
if agentPath == "" || skip[entry.Name] != nil {
continue
}
entryName := entry.Name + "-agents"
@@ -189,6 +189,9 @@ func syncAgentsProject(projectRoot string, dryRun, force, jsonOutput bool, start
var targets []sync.AgentTarget
for _, entry := range projCfg.Targets {
if skip[entry.Name] != nil {
continue
}
targets = append(targets, sync.AgentTarget{
Name: entry.Name,
Path: resolveProjectAgentTargetPath(entry, builtinAgents, projectRoot),
+4 -2
View File
@@ -64,7 +64,8 @@ func cmdSyncExtrasGlobal(dryRun, force, jsonOutput bool, start time.Time) error
return err
}
if _, err := config.ValidateConfig(cfg); err != nil {
// Target problems fail only those targets' skills and agents, not extras.
if _, _, err := config.ValidateConfigForSync(cfg); err != nil {
return err
}
if len(cfg.Extras) == 0 {
@@ -197,7 +198,8 @@ func cmdSyncExtrasProject(cwd string, dryRun, force, jsonOutput bool, start time
return err
}
if _, err := config.ValidateProjectConfig(projCfg, cwd); err != nil {
// Target problems fail only those targets' skills and agents, not extras.
if _, _, err := config.ValidateProjectConfigForSync(projCfg, cwd); err != nil {
return err
}
if len(projCfg.Extras) == 0 {
+8 -1
View File
@@ -175,6 +175,8 @@ type syncTargetEntry struct {
name string
target config.TargetConfig
mode string
// configErr fails the target without syncing it: its settings are invalid.
configErr error
}
// collectSyncResult runs sync for one target and returns a result struct.
@@ -375,7 +377,12 @@ func runParallelSyncCore(entries []syncTargetEntry, source string, skills []sync
if progress != nil {
progress.startTarget(m.entry.name)
}
r := collectSyncResult(m.entry.name, m.entry.target, source, m.entry.mode, skills, ignorePatterns, dryRun, force, progress, projectRoot)
r := syncTargetResult{name: m.entry.name, mode: m.entry.mode}
if m.entry.configErr != nil {
r.errMsg = invalidConfigMessage(m.entry.configErr)
} else {
r = collectSyncResult(m.entry.name, m.entry.target, source, m.entry.mode, skills, ignorePatterns, dryRun, force, progress, projectRoot)
}
if progress != nil {
progress.doneTarget(m.entry.name, r)
}
+13 -11
View File
@@ -12,7 +12,8 @@ import (
"skillshare/internal/ui"
)
func cmdSyncProject(root string, dryRun, force, jsonOutput, quiet bool) (syncLogStats, []syncTargetResult, *skillignore.IgnoreStats, *contextCostJSON, error) {
// The returned map holds the targets skipped for invalid settings.
func cmdSyncProject(root string, dryRun, force, jsonOutput, quiet bool) (syncLogStats, []syncTargetResult, *skillignore.IgnoreStats, *contextCostJSON, map[string]error, error) {
start := time.Now()
stats := syncLogStats{
DryRun: dryRun,
@@ -21,19 +22,20 @@ func cmdSyncProject(root string, dryRun, force, jsonOutput, quiet bool) (syncLog
}
if err := ensureProjectConfig(root); err != nil {
return stats, nil, nil, nil, err
return stats, nil, nil, nil, nil, err
}
runtime, err := loadProjectRuntime(root)
if err != nil {
return stats, nil, nil, nil, err
return stats, nil, nil, nil, nil, err
}
stats.Targets = len(runtime.config.Targets)
// Validate project config before sync
warnings, validErr := config.ValidateProjectConfig(runtime.config, root)
// Validate project config before sync. A target with invalid settings
// fails alone; the other targets still sync.
warnings, invalid, validErr := config.ValidateProjectConfigForSync(runtime.config, root)
if validErr != nil {
return stats, nil, nil, nil, validErr
return stats, nil, nil, nil, nil, validErr
}
if !jsonOutput {
for _, w := range warnings {
@@ -44,7 +46,7 @@ func cmdSyncProject(root string, dryRun, force, jsonOutput, quiet bool) (syncLog
// ValidateProjectConfig warns on missing source (may not exist yet after init).
// Gate here as a hard error — sync cannot proceed without source skills.
if _, err := os.Stat(runtime.sourcePath); os.IsNotExist(err) {
return stats, nil, nil, nil, fmt.Errorf("source directory does not exist: %s", runtime.sourcePath)
return stats, nil, nil, nil, nil, fmt.Errorf("source directory does not exist: %s", runtime.sourcePath)
}
// Phase 1: Discovery
@@ -57,7 +59,7 @@ func cmdSyncProject(root string, dryRun, force, jsonOutput, quiet bool) (syncLog
if spinner != nil {
spinner.Fail("Discovery failed")
}
return stats, nil, nil, nil, discoverErr
return stats, nil, nil, nil, nil, discoverErr
}
if spinner != nil {
spinner.Success(fmt.Sprintf("Discovered %d skills", len(discoveredSkills)))
@@ -88,7 +90,7 @@ func cmdSyncProject(root string, dryRun, force, jsonOutput, quiet bool) (syncLog
if mode == "" {
mode = "merge"
}
entries = append(entries, syncTargetEntry{name: name, target: target, mode: mode})
entries = append(entries, syncTargetEntry{name: name, target: target, mode: mode, configErr: invalid[name]})
}
var results []syncTargetResult
@@ -159,10 +161,10 @@ func cmdSyncProject(root string, dryRun, force, jsonOutput, quiet bool) (syncLog
}
if len(stats.FailedTargets) > 0 {
return stats, results, ignoreStats, ctxCost, fmt.Errorf("some targets failed to sync")
return stats, results, ignoreStats, ctxCost, invalid, fmt.Errorf("some targets failed to sync")
}
return stats, results, ignoreStats, ctxCost, nil
return stats, results, ignoreStats, ctxCost, invalid, nil
}
func projectTargetDisplayPath(entry config.ProjectTargetEntry) string {
+136 -85
View File
@@ -3,8 +3,10 @@ package config
import (
"errors"
"fmt"
"maps"
"os"
"path/filepath"
"slices"
"strings"
)
@@ -14,6 +16,14 @@ const errAgentsEnabled = "agents.enabled is not supported (only skills.enabled)"
// ValidateConfig validates a global config semantically (after YAML parsing).
// Returns warnings (non-fatal) and error (fatal, should return 400).
func ValidateConfig(cfg *Config) (warnings []string, err error) {
warnings, invalid, err := ValidateConfigForSync(cfg)
return warnings, joinTargetErrors(err, invalid)
}
// ValidateConfigForSync validates a global config for sync, which runs every
// target it can: invalid maps each target whose own settings are wrong to its
// problems, and err holds the problems that stop the whole sync.
func ValidateConfigForSync(cfg *Config) (warnings []string, invalid map[string]error, err error) {
var errs []string
// Source path validation checks the effective source, including the default
@@ -50,48 +60,75 @@ func ValidateConfig(cfg *Config) (warnings []string, err error) {
errs = append(errs, err.Error())
}
// Per-target validation
for name, target := range cfg.Targets {
if err := ValidateTargetInstructions(target.Instructions, false); err != nil {
errs = append(errs, fmt.Sprintf("target %q: %v", name, err))
}
if target.Agents != nil && target.Agents.Enabled != nil {
errs = append(errs, fmt.Sprintf("target %q: %s", name, errAgentsEnabled))
}
sc := target.SkillsConfig()
if !IsValidSyncMode(sc.Mode) {
errs = append(errs, fmt.Sprintf("target %q: invalid sync mode %q (valid: %s)", name, sc.Mode, strings.Join(ValidSyncModes, ", ")))
continue
}
if !IsValidTargetNaming(sc.TargetNaming) {
errs = append(errs, fmt.Sprintf("target %q: invalid target naming %q (valid: %s)", name, sc.TargetNaming, strings.Join(ValidTargetNamings, ", ")))
continue
}
path := sc.Path
if path == "" {
// Known built-in targets get their path from targets.yaml at runtime;
// custom targets must specify a path explicitly.
if _, known := LookupGlobalTarget(name); !known && target.Agent == "" {
errs = append(errs, fmt.Sprintf("target %q: missing path (custom targets require skills.path)", name))
continue
}
} else {
errs = append(errs, validateTargetPath(name, ExpandPath(path))...)
}
}
if err := cfg.ValidateExtras(); err != nil {
errs = append(errs, err.Error())
}
if len(errs) > 0 {
return warnings, errors.New(strings.Join(errs, "; "))
invalid = map[string]error{}
for name, target := range cfg.Targets {
if problems := validateGlobalTarget(name, target); len(problems) > 0 {
invalid[name] = errors.New(strings.Join(problems, "; "))
}
}
return warnings, nil
if len(errs) > 0 {
err = errors.New(strings.Join(errs, "; "))
}
return warnings, invalid, err
}
// validateGlobalTarget returns the problems of one global target's settings.
func validateGlobalTarget(name string, target TargetConfig) []string {
var problems []string
if err := ValidateTargetInstructions(target.Instructions, false); err != nil {
problems = append(problems, err.Error())
}
if target.Agents != nil && target.Agents.Enabled != nil {
problems = append(problems, errAgentsEnabled)
}
sc := target.SkillsConfig()
if !IsValidSyncMode(sc.Mode) {
return append(problems, fmt.Sprintf("invalid sync mode %q (valid: %s)", sc.Mode, strings.Join(ValidSyncModes, ", ")))
}
if !IsValidTargetNaming(sc.TargetNaming) {
return append(problems, fmt.Sprintf("invalid target naming %q (valid: %s)", sc.TargetNaming, strings.Join(ValidTargetNamings, ", ")))
}
if sc.Path == "" {
// Known built-in targets get their path from targets.yaml at runtime;
// custom targets must specify a path explicitly.
if _, known := LookupGlobalTarget(name); !known && target.Agent == "" {
problems = append(problems, "missing path (custom targets require skills.path)")
}
} else if err := validateTargetPath(ExpandPath(sc.Path)); err != nil {
problems = append(problems, err.Error())
}
return problems
}
// joinTargetErrors folds the per-target problems into err, as one error that
// names each target, for callers that reject the whole config.
func joinTargetErrors(err error, invalid map[string]error) error {
var errs []string
if err != nil {
errs = append(errs, err.Error())
}
for _, name := range slices.Sorted(maps.Keys(invalid)) {
errs = append(errs, fmt.Sprintf("target %q: %v", name, invalid[name]))
}
if len(errs) == 0 {
return nil
}
return errors.New(strings.Join(errs, "; "))
}
// ValidateProjectConfig validates a project config semantically.
func ValidateProjectConfig(cfg *ProjectConfig, projectRoot string) (warnings []string, err error) {
warnings, invalid, err := ValidateProjectConfigForSync(cfg, projectRoot)
return warnings, joinTargetErrors(err, invalid)
}
// ValidateProjectConfigForSync is ValidateConfigForSync for a project config.
func ValidateProjectConfigForSync(cfg *ProjectConfig, projectRoot string) (warnings []string, invalid map[string]error, err error) {
var errs []string
sourcePath := cfg.EffectiveSkillsSource(projectRoot)
@@ -108,64 +145,78 @@ func ValidateProjectConfig(cfg *ProjectConfig, projectRoot string) (warnings []s
errs = append(errs, fmt.Sprintf("source path is not a directory: %s", sourcePath))
}
// Target validation
if !IsValidTargetNaming(cfg.TargetNaming) {
errs = append(errs, fmt.Sprintf("invalid project target naming %q (valid: %s)", cfg.TargetNaming, strings.Join(ValidTargetNamings, ", ")))
}
for _, entry := range cfg.Targets {
if err := ValidateTargetInstructions(entry.Instructions, true); err != nil {
errs = append(errs, fmt.Sprintf("target %q: %v", entry.Name, err))
}
if entry.Agents != nil && entry.Agents.Enabled != nil {
errs = append(errs, fmt.Sprintf("target %q: %s", entry.Name, errAgentsEnabled))
}
sc := entry.SkillsConfig()
if !IsValidSyncMode(sc.Mode) {
errs = append(errs, fmt.Sprintf("target %q: invalid sync mode %q (valid: %s)", entry.Name, sc.Mode, strings.Join(ValidSyncModes, ", ")))
continue
}
if !IsValidTargetNaming(sc.TargetNaming) {
errs = append(errs, fmt.Sprintf("target %q: invalid target naming %q (valid: %s)", entry.Name, sc.TargetNaming, strings.Join(ValidTargetNamings, ", ")))
continue
}
var skillsBuiltin string
if t, ok := LookupProjectTarget(entry.Name); ok {
skillsBuiltin = t.Path
}
if sc.Path == "" && skillsBuiltin == "" {
// Known built-in targets are resolved from targets.yaml;
// custom targets must have an explicit path.
errs = append(errs, fmt.Sprintf("target %q: missing path (custom targets require skills.path)", entry.Name))
} else {
skillsTargetPath := resolveProjectTargetPath(projectRoot, sc.Path, skillsBuiltin)
if sc.Path != "" {
errs = append(errs, validateTargetPath(entry.Name, skillsTargetPath)...)
}
if skillsTargetPath != "" && pathsOverlap(sourcePath, skillsTargetPath) {
errs = append(errs, fmt.Sprintf("target %q: skills target path %s overlaps skills source %s — sync --force could destroy the source", entry.Name, skillsTargetPath, sourcePath))
}
}
ac := entry.AgentsConfig()
var agentsBuiltin string
if t, ok := LookupProjectAgentTarget(entry.Name); ok {
agentsBuiltin = t.Path
}
agentsTargetPath := resolveProjectTargetPath(projectRoot, ac.Path, agentsBuiltin)
if agentsTargetPath != "" && pathsOverlap(agentsSourcePath, agentsTargetPath) {
errs = append(errs, fmt.Sprintf("target %q: agents target path %s overlaps agents source %s — sync --force could destroy the source", entry.Name, agentsTargetPath, agentsSourcePath))
}
}
if err := cfg.ValidateExtras(projectRoot); err != nil {
errs = append(errs, err.Error())
}
if len(errs) > 0 {
return warnings, errors.New(strings.Join(errs, "; "))
problems := map[string][]string{}
for _, entry := range cfg.Targets {
problems[entry.Name] = append(problems[entry.Name], validateProjectTarget(entry, projectRoot, sourcePath, agentsSourcePath)...)
}
return warnings, nil
invalid = map[string]error{}
for name, p := range problems {
if len(p) > 0 {
invalid[name] = errors.New(strings.Join(p, "; "))
}
}
if len(errs) > 0 {
err = errors.New(strings.Join(errs, "; "))
}
return warnings, invalid, err
}
// validateProjectTarget returns the problems of one project target's settings.
func validateProjectTarget(entry ProjectTargetEntry, projectRoot, sourcePath, agentsSourcePath string) []string {
var problems []string
if err := ValidateTargetInstructions(entry.Instructions, true); err != nil {
problems = append(problems, err.Error())
}
if entry.Agents != nil && entry.Agents.Enabled != nil {
problems = append(problems, errAgentsEnabled)
}
sc := entry.SkillsConfig()
if !IsValidSyncMode(sc.Mode) {
return append(problems, fmt.Sprintf("invalid sync mode %q (valid: %s)", sc.Mode, strings.Join(ValidSyncModes, ", ")))
}
if !IsValidTargetNaming(sc.TargetNaming) {
return append(problems, fmt.Sprintf("invalid target naming %q (valid: %s)", sc.TargetNaming, strings.Join(ValidTargetNamings, ", ")))
}
var skillsBuiltin string
if t, ok := LookupProjectTarget(entry.Name); ok {
skillsBuiltin = t.Path
}
if sc.Path == "" && skillsBuiltin == "" {
// Known built-in targets are resolved from targets.yaml;
// custom targets must have an explicit path.
problems = append(problems, "missing path (custom targets require skills.path)")
} else {
skillsTargetPath := resolveProjectTargetPath(projectRoot, sc.Path, skillsBuiltin)
if sc.Path != "" {
if err := validateTargetPath(skillsTargetPath); err != nil {
problems = append(problems, err.Error())
}
}
if skillsTargetPath != "" && pathsOverlap(sourcePath, skillsTargetPath) {
problems = append(problems, fmt.Sprintf("skills target path %s overlaps skills source %s — sync --force could destroy the source", skillsTargetPath, sourcePath))
}
}
ac := entry.AgentsConfig()
var agentsBuiltin string
if t, ok := LookupProjectAgentTarget(entry.Name); ok {
agentsBuiltin = t.Path
}
agentsTargetPath := resolveProjectTargetPath(projectRoot, ac.Path, agentsBuiltin)
if agentsTargetPath != "" && pathsOverlap(agentsSourcePath, agentsTargetPath) {
problems = append(problems, fmt.Sprintf("agents target path %s overlaps agents source %s — sync --force could destroy the source", agentsTargetPath, agentsSourcePath))
}
return problems
}
// ValidateTargetInstructions checks a user-set instruction file: a file path,
@@ -227,7 +278,7 @@ func pathsOverlap(a, b string) bool {
// validateTargetPath checks a single target's path is accessible and is a directory.
// Missing paths are accepted — sync will auto-create them with a visible notification.
func validateTargetPath(name, expandedPath string) []string {
func validateTargetPath(expandedPath string) error {
if expandedPath == "" {
return nil // path resolved by target registry; skip filesystem check
}
@@ -237,10 +288,10 @@ func validateTargetPath(name, expandedPath string) []string {
if os.IsNotExist(statErr) {
return nil // sync will auto-create and notify
}
return []string{fmt.Sprintf("target %q: cannot access path: %v", name, statErr)}
return fmt.Errorf("cannot access path: %v", statErr)
}
if !info.IsDir() {
return []string{fmt.Sprintf("target %q: path is not a directory: %s", name, expandedPath)}
return fmt.Errorf("path is not a directory: %s", expandedPath)
}
return nil
+54
View File
@@ -473,3 +473,57 @@ func TestValidateConfig_RejectsRelativeInstructionsPath(t *testing.T) {
t.Fatalf("err = %v, want instructions.path error", err)
}
}
func TestValidateConfigForSync_TargetProblemFailsOnlyThatTarget(t *testing.T) {
file := filepath.Join(t.TempDir(), "skills-file")
if err := os.WriteFile(file, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
cfg := &Config{
Source: t.TempDir(),
Targets: map[string]TargetConfig{
"broken": {Skills: &ResourceTargetConfig{Path: file}},
"good": {Skills: &ResourceTargetConfig{Path: filepath.Join(t.TempDir(), "skills")}},
},
}
_, invalid, err := ValidateConfigForSync(cfg)
if err != nil || len(invalid) != 1 || invalid["broken"] == nil || !strings.Contains(invalid["broken"].Error(), "path is not a directory") {
t.Fatalf("err = %v, invalid = %v; want only broken invalid", err, invalid)
}
}
func TestValidateConfigForSync_GlobalProblemStillFails(t *testing.T) {
cfg := &Config{Source: t.TempDir(), Mode: "bogus", Targets: map[string]TargetConfig{}}
if _, _, err := ValidateConfigForSync(cfg); err == nil || !strings.Contains(err.Error(), "invalid global sync mode") {
t.Fatalf("err = %v, want invalid global sync mode", err)
}
}
func TestValidateConfig_TargetPathIsFileStillRejected(t *testing.T) {
file := filepath.Join(t.TempDir(), "skills-file")
if err := os.WriteFile(file, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
cfg := &Config{Source: t.TempDir(), Targets: map[string]TargetConfig{"broken": {Skills: &ResourceTargetConfig{Path: file}}}}
if _, err := ValidateConfig(cfg); err == nil || !strings.Contains(err.Error(), `target "broken": path is not a directory`) {
t.Fatalf("err = %v, want target path error", err)
}
}
func TestValidateProjectConfigForSync_TargetProblemFailsOnlyThatTarget(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, ".skillshare", "skills"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "skills-file"), []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
cfg := &ProjectConfig{Targets: []ProjectTargetEntry{
{Name: "broken", Skills: &ResourceTargetConfig{Path: "skills-file"}},
{Name: "claude"},
}}
_, invalid, err := ValidateProjectConfigForSync(cfg, root)
if err != nil || len(invalid) != 1 || invalid["broken"] == nil || !strings.Contains(invalid["broken"].Error(), "path is not a directory") {
t.Fatalf("err = %v, invalid = %v; want only broken invalid", err, invalid)
}
}
+33 -12
View File
@@ -44,7 +44,7 @@ func ignorePayload(stats *skillignore.IgnoreStats) map[string]any {
// failures apart from the other warnings.
type syncFailure struct {
Target string `json:"target"`
Part string `json:"part"` // "skill" or "agent"
Part string `json:"part"` // "skill", "agent", or "config"
Error string `json:"error"`
Message string `json:"message"`
Conflict bool `json:"conflict,omitempty"` // a symlink points elsewhere; force replaces it
@@ -173,21 +173,45 @@ func (s *Server) syncResources(start time.Time, dryRun, force bool, kind, projec
}
// Pre-check warnings via shared config validation
warnings, validErr := config.ValidateConfig(s.cfg)
warnings, invalid, validErr := config.ValidateConfigForSync(s.cfg)
if validErr != nil {
return nil, http.StatusBadRequest, validErr
}
conflicts, overlap := folderConflicts(s.cfg.Targets, s.IsProjectMode())
if !dryRun {
warnings = append(warnings, s.backupBeforeSync(targets, kind != kindAgent, kind != kindSkill)...)
}
results := make([]syncTargetResult, 0)
failed := make([]syncFailure, 0)
skillFailed := 0
// A target with invalid settings fails alone: it is skipped for skills and
// agents, and counts as a failed skill target when skills are synced.
var firstErr error
var firstFailed string
runTargets := maps.Clone(targets)
for _, name := range slices.Sorted(maps.Keys(invalid)) {
target, ok := targets[name]
if !ok {
continue
}
delete(runTargets, name)
err := invalid[name]
msg := name + ": invalid config: " + err.Error()
warnings = append(warnings, msg)
failed = append(failed, syncFailure{Target: name, Part: "config", Error: err.Error(), Message: msg})
if kind != kindAgent && target.SkillsConfig().IsEnabled() {
skillFailed++
if firstErr == nil {
firstErr, firstFailed = fmt.Errorf("invalid config for %s: %w", name, err), name
}
}
}
skillRan := skillFailed
if !dryRun {
warnings = append(warnings, s.backupBeforeSync(runTargets, kind != kindAgent, kind != kindSkill)...)
}
var ignoreStats *skillignore.IgnoreStats
var allSkills []ssync.DiscoveredSkill
ignorePatterns := ssync.EffectiveFileIgnorePatterns(s.cfg.Ignore)
@@ -209,8 +233,6 @@ func (s *Server) syncResources(start time.Time, dryRun, force bool, kind, projec
// for installed skills whose files may be missing from disk.
// A failed target adds a warning and no results row; the rest still sync.
var firstErr error
var firstFailed string
failTarget := func(name string, err error) {
skillFailed++
if firstErr == nil {
@@ -224,8 +246,7 @@ func (s *Server) syncResources(start time.Time, dryRun, force bool, kind, projec
Source: s.cfg.EffectiveSkillsSource(), ProjectRoot: s.projectRoot, IgnorePatterns: ignorePatterns,
DryRun: dryRun, Force: force,
}
skillRan := 0
for name, target := range targets {
for name, target := range runTargets {
sc := target.SkillsConfig()
if !sc.IsEnabled() {
continue // skills off: agents, extras and MCP below still run
@@ -299,8 +320,8 @@ func (s *Server) syncResources(start time.Time, dryRun, force bool, kind, projec
agents := discoverActiveAgents(agentsSource)
builtinAgents := s.builtinAgentTargets()
agentTargets := make([]ssync.AgentTarget, 0, len(targets))
for name, target := range targets {
agentTargets := make([]ssync.AgentTarget, 0, len(runTargets))
for name, target := range runTargets {
agentTargets = append(agentTargets, ssync.AgentTarget{
Name: name,
Path: resolveAgentPath(target, builtinAgents, name, s.IsProjectMode()),
+55
View File
@@ -771,3 +771,58 @@ func TestHandleSync_SymlinkConflictReplacedWithForce(t *testing.T) {
t.Fatalf("expected %s linked to the source after force", linkPath)
}
}
func TestHandleSync_InvalidTargetConfigFailsOnlyThatTarget(t *testing.T) {
s, src, _ := newAgentSyncServer(t)
addSkill(t, src, "alpha")
file := filepath.Join(t.TempDir(), "skills-file")
if err := os.WriteFile(file, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
brokenAgents := filepath.Join(t.TempDir(), "broken-agents")
s.cfg.Targets["broken"] = config.TargetConfig{
Skills: &config.ResourceTargetConfig{Path: file},
Agents: &config.ResourceTargetConfig{Path: brokenAgents},
}
s.cfg.Targets["claude"] = config.TargetConfig{
Skills: &config.ResourceTargetConfig{Path: filepath.Join(t.TempDir(), "claude-skills")},
Agents: &config.ResourceTargetConfig{Path: filepath.Join(t.TempDir(), "claude-agents")},
}
if err := s.cfg.Save(); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/api/sync", strings.NewReader(`{}`))
rr := httptest.NewRecorder()
s.handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
}
var resp struct {
Results []syncTargetResult `json:"results"`
Warnings []string `json:"warnings"`
Failed []syncFailure `json:"failed"`
}
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
t.Fatal(err)
}
if len(resp.Results) != 1 || resp.Results[0].Target != "claude" || !slices.Equal(resp.Results[0].Linked, []string{"alpha", "tutor.md"}) {
t.Fatalf("expected only the claude row with alpha and tutor.md, got %+v", resp.Results)
}
if len(resp.Failed) != 1 || resp.Failed[0].Target != "broken" || resp.Failed[0].Part != "config" ||
!strings.Contains(resp.Failed[0].Error, "path is not a directory") || !slices.Contains(resp.Warnings, resp.Failed[0].Message) {
t.Fatalf("expected one config failure for broken also in warnings, got failed %+v warnings %v", resp.Failed, resp.Warnings)
}
if _, err := os.Stat(brokenAgents); !os.IsNotExist(err) {
t.Fatalf("expected no agent sync into the invalid target, stat err = %v", err)
}
entries, err := oplog.Read(config.ConfigPath(), oplog.OpsFile, 1)
if err != nil || len(entries) != 1 {
t.Fatalf("read ops log: %v (%d entries)", err, len(entries))
}
got, _ := json.Marshal(entries[0].Args["failed_targets"])
if e := entries[0]; e.Status != "partial" || e.Args["targets_failed"] != float64(1) || string(got) != `["broken"]` {
t.Fatalf("expected partial sync with broken failed, got status %q args %v", e.Status, e.Args)
}
}
+2
View File
@@ -22,6 +22,8 @@ skillshare sync --json # JSON output
skillshare sync -g # Force global mode
```
Sync runs every target. A target whose sync fails, or whose own settings are invalid (for example a skills path that is a file), is reported as failed and skipped; the rest still sync and the command exits non-zero. Config-wide problems (source, global `mode`/`target_naming`, `git_root`, extras) still stop sync before any target runs.
### Sync modes (quick reference)
- `merge` (default): per-skill symlinks, preserves local target skills.
@@ -0,0 +1,106 @@
//go:build !online
package integration
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"skillshare/internal/testutil"
)
// writeConfigWithFileTarget configures a valid claude target plus a "broken"
// target whose skills path is a regular file.
func writeConfigWithFileTarget(t *testing.T, sb *testutil.Sandbox) (claudeSkills string) {
t.Helper()
sb.CreateSkill("test-skill", map[string]string{"SKILL.md": "# Test\n\nTest."})
claudeSkills = sb.CreateTarget("claude")
file := filepath.Join(sb.Home, "skills-file")
sb.WriteFile(file, "x")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
skills:
path: ` + claudeSkills + `
broken:
skills:
path: ` + file + `
`)
return claudeSkills
}
func TestSync_InvalidTargetConfigFailsOnlyThatTarget(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeSkills := writeConfigWithFileTarget(t, sb)
result := sb.RunCLI("sync")
result.AssertFailure(t)
result.AssertOutputContains(t, "broken: invalid config: path is not a directory")
if !sb.IsSymlink(filepath.Join(claudeSkills, "test-skill")) {
t.Fatal("valid target should still be synced")
}
status, args := lastSyncLogEntry(t, sb)
got, _ := json.Marshal(args["failed_targets"])
if status != "partial" || args["targets_failed"] != float64(1) || string(got) != `["broken"]` {
t.Fatalf("expected partial sync with broken failed, got status %q args %v", status, args)
}
}
func TestSync_InvalidTargetConfigReportedInJSON(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
writeConfigWithFileTarget(t, sb)
result := sb.RunCLI("sync", "--json")
result.AssertFailure(t)
var out struct {
Details []struct {
Name string `json:"name"`
Linked int `json:"linked"`
Error string `json:"error"`
} `json:"details"`
}
if err := json.Unmarshal([]byte(result.Stdout), &out); err != nil {
t.Fatalf("parse sync JSON: %v\n%s", err, result.Stdout)
}
byName := map[string]string{}
linked := map[string]int{}
for _, d := range out.Details {
byName[d.Name], linked[d.Name] = d.Error, d.Linked
}
if byName["claude"] != "" || linked["claude"] != 1 {
t.Fatalf("expected claude to sync 1 skill, got %+v", out.Details)
}
if want := "invalid config: path is not a directory: " + filepath.Join(sb.Home, "skills-file"); byName["broken"] != want {
t.Fatalf("broken error = %q, want %q", byName["broken"], want)
}
}
func TestSyncProject_InvalidTargetConfigFailsOnlyThatTarget(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
projectRoot := sb.SetupProjectDir("claude")
sb.CreateProjectSkill(projectRoot, "my-skill", map[string]string{"SKILL.md": "# My Skill"})
if err := os.WriteFile(filepath.Join(projectRoot, "skills-file"), []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
sb.WriteProjectConfig(projectRoot, `targets:
- claude
- name: broken
skills:
path: skills-file
`)
result := sb.RunCLIInDir(projectRoot, "sync", "-p")
result.AssertFailure(t)
result.AssertOutputContains(t, "broken: invalid config: path is not a directory")
if !sb.IsSymlink(filepath.Join(projectRoot, ".claude", "skills", "my-skill")) {
t.Fatal("valid project target should still be synced")
}
}
+6
View File
@@ -191,6 +191,12 @@ flowchart TD
S2 --> SYMLINK --> S3
```
### When a target fails {#when-a-target-fails}
Sync runs every target; one failed target does not stop the others. A target fails when syncing it hits an error, or when its own settings in the config are invalid, for example its skills path is a file instead of a folder or its `mode` is unknown. A target with invalid settings is skipped for skills and agents in that run. Each failed target is reported (`✗ <target>: invalid config: …` in text output, `error` in its `--json` `details` entry), and the command exits non-zero after the other targets have synced.
Problems with the config as a whole still stop sync before any target runs: a missing or invalid source folder, an invalid global `mode` or `target_naming`, an invalid `git_root`, or invalid extras.
### Example Output
```text
@@ -184,6 +184,12 @@ flowchart TD
S2 --> SYMLINK --> S3
```
### target が失敗した場合 {#when-a-target-fails}
sync はすべての target を実行し、1 つの target が失敗しても他の target は止まりません。target が失敗するのは、sync 中にエラーが起きたとき、またはその target 自身の設定が不正なとき(例:skills path がフォルダではなくファイル、`mode` が不明)です。設定が不正な target は、その実行では skills と agents の両方がスキップされます。失敗した target はそれぞれ報告され(テキスト出力では `✗ <target>: invalid config: …`、`--json` では該当する `details` エントリの `error`)、他の target の sync が終わった後にコマンドは非ゼロで終了します。
config 全体に関わる問題は、これまでどおりどの target も実行する前に sync を止めます:source フォルダが存在しない・不正、グローバルの `mode` や `target_naming` が不正、`git_root` が不正、extras が不正。
### 出力例
```text
@@ -185,6 +185,12 @@ flowchart TD
S2 --> SYMLINK --> S3
```
### target이 실패하는 경우 {#when-a-target-fails}
sync는 모든 target을 실행하며, target 하나가 실패해도 나머지 target은 멈추지 않습니다. target은 sync 중 오류가 발생하거나, 해당 target 자체의 설정이 잘못된 경우(예: skills path가 폴더가 아닌 파일이거나 `mode`를 알 수 없는 경우) 실패합니다. 설정이 잘못된 target은 해당 실행에서 skills와 agents 모두 건너뜁니다. 실패한 target은 각각 보고되며(텍스트 출력에서는 `✗ <target>: invalid config: …`, `--json`에서는 해당 `details` 항목의 `error`), 나머지 target의 sync가 끝난 뒤 명령은 0이 아닌 코드로 종료됩니다.
config 전체에 관한 문제는 여전히 어떤 target도 실행하기 전에 sync를 중단합니다: source 폴더가 없거나 잘못됨, 전역 `mode` 또는 `target_naming`이 잘못됨, `git_root`가 잘못됨, extras가 잘못됨.
### 출력 예시
```text
@@ -196,6 +196,12 @@ flowchart TD
S2 --> SYMLINK --> S3
```
### target 失败时 {#when-a-target-fails}
sync 会运行每个 target,一个 target 失败不会中断其他 target。target 在同步出错时失败,或在其自身配置无效时失败,例如 skills path 是文件而不是文件夹,或 `mode` 无法识别。配置无效的 target 在本次运行中会跳过 skills 和 agents。每个失败的 target 都会被报告(文本输出为 `✗ <target>: invalid config: …`,`--json` 中为对应 `details` 条目的 `error`),并在其他 target 同步完成后以非零状态退出。
影响整个配置的问题仍会在任何 target 运行前中止 sync:source 文件夹不存在或无效、全局 `mode` 或 `target_naming` 无效、`git_root` 无效,或 extras 无效。
### 示例输出
```text
@@ -184,6 +184,12 @@ flowchart TD
S2 --> SYMLINK --> S3
```
### target 失敗時 {#when-a-target-fails}
sync 會執行每個 target,一個 target 失敗不會中斷其他 target。target 在同步出錯時失敗,或在自身設定無效時失敗,例如 skills path 是檔案而不是資料夾,或 `mode` 無法辨識。設定無效的 target 在該次執行中會略過 skills 與 agents。每個失敗的 target 都會被回報(文字輸出為 `✗ <target>: invalid config: …`,`--json` 中為對應 `details` 項目的 `error`),並在其他 target 同步完成後以非零狀態結束。
影響整份設定的問題仍會在任何 target 執行前中止 sync:source 資料夾不存在或無效、全域 `mode` 或 `target_naming` 無效、`git_root` 無效,或 extras 無效。
### 輸出範例
```text