diff --git a/cmd/skillshare/collect.go b/cmd/skillshare/collect.go index 7b97886df..9985ae56a 100644 --- a/cmd/skillshare/collect.go +++ b/cmd/skillshare/collect.go @@ -85,7 +85,7 @@ func cmdCollect(args []string) error { summary, err = cmdCollectProject(opts, cwd, start) } default: - cfg, loadErr := config.Load() + cfg, loadErr := config.LoadWithoutProjects() if loadErr != nil { err = collectCommandError(loadErr, opts.jsonOutput) logCollectOp(cfgPath, start, err, summary) diff --git a/cmd/skillshare/sync.go b/cmd/skillshare/sync.go index 73338395e..2b5cde6cd 100644 --- a/cmd/skillshare/sync.go +++ b/cmd/skillshare/sync.go @@ -308,6 +308,9 @@ func cmdSync(args []string) error { if dryRun { ui.Warning("Dry run mode - no changes will be made") } + for _, root := range cfg.MissingProjects() { + ui.Warning("project %s: folder not found, skipped", root) + } } var entries []syncTargetEntry diff --git a/cmd/skillshare/target.go b/cmd/skillshare/target.go index cabb2d666..aa1ea7977 100644 --- a/cmd/skillshare/target.go +++ b/cmd/skillshare/target.go @@ -189,7 +189,7 @@ func targetAdd(args []string) error { } } - cfg, err := config.Load() + cfg, err := config.LoadWithoutProjects() if err != nil { return err } @@ -320,7 +320,7 @@ func targetRemove(args []string) error { return err } - cfg, err := config.Load() + cfg, err := config.LoadWithoutProjects() if err != nil { return err } @@ -460,7 +460,7 @@ type targetListJSONItem struct { } func targetList(jsonOutput bool) error { - cfg, err := config.Load() + cfg, err := config.LoadWithoutProjects() if err != nil { return err } @@ -507,7 +507,7 @@ func targetInfo(name string, args []string) error { return err } - cfg, err := config.Load() + cfg, err := config.LoadWithoutProjects() if err != nil { return err } diff --git a/cmd/skillshare/target_list_tui.go b/cmd/skillshare/target_list_tui.go index 89a4818a3..1e3779317 100644 --- a/cmd/skillshare/target_list_tui.go +++ b/cmd/skillshare/target_list_tui.go @@ -195,7 +195,7 @@ func buildTargetTUIItems(isProject bool, cwd string) ([]targetTUIItem, error) { }) } } else { - cfg, err := config.Load() + cfg, err := config.LoadWithoutProjects() if err != nil { return nil, err } @@ -531,7 +531,7 @@ func (m targetListTUIModel) doSetTargetMode(name, scope, newMode string) (string return "", err } } else { - cfg, err := config.Load() + cfg, err := config.LoadWithoutProjects() if err != nil { return "", err } @@ -606,7 +606,7 @@ func (m targetListTUIModel) doSetTargetNaming(name, newNaming string) (string, e return "", err } } else { - cfg, err := config.Load() + cfg, err := config.LoadWithoutProjects() if err != nil { return "", err } @@ -733,7 +733,7 @@ func (m targetListTUIModel) doAddPattern(name, scope, filterType, pattern string return "", err } } else { - cfg, err := config.Load() + cfg, err := config.LoadWithoutProjects() if err != nil { return "", err } @@ -783,7 +783,7 @@ func (m targetListTUIModel) doRemovePattern(name, scope, filterType, pattern str return "", err } } else { - cfg, err := config.Load() + cfg, err := config.LoadWithoutProjects() if err != nil { return "", err } @@ -1190,7 +1190,7 @@ func runTargetListTUI(mode runMode, cwd string) (string, string, error) { projCfg = pc } else { modeLabel = "global" - c, err := config.Load() + c, err := config.LoadWithoutProjects() if err != nil { return "", "", err } diff --git a/internal/config/config.go b/internal/config/config.go index 2a684dd17..547b9c645 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -87,6 +87,8 @@ type TargetConfig struct { Agents *ResourceTargetConfig `yaml:"agents,omitempty"` defaultTargetNaming string `yaml:"-"` + // projectRoot marks a target expanded from projects; see expandProjects. + projectRoot string `yaml:"-"` } // SkillsConfig returns the effective skills configuration. @@ -278,21 +280,23 @@ type Config struct { // operates on. One of: "skills" (default), "agents", "extras", "root". // "root" is BaseDir() and version-controls skills + agents + extras together. // Empty is treated as "skills" for backward compatibility. - GitRoot string `yaml:"git_root,omitempty"` - Mode string `yaml:"mode,omitempty"` // default mode: merge - TargetNaming string `yaml:"target_naming,omitempty"` - Targets map[string]TargetConfig `yaml:"targets"` - Extras []ExtraConfig `yaml:"extras,omitempty"` - Ignore []string `yaml:"ignore,omitempty"` - Audit AuditConfig `yaml:"audit,omitempty"` - Hub HubConfig `yaml:"hub,omitempty"` - Log LogConfig `yaml:"log,omitempty"` - ContextBudget ContextBudgetConfig `yaml:"context_budget,omitempty"` - TUI *bool `yaml:"tui,omitempty"` // nil = default true - GitLabHosts []string `yaml:"gitlab_hosts,omitempty"` - AzureHosts []string `yaml:"azure_hosts,omitempty"` - CNBHosts []string `yaml:"cnb_hosts,omitempty"` - GiteaHosts []string `yaml:"gitea_hosts,omitempty"` + GitRoot string `yaml:"git_root,omitempty"` + Mode string `yaml:"mode,omitempty"` // default mode: merge + TargetNaming string `yaml:"target_naming,omitempty"` + Targets map[string]TargetConfig `yaml:"targets"` + // Projects are project folders synced from this config, keyed by root as written. + Projects map[string]ManagedProject `yaml:"projects,omitempty"` + Extras []ExtraConfig `yaml:"extras,omitempty"` + Ignore []string `yaml:"ignore,omitempty"` + Audit AuditConfig `yaml:"audit,omitempty"` + Hub HubConfig `yaml:"hub,omitempty"` + Log LogConfig `yaml:"log,omitempty"` + ContextBudget ContextBudgetConfig `yaml:"context_budget,omitempty"` + TUI *bool `yaml:"tui,omitempty"` // nil = default true + GitLabHosts []string `yaml:"gitlab_hosts,omitempty"` + AzureHosts []string `yaml:"azure_hosts,omitempty"` + CNBHosts []string `yaml:"cnb_hosts,omitempty"` + GiteaHosts []string `yaml:"gitea_hosts,omitempty"` // PreserveTildeOnSave folds $HOME prefixes back to ~ when serializing the // config to YAML. Useful when the config is shared via dotfiles across @@ -635,6 +639,9 @@ func Load() (*Config, error) { cfg.Targets[name] = target } + if err := cfg.expandProjects(); err != nil { + return nil, err + } // Expand ~ in extras paths for i, extra := range cfg.Extras { cfg.Extras[i].Source = expandPath(extra.Source) @@ -668,11 +675,9 @@ func (c *Config) Save() error { // machine-agnostic (dotfiles-friendly). Opt-in via preserve_tilde_on_save. // The in-memory config is left untouched; we marshal a shallow copy with // folded path fields. - var payload *Config + payload := c.withoutProjectTargets() if c.PreserveTildeOnSave { - payload = c.cloneForSave() - } else { - payload = c + payload = payload.cloneForSave() } data, err := marshalYAML(payload) if err != nil { diff --git a/internal/config/projects.go b/internal/config/projects.go new file mode 100644 index 000000000..a70318dea --- /dev/null +++ b/internal/config/projects.go @@ -0,0 +1,321 @@ +package config + +import ( + "fmt" + "os" + "path/filepath" + "reflect" + "sort" + "strings" +) + +// ProjectTargetSep joins a project name and a tool into a target name. User-defined +// target names cannot contain it, so a project target never shadows one. +const ProjectTargetSep = "@" + +// ManagedProject is a project folder the global config syncs skills and agents into, +// using each tool's project paths from targets.yaml. The folder needs no .skillshare/. +// Its MCP servers live under mcp.projects, keyed by the same root. +type ManagedProject struct { + // Name labels the project's targets. Defaults to the folder's base name. + Name string `yaml:"name,omitempty"` + Targets []string `yaml:"targets,omitempty"` + // Skills and Agents turn that resource on when present; an empty value syncs all. + Skills *ResourceTargetConfig `yaml:"skills,omitempty"` + Agents *ResourceTargetConfig `yaml:"agents,omitempty"` +} + +// ProjectTargetName returns the target name of one tool in a project. +func ProjectTargetName(project, tool string) string { + return project + ProjectTargetSep + tool +} + +// SplitProjectTarget splits a project target name. ok is false for an ordinary target. +func SplitProjectTarget(name string) (project, tool string, ok bool) { + i := strings.LastIndex(name, ProjectTargetSep) + if i < 0 { + return "", name, false + } + return name[:i], name[i+1:], true +} + +// ProjectRoot is the folder a project target writes into, or "" for an ordinary target. +func (tc TargetConfig) ProjectRoot() string { return tc.projectRoot } + +// ProjectName returns the effective name of the project declared under root. +func (p ManagedProject) ProjectName(root string) string { + if p.Name != "" { + return p.Name + } + return filepath.Base(expandPath(root)) +} + +// ProjectToolGroup is the tools of one project that write skills to the same folder. +type ProjectToolGroup struct { + Tools []string + SkillsPath string // absolute + AgentsPath string // absolute; "" when no tool in the group has a project agents path +} + +// Target is the tool the group's target is named after: the one that takes agents, +// else the first listed. +func (g ProjectToolGroup) Target() string { + for _, tool := range g.Tools { + if _, ok := LookupProjectAgentTarget(tool); ok { + return tool + } + } + return g.Tools[0] +} + +// ToolGroups resolves the project's tools to folders under root, merging tools that +// share a skills folder such as .agents/skills so it is written once. +func (p ManagedProject) ToolGroups(root string) ([]ProjectToolGroup, error) { + root = expandPath(root) + var groups []ProjectToolGroup + byPath := map[string]int{} + for _, tool := range p.Targets { + skills, ok := LookupProjectTarget(tool) + if !ok { + return nil, fmt.Errorf("unknown target %q", tool) + } + path := filepath.Join(root, skills.Path) + i, seen := byPath[path] + if !seen { + i = len(groups) + byPath[path] = i + groups = append(groups, ProjectToolGroup{SkillsPath: path}) + } + groups[i].Tools = append(groups[i].Tools, tool) + // ponytail: one agents folder per group. targets.yaml has at most one tool with + // project agents per shared skills folder; split the group if that changes. + if agents, ok := LookupProjectAgentTarget(tool); ok && groups[i].AgentsPath == "" { + groups[i].AgentsPath = filepath.Join(root, agents.Path) + } + } + return groups, nil +} + +// MissingProjects lists declared roots that are not folders. They get no targets, so a +// sync never creates a project that was moved or deleted. +func (c *Config) MissingProjects() []string { + var missing []string + for root := range c.Projects { + if info, err := os.Stat(expandPath(root)); err != nil || !info.IsDir() { + missing = append(missing, root) + } + } + sort.Strings(missing) + return missing +} + +// expandProjects adds each project's targets to c.Targets, where sync, status, diff and +// doctor find them like any other. Save leaves them out again. +func (c *Config) expandProjects() error { + names := map[string]string{} + for root, project := range c.Projects { + abs := expandPath(root) + if !filepath.IsAbs(abs) { + return fmt.Errorf("projects: %s must be an absolute path or start with ~", root) + } + name := project.ProjectName(root) + if strings.ContainsAny(name, ProjectTargetSep+`/\`) { + return fmt.Errorf("projects: %s: name %q cannot contain %s, / or \\", root, name, ProjectTargetSep) + } + if other, taken := names[name]; taken { + return fmt.Errorf("projects: %s and %s are both named %q; set name on one of them", other, root, name) + } + names[name] = root + for _, rc := range []*ResourceTargetConfig{project.Skills, project.Agents} { + if rc != nil && rc.Path != "" { + return fmt.Errorf("projects: %s: path is not allowed; each target's project path is used", root) + } + } + groups, err := project.ToolGroups(root) + if err != nil { + return fmt.Errorf("projects: %s: %w", root, err) + } + if info, err := os.Stat(abs); err != nil || !info.IsDir() { + continue + } + if project.Skills == nil && project.Agents == nil { + continue + } + for _, group := range groups { + if project.Skills == nil && group.AgentsPath == "" { + continue + } + // ponytail: every target syncs skills, so an agents-only project excludes + // them all and is left with an empty skills folder. Teach the sync loops + // to skip skills if that folder ever matters. + skills := ResourceTargetConfig{Exclude: []string{"*"}} + if project.Skills != nil { + skills = *project.Skills + } + skills.Path = group.SkillsPath + target := TargetConfig{Skills: &skills, projectRoot: abs, defaultTargetNaming: c.TargetNaming} + if project.Agents != nil && group.AgentsPath != "" { + agents := *project.Agents + agents.Path = group.AgentsPath + target.Agents = &agents + } + if c.Targets == nil { + c.Targets = map[string]TargetConfig{} + } + c.Targets[ProjectTargetName(name, group.Target())] = target + } + } + return nil +} + +// OwnTargets returns the targets declared under targets, without the project ones. +func (c *Config) OwnTargets() map[string]TargetConfig { + own := make(map[string]TargetConfig, len(c.Targets)) + for name, target := range c.Targets { + if target.projectRoot == "" { + own[name] = target + } + } + return own +} + +// withoutProjectTargets returns c as it should be written: project targets come from +// projects, never from targets. +func (c *Config) withoutProjectTargets() *Config { + out := *c + out.Targets = c.OwnTargets() + return &out +} + +// LoadWithoutProjects loads the config for commands that edit or collect from targets. +// Project targets are edited under projects, and a project's own skills stay in it. +func LoadWithoutProjects() (*Config, error) { + cfg, err := Load() + if err != nil { + return nil, err + } + cfg.Targets = cfg.OwnTargets() + return cfg, nil +} + +// ValidateProjects reports whether projects could replace c.Projects, without changing c. +func (c *Config) ValidateProjects(projects map[string]ManagedProject) error { + probe := Config{Targets: c.OwnTargets(), Projects: projects, TargetNaming: c.TargetNaming} + for _, project := range projects { + for _, rc := range []*ResourceTargetConfig{project.Skills, project.Agents} { + if rc != nil && !IsValidSyncMode(rc.Mode) { + return fmt.Errorf("invalid sync mode %q (valid: %s)", rc.Mode, strings.Join(ValidSyncModes, ", ")) + } + } + } + return probe.expandProjects() +} + +// ConvertibleProject is a group of ordinary targets whose folders are the tool paths of +// one project folder, so projects can declare them instead. +type ConvertibleProject struct { + Root string + Targets []string // target names, sorted + Project ManagedProject +} + +// ConvertibleProjects finds targets with a custom path such as ~/work/app/.claude/skills. +// A folder is offered only when its targets agree on mode and filters, because a project +// has one set of each. +func (c *Config) ConvertibleProjects() []ConvertibleProject { + specs, err := loadTargetSpecs() + if err != nil { + return nil + } + home, _ := os.UserHomeDir() + declared := map[string]bool{} + for root := range c.Projects { + declared[expandPath(root)] = true + } + withoutPath := func(rc ResourceTargetConfig) ResourceTargetConfig { + rc.Path = "" + return rc + } + + byRoot := map[string]*ConvertibleProject{} + mixed := map[string]bool{} + for _, name := range sortedTargetNames(c.OwnTargets()) { + target := c.Targets[name] + skills := target.SkillsConfig() + root, tool := projectToolForPath(specs, name, skills.Path) + if root == "" || root == home || declared[root] { + continue + } + var agents *ResourceTargetConfig + if ac := target.AgentsConfig(); ac.Path != "" { + known, ok := LookupProjectAgentTarget(tool) + if !ok || ac.Path != filepath.Join(root, known.Path) { + mixed[root] = true + continue + } + rc := withoutPath(ac) + agents = &rc + } + sk := withoutPath(skills) + sk.TargetNaming = "" + if target.Skills != nil { + sk.TargetNaming = target.Skills.TargetNaming + } + found := byRoot[root] + if found == nil { + byRoot[root] = &ConvertibleProject{Root: root, Targets: []string{name}, Project: ManagedProject{Targets: []string{tool}, Skills: &sk, Agents: agents}} + continue + } + if !reflect.DeepEqual(*found.Project.Skills, sk) || (agents != nil && found.Project.Agents != nil && !reflect.DeepEqual(*found.Project.Agents, *agents)) { + mixed[root] = true + continue + } + found.Targets = append(found.Targets, name) + found.Project.Targets = append(found.Project.Targets, tool) + if found.Project.Agents == nil { + found.Project.Agents = agents + } + } + + var out []ConvertibleProject + for root, found := range byRoot { + if !mixed[root] { + out = append(out, *found) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].Root < out[j].Root }) + return out +} + +func sortedTargetNames(targets map[string]TargetConfig) []string { + names := make([]string, 0, len(targets)) + for name := range targets { + names = append(names, name) + } + sort.Strings(names) + return names +} + +// projectToolForPath reads a skills folder as /. The longest +// project path wins; among tools sharing it, the one named like the target, then +// universal, then the first listed. +func projectToolForPath(specs []targetSpec, targetName, path string) (root, tool string) { + longest := 0 + for _, spec := range specs { + rel := normalizeTargetPath(spec.Skills.Project) + // ponytail: a bare folder name such as "skills" would match almost any custom + // path, so only tool paths with a parent folder are recognised. + if !strings.ContainsRune(rel, filepath.Separator) || !strings.HasSuffix(path, string(filepath.Separator)+rel) { + continue + } + better := len(rel) > longest + if len(rel) == longest { + better = tool != targetName && (targetSpecMatchesName(spec, targetName) || (spec.Name == "universal" && !strings.EqualFold(tool, "universal"))) + } + if better { + longest = len(rel) + root, tool = strings.TrimSuffix(path, string(filepath.Separator)+rel), spec.Name + } + } + return root, tool +} diff --git a/internal/config/projects_test.go b/internal/config/projects_test.go new file mode 100644 index 000000000..c75af59e3 --- /dev/null +++ b/internal/config/projects_test.go @@ -0,0 +1,156 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// loadWithProjects writes a global config whose projects section is body, with $ROOT +// replaced by a temp dir holding the folders named in dirs, and loads it. +func loadWithProjects(t *testing.T, body string, dirs ...string) (*Config, string, error) { + t.Helper() + root := t.TempDir() + for _, dir := range append(dirs, "skills") { + if err := os.MkdirAll(filepath.Join(root, dir), 0755); err != nil { + t.Fatal(err) + } + } + path := filepath.Join(root, "config.yaml") + t.Setenv("SKILLSHARE_CONFIG", path) + data := "source: $ROOT/skills\ntargets: {}\nprojects:\n" + body + if err := os.WriteFile(path, []byte(strings.ReplaceAll(data, "$ROOT", root)), 0644); err != nil { + t.Fatal(err) + } + cfg, err := Load() + return cfg, root, err +} + +func TestProjects_ExpandIntoOneTargetPerSkillsFolder(t *testing.T) { + cfg, root, err := loadWithProjects(t, ` $ROOT/app: + targets: [claude, codex, cursor] + skills: + mode: copy + include: [security__*] + agents: {} +`, "app") + if err != nil { + t.Fatal(err) + } + if len(cfg.Targets) != 2 { + t.Fatalf("targets %v, want app@claude and app@cursor", cfg.Targets) + } + claude := cfg.Targets["app@claude"] + if sc := claude.SkillsConfig(); sc.Path != filepath.Join(root, "app", ".claude", "skills") || sc.Mode != "copy" || len(sc.Include) != 1 { + t.Errorf("app@claude skills %+v", sc) + } + if got := claude.AgentsConfig().Path; got != filepath.Join(root, "app", ".claude", "agents") { + t.Errorf("app@claude agents path %q", got) + } + // codex and cursor share .agents/skills; cursor names the target because it takes agents. + shared := cfg.Targets["app@cursor"] + if got := shared.SkillsConfig().Path; got != filepath.Join(root, "app", ".agents", "skills") { + t.Errorf("app@cursor skills path %q", got) + } + if shared.ProjectRoot() != filepath.Join(root, "app") { + t.Errorf("project root %q", shared.ProjectRoot()) + } +} + +func TestProjects_SaveKeepsProjectTargetsOutOfTargets(t *testing.T) { + cfg, _, err := loadWithProjects(t, " $ROOT/app:\n targets: [claude]\n skills: {}\n", "app") + if err != nil { + t.Fatal(err) + } + if err := cfg.Save(); err != nil { + t.Fatal(err) + } + data, _ := os.ReadFile(ConfigPath()) + if strings.Contains(string(data), "app@claude") || !strings.Contains(string(data), "skills: {}") { + t.Fatalf("saved config:\n%s", data) + } +} + +func TestProjects_AgentsOnlyExcludesEverySkill(t *testing.T) { + cfg, _, err := loadWithProjects(t, " $ROOT/app:\n targets: [claude, codex]\n agents: {}\n", "app") + if err != nil { + t.Fatal(err) + } + // codex has no project agents folder, so it gets no target at all. + if len(cfg.Targets) != 1 { + t.Fatalf("targets %v", cfg.Targets) + } + claude := cfg.Targets["app@claude"] + if got := claude.SkillsConfig().Exclude; len(got) != 1 || got[0] != "*" { + t.Errorf("skills exclude %v", got) + } +} + +func TestProjects_MissingFolderGetsNoTargets(t *testing.T) { + cfg, _, err := loadWithProjects(t, " $ROOT/gone:\n targets: [claude]\n skills: {}\n") + if err != nil { + t.Fatal(err) + } + if len(cfg.Targets) != 0 || len(cfg.MissingProjects()) != 1 { + t.Fatalf("targets %v, missing %v", cfg.Targets, cfg.MissingProjects()) + } +} + +func TestProjects_Rejected(t *testing.T) { + for name, body := range map[string]string{ + "relative root": " work/app:\n targets: [claude]\n", + "unknown target": " $ROOT/app:\n targets: [nope]\n", + "explicit path": " $ROOT/app:\n targets: [claude]\n skills:\n path: /tmp/x\n", + "same name": " $ROOT/app:\n targets: [claude]\n $ROOT/other/app:\n targets: [claude]\n", + "name with @": " $ROOT/app:\n name: a@b\n targets: [claude]\n", + } { + if _, _, err := loadWithProjects(t, body, "app", "other/app"); err == nil { + t.Errorf("%s: loaded", name) + } + } +} + +func TestMatchesTargetName_SeesThroughProjectTargets(t *testing.T) { + if !MatchesTargetName("claude", "app@claude") || !MatchesTargetName("codex", "app@cursor") || MatchesTargetName("pi", "app@claude") { + t.Fatal("project target matching is wrong") + } +} + +func TestConvertibleProjects_GroupsCustomPathTargetsByFolder(t *testing.T) { + root := filepath.Join(t.TempDir(), "legacy") + same := ResourceTargetConfig{Mode: "copy", Include: []string{"team-*"}} + target := func(rel string, rc ResourceTargetConfig) TargetConfig { + rc.Path = filepath.Join(root, rel) + return TargetConfig{Skills: &rc} + } + cfg := &Config{Targets: map[string]TargetConfig{ + "skill-path01": target(".agents/skills", same), + "claude-legacy": { + Skills: target(".claude/skills", same).Skills, + Agents: &ResourceTargetConfig{Path: filepath.Join(root, ".claude", "agents")}, + }, + "elsewhere": target("custom/skills", same), + }} + + found := cfg.ConvertibleProjects() + + if len(found) != 1 || found[0].Root != root || strings.Join(found[0].Targets, ",") != "claude-legacy,skill-path01" { + t.Fatalf("found %+v", found) + } + project := found[0].Project + if strings.Join(project.Targets, ",") != "claude,universal" || project.Skills.Mode != "copy" || project.Skills.Path != "" || project.Agents == nil { + t.Errorf("project %+v skills %+v", project, project.Skills) + } +} + +func TestConvertibleProjects_SkipsFoldersWhoseTargetsDisagree(t *testing.T) { + root := filepath.Join(t.TempDir(), "legacy") + cfg := &Config{Targets: map[string]TargetConfig{ + "a": {Skills: &ResourceTargetConfig{Path: filepath.Join(root, ".claude", "skills"), Mode: "copy"}}, + "b": {Skills: &ResourceTargetConfig{Path: filepath.Join(root, ".agents", "skills"), Mode: "merge"}}, + }} + if found := cfg.ConvertibleProjects(); len(found) != 0 { + t.Fatalf("found %+v", found) + } +} diff --git a/internal/config/targets.go b/internal/config/targets.go index 893fc30a5..a577e8d14 100644 --- a/internal/config/targets.go +++ b/internal/config/targets.go @@ -330,6 +330,13 @@ func MatchesTargetName(skillTarget, configTarget string) bool { if skillTarget == configTarget { return true } + // A skill for claude also belongs in a project's claude target. + if _, tool, ok := SplitProjectTarget(configTarget); ok { + configTarget = tool + if skillTarget == tool { + return true + } + } specs, err := loadTargetSpecs() if err != nil { diff --git a/internal/server/handler_collect.go b/internal/server/handler_collect.go index 9ebe1505e..500ea3056 100644 --- a/internal/server/handler_collect.go +++ b/internal/server/handler_collect.go @@ -43,7 +43,7 @@ func (s *Server) handleCollectScan(w http.ResponseWriter, r *http.Request) { s.mu.RLock() source := s.cfg.EffectiveSkillsSource() globalMode := s.cfg.Mode - targets := s.cloneTargets() + targets := s.cfg.OwnTargets() // a project's own skills stay in the project agentsSource := s.agentsSource() s.mu.RUnlock() diff --git a/internal/server/handler_projects.go b/internal/server/handler_projects.go new file mode 100644 index 000000000..3779cf414 --- /dev/null +++ b/internal/server/handler_projects.go @@ -0,0 +1,281 @@ +package server + +import ( + "encoding/json" + "net/http" + "os" + "path/filepath" + "sort" + "time" + + "skillshare/internal/config" + ssync "skillshare/internal/sync" +) + +// projectResource is one resource kind of a project. nil means it is not sent. +type projectResource struct { + Mode string `json:"mode"` + TargetNaming string `json:"targetNaming,omitempty"` + Include []string `json:"include"` + Exclude []string `json:"exclude"` +} + +type projectGroup struct { + Target string `json:"target"` // target name, as the sync and target lists show it + Tools []string `json:"tools"` + SkillsPath string `json:"skillsPath"` + AgentsPath string `json:"agentsPath"` +} + +type projectItem struct { + Root string `json:"root"` // as written in config.yaml + Path string `json:"path"` // absolute + Name string `json:"name"` + CustomName string `json:"customName,omitempty"` + Targets []string `json:"targets"` + Skills *projectResource `json:"skills"` + Agents *projectResource `json:"agents"` + Groups []projectGroup `json:"groups"` + Missing bool `json:"missing"` + HasOwnConfig bool `json:"hasOwnConfig"` +} + +type projectBody struct { + Root string `json:"root"` + Name string `json:"name"` + Targets []string `json:"targets"` + Skills *projectResource `json:"skills"` + Agents *projectResource `json:"agents"` + // Create refuses a root that is already declared. + Create bool `json:"create"` +} + +func toProjectResource(rc *config.ResourceTargetConfig) *projectResource { + if rc == nil { + return nil + } + return &projectResource{Mode: rc.Mode, TargetNaming: rc.TargetNaming, Include: append([]string{}, rc.Include...), Exclude: append([]string{}, rc.Exclude...)} +} + +func (r *projectResource) config() *config.ResourceTargetConfig { + if r == nil { + return nil + } + return &config.ResourceTargetConfig{Mode: r.Mode, TargetNaming: r.TargetNaming, Include: r.Include, Exclude: r.Exclude} +} + +// hasOwnProjectConfig reports a folder that project mode manages too. Sync never +// overwrites what it does not own there, so the dashboard says so up front. +func hasOwnProjectConfig(root string) bool { + _, err := os.Stat(filepath.Join(root, ".skillshare", "config.yaml")) + return err == nil +} + +func (s *Server) requireGlobalProjects(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if s.IsProjectMode() { + writeError(w, http.StatusBadRequest, "projects belong in the global config") + return + } + next(w, r) + } +} + +func (s *Server) handleListProjects(w http.ResponseWriter, r *http.Request) { + s.mu.RLock() + defer s.mu.RUnlock() + + items := []projectItem{} + for root, project := range s.cfg.Projects { + abs := config.ExpandPath(root) + name := project.ProjectName(root) + item := projectItem{ + Root: root, Path: abs, Name: name, CustomName: project.Name, + Targets: append([]string{}, project.Targets...), + Skills: toProjectResource(project.Skills), Agents: toProjectResource(project.Agents), + Groups: []projectGroup{}, + HasOwnConfig: hasOwnProjectConfig(abs), + } + if info, err := os.Stat(abs); err != nil || !info.IsDir() { + item.Missing = true + } + groups, _ := project.ToolGroups(root) // Load has already accepted every target + for _, group := range groups { + item.Groups = append(item.Groups, projectGroup{Target: config.ProjectTargetName(name, group.Target()), Tools: group.Tools, SkillsPath: group.SkillsPath, AgentsPath: group.AgentsPath}) + } + items = append(items, item) + } + sort.Slice(items, func(i, j int) bool { return items[i].Name < items[j].Name }) + + type convertible struct { + Root string `json:"root"` + Targets []string `json:"targets"` + Tools []string `json:"tools"` + Agents bool `json:"agents"` + } + offers := []convertible{} + for _, found := range s.cfg.ConvertibleProjects() { + offers = append(offers, convertible{Root: found.Root, Targets: found.Targets, Tools: found.Project.Targets, Agents: found.Project.Agents != nil}) + } + + type tool struct { + Name string `json:"name"` + SkillsPath string `json:"skillsPath"` + AgentsPath string `json:"agentsPath"` + } + tools := []tool{} + agentPaths := config.ProjectAgentTargets() + for name, target := range config.ProjectTargets() { + tools = append(tools, tool{Name: name, SkillsPath: target.Path, AgentsPath: agentPaths[name].Path}) + } + sort.Slice(tools, func(i, j int) bool { return tools[i].Name < tools[j].Name }) + + writeJSON(w, map[string]any{"projects": items, "convertible": offers, "tools": tools}) +} + +// handleSaveProject adds a project or replaces the one declared under the same root. +func (s *Server) handleSaveProject(w http.ResponseWriter, r *http.Request) { + start := time.Now() + var body projectBody + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + if body.Root == "" { + writeError(w, http.StatusBadRequest, "root is required") + return + } + for _, rc := range []*projectResource{body.Skills, body.Agents} { + if rc == nil { + continue + } + if _, err := ssync.FilterSkills(nil, rc.Include, rc.Exclude); err != nil { + writeError(w, http.StatusBadRequest, "invalid include/exclude pattern: "+err.Error()) + return + } + } + + s.mu.Lock() + defer s.mu.Unlock() + + root := s.declaredProjectRoot(body.Root) + _, exists := s.cfg.Projects[root] + if body.Create { + if exists { + writeError(w, http.StatusConflict, "project is already declared: "+body.Root) + return + } + if info, err := os.Stat(config.ExpandPath(root)); err != nil || !info.IsDir() { + writeError(w, http.StatusBadRequest, "folder not found: "+body.Root) + return + } + } else if !exists { + writeError(w, http.StatusNotFound, "project not found: "+body.Root) + return + } + + projects := make(map[string]config.ManagedProject, len(s.cfg.Projects)+1) + for k, v := range s.cfg.Projects { + projects[k] = v + } + projects[root] = config.ManagedProject{Name: body.Name, Targets: body.Targets, Skills: body.Skills.config(), Agents: body.Agents.config()} + if err := s.cfg.ValidateProjects(projects); err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + s.cfg.Projects = projects + if err := s.saveAndReloadConfig(); err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + action := "update" + if body.Create { + action = "add" + } + s.writeOpsLog("project", "ok", start, map[string]any{"action": action, "root": root, "scope": "ui"}, "") + writeJSON(w, map[string]any{"success": true, "root": root}) +} + +func (s *Server) handleRemoveProject(w http.ResponseWriter, r *http.Request) { + start := time.Now() + s.mu.Lock() + defer s.mu.Unlock() + + root := s.declaredProjectRoot(r.URL.Query().Get("root")) + if _, exists := s.cfg.Projects[root]; !exists { + writeError(w, http.StatusNotFound, "project not found: "+root) + return + } + abs := config.ExpandPath(root) + for name, target := range s.cfg.Targets { + if target.ProjectRoot() != abs { + continue + } + if status, err := s.detachSkillsTarget(target.SkillsConfig().Path); err != nil { + writeError(w, status, name+": "+err.Error()) + return + } + } + delete(s.cfg.Projects, root) + if err := s.saveAndReloadConfig(); err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + s.writeOpsLog("project", "ok", start, map[string]any{"action": "remove", "root": root, "scope": "ui"}, "") + writeJSON(w, map[string]any{"success": true, "root": root}) +} + +// handleConvertProject moves the targets that write into one folder under projects. +// They keep their folders, mode and filters, so the next sync changes nothing. +func (s *Server) handleConvertProject(w http.ResponseWriter, r *http.Request) { + start := time.Now() + var body struct { + Root string `json:"root"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + + s.mu.Lock() + defer s.mu.Unlock() + + for _, found := range s.cfg.ConvertibleProjects() { + if found.Root != body.Root { + continue + } + projects := make(map[string]config.ManagedProject, len(s.cfg.Projects)+1) + for k, v := range s.cfg.Projects { + projects[k] = v + } + projects[found.Root] = found.Project + if err := s.cfg.ValidateProjects(projects); err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + for _, name := range found.Targets { + delete(s.cfg.Targets, name) + } + s.cfg.Projects = projects + if err := s.saveAndReloadConfig(); err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + s.writeOpsLog("project", "ok", start, map[string]any{"action": "convert", "root": found.Root, "targets": found.Targets, "scope": "ui"}, "") + writeJSON(w, map[string]any{"success": true, "root": found.Root}) + return + } + writeError(w, http.StatusNotFound, "no targets to convert for "+body.Root) +} + +// declaredProjectRoot returns the key a root is declared under, so ~/app and its +// absolute form name the same project. An undeclared root is returned as given. +func (s *Server) declaredProjectRoot(root string) string { + abs := filepath.Clean(config.ExpandPath(root)) + for key := range s.cfg.Projects { + if filepath.Clean(config.ExpandPath(key)) == abs { + return key + } + } + return root +} diff --git a/internal/server/handler_projects_test.go b/internal/server/handler_projects_test.go new file mode 100644 index 000000000..d3926a8b8 --- /dev/null +++ b/internal/server/handler_projects_test.go @@ -0,0 +1,106 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "skillshare/internal/config" +) + +func projectRequest(t *testing.T, s *Server, method, url, body string) *httptest.ResponseRecorder { + t.Helper() + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(method, url, strings.NewReader(body))) + return rr +} + +func addProject(t *testing.T, s *Server, root string) { + t.Helper() + if err := os.MkdirAll(root, 0755); err != nil { + t.Fatal(err) + } + body := `{"create":true,"root":"` + root + `","targets":["claude","codex"],"skills":{"mode":"copy","include":["team-*"],"exclude":[]}}` + if rr := projectRequest(t, s, http.MethodPut, "/api/projects", body); rr.Code != http.StatusOK { + t.Fatalf("add project: %d %s", rr.Code, rr.Body) + } +} + +func TestSaveProject_AddsTargetsThatOnlyTheProjectScopeLists(t *testing.T) { + s, src := newTestServer(t) + root := filepath.Join(filepath.Dir(src), "app") + addProject(t, s, root) + + var listed struct { + Targets []targetItem `json:"targets"` + } + json.Unmarshal(projectRequest(t, s, http.MethodGet, "/api/targets?scope=projects", "").Body.Bytes(), &listed) + if len(listed.Targets) != 2 || listed.Targets[0].Project != root { + t.Fatalf("project targets %+v", listed.Targets) + } + json.Unmarshal(projectRequest(t, s, http.MethodGet, "/api/targets", "").Body.Bytes(), &listed) + if len(listed.Targets) != 0 { + t.Fatalf("own targets %+v", listed.Targets) + } +} + +func TestSaveProject_Rejected(t *testing.T) { + s, src := newTestServer(t) + root := filepath.Join(filepath.Dir(src), "app") + addProject(t, s, root) + for name, body := range map[string]string{ + "already declared": `{"create":true,"root":"` + root + `","targets":["claude"]}`, + "folder not found": `{"create":true,"root":"` + root + `-gone","targets":["claude"]}`, + "unknown target": `{"root":"` + root + `","targets":["nope"]}`, + "invalid mode": `{"root":"` + root + `","targets":["claude"],"skills":{"mode":"mirror"}}`, + } { + if rr := projectRequest(t, s, http.MethodPut, "/api/projects", body); rr.Code == http.StatusOK { + t.Errorf("%s: saved", name) + } + } +} + +func TestProjectTargets_CannotBeEditedAsTargets(t *testing.T) { + s, src := newTestServer(t) + addProject(t, s, filepath.Join(filepath.Dir(src), "app")) + + for _, method := range []string{http.MethodPatch, http.MethodDelete} { + if rr := projectRequest(t, s, method, "/api/targets/app@claude", `{"mode":"merge"}`); rr.Code != http.StatusBadRequest { + t.Errorf("%s: %d %s", method, rr.Code, rr.Body) + } + } +} + +func TestRemoveProject_DropsItsTargets(t *testing.T) { + s, src := newTestServer(t) + root := filepath.Join(filepath.Dir(src), "app") + addProject(t, s, root) + + if rr := projectRequest(t, s, http.MethodDelete, "/api/projects?root="+root, ""); rr.Code != http.StatusOK { + t.Fatalf("%d %s", rr.Code, rr.Body) + } + if len(s.cfg.Projects) != 0 || len(s.cfg.Targets) != 0 { + t.Fatalf("projects %v, targets %v", s.cfg.Projects, s.cfg.Targets) + } +} + +func TestConvertProject_MovesTargetsUnderProjectsWithTheSameFolders(t *testing.T) { + root := filepath.Join(t.TempDir(), "legacy") + skills := filepath.Join(root, ".claude", "skills") + s, _ := newTestServerWithTargets(t, map[string]string{"old-claude": skills}) + + if rr := projectRequest(t, s, http.MethodPost, "/api/projects/convert", `{"root":"`+root+`"}`); rr.Code != http.StatusOK { + t.Fatalf("%d %s", rr.Code, rr.Body) + } + if _, kept := s.cfg.Targets["old-claude"]; kept { + t.Error("old-claude is still a target") + } + converted := s.cfg.Targets[config.ProjectTargetName("legacy", "claude")] + if got := converted.SkillsConfig().Path; got != skills { + t.Errorf("skills path %q, want %q", got, skills) + } +} diff --git a/internal/server/handler_sync_matrix.go b/internal/server/handler_sync_matrix.go index 77b064aa5..95764c702 100644 --- a/internal/server/handler_sync_matrix.go +++ b/internal/server/handler_sync_matrix.go @@ -188,7 +188,8 @@ func (s *Server) handleSyncMatrixPreview(w http.ResponseWriter, r *http.Request) // Agents — resolve path from config or builtin defaults target, ok := targets[body.Target] - if ok && agentsSource != "" { + _, projectTool, isProject := config.SplitProjectTarget(body.Target) + if (ok || isProject) && agentsSource != "" { ac := target.AgentsConfig() agentPath := ac.Path if agentPath == "" { @@ -201,6 +202,10 @@ func (s *Server) handleSyncMatrixPreview(w http.ResponseWriter, r *http.Request) if builtin, found := previewBuiltin[body.Target]; found { agentPath = builtin.Path } + // A project's draft can turn agents on before the project is saved. + if builtin, found := config.LookupProjectAgentTarget(projectTool); isProject && found { + agentPath = builtin.Path + } } if agentPath != "" { discovered, _ := resource.AgentKind{}.Discover(agentsSource) diff --git a/internal/server/handler_sync_matrix_test.go b/internal/server/handler_sync_matrix_test.go index a3fc4ae8d..803d54f99 100644 --- a/internal/server/handler_sync_matrix_test.go +++ b/internal/server/handler_sync_matrix_test.go @@ -338,3 +338,21 @@ func TestHandleSyncMatrixPreview_InvalidAgentPattern(t *testing.T) { t.Errorf("expected 400 for invalid agent pattern, got %d", rr.Code) } } + +func TestHandleSyncMatrixPreview_ProjectDraftGetsAgents(t *testing.T) { + home := filepath.Join(t.TempDir(), "home") + os.MkdirAll(home, 0755) + t.Setenv("HOME", home) + + s, _ := newTestServerWithTargets(t, map[string]string{"claude": filepath.Join(t.TempDir(), "claude-skills")}) + addAgentFile(t, s.cfg.EffectiveAgentsSource(), "code-reviewer.md") + + // No target is called shop@claude yet: the project page previews before it saves. + body := `{"target":"shop@claude","include":[],"exclude":[]}` + req := httptest.NewRequest(http.MethodPost, "/api/sync-matrix/preview", strings.NewReader(body)) + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, req) + if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), `"kind":"agent"`) { + t.Fatalf("status %d, body %s", rr.Code, rr.Body.String()) + } +} diff --git a/internal/server/handler_targets.go b/internal/server/handler_targets.go index ec053ec7b..e8f202376 100644 --- a/internal/server/handler_targets.go +++ b/internal/server/handler_targets.go @@ -17,6 +17,7 @@ import ( type targetItem struct { Name string `json:"name"` + Project string `json:"project,omitempty"` // root of the project this target belongs to Path string `json:"path"` Mode string `json:"mode"` TargetNaming string `json:"targetNaming"` @@ -82,7 +83,13 @@ func (s *Server) handleListTargets(w http.ResponseWriter, r *http.Request) { items := make([]targetItem, 0, len(targets)) discovered, discoveredErr := ssync.DiscoverSourceSkills(source) + // Project targets are edited under projects, so they are listed only on request: + // scope=projects for them alone, scope=all for what a sync writes. + scope := r.URL.Query().Get("scope") for name, target := range targets { + if scope != "all" && (target.ProjectRoot() != "") != (scope == "projects") { + continue + } sc := target.SkillsConfig() mode := sc.Mode if mode == "" { @@ -91,6 +98,7 @@ func (s *Server) handleListTargets(w http.ResponseWriter, r *http.Request) { item := targetItem{ Name: name, + Project: target.ProjectRoot(), Path: sc.Path, Mode: mode, TargetNaming: config.EffectiveTargetNaming(sc.TargetNaming), @@ -264,29 +272,12 @@ func (s *Server) handleRemoveTarget(w http.ResponseWriter, r *http.Request) { sc := target.SkillsConfig() - // Clean up symlinks/manifest from the target before deleting from config - info, err := os.Lstat(sc.Path) - if err == nil { - if info.Mode()&os.ModeSymlink != 0 { - // Symlink mode: entire directory is a symlink - if err := removeTargetPath(sc.Path); err != nil { - writeError(w, http.StatusInternalServerError, "failed to remove target symlink: "+err.Error()) - return - } - } else if info.IsDir() { - // Remove manifest if present (merge/copy mode) - if err := ssync.RemoveManifest(sc.Path); err != nil { - writeError(w, http.StatusInternalServerError, "failed to remove target manifest: "+err.Error()) - return - } - // Merge mode: remove individual skill symlinks pointing to source - if err := s.unlinkMergeSymlinks(sc.Path); err != nil { - writeError(w, http.StatusInternalServerError, "failed to clean target symlinks: "+err.Error()) - return - } - } - } else if !os.IsNotExist(err) { - writeError(w, http.StatusInternalServerError, "failed to inspect target: "+err.Error()) + if target.ProjectRoot() != "" { + writeError(w, http.StatusBadRequest, name+" belongs to a project; remove the project instead") + return + } + if status, err := s.detachSkillsTarget(sc.Path); err != nil { + writeError(w, status, err.Error()) return } @@ -330,6 +321,10 @@ func (s *Server) handleUpdateTarget(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusNotFound, "target not found: "+name) return } + if target.ProjectRoot() != "" { + writeError(w, http.StatusBadRequest, name+" belongs to a project; edit the project instead") + return + } var body struct { Include *[]string `json:"include"` // null = no change, [] = clear @@ -461,6 +456,35 @@ func (s *Server) handleUpdateTarget(w http.ResponseWriter, r *http.Request) { writeJSON(w, map[string]any{"success": true}) } +// detachSkillsTarget removes what sync owns in a skills folder before its target leaves +// the config: the folder symlink, or the manifest and the symlinks into the source. +// Copies and local skills stay. +func (s *Server) detachSkillsTarget(path string) (int, error) { + info, err := os.Lstat(path) + if os.IsNotExist(err) { + return 0, nil + } + if err != nil { + return http.StatusInternalServerError, fmt.Errorf("failed to inspect target: %w", err) + } + if info.Mode()&os.ModeSymlink != 0 { + // Symlink mode: entire directory is a symlink + if err := removeTargetPath(path); err != nil { + return http.StatusInternalServerError, fmt.Errorf("failed to remove target symlink: %w", err) + } + } else if info.IsDir() { + // Remove manifest if present (merge/copy mode) + if err := ssync.RemoveManifest(path); err != nil { + return http.StatusInternalServerError, fmt.Errorf("failed to remove target manifest: %w", err) + } + // Merge mode: remove individual skill symlinks pointing to source + if err := s.unlinkMergeSymlinks(path); err != nil { + return http.StatusInternalServerError, fmt.Errorf("failed to clean target symlinks: %w", err) + } + } + return 0, nil +} + // unlinkMergeSymlinks removes symlinks in targetPath that point under the // source directory and copies the skill contents back as real files. func (s *Server) unlinkMergeSymlinks(targetPath string) error { diff --git a/internal/server/server.go b/internal/server/server.go index 9fabf39a5..e392554ac 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -398,6 +398,12 @@ func (s *Server) registerRoutes() { s.mux.HandleFunc("PATCH /api/targets/{name}", s.handleUpdateTarget) s.mux.HandleFunc("DELETE /api/targets/{name}", s.handleRemoveTarget) + // Projects (global config only) + s.mux.HandleFunc("GET /api/projects", s.requireGlobalProjects(s.handleListProjects)) + s.mux.HandleFunc("PUT /api/projects", s.requireGlobalProjects(s.handleSaveProject)) + s.mux.HandleFunc("DELETE /api/projects", s.requireGlobalProjects(s.handleRemoveProject)) + s.mux.HandleFunc("POST /api/projects/convert", s.requireGlobalProjects(s.handleConvertProject)) + // Sync matrix s.mux.HandleFunc("GET /api/sync-matrix", s.handleSyncMatrix) s.mux.HandleFunc("POST /api/sync-matrix/preview", s.handleSyncMatrixPreview) diff --git a/schemas/config.schema.json b/schemas/config.schema.json index c9c1bdb75..366158f89 100644 --- a/schemas/config.schema.json +++ b/schemas/config.schema.json @@ -77,6 +77,18 @@ } ] }, + "projects": { + "type": "object", + "description": "Project folders to sync skills and agents into from this global config. Keys are absolute paths or start with ~. Each target's project path is used (for example .claude/skills), so the folder needs no .skillshare/. MCP servers for the same folder go under mcp.projects.", + "additionalProperties": { + "$ref": "#/$defs/managedProject" + }, + "examples": [ + { + "~/work/app": { "targets": ["claude", "codex"], "skills": { "mode": "copy", "include": ["team-*"] }, "agents": {} } + } + ] + }, "ignore": { "type": "array", "description": "Glob patterns for files to skip during sync.", @@ -139,6 +151,45 @@ } }, "$defs": { + "managedProject": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + "description": "Label for this project's targets, shown as @. Defaults to the folder name. Must be unique and cannot contain @, / or \\.", + "pattern": "^[^@/\\\\]+$" + }, + "targets": { + "type": "array", + "description": "Tools used in this project. Tools that share a skills folder, such as .agents/skills, are written once.", + "items": { "type": "string" }, + "uniqueItems": true, + "examples": [["claude", "codex"]] + }, + "skills": { + "type": "object", + "description": "Send skills into this project. An empty value sends all of them.", + "additionalProperties": false, + "properties": { + "mode": { "type": "string", "enum": ["merge", "symlink", "copy"] }, + "target_naming": { "type": "string", "enum": ["flat", "standard"] }, + "include": { "type": "array", "items": { "type": "string" } }, + "exclude": { "type": "array", "items": { "type": "string" } } + } + }, + "agents": { + "type": "object", + "description": "Send agents into this project. An empty value sends all of them.", + "additionalProperties": false, + "properties": { + "mode": { "type": "string", "enum": ["merge", "symlink", "copy"] }, + "include": { "type": "array", "items": { "type": "string" } }, + "exclude": { "type": "array", "items": { "type": "string" } } + } + } + } + }, "targetConfig": { "type": "object", "description": "Configuration for a single sync target. Supports both legacy flat format (path/mode/include/exclude) and new resource sub-keys (skills/agents). Legacy flat fields are auto-migrated to skills: on load.", diff --git a/skills/skillshare/references/targets.md b/skills/skillshare/references/targets.md index a150ded88..12a4f0aaf 100644 --- a/skills/skillshare/references/targets.md +++ b/skills/skillshare/references/targets.md @@ -34,6 +34,23 @@ targets: mode: merge ``` +## Project Folders From the Global Config (`projects`) + +Use when projects should get **different** skills. Global targets already give every project the same set; project mode (`-p`) keeps the setup in the repo for teammates. For personal projects, list the folders in the global `config.yaml` instead of giving each a `.skillshare/`. One `skillshare sync` writes them all. + +```yaml +projects: + ~/work/shop-web: + targets: [claude, cursor, codex] # tools used there; paths are derived + skills: { mode: copy, include: ["frontend-*"] } # present = on, empty = all + agents: {} +``` + +- Shows up in `sync`/`status`/`diff` as `@` (e.g. `shop-web@claude`). Tools sharing a folder (`.agents/skills`) are one target. +- A missing folder is skipped with a warning, never recreated. +- `skillshare target` and `collect` ignore these; edit `config.yaml` or the dashboard's Projects page. +- MCP for the same folders lives under `mcp.projects` (see [mcp.md](mcp.md)). + ## Target Filters Control which skills and agents sync to each target using include/exclude glob patterns. diff --git a/tests/integration/projects_test.go b/tests/integration/projects_test.go new file mode 100644 index 000000000..9699d1b89 --- /dev/null +++ b/tests/integration/projects_test.go @@ -0,0 +1,72 @@ +//go:build !online + +package integration + +import ( + "os" + "path/filepath" + "testing" + + "skillshare/internal/testutil" +) + +// projectsSandbox has two skills, one agent and a project folder declared in the +// global config under projects. +func projectsSandbox(t *testing.T, project string) (*testutil.Sandbox, string) { + t.Helper() + sb := testutil.NewSandbox(t) + sb.CreateSkill("team-lint", map[string]string{"SKILL.md": "---\nname: team-lint\n---\n# Lint"}) + sb.CreateSkill("draft", map[string]string{"SKILL.md": "---\nname: draft\n---\n# Draft"}) + sb.WriteFile(filepath.Join(filepath.Dir(sb.SourcePath), "agents", "reviewer.md"), "# Reviewer") + root := filepath.Join(sb.Home, "work", "app") + if err := os.MkdirAll(root, 0755); err != nil { + t.Fatal(err) + } + sb.WriteConfig("source: " + sb.SourcePath + "\ntargets: {}\nprojects:\n " + root + ":\n" + project) + return sb, root +} + +func TestProjects_SyncWritesSkillsAndAgentsIntoTheFolder(t *testing.T) { + sb, root := projectsSandbox(t, " targets: [claude, codex]\n skills:\n mode: copy\n include: [team-*]\n agents: {}\n") + defer sb.Cleanup() + + sb.RunCLI("sync", "--all").AssertSuccess(t) + + for _, path := range []string{".claude/skills/team-lint/SKILL.md", ".agents/skills/team-lint/SKILL.md", ".claude/agents/reviewer.md"} { + if !sb.FileExists(filepath.Join(root, path)) { + t.Errorf("%s was not written", path) + } + } + if sb.FileExists(filepath.Join(root, ".claude", "skills", "draft")) { + t.Error("draft is not included but was written") + } + if sb.FileExists(filepath.Join(root, ".skillshare")) { + t.Error("the project folder got a .skillshare/") + } +} + +func TestProjects_CollectLeavesAProjectsOwnSkills(t *testing.T) { + sb, root := projectsSandbox(t, " targets: [claude]\n skills: {}\n") + defer sb.Cleanup() + sb.RunCLI("sync").AssertSuccess(t) + sb.WriteFile(filepath.Join(root, ".claude", "skills", "local-only", "SKILL.md"), "---\nname: local-only\n---\n") + + sb.RunCLI("collect", "--all", "--force") + + if sb.FileExists(filepath.Join(sb.SourcePath, "local-only")) { + t.Error("collect pulled a skill out of a project") + } +} + +func TestProjects_TargetCommandDoesNotSeeProjectTargets(t *testing.T) { + sb, _ := projectsSandbox(t, " targets: [claude]\n skills: {}\n") + defer sb.Cleanup() + + result := sb.RunCLI("target", "remove", "app@claude") + + result.AssertFailure(t) + if !sb.FileExists(sb.ConfigPath) { + t.Fatal("config is gone") + } + sb.RunCLI("status").AssertAnyOutputContains(t, "app@claude") +} diff --git a/ui/src/App.tsx b/ui/src/App.tsx index e971e6335..074d829e1 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -31,6 +31,8 @@ const LogPage = lazy(() => import('./pages/LogPage')); const ConfigPage = lazy(() => import('./pages/ConfigPage')); const SettingsPage = lazy(() => import('./pages/SettingsPage')); const TargetDetailPage = lazy(() => import('./pages/TargetDetailPage')); +const ProjectsPage = lazy(() => import('./pages/ProjectsPage')); +const ProjectDetailPage = lazy(() => import('./pages/ProjectDetailPage')); const NewSkillPage = lazy(() => import('./pages/NewSkillPage')); const DoctorPage = lazy(() => import('./pages/DoctorPage')); @@ -81,6 +83,8 @@ function AppRoutes() { } /> } /> } /> + } /> + } /> } /> } /> } /> diff --git a/ui/src/api/client.ts b/ui/src/api/client.ts index a7f0d5c2a..13b4d26f1 100644 --- a/ui/src/api/client.ts +++ b/ui/src/api/client.ts @@ -277,7 +277,12 @@ export const api = { }), // Targets - listTargets: () => apiFetch<{ targets: Target[]; sourceSkillCount: number }>('/targets'), + /** Own targets by default. 'projects' lists the targets of projects alone, 'all' what a sync writes. */ + listTargets: (scope?: 'projects' | 'all') => apiFetch<{ targets: Target[]; sourceSkillCount: number }>(`/targets${scope ? `?scope=${scope}` : ''}`), + listProjects: () => apiFetch('/projects'), + saveProject: (project: ProjectInput) => apiFetch<{ success: boolean; root: string }>('/projects', { method: 'PUT', body: JSON.stringify(project) }), + removeProject: (root: string) => apiFetch<{ success: boolean }>(`/projects?root=${encodeURIComponent(root)}`, { method: 'DELETE' }), + convertProject: (root: string) => apiFetch<{ success: boolean; root: string }>('/projects/convert', { method: 'POST', body: JSON.stringify({ root }) }), addTarget: (name: string, path: string, agentPath?: string) => apiFetch<{ success: boolean }>('/targets', { method: 'POST', @@ -816,8 +821,44 @@ export interface CreateSkillResponse { createdFiles: string[]; } +/** One resource kind of a project; null means the project does not take it. */ +export interface ProjectResource { + mode: string; + targetNaming?: string; + include: string[]; + exclude: string[]; +} + +export interface Project { + /** The key in config.yaml, as written */ + root: string; + /** Absolute folder */ + path: string; + name: string; + customName?: string; + targets: string[]; + skills: ProjectResource | null; + agents: ProjectResource | null; + /** Tools that share a skills folder are one group, written once */ + groups: { target: string; tools: string[]; skillsPath: string; agentsPath: string }[]; + missing: boolean; + hasOwnConfig: boolean; +} + +export type ProjectInput = Pick & { name?: string; create?: boolean }; + +export interface ProjectList { + projects: Project[]; + /** Ordinary targets whose folders are one project's tool paths */ + convertible: { root: string; targets: string[]; tools: string[]; agents: boolean }[]; + /** Every tool with a project skills path, relative to the project folder */ + tools: { name: string; skillsPath: string; agentsPath: string }[]; +} + export interface Target { name: string; + /** Root of the project this target belongs to */ + project?: string; path: string; mode: string; targetNaming: string; diff --git a/ui/src/components/AgentIcon.tsx b/ui/src/components/AgentIcon.tsx index ca4d2bcee..e7e81fe91 100644 --- a/ui/src/components/AgentIcon.tsx +++ b/ui/src/components/AgentIcon.tsx @@ -95,6 +95,8 @@ const mono: Record = { }; export default function AgentIcon({ target, size = 16 }: { target: string; size?: number }) { + // A project's target is `@`; the logo is the tool's. + target = target.slice(target.lastIndexOf('@') + 1); // universal is the cross-client ~/.agents/skills convention: the Agent Skills hexagon in a // multi-color gradient so the shared path stands apart from single-vendor marks. if (target === 'universal') { diff --git a/ui/src/components/Layout.tsx b/ui/src/components/Layout.tsx index 3bd7c3b3f..5eecb51ff 100644 --- a/ui/src/components/Layout.tsx +++ b/ui/src/components/Layout.tsx @@ -8,6 +8,7 @@ import { Puzzle, Bot, FolderPlus, + Folders, Plug, Package, Target, @@ -61,7 +62,10 @@ const navGroups: { labelKey?: string; items: NavItem[] }[] = [ }, { labelKey: 'layout.group.destinations', - items: [{ to: '/targets', icon: Target, labelKey: 'layout.nav.targets', also: ['/collect'] }], + items: [ + { to: '/targets', icon: Target, labelKey: 'layout.nav.targets', also: ['/collect'] }, + { to: '/projects', icon: Folders, labelKey: 'projects.title', hideInProject: true }, + ], }, { labelKey: 'layout.group.maintain', @@ -166,7 +170,7 @@ const live = { refetchInterval: 15_000, refetchOnWindowFocus: true } as const; /** Sidebar badges: pending sync changes, git work to share, and skills a cached audit scan blocks. */ function useNavCounts(isProjectMode: boolean): Record { - const targets = useQuery({ queryKey: queryKeys.targets.all, queryFn: () => api.listTargets(), staleTime: staleTimes.targets, ...live }); + const targets = useQuery({ queryKey: queryKeys.targets.synced, queryFn: () => api.listTargets('all'), staleTime: staleTimes.targets, ...live }); const diff = useQuery({ queryKey: queryKeys.diff(), queryFn: () => api.diff(), staleTime: staleTimes.diff, ...live }); const extras = useQuery({ queryKey: queryKeys.extrasDiff(), queryFn: () => api.diffExtras(), staleTime: staleTimes.extras, ...live }); const mcp = useQuery({ queryKey: queryKeys.mcp, queryFn: () => mcpApi.list(), staleTime: staleTimes.extras, ...live }); diff --git a/ui/src/components/Select.tsx b/ui/src/components/Select.tsx index fe81b1235..945d62e8c 100644 --- a/ui/src/components/Select.tsx +++ b/ui/src/components/Select.tsx @@ -13,8 +13,13 @@ interface SelectProps { label?: string; /** Names the control when it has no visible label. */ ariaLabel?: string; - value: string; - onChange: (value: string) => void; + value?: string; + onChange?: (value: string) => void; + /** Multi-select: the chosen values. A click toggles one and the menu stays open. */ + values?: string[]; + onChangeValues?: (values: string[]) => void; + /** Multi-select: shown in the trigger while nothing is chosen. */ + placeholder?: string; options: SelectOption[]; className?: string; size?: 'sm' | 'md'; @@ -36,7 +41,7 @@ interface DropdownPos { bottom?: number; } -export function Select({ label, ariaLabel, value, onChange, options, className = '', size = 'md', disabled = false, prefix }: SelectProps) { +export function Select({ label, ariaLabel, value = '', onChange, values, onChangeValues, placeholder, options, className = '', size = 'md', disabled = false, prefix }: SelectProps) { const labelId = useId(); const [open, setOpen] = useState(false); const [focusIdx, setFocusIdx] = useState(-1); @@ -44,9 +49,9 @@ export function Select({ label, ariaLabel, value, onChange, options, className = const triggerRef = useRef(null); const listRef = useRef(null); - const selected = options.find((o) => o.value === value); - const selectedLabel = selected?.label ?? value; - const selectedIcon = selected?.icon; + const isOn = (v: string) => (values ? values.includes(v) : v === value); + const chosen = options.filter((o) => isOn(o.value)); + const selectedLabel = values ? chosen.map((o) => o.label).join(', ') : chosen[0]?.label ?? value; // Options with descriptions need room to read; widen the popup to ~15rem // (matching the dropdownWidth estimate below) so descriptions wrap nicely. const hasDescriptions = options.some((o) => o.description); @@ -128,9 +133,14 @@ export function Select({ label, ariaLabel, value, onChange, options, className = }, [open, focusIdx]); const select = useCallback((val: string) => { - onChange(val); + if (values) { + // Option order, so the saved list does not depend on the click order. + onChangeValues?.(options.map((o) => o.value).filter((v) => (v === val ? !values.includes(v) : values.includes(v)))); + return; + } + onChange?.(val); setOpen(false); - }, [onChange]); + }, [onChange, onChangeValues, values, options]); const handleKeyDown = useCallback((e: React.KeyboardEvent) => { switch (e.key) { @@ -156,14 +166,17 @@ export function Select({ label, ariaLabel, value, onChange, options, className = select(options[focusIdx].value); } else { openMenu(); - setFocusIdx(Math.max(0, options.findIndex((o) => o.value === value))); + setFocusIdx(Math.max(0, options.findIndex((o) => isOn(o.value)))); } break; case 'Escape': + // An open menu takes the key; the dialog around it stays. + if (open) e.stopPropagation(); setOpen(false); break; } - }, [open, focusIdx, options, value, select, openMenu]); + // eslint-disable-next-line react-hooks/exhaustive-deps -- isOn reads value and values + }, [open, focusIdx, options, value, values, select, openMenu]); return (
@@ -178,7 +191,7 @@ export function Select({ label, ariaLabel, value, onChange, options, className = onClick={() => { if (disabled) return; if (open) { setOpen(false); } - else { openMenu(); setFocusIdx(options.findIndex((o) => o.value === value)); } + else { openMenu(); setFocusIdx(options.findIndex((o) => isOn(o.value))); } }} onKeyDown={handleKeyDown} className={`ss-inp w-full justify-between text-left outline-none ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'} ${selectTriggerSizes[size]} ${open ? 'border-accent' : ''}`} @@ -190,8 +203,12 @@ export function Select({ label, ariaLabel, value, onChange, options, className = > {prefix && {prefix}} - {selectedIcon && {selectedIcon}} - {selectedLabel} + {chosen.some((o) => o.icon) && ( + + {chosen.slice(0, 6).map((o) => (values ? {o.icon} : o.icon))} + + )} + {chosen.length === 0 && placeholder ? placeholder : selectedLabel} {options.map((opt, i) => { - const isSelected = opt.value === value; + const isSelected = isOn(opt.value); const isFocused = i === focusIdx; return (
  • void; - onSaved: () => void; -} - -/** Add one root to mcp.projects. Its servers are added from the project's own page. */ -export default function MCPProjectDialog({ existing, defaults, defaultDirectTools, offered, configPath, onClose, onSaved }: Props) { - const t = useT(); - const directLabel = useDirectToolsLabel(); - const [path, setPath] = useState(''); - const [targets, setTargets] = useState(undefined); - const [directTools, setDirectTools] = useState(() => directToolsDraft(undefined)); - const [error, setError] = useState(''); - const [saving, setSaving] = useState(false); - - // Trailing separators aside, this is the key config.yaml will hold. - const root = path.trim().replace(/(?<=.)[\\/]+$/, ''); - const absolute = /^(~($|[\\/])|\/|[A-Za-z]:[\\/])/.test(root); - const taken = existing.some((x) => x === root || shortenHome(x) === root); - const pathError = root && !absolute ? t('mcp.projects.folderHint') : taken ? t('mcp.projects.taken') : ''; - const pi = (targets ?? defaults).includes('pi'); - const canSave = Boolean(root) && !pathError && (targets === undefined || targets.length > 0) && (!pi || directToolsComplete(directTools)) && !saving; - - const save = async () => { - if (!canSave) return; - setSaving(true); - setError(''); - try { - await mcpApi.save({ project: root, settings: { targets, directTools: pi ? directToolsValue(directTools) : undefined } }); - onSaved(); - } catch (e) { - setError((e as Error).message); - setSaving(false); - } - }; - - return ( - -
    -

    {t('mcp.projects.add')}

    - -
    -
    { e.preventDefault(); void save(); }}> -
    - - - - setPath(e.target.value)} placeholder="~/work/my-project" disabled={saving} /> - - {pathError || t('mcp.projects.folderHint')} -
    -
    - {t('mcp.targets')} - -
    - {pi && } - {error &&
    {error}
    } - -
    - {t('mcp.projects.savedTo', { path: shortenHome(configPath) })} - - -
    -
    - ); -} diff --git a/ui/src/components/mcp/MCPProjectList.tsx b/ui/src/components/mcp/MCPProjectList.tsx deleted file mode 100644 index 03e0401cc..000000000 --- a/ui/src/components/mcp/MCPProjectList.tsx +++ /dev/null @@ -1,70 +0,0 @@ -import { Fragment, useState } from 'react'; -import { Ellipsis, Folder } from 'lucide-react'; -import type { MCPProject, MCPSettings } from '../../api/mcp'; -import { useT } from '../../i18n'; -import { shortenHome } from '../../lib/paths'; -import { ProjectTargets } from './MCPProjectSettings'; -import { TargetPill } from './TargetPicker'; -import { projectOf, type MCPChange } from './mcpView'; - -interface Props { - projects: Record; - defaults: string[]; - /** Names of the global servers, to tell a switch from a server of the project's own. */ - globalNames: string[]; - offered: readonly string[]; - changes: MCPChange[]; - onOpen: (root: string) => void; - onSettings: (root: string, settings: MCPSettings) => void; - onMenu: (e: React.MouseEvent, root: string) => void; -} - -/** One row per root under mcp.projects. */ -export default function MCPProjectList({ projects, defaults, globalNames, offered, changes, onOpen, onSettings, onMenu }: Props) { - const t = useT(); - const [open, setOpen] = useState([]); - const roots = Object.keys(projects).sort(); - const plural = (key: string, count: number) => t(`${key}.${count === 1 ? 'one' : 'other'}`, { count }); - - return ( -
    - {roots.map((root) => { - const project = projects[root]; - const name = shortenHome(root); - const servers = Object.entries(project.servers ?? {}); - const off = servers.filter(([n, s]) => s.disabled && globalNames.includes(n)).length; - const own = servers.length - off; - const selected = project.targets ?? defaults; - const expanded = open.includes(root); - const pending = changes.some((c) => projectOf(roots, c.path) === root && (c.action === 'add' || c.action === 'update' || c.action === 'remove')); - return ( - -
    - - - setOpen((prev) => (expanded ? prev.filter((x) => x !== root) : [...prev, root]))} - /> - -
    - {expanded && ( -
    - onSettings(root, { targets, directTools: project.directTools })} /> -
    - )} -
    - ); - })} -
    - ); -} diff --git a/ui/src/components/mcp/MCPProjectView.tsx b/ui/src/components/mcp/MCPProjectView.tsx index 72fea9a55..5f7375772 100644 --- a/ui/src/components/mcp/MCPProjectView.tsx +++ b/ui/src/components/mcp/MCPProjectView.tsx @@ -1,9 +1,8 @@ import { useState } from 'react'; -import { AlertCircle, Pencil, Plug, Plus, Trash2 } from 'lucide-react'; +import { Pencil, Plug, Plus, Trash2 } from 'lucide-react'; import { mcpApi, mcpOffTargets, mcpTargets, type MCPMutation, type MCPServer } from '../../api/mcp'; import Button from '../Button'; import ConfirmDialog from '../ConfirmDialog'; -import PageHeader from '../PageHeader'; import { RailLayout } from '../StatusRail'; import { SkillContextMenu, type ContextMenuItem } from '../TargetMenu'; import { useToast } from '../Toast'; @@ -26,13 +25,12 @@ interface Props { data: MCPList; root: string; offered: readonly string[]; - onBack: () => void; onChanged: () => void; onRemoved: () => void; } /** One root under mcp.projects: its defaults, the global servers it turns off, and servers of its own. */ -export default function MCPProjectView({ data, root, offered, onBack, onChanged, onRemoved }: Props) { +export default function MCPProjectView({ data, root, offered, onChanged, onRemoved }: Props) { const t = useT(); const { toast } = useToast(); const directLabel = useDirectToolsLabel(); @@ -107,20 +105,10 @@ export default function MCPProjectView({ data, root, offered, onBack, onChanged, const shown = mcpTargets.filter((x) => offered.includes(x) || ownRows.some((row) => targetsOf(row.name).includes(x))); return ( -
    - setDropping(true)}>{t('mcp.projects.remove')}} - /> +
    }> - {data.projectConfigs.includes(root) &&
    {t('mcp.projects.ownConfig')}
    }
    -
    {t('mcp.projects.path')}
    -
    {root}
    {t('mcp.targets')}
    setPickTargets(!pickTargets)} />
    {/* Only pi-mcp-adapter reads it, so it is offered once Pi is one of the project's targets. */} @@ -171,6 +159,7 @@ export default function MCPProjectView({ data, root, offered, onBack, onChanged, ? :

    {t('mcp.projects.noOnlyHere')}

    } + {editing !== null && ( @@ -186,7 +175,7 @@ export default function MCPProjectView({ data, root, offered, onBack, onChanged, /> )} {removing && projectOf(roots, path) === root} onClose={() => setRemoving('')} onSaved={() => { const n = removing; setRemoving(''); onChanged(); toast(t('mcp.toast.removed', { name: n }), 'success'); }} />} - setDropping(false)} onConfirm={() => void drop()} /> + setDropping(false)} onConfirm={() => void drop()} /> setMenu(null)} />
    ); diff --git a/ui/src/components/projects/AddProjectDialog.tsx b/ui/src/components/projects/AddProjectDialog.tsx new file mode 100644 index 000000000..86b125bd4 --- /dev/null +++ b/ui/src/components/projects/AddProjectDialog.tsx @@ -0,0 +1,110 @@ +import { useState } from 'react'; +import { Check, Folder, X } from 'lucide-react'; +import { api, type ProjectList } from '../../api/client'; +import { mcpApi, mcpTargets } from '../../api/mcp'; +import Button from '../Button'; +import DialogShell from '../DialogShell'; +import { useT } from '../../i18n'; +import { shortenHome } from '../../lib/paths'; +import ProjectTools from './ProjectTools'; +import { toolGroups } from './projectView'; + +interface Props { + tools: ProjectList['tools']; + common: string[]; + /** Absolute paths of the projects that exist */ + existing: string[]; + onClose: () => void; + onAdded: (root: string) => void; +} + +const PARTS = ['skills', 'agents', 'mcp'] as const; +type PartName = (typeof PARTS)[number]; + +/** Add one folder to projects. Filters and MCP servers are edited on the project's page. */ +export default function AddProjectDialog({ tools, common, existing, onClose, onAdded }: Props) { + const t = useT(); + const [path, setPath] = useState(''); + const [targets, setTargets] = useState([]); + const [parts, setParts] = useState>({ skills: true, agents: false, mcp: false }); + const [error, setError] = useState(''); + const [saving, setSaving] = useState(false); + + // Trailing separators aside, this is the key config.yaml will hold. + const root = path.trim().replace(/(?<=.)[\\/]+$/, ''); + const absolute = /^(~($|[\\/])|\/|[A-Za-z]:[\\/])/.test(root); + const taken = existing.some((x) => x === root || shortenHome(x) === root); + const pathError = root && !absolute ? t('projects.add.folderHint') : taken ? t('projects.add.taken') : ''; + const agentTools = targets.filter((x) => tools.find((tool) => tool.name === x)?.agentsPath); + const folders = toolGroups(tools, targets).length; + const canSave = Boolean(root) && !pathError && targets.length > 0 && PARTS.some((p) => parts[p]) && !saving; + + const partHint = (p: PartName) => { + if (p === 'agents' && targets.length > 0) { + return agentTools.length === 0 ? t('projects.add.agentsNone') : agentTools.length < targets.length ? t('projects.add.agentsSome', { targets: agentTools.join(', ') }) : t('projects.add.agentsHint'); + } + return t(`projects.add.${p}Hint`); + }; + + const save = async () => { + if (!canSave) return; + setSaving(true); + setError(''); + const all = { mode: '', include: [], exclude: [] }; + try { + const saved = await api.saveProject({ create: true, root, targets, skills: parts.skills ? all : null, agents: parts.agents ? all : null }); + if (parts.mcp) { + const clients = mcpTargets.filter((x) => targets.includes(x)); + await mcpApi.save({ project: root, settings: { targets: clients.length > 0 ? clients : undefined } }); + } + onAdded(saved.root); + } catch (e) { + setError((e as Error).message); + setSaving(false); + } + }; + + return ( + +
    +

    {t('projects.add.title')}

    + +
    +
    { e.preventDefault(); void save(); }}> +
    + + + + setPath(e.target.value)} placeholder="~/work/my-project" disabled={saving} /> + + {pathError || t('projects.add.folderHint')} +
    +
    + {t('projects.targets')} + + {t('projects.add.targetsHint')} +
    +
    + {t('projects.add.parts')} +
    + {PARTS.map((p) => ( + + ))} +
    +
    + {error &&
    {error}
    } +
    +
    + {folders > 0 && t(folders === 1 ? 'projects.add.writes.one' : 'projects.add.writes.other', { count: folders })} + + +
    +
    + ); +} diff --git a/ui/src/components/projects/ProjectTools.tsx b/ui/src/components/projects/ProjectTools.tsx new file mode 100644 index 000000000..d187b469e --- /dev/null +++ b/ui/src/components/projects/ProjectTools.tsx @@ -0,0 +1,32 @@ +import type { ProjectList } from '../../api/client'; +import { useT } from '../../i18n'; +import AgentIcon from '../AgentIcon'; +import { Select } from '../Select'; +import { targetLabel } from '../mcp/mcpView'; + +interface Props { + tools: ProjectList['tools']; + /** Tools listed before the rest: the ones found on this machine */ + common: string[]; + selected: string[]; + onChange: (next: string[]) => void; + disabled?: boolean; +} + +/** The tools used in one project, from every tool that has a project path. */ +export default function ProjectTools({ tools, common, selected, onChange, disabled }: Props) { + const t = useT(); + const names = tools.map((x) => x.name); + // ponytail: no search box; the tools on this machine come first. Add one if 60+ rows gets slow to scan. + const ordered = [...names.filter((x) => common.includes(x)), ...names.filter((x) => !common.includes(x))]; + return ( +