Files
skillshare/internal/config/config_validate.go
T
Willie b0d87fba28 feat(sync): make prefixed target naming misconfigurations visible (#503)
* feat(sync): make prefixed target naming misconfigurations visible

Prefixed naming (#497) works, but several of its failure modes only showed up
at sync time or gave advice that cannot be followed:

- A collision that only prefixing creates told the user to "rename one in
  SKILL.md", which a tracked skill cannot do, and never said the prefix caused
  it. The hint now names the prefixing and points at renaming the other skill or
  re-tracking the repo with --name.
- `target add` silently wrote mode: copy when the inherited naming is prefixed.
  The CLI now says so.
- A target that resolves to prefixed outside copy mode was reported only by
  sync. status, doctor and target list (plain and JSON) now flag it, and the
  sync/validation and `--skills=true` errors say how to fix it.
- The dim "duplicate skill names (isolated by ...)" line printed on every sync
  even when nothing was wrong, and before a failing sync. Isolated duplicates
  are not a problem, so it is dropped; the website docs still showed an
  outdated form of this output and are corrected in all locales.

* fix(status): flag prefixed-outside-copy in the TUI list and status --json

Codex review of #503 found two surfaces the new check missed:

- The interactive `target list` (the default on a terminal) never read the
  item's naming error, so a prefixed + merge target looked healthy there. The
  list row now marks the mode with "!" and the detail panel shows the fix.
- `status --json` (global and project) builds its target entries directly, so
  scripts got no signal. Each target now carries a `warning` string, matching
  `target list --json`.

* docs(troubleshooting): sync no longer prints a message for isolated duplicates

The collision troubleshooting tip still said sync shows an info message when
filters isolate duplicate skill names. That line was dropped, so the tip now
says sync prints nothing about them. Codex review of #503 flagged the stale
English page and its four translations.

* fix(config): point managed-project naming errors at the project settings

The "set mode: copy on the target" hint is wrong for a target a global
`projects:` entry expands into: it cannot be edited with `target` or under
`targets:`, and the mode lives in the project's skills settings. The hint now
depends on whether the target belongs to a managed project (Codex review of
#503).

The naming/mode check becomes a TargetConfig method so status, doctor and
target list share it, which also lets the hint see the project root. Along the
way: doctor reuses it, the TUI list renders the mode once, and
reportTargetAdded takes a flag instead of comparing a mode string.

* fix(config): hint the project settings for managed-project naming errors

ProjectNamingError (the config-load check for a global `projects:` entry) still
returned the bare naming error, so a project that inherits prefixed with a
non-copy mode got no fix. It now names the project's skills settings, like the
expanded targets do. The built-in skill's sync reference also mentions that
status, doctor and target list flag the misconfiguration before sync.

Found by the second /code-review pass on #503.

* fix(sync): detect prefix collisions from the colliding paths

reportCollisions decided a collision came from prefixing when its name was not
also a duplicate in the source. A tracked skill that joined two ordinary
skills already sharing the name was therefore sent to the "rename one in
SKILL.md" hint, which a tracked skill cannot follow (Codex review of #503).

A collision on a prefixed target that includes a tracked path now gets the
tracked-skill hint, whatever else shares the name. The wording no longer claims
prefixing renamed the skill, since a name that already starts with the repo
name is unchanged.

* fix(sync): use discovered repo metadata for the tracked-skill hint

The collision hint treated any path segment starting with "_" as a tracked
repo, so an ordinary skill under a folder such as org/_drafts (no .git) was
told it could not be renamed and to re-track a repo that does not exist. It now
uses DiscoveredSkill.IsInRepo, the same signal prefixed naming uses.

The prefixed docs also gain the fix for a target a global `projects:` entry
expands into (projects.<root>.skills.mode: copy), since `target` cannot edit
those. Both from Codex review of #503.

* fix(sync): keep both collision hints when targets disagree

The same name can clash on a prefixed target with a tracked skill and on
another target between ordinary skills only. The prefixed flag was OR-ed across
targets, so the second case lost its rename/filter hint. Track both kinds
separately while grouping, and print each hint that applies (Codex review of
#503).

* fix(sync): keep the rename hint inside a mixed collision group

When a tracked skill and two ordinary skills share a prefixed name, re-tracking
the repo fixes only the tracked one; the ordinary pair still clashes and is
excluded. The group now also shows the rename/filter hint when at least two of
its participants are not tracked (Codex review of #503).

* fix(sync): offer filters in the tracked-skill collision hint

Two tracked skills of the same repo with the same name collide after
prefixing, and neither renaming a tracked skill nor re-tracking the repo
separates them. The hint now also names include/exclude filters, so every
collision on a prefixed target has an actionable remedy (Codex review of #503).

* docs(sync-modes): limit the target list claim to targets under targets

target list builds from the config without project expansion, so it cannot
flag a target a `projects:` entry expands into; status and doctor can. The
prefixed paragraph and the built-in skill reference said all three flag it
(Codex review of #503).
2026-10-10 00:00:23 +08:00

311 lines
12 KiB
Go

package config
import (
"cmp"
"errors"
"fmt"
"maps"
"os"
"path/filepath"
"slices"
"strings"
)
// errAgentsEnabled rejects enabled under agents: only skills can be switched off.
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)
// A raw config (the dashboard's config save) has not expanded projects into targets yet.
return warnings, errors.Join(joinTargetErrors(err, invalid), cfg.ProjectNamingError(cfg.Projects, cfg.Mode))
}
// 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
// <BaseDir>/skills fallback when source/sources.skills are omitted.
sourcePath := cfg.EffectiveSkillsSource()
info, statErr := os.Stat(sourcePath)
if statErr != nil {
if os.IsNotExist(statErr) {
errs = append(errs, fmt.Sprintf("source path does not exist: %s", sourcePath))
} else {
errs = append(errs, fmt.Sprintf("cannot access source path: %v", statErr))
}
} else if !info.IsDir() {
errs = append(errs, fmt.Sprintf("source path is not a directory: %s", sourcePath))
}
// Global sync mode
if !IsValidSyncMode(cfg.Mode) {
errs = append(errs, fmt.Sprintf("invalid global sync mode %q (valid: %s)", cfg.Mode, strings.Join(ValidSyncModes, ", ")))
}
if !IsValidTargetNaming(cfg.TargetNaming) {
errs = append(errs, fmt.Sprintf("invalid global target naming %q (valid: %s)", cfg.TargetNaming, strings.Join(ValidTargetNamings, ", ")))
}
// git_root scope keyword. An unknown value silently falls back to the skills
// scope in ScopeDir, so commit/push/pull would operate on the wrong repo
// without warning — reject it here instead.
if !ValidGitRoot(cfg.GitRoot) {
errs = append(errs, fmt.Sprintf("invalid git_root %q (valid: %s)", cfg.GitRoot, strings.Join(ValidGitRoots, ", ")))
}
// A target that is another config directory of an Agent gets its paths from there.
if err := cfg.expandAgentConfigDirs(); err != nil {
errs = append(errs, err.Error())
}
if err := cfg.ValidateExtras(); err != nil {
errs = append(errs, err.Error())
}
invalid = map[string]error{}
for name, target := range cfg.Targets {
if problems := validateGlobalTarget(name, target, cfg.Mode, cfg.TargetNaming); len(problems) > 0 {
invalid[name] = errors.New(strings.Join(problems, "; "))
}
}
if len(errs) > 0 {
err = errors.New(strings.Join(errs, "; "))
}
return warnings, invalid, err
}
// validateGlobalTarget returns the problems of one global target's settings.
// globalMode and globalNaming are the defaults the target inherits.
func validateGlobalTarget(name string, target TargetConfig, globalMode, globalNaming string) []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, ", ")))
}
naming, mode := cmp.Or(sc.TargetNaming, globalNaming), cmp.Or(sc.Mode, globalMode)
// Skills off syncs no skill, and the target's agents must still sync.
if err := TargetNamingModeConfigError(naming, mode, target.ProjectRoot()); err != nil && sc.IsEnabled() {
problems = append(problems, err.Error())
}
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)
agentsSourcePath := cfg.EffectiveAgentsSource(projectRoot)
if info, statErr := os.Stat(sourcePath); statErr != nil {
if os.IsNotExist(statErr) {
// For project mode, missing source is a warning not an error —
// it gets created by init/install flows.
warnings = append(warnings, fmt.Sprintf("source directory does not exist yet: %s", sourcePath))
} else {
errs = append(errs, fmt.Sprintf("cannot access source path: %v", statErr))
}
} else if !info.IsDir() {
errs = append(errs, fmt.Sprintf("source path is not a directory: %s", sourcePath))
}
if !IsValidTargetNaming(cfg.TargetNaming) {
errs = append(errs, fmt.Sprintf("invalid project target naming %q (valid: %s)", cfg.TargetNaming, strings.Join(ValidTargetNamings, ", ")))
}
if err := cfg.ValidateExtras(projectRoot); err != nil {
errs = append(errs, err.Error())
}
problems := map[string][]string{}
for _, entry := range cfg.Targets {
entry.defaultTargetNaming = cfg.TargetNaming // a raw config has not been through LoadProject
problems[entry.Name] = append(problems[entry.Name], validateProjectTarget(entry, projectRoot, sourcePath, agentsSourcePath)...)
}
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, ", ")))
}
if err := TargetNamingModeConfigError(sc.TargetNaming, sc.Mode, ""); err != nil && sc.IsEnabled() {
problems = append(problems, err.Error())
}
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,
// absolute or ~/ in global mode, relative to the project root in project mode.
// A nil config is valid.
func ValidateTargetInstructions(ic *TargetInstructionsConfig, project bool) error {
if ic == nil {
return nil
}
path := strings.TrimSpace(ic.Path)
switch {
case path == "":
return errors.New("instructions.path is empty")
case strings.HasSuffix(path, "/") || strings.HasSuffix(path, `\`):
return fmt.Errorf("instructions.path %q must name a file, not a directory", path)
case project && (filepath.IsAbs(path) || strings.HasPrefix(path, "~")):
return fmt.Errorf("instructions.path %q must be relative to the project root", path)
case !project && !filepath.IsAbs(path) && !strings.HasPrefix(path, "~/"):
return fmt.Errorf("instructions.path %q must be absolute or start with ~/", path)
}
return nil
}
// resolveProjectTargetPath returns an absolute path for a project target.
// Uses configPath if non-empty, else builtinDefault. Returns "" if both empty.
func resolveProjectTargetPath(projectRoot, configPath, builtinDefault string) string {
path := strings.TrimSpace(configPath)
if path == "" {
path = strings.TrimSpace(builtinDefault)
}
if path == "" {
return ""
}
if filepath.IsAbs(path) {
return ExpandPath(path)
}
return filepath.Join(projectRoot, filepath.FromSlash(path))
}
// pathsOverlap returns true when a and b refer to the same directory or one
// contains the other. Both inputs must be absolute. Used to reject configs
// where a source directory aliases a sync target, which sync --force could
// wipe.
func pathsOverlap(a, b string) bool {
a = filepath.Clean(a)
b = filepath.Clean(b)
if a == b {
return true
}
upPrefix := ".." + string(filepath.Separator)
if rel, err := filepath.Rel(a, b); err == nil && rel != ".." && !strings.HasPrefix(rel, upPrefix) {
return true
}
if rel, err := filepath.Rel(b, a); err == nil && rel != ".." && !strings.HasPrefix(rel, upPrefix) {
return true
}
return false
}
// 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(expandedPath string) error {
if expandedPath == "" {
return nil // path resolved by target registry; skip filesystem check
}
info, statErr := os.Stat(expandedPath)
if statErr != nil {
if os.IsNotExist(statErr) {
return nil // sync will auto-create and notify
}
return fmt.Errorf("cannot access path: %v", statErr)
}
if !info.IsDir() {
return fmt.Errorf("path is not a directory: %s", expandedPath)
}
return nil
}