From 85bcf589a7a969c4fd4f751cc05374534c97af7e Mon Sep 17 00:00:00 2001 From: Rusty Shackleford <182032677+salmonumbrella@users.noreply.github.com> Date: Thu, 29 Oct 2026 01:47:38 -0700 Subject: [PATCH] feat(sync): recognize and route agent-specific skill variants (#649) * docs(proposals): propose agent-specific skill variants Tracked repositories can ship different files for the same skill across agents. Counting and syncing each copy independently sends incompatible instructions to every target unless users maintain routing filters. Propose repository-scoped logical identity and exact variant routing while preserving source files, explicit controls, and existing naming behavior. Leave activation and compatibility decisions for maintainer review. Refs #648 * docs(proposals): clarify variant routing compatibility Explain how recognition affects universal-only targets and how existing per-variant overrides preserve the desired routing. Fix the precedence between variant identity and generic host-style path inference. Include analyze, move, and catalog consumers while preserving physical identifiers and actual context-cost accounting. Refs #648 * docs(proposals): clarify activation assumptions and scope Make acceptance cases conditional on maintainer-approved recognition being enabled for the tracked source. Separate the provisional implementation estimate from this proposal-only PR so its size is clear. Refs #648 * docs(proposals): qualify naming and opt-in assumptions State that the reproduced routing behavior uses default flat target naming. Leave any opt-in surface with the maintainer's activation decision without ruling out future CLI or config fields. Refs #648 * feat: recognize and route tracked agent skill variants Count tracked variants as logical skills in source and repository summaries, while preserving physical paths, sync operations, and context costs. Select matching canonical agent variants, including account targets, through shared discovery and selection with existing explicit routing precedence. Refs #648 * fix: count logical skills in sync inventory summaries Use shared logical and physical inventory counts in global and project sync closing lines while preserving each target's operation totals. Refs #648 * fix: preserve variant routing diagnostics across previews Resolve target selections once so CLI and server previews keep ambiguity reasons and physical skip counts. Explain managed variants removed by automatic agent routing, and report logical inventory in doctor. Keep warning rows read-only, document upgrade recovery in translated filtering references, and remove the optional README-only addition. Refs #648 * fix: align sync matrix previews with shared variant selection Classify the full source selection once per target so matrix previews honor canonical aliases, account identity, exact-agent routing, and ambiguous variant skips. Preserve each rejected physical path's existing diagnostic and draft filter disambiguation; skipped preview rows remain read-only. Refs #648 * test: expect singular skill wording in doctor source checks Keep the undiscovered-link count assertion aligned with logical source inventory formatting for one skill in global and project mode. Refs #648 * fix: retain selection diagnostics in catalog and diff verdicts Report warning-only diff targets as requiring attention while preserving local-only folder semantics. Reuse shared per-path selection diagnostics in target-scoped catalogs without applying target naming to served paths. Compute source counts once in summary callers and require variant counts in the source status formatter. Refs #648 * test: tighten tracked variant preview fixtures Use a real committed tracked repository for status counts, verify sync preview banners retain server warnings, and use emitted ambiguity reason text in target preview fixtures. Refs #648 * fix(sync): keep agent variants in shared target folders Compatible targets sharing a skills folder need a combined selection so Codex and universal do not prune one another in merge or copy mode. Carry every shared reader through selection, pruning and previews, including project targets, account identities and path aliases. Require a matching skill suffix under two distinct agents before inferring variants, keeping ordinary agent-named categories unrestricted. Separate naming warnings from ambiguous selection in diff and explain ambiguous removals. Add global/project regression coverage for repeated sync, target-only sync, status JSON, diff and API consumers. * fix(variants): align consumer counts, hints and diagnostics Use logical source counts in list, tracked install and init summaries while matching audit caches against physical variants. Restore localized dashboard skip hints and explain symlink routing limits in status and doctor, including project and JSON output. Document paired-agent detection and compatible shared-folder selection in the proposal, built-in skill and English plus translated command pages. Add focused regressions for the affected consumers. * fix(sync): cover initial sync and ignored variant diagnostics Init syncs a fresh in-memory config, so resolve shared target identities before its first sync as well as when loading saved configuration. A whole-directory symlink exposes ignored skills too. Diagnose agent variants using physical inventory when active discovery has none, while keeping logical counts and merge/copy selection restricted to enabled skills. Cover global/project JSON status and doctor with regressions. Reuse sourcewalk directory and canonical-path helpers so traversal guards remain enforced and path resolution has a single existing owner. * fix(variants): address conversion, counts and selection diagnostics Ignore runtime agent identities when comparing convertible project targets and count logical skills during init. Keep selection warnings separate from naming warnings and preserve agent-named parent skills as ordinary skills. Cover account sync/prune, project ambiguity and overrides in merge/copy modes, and init/status agreement. Focused verification ran in an isolated Linux Codex container, not the devcontainer, as authorized. * refactor(variants): remove obsolete selection helpers Remove the unused FilterSkillsByTarget wrapper and prune agent parameter, cache canonical target aliases once, and restore catalog skip ordering to avoid an unrelated behavior change. Completes the optional cleanup from PR 649 review. * fix(ui): expose localized variant selection diagnostics Show target warnings with source paths, localize ambiguity across preview and detail consumers, and let skipped preview rows add a physical exclude pattern. Show tracked repository variant counts alongside logical skills. Drop display-only rendered cases while retaining mutation protection and plain TypeScript logic coverage. Inspect target states in Clean/Playful light/dark and Traditional Chinese. * docs(variants): explain diagnostics and add sync runbook Document doctor variant_routing and logical/physical counts, diff selection skips, and the nested parent-skill boundary. Keep all four command translations aligned and add isolated account/project E2E scenarios. Both runbook steps passed in the authorized Linux Codex container with separate HOME/XDG/TMPDIR fixtures. Website typecheck and all five locale builds passed. * test(config): use native paths in project conversion fixture The shared-agent regression fixture appended slash-separated suffixes to Windows temporary paths, so project path matching returned no candidates. Build each path with filepath.Join and preserve all conversion assertions. Focused project configuration tests passed in the authorized isolated Linux Codex container, not the devcontainer. Windows CI verifies the platform-specific fixture correction. * fix(ui): recompute shared skill routing for filter previews Evaluate edited include/exclude settings in the complete target map before classifying the draft, so a formerly shared folder no longer keeps its old union when the filters differ. Preserve the saved target configuration. * fix(mcp): keep parent skills when peer variants route elsewhere Do not treat an otherwise eligible variant for another agent as an unserved nested skill. Continue blocking parent publication for explicitly filtered, disabled, ambiguous, or invalid children so filters still hide their files. * fix(ui): distinguish agent selection from naming skips Expose separate naming and selection skip counts on target summaries. Show each applicable remedy in target details and sync previews so ambiguity keeps its filter/override guidance alongside naming and collision hints. * fix(list): include disabled rows in tracked repository counts Count the complete inventory that list displays, including ignored skills and physical variants, without changing the enabled counts used by status, install, or sync. Clone rows before counting to preserve disabled state. * docs: align variant counts and routing recovery guidance Show logical skill and physical variant counts in list/install documentation and keep the four translations aligned with the filtering examples. Explain that agent-named skill parents keep ordinary nested skills and retain the devcontainer-only runbook environment. Removal warnings now recommend a source-local override, since include filters cannot undo agent routing. * fix(mcp): preserve explicit target restrictions on nested variants Limit the differently routed child exemption to automatic layout inference. Frontmatter targets and dashboard source-local overrides must still prevent a parent from publishing files explicitly restricted to another target. * fix(ui): fill target name in naming warning guidance Pass the current target name when rendering localized warning hints so the same naming guidance shown beside the controls does not expose a placeholder in the warning banner. Verified in the populated target preview. --------- Co-authored-by: Willie --- ai_docs/tests/agent_skill_variants_runbook.md | 118 ++++++ cmd/skillshare/consumer_variants_test.go | 235 +++++++++++ cmd/skillshare/diff.go | 48 ++- cmd/skillshare/diff_project.go | 18 +- cmd/skillshare/doctor.go | 10 +- cmd/skillshare/init.go | 4 +- cmd/skillshare/init_apply.go | 8 +- cmd/skillshare/init_remote.go | 4 +- cmd/skillshare/install_handlers.go | 9 +- cmd/skillshare/list.go | 25 +- cmd/skillshare/list_counts_test.go | 25 ++ cmd/skillshare/status.go | 42 +- cmd/skillshare/status_project.go | 14 +- cmd/skillshare/status_render.go | 22 +- cmd/skillshare/status_variant_warning.go | 69 +++ cmd/skillshare/status_variants_test.go | 104 +++++ cmd/skillshare/sync.go | 13 +- cmd/skillshare/sync_parallel.go | 24 +- cmd/skillshare/sync_project.go | 2 +- internal/config/config.go | 28 +- internal/config/path_overlap.go | 58 +++ internal/config/project.go | 2 +- internal/config/projects.go | 7 + internal/config/projects_test.go | 39 ++ internal/config/shared_skills_test.go | 57 +++ internal/config/targets.go | 31 +- internal/server/handler_diff_stream.go | 17 +- internal/server/handler_overview.go | 27 +- internal/server/handler_overview_test.go | 109 +++++ internal/server/handler_sync.go | 1 + internal/server/handler_sync_matrix.go | 29 +- internal/server/handler_sync_matrix_test.go | 116 ++++++ internal/server/handler_sync_test.go | 42 ++ internal/server/handler_targets.go | 78 ++-- internal/server/handler_targets_test.go | 41 ++ internal/server/server.go | 2 +- internal/skillserve/catalog.go | 15 +- internal/skillserve/catalog_test.go | 97 +++++ internal/sourcefs/testdata/raw_writes.tsv | 2 +- internal/sync/classify.go | 36 ++ internal/sync/copy.go | 13 +- internal/sync/discover_walk.go | 40 +- internal/sync/execute_targets.go | 11 + internal/sync/filter.go | 81 +++- internal/sync/filter_target_test.go | 64 --- internal/sync/skill_run.go | 9 +- internal/sync/sync.go | 61 +-- internal/sync/target_naming.go | 25 +- internal/sync/variants.go | 169 ++++++++ internal/sync/variants_test.go | 392 ++++++++++++++++++ proposals/648-agent-skill-variants.md | 179 ++++++++ skills/skillshare/SKILL.md | 8 + skills/skillshare/references/sync.md | 18 + tests/integration/doctor_source_links_test.go | 2 +- tests/integration/sync_target_naming_test.go | 2 +- tests/integration/variants_test.go | 223 ++++++++++ ui/src/api/types/resources.ts | 2 + ui/src/api/types/sync.ts | 3 +- ui/src/api/types/targets.ts | 3 + ui/src/components/memory/MemoryTools.test.tsx | 2 +- ui/src/components/sync/syncView.test.ts | 19 +- ui/src/components/sync/syncView.ts | 18 +- ui/src/components/targets/FilterSection.tsx | 3 +- ui/src/components/targets/targetView.test.ts | 17 +- ui/src/components/targets/targetView.ts | 19 + ui/src/i18n/locales/de.json | 5 +- ui/src/i18n/locales/en.json | 5 +- ui/src/i18n/locales/es.json | 5 +- ui/src/i18n/locales/fa.json | 5 +- ui/src/i18n/locales/fr.json | 5 +- ui/src/i18n/locales/id.json | 5 +- ui/src/i18n/locales/ja.json | 5 +- ui/src/i18n/locales/ko.json | 5 +- ui/src/i18n/locales/pt-BR.json | 5 +- ui/src/i18n/locales/zh-CN.json | 5 +- ui/src/i18n/locales/zh-TW.json | 5 +- ui/src/pages/AuditPage.tsx | 2 +- ui/src/pages/AuditRulesPage.tsx | 2 +- ui/src/pages/DashboardPage.tsx | 4 +- ui/src/pages/ResourceDetailPage.tsx | 2 + ui/src/pages/SyncPage.test.tsx | 8 +- ui/src/pages/SyncPage.tsx | 4 +- ui/src/pages/TargetDetailPage.test.tsx | 5 +- ui/src/pages/TargetDetailPage.tsx | 13 +- website/docs/reference/commands/diff.md | 2 + website/docs/reference/commands/doctor.md | 2 + website/docs/reference/commands/install.md | 4 + website/docs/reference/commands/list.md | 4 +- website/docs/reference/commands/status.md | 13 +- website/docs/reference/commands/sync.md | 8 + website/docs/reference/filtering.md | 50 +++ .../current/reference/commands/diff.md | 2 + .../current/reference/commands/doctor.md | 2 + .../current/reference/commands/install.md | 2 + .../current/reference/commands/list.md | 4 +- .../current/reference/commands/status.md | 13 +- .../current/reference/commands/sync.md | 8 + .../current/reference/filtering.md | 19 + .../current/reference/commands/diff.md | 2 + .../current/reference/commands/doctor.md | 2 + .../current/reference/commands/install.md | 2 + .../current/reference/commands/list.md | 4 +- .../current/reference/commands/status.md | 13 +- .../current/reference/commands/sync.md | 8 + .../current/reference/filtering.md | 19 + .../current/reference/commands/diff.md | 2 + .../current/reference/commands/doctor.md | 2 + .../current/reference/commands/install.md | 2 + .../current/reference/commands/list.md | 4 +- .../current/reference/commands/status.md | 13 +- .../current/reference/commands/sync.md | 8 + .../current/reference/filtering.md | 19 + .../current/reference/commands/diff.md | 2 + .../current/reference/commands/doctor.md | 2 + .../current/reference/commands/install.md | 2 + .../current/reference/commands/list.md | 4 +- .../current/reference/commands/status.md | 13 +- .../current/reference/commands/sync.md | 8 + .../current/reference/filtering.md | 19 + 119 files changed, 2985 insertions(+), 404 deletions(-) create mode 100644 ai_docs/tests/agent_skill_variants_runbook.md create mode 100644 cmd/skillshare/consumer_variants_test.go create mode 100644 cmd/skillshare/list_counts_test.go create mode 100644 cmd/skillshare/status_variant_warning.go create mode 100644 cmd/skillshare/status_variants_test.go create mode 100644 internal/config/shared_skills_test.go create mode 100644 internal/sync/variants.go create mode 100644 internal/sync/variants_test.go create mode 100644 proposals/648-agent-skill-variants.md create mode 100644 tests/integration/variants_test.go diff --git a/ai_docs/tests/agent_skill_variants_runbook.md b/ai_docs/tests/agent_skill_variants_runbook.md new file mode 100644 index 000000000..c4ce19a84 --- /dev/null +++ b/ai_docs/tests/agent_skill_variants_runbook.md @@ -0,0 +1,118 @@ +# CLI E2E Runbook: Agent skill variants + +Verify logical counts, account routing, ambiguity, explicit selection and pruning. + +**Origin**: PR #649 review — agent variants in tracked repositories. + +## Scope + +- Account targets preserve the selected agent's bytes in merge and copy modes. +- Init and status count logical skills separately from physical variants. +- Project ambiguity skips automatic matches; an explicit include resolves it. +- Repeat sync preserves selected entries; changing filters prunes managed entries. + +## Environment + +Run with a freshly built `skillshare` on PATH inside a fresh ssenv in the devcontainer. +Each step creates its own fixture under the isolated `$HOME`; no network is needed. + +## Steps + +### 1. Init, account routing and pruning + +```bash +set -euo pipefail +fixture=$(mktemp -d "$HOME/variants-account.XXXXXX") +export SKILLSHARE_CONFIG="$fixture/config.yaml" +mkdir -p "$fixture/producer/_repo/skills" "$fixture/source" +for agent in claude codex; do + for skill in fix review; do + mkdir -p "$fixture/producer/_repo/skills/$agent/$skill" + printf '# %s %s\n' "$agent" "$skill" > "$fixture/producer/_repo/skills/$agent/$skill/SKILL.md" + done +done +git -C "$fixture/producer" init -q -b main +git -C "$fixture/producer" add . +git -C "$fixture/producer" -c user.name=Test -c user.email=test@example.invalid commit -qm fixture +skillshare init -g --remote "file://$fixture/producer" --no-skill --source "$fixture/source" > "$fixture/init.txt" +python3 - "$fixture/init.txt" <<'PY' +import sys +text = open(sys.argv[1]).read() +assert '2 skills' in text and '4 skills' not in text, text +PY +skillshare status -g --json > "$fixture/status.json" +python3 - "$fixture/status.json" <<'PY' +import json, sys +s = json.load(open(sys.argv[1])) +assert (s['skill_count'], s['variant_count']) == (2, 4), s +PY +for mode in merge copy; do + cat > "$SKILLSHARE_CONFIG" < "$project/.skillshare/skills/_repo/skills/$agent/fix/SKILL.md" + done + cat > "$project/.skillshare/config.yaml" < .skillshare/config.yaml < 0 { + r.synced = false } // Compute mtime only for copy mode (merge uses symlinks, mtime is misleading) @@ -881,7 +881,7 @@ func categorizeItems(items []copyDiffEntry) []actionCategory { case item.reason == "local only" || item.reason == "not in source" || item.reason == "local file": add("local", "local", "Local Only", item.name) default: - add("warn", "warn", item.reason, item.name) + add("warn:"+item.reason, "warn", item.reason, item.name) } } @@ -1140,6 +1140,8 @@ func renderDiffGroup(r targetDiffResult, opts diffRenderOpts, next *diffNext, wi agent = true } switch { + case cat.kind == "warn": + // Selection diagnostics describe skipped files, not sync work. case cat.kind == "override": next.force = true case cat.kind == "kept": diff --git a/cmd/skillshare/diff_project.go b/cmd/skillshare/diff_project.go index 841acc6d5..e9ccb2cf7 100644 --- a/cmd/skillshare/diff_project.go +++ b/cmd/skillshare/diff_project.go @@ -55,12 +55,12 @@ func cmdDiffProject(root, targetName string, kind resourceKindFilter, opts diffR } } - // Pre-filter skills per target and compute total for progress bar + // Resolve each target once, preserving selection diagnostics for the preview. type resolvedTarget struct { - name string - target config.TargetConfig - mode string - filtered []sync.DiscoveredSkill + name string + target config.TargetConfig + mode string + resolution *sync.TargetSkillResolution } var resolved []resolvedTarget totalSkills := 0 @@ -75,7 +75,7 @@ func cmdDiffProject(root, targetName string, kind resourceKindFilter, opts diffR if !sc.IsEnabled() { continue } - filtered, err := sync.SelectTargetSkills(discovered, entry.Name, sc) + resolution, err := sync.ResolveTargetSkillsForTarget(entry.Name, sc, discovered) if err != nil { return fmt.Errorf("target %s has invalid include/exclude config: %w", entry.Name, err) } @@ -83,8 +83,8 @@ func cmdDiffProject(root, targetName string, kind resourceKindFilter, opts diffR if mode == "" { mode = "merge" } - resolved = append(resolved, resolvedTarget{entry.Name, target, mode, filtered}) - totalSkills += len(filtered) + resolved = append(resolved, resolvedTarget{entry.Name, target, mode, resolution}) + totalSkills += len(resolution.Skills) if mode == "copy" { hasCopyMode = true } @@ -110,7 +110,7 @@ func cmdDiffProject(root, targetName string, kind resourceKindFilter, opts diffR defer wg.Done() defer func() { <-sem }() progress.startTarget(rt.name) - r := collectTargetDiff(rt.name, rt.target, runtime.sourcePath, rt.mode, rt.filtered, ignorePatterns, progress) + r := collectTargetDiff(rt.name, rt.target, runtime.sourcePath, rt.mode, rt.resolution, ignorePatterns, progress) progress.doneTarget(rt.name, r) results[idx] = r }(i, rt) diff --git a/cmd/skillshare/doctor.go b/cmd/skillshare/doctor.go index f68952f19..7b5cd4073 100644 --- a/cmd/skillshare/doctor.go +++ b/cmd/skillshare/doctor.go @@ -382,8 +382,10 @@ func checkSource(cfg *config.Config, walk sourcewalk.Options, result *doctorResu } skillCount := 0 + var variants int if discoverErr == nil { - skillCount = len(discovered) + counts := sync.CountSkills(discovered) + skillCount, variants = counts.Skills, counts.Variants } else { entries, _ := sourcewalk.ReadDir(cfg.EffectiveSkillsSource(), walk) for _, e := range entries { @@ -392,8 +394,9 @@ func checkSource(cfg *config.Config, walk sourcewalk.Options, result *doctorResu } } } - ui.Row(ui.MarkOK, "Source", shortenPath(cfg.EffectiveSkillsSource())+ui.DimText(" · "+plural(skillCount, "skill")), doctorWidth) - result.addCheck("source", checkPass, fmt.Sprintf("Source: %s (%d skills)", cfg.EffectiveSkillsSource(), skillCount), nil) + count := sourceSkillCountText(skillCount, variants) + ui.Row(ui.MarkOK, "Source", shortenPath(cfg.EffectiveSkillsSource())+ui.DimText(" · "+count), doctorWidth) + result.addCheck("source", checkPass, fmt.Sprintf("Source: %s (%s)", cfg.EffectiveSkillsSource(), count), nil) } func checkAgentsSource(cfg *config.Config, result *doctorResult) { @@ -735,6 +738,7 @@ func displayTargetStatus(target config.TargetConfig, source, mode string, row fu } func checkSyncDrift(cfg *config.Config, result *doctorResult, discovered []sync.DiscoveredSkill, targetCache map[string]cachedTargetStatus) { + checkVariantRouting(cfg, result, discovered) if discovered == nil { result.addCheck("sync_drift", checkPass, "No skills discovered, skipping drift check", nil) return diff --git a/cmd/skillshare/init.go b/cmd/skillshare/init.go index eecd79edc..0c2a796f5 100644 --- a/cmd/skillshare/init.go +++ b/cmd/skillshare/init.go @@ -802,9 +802,9 @@ func tryPullAfterRemoteSetup(sourcePath, remoteURL string) bool { trackCmd.Dir = sourcePath trackCmd.Run() // best-effort - // Count pulled skills (deep: count SKILL.md files, not top-level dirs) + // Count logical skills, including nested skills and agent variant families. discovered, _ := ssync.DiscoverSourceSkills(sourcePath) - skillCount := len(discovered) + skillCount := ssync.CountSkills(discovered).Skills spinner.Stop() ui.Row(ui.MarkOK, "Pull", plural(skillCount, "skill")+" from origin/"+remoteBranch, gitRowWidth) diff --git a/cmd/skillshare/init_apply.go b/cmd/skillshare/init_apply.go index d93489f85..9e7b878d5 100644 --- a/cmd/skillshare/init_apply.go +++ b/cmd/skillshare/init_apply.go @@ -165,7 +165,7 @@ func applyRemote(p *initPlan, res *initResult, hadRepo bool) { return } if discovered, err := ssync.DiscoverSourceSkills(p.source()); err == nil { - res.pulled = len(discovered) + res.pulled = ssync.CountSkills(discovered).Skills } } @@ -263,6 +263,7 @@ func printInitDone(p *initPlan, res *initResult) { // syncs skills (and agents, if any) quietly. It returns the folders left as // they were because they differ from the source. func firstSync(cfg *config.Config) (skills int, kept []string, err error) { + cfg.Targets = config.WithSharedSkillsTargets(cfg.Targets, cfg.Mode) start := time.Now() spinner := ui.StartSpinner("Syncing…") discovered, err := ssync.DiscoverSourceSkills(cfg.EffectiveSkillsSource(), cfg.SkillsWalk()) @@ -284,8 +285,9 @@ func firstSync(cfg *config.Config) (skills int, kept []string, err error) { if failed > 0 { err = fmt.Errorf("%s failed to sync; run skillshare sync for details", plural(failed, "tool")) } - ui.Answered("Synced", fmt.Sprintf("%s to %s", plural(len(discovered), "skill"), plural(len(cfg.Targets), "tool"))+ui.Took(time.Since(start))) - return len(discovered), kept, err + counts := ssync.CountSkills(discovered) + ui.Answered("Synced", fmt.Sprintf("%s to %s", sourceSkillCountText(counts.Skills, counts.Variants), plural(len(cfg.Targets), "tool"))+ui.Took(time.Since(start))) + return counts.Skills, kept, err } // replaceIdenticalCopies removes real skill folders in merge-mode targets diff --git a/cmd/skillshare/init_remote.go b/cmd/skillshare/init_remote.go index b73bed3a0..ffaa82077 100644 --- a/cmd/skillshare/init_remote.go +++ b/cmd/skillshare/init_remote.go @@ -22,7 +22,7 @@ type remoteRepo struct { reachable bool reason string // why it could not be reached names []string // top-level skill folder names - skills int // skills found (nested folders count individually) + skills int // logical skills found (agent variants count once) agents int extras int // rootScope means the repo versions the whole skillshare folder @@ -82,7 +82,7 @@ func inspectRemote(url string) *remoteRepo { } } if discovered, err := ssync.DiscoverSourceSkills(skillsDir); err == nil { - r.skills = len(discovered) + r.skills = ssync.CountSkills(discovered).Skills } return r } diff --git a/cmd/skillshare/install_handlers.go b/cmd/skillshare/install_handlers.go index ef0f0de2b..b5dc3c3eb 100644 --- a/cmd/skillshare/install_handlers.go +++ b/cmd/skillshare/install_handlers.go @@ -10,6 +10,7 @@ import ( "skillshare/internal/audit" "skillshare/internal/config" "skillshare/internal/install" + "skillshare/internal/sync" "skillshare/internal/ui" "skillshare/internal/utils" "skillshare/internal/validate" @@ -81,7 +82,13 @@ func handleTrackedRepoInstall(source *install.Source, cfg *config.Config, opts i ui.StepContinue("Found", plural(result.AgentCount, "agent")) renderTrackedRepoMeta("Agents", result.Agents) } else { - ui.StepContinue("Found", plural(result.SkillCount, "skill")) + counts := sync.SkillCounts{Skills: result.SkillCount, Variants: result.SkillCount} + if discovered, err := sync.DiscoverSourceSkills(trackSourceDir, cfg.SkillsWalk()); err == nil { + _, repos := sync.CountSkillsByRepo(discovered) + rel, _ := filepath.Rel(trackSourceDir, result.RepoPath) + counts = repos[filepath.ToSlash(rel)] + } + ui.StepContinue("Found", sourceSkillCountText(counts.Skills, counts.Variants)) renderTrackedRepoMeta("Skills", result.Skills) } } diff --git a/cmd/skillshare/list.go b/cmd/skillshare/list.go index 30aeaece0..e34ea3438 100644 --- a/cmd/skillshare/list.go +++ b/cmd/skillshare/list.go @@ -551,9 +551,11 @@ func displayTrackedRepos(trackedRepos []string, discovered []sync.DiscoveredSkil } wg.Wait() + counts := listedRepoCounts(discovered) width := ui.RowWidth(trackedRepos...) for i, repoName := range trackedRepos { - skills := ui.DimText(" · " + plural(countRepoSkills(repoName, discovered), "skill")) + c := counts[repoName] + skills := ui.DimText(" · " + sourceSkillCountText(c.Skills, c.Variants)) if err := results[i].err; err != nil { ui.Row(ui.MarkWarn, repoName, "git status unknown"+skills, width) ui.Note((&gitStatusError{err: err}).Error()) @@ -565,17 +567,6 @@ func displayTrackedRepos(trackedRepos []string, discovered []sync.DiscoveredSkil } } -// countRepoSkills counts skills in a tracked repo -func countRepoSkills(repoName string, discovered []sync.DiscoveredSkill) int { - count := 0 - for _, d := range discovered { - if d.RepoRelPath == repoName { - count++ - } - } - return count -} - func cmdList(args []string) error { mode, rest, err := parseModeArgs(args, "--type", "-t", "--sort", "-s", "--status") if err != nil { @@ -911,3 +902,13 @@ func printListHelp() { ), ) } + +// listedRepoCounts includes disabled rows, which list still displays. +func listedRepoCounts(skills []sync.DiscoveredSkill) map[string]sync.SkillCounts { + rows := append([]sync.DiscoveredSkill(nil), skills...) + for i := range rows { + rows[i].Disabled = false + } + _, counts := sync.CountSkillsByRepo(rows) + return counts +} diff --git a/cmd/skillshare/list_counts_test.go b/cmd/skillshare/list_counts_test.go new file mode 100644 index 000000000..a7a1154ef --- /dev/null +++ b/cmd/skillshare/list_counts_test.go @@ -0,0 +1,25 @@ +package main + +import ( + ssync "skillshare/internal/sync" + "testing" +) + +func TestListedRepoCountsIncludeDisabledRows(t *testing.T) { + skills := []ssync.DiscoveredSkill{ + {RelPath: "_repo/one", RepoRelPath: "_repo"}, + {RelPath: "_repo/two", RepoRelPath: "_repo", Disabled: true}, + {RelPath: "_repo/skills/claude/fix", RepoRelPath: "_repo", LogicalID: "fix"}, + {RelPath: "_repo/skills/codex/fix", RepoRelPath: "_repo", LogicalID: "fix", Disabled: true}, + } + counts := listedRepoCounts(skills) + if counts["_repo"] != (ssync.SkillCounts{Skills: 3, Variants: 4}) { + t.Fatalf("listed repo counts = %+v", counts) + } + if !skills[1].Disabled || !skills[3].Disabled { + t.Fatal("list counting changed disabled state") + } + if enabled := ssync.CountSkills(skills); enabled != (ssync.SkillCounts{Skills: 2, Variants: 2}) { + t.Fatalf("enabled counts changed: %+v", enabled) + } +} diff --git a/cmd/skillshare/status.go b/cmd/skillshare/status.go index b263336a3..1f2705615 100644 --- a/cmd/skillshare/status.go +++ b/cmd/skillshare/status.go @@ -28,6 +28,7 @@ import ( type statusJSONOutput struct { Source statusJSONSource `json:"source"` SkillCount int `json:"skill_count"` + VariantCount int `json:"variant_count"` TrackedRepos []statusJSONRepo `json:"tracked_repos"` Targets []statusJSONTarget `json:"targets"` Agents *statusJSONAgents `json:"agents,omitempty"` @@ -50,11 +51,12 @@ type statusJSONSourceIgnore struct { } type statusJSONRepo struct { - Name string `json:"name"` - SkillCount int `json:"skill_count"` - Dirty bool `json:"dirty"` - Status string `json:"status,omitempty"` - Message string `json:"message,omitempty"` + Name string `json:"name"` + SkillCount int `json:"skill_count"` + VariantCount int `json:"variant_count"` + Dirty bool `json:"dirty"` + Status string `json:"status,omitempty"` + Message string `json:"message,omitempty"` } type statusJSONTarget struct { @@ -67,7 +69,7 @@ type statusJSONTarget struct { Exclude []string `json:"exclude"` // SkillsEnabled is false for a target with skills switched off. SkillsEnabled bool `json:"skills_enabled"` - // Warning says why sync will reject the target, with the fix. + // Warning describes target configuration errors or routing limitations. Warning string `json:"warning,omitempty"` } @@ -129,7 +131,8 @@ func cmdStatus(args []string) error { sp.Stop() printSkippedSourceLinkWarnings(walk, false) - printSourceStatus(cfg.EffectiveSkillsSource(), cfg.EffectiveAgentsSource(), utils.FoldHomePath, len(discovered), countSourceAgents(cfg.EffectiveAgentsSource()), stats) + counts := sync.CountSkills(discovered) + printSourceStatus(cfg.EffectiveSkillsSource(), cfg.EffectiveAgentsSource(), utils.FoldHomePath, counts.Skills, countSourceAgents(cfg.EffectiveAgentsSource()), stats, counts.Variants) printTrackedReposStatus(cfg.EffectiveSkillsSource(), discovered, trackedRepos) if err := printTargetsStatus(cfg, discovered); err != nil { return err @@ -160,8 +163,10 @@ func cmdStatus(args []string) error { Exists: dirExists(cfg.EffectiveSkillsSource()), Skillignore: buildSkillignoreJSON(stats), } - output.SkillCount = len(discovered) + counts := sync.CountSkills(discovered) + output.SkillCount, output.VariantCount = counts.Skills, counts.Variants output.TrackedRepos = buildTrackedRepoJSON(cfg.EffectiveSkillsSource(), trackedRepos, discovered, walk) + warningSkills := variantWarningSkills(cfg.EffectiveSkillsSource(), cfg.Targets, cfg.Mode, walk, discovered) for name, target := range cfg.Targets { sc := target.SkillsConfig() @@ -177,7 +182,7 @@ func cmdStatus(args []string) error { Exclude: sc.Exclude, SkillsEnabled: sc.IsEnabled(), - Warning: namingWarning(target, tMode), + Warning: skillTargetWarning(target, tMode, warningSkills), }) } @@ -265,12 +270,7 @@ func buildTrackedRepoJSON(sourcePath string, trackedRepos []string, discovered [ // Count skills per repo (single pass). RepoRelPath covers skills at the // repo root and nested ones, and repos placed with --into (org/_repo). - repoSkillCount := make(map[string]int, len(trackedRepos)) - for _, d := range discovered { - if d.IsInRepo { - repoSkillCount[d.RepoRelPath]++ - } - } + _, repoCounts := sync.CountSkillsByRepo(discovered) // Parallel git.IsDirty checks var wg gosync.WaitGroup @@ -281,9 +281,10 @@ func buildTrackedRepoJSON(sourcePath string, trackedRepos []string, discovered [ repoPath := filepath.Join(sourcePath, name) dirty, err := git.IsDirty(repoPath) results[idx] = statusJSONRepo{ - Name: name, - SkillCount: repoSkillCount[name], - Dirty: dirty, + Name: name, + SkillCount: repoCounts[name].Skills, + VariantCount: repoCounts[name].Variants, + Dirty: dirty, } if err != nil { results[idx].Status = "unknown" @@ -312,6 +313,7 @@ type targetStatusResult struct { } func printTargetsStatus(cfg *config.Config, discovered []sync.DiscoveredSkill) error { + warningSkills := variantWarningSkills(cfg.EffectiveSkillsSource(), cfg.Targets, cfg.Mode, cfg.SkillsWalk(), discovered) builtinAgents := config.DefaultAgentTargets() agentsSource := cfg.EffectiveAgentsSource() agentsExist := dirExists(agentsSource) @@ -328,8 +330,8 @@ func printTargetsStatus(cfg *config.Config, discovered []sync.DiscoveredSkill) e sc := target.SkillsConfig() mode := getTargetMode(sc.Mode, cfg.Mode) res := getTargetStatusDetail(target, cfg.EffectiveSkillsSource(), mode) - if err := target.NamingModeConfigError(mode); err != nil { - warnings = append(warnings, name+": "+err.Error()) + if warning := skillTargetWarning(target, mode, warningSkills); warning != "" { + warnings = append(warnings, name+": "+warning) } // A target with skills off expects nothing, so it has no drift. diff --git a/cmd/skillshare/status_project.go b/cmd/skillshare/status_project.go index 1ec9ba7b6..c92f57cdf 100644 --- a/cmd/skillshare/status_project.go +++ b/cmd/skillshare/status_project.go @@ -38,7 +38,8 @@ func cmdStatusProject(root string) error { agentCount = len(agents) } show := func(path string) string { return projectStatusPath(runtime.root, path) } - printSourceStatus(runtime.sourcePath, runtime.agentsSourcePath, show, len(discovered), agentCount, stats) + counts := sync.CountSkills(discovered) + printSourceStatus(runtime.sourcePath, runtime.agentsSourcePath, show, counts.Skills, agentCount, stats, counts.Variants) printTrackedReposStatus(runtime.sourcePath, discovered, trackedRepos) if err := printProjectTargetsStatus(runtime, discovered); err != nil { return err @@ -79,8 +80,10 @@ func cmdStatusProjectJSON(root string) error { Exists: dirExists(runtime.sourcePath), Skillignore: buildSkillignoreJSON(stats), } - output.SkillCount = len(discovered) + counts := sync.CountSkills(discovered) + output.SkillCount, output.VariantCount = counts.Skills, counts.Variants output.TrackedRepos = buildTrackedRepoJSON(runtime.sourcePath, trackedRepos, discovered, walk) + warningSkills := variantWarningSkills(runtime.sourcePath, runtime.targets, "merge", walk, discovered) for _, entry := range runtime.config.Targets { target, ok := runtime.targets[entry.Name] @@ -103,7 +106,7 @@ func cmdStatusProjectJSON(root string) error { Exclude: sc.Exclude, SkillsEnabled: sc.IsEnabled(), - Warning: namingWarning(target, mode), + Warning: skillTargetWarning(target, mode, warningSkills), }) } @@ -181,6 +184,7 @@ func resolveProjectAgentTargetPath(entry config.ProjectTargetEntry, builtinAgent } func printProjectTargetsStatus(runtime *projectRuntime, discovered []sync.DiscoveredSkill) error { + warningSkills := variantWarningSkills(runtime.sourcePath, runtime.targets, "merge", runtime.skillsWalk(), discovered) builtinAgents := config.ProjectAgentTargets() agentsExist := dirExists(runtime.agentsSourcePath) var agents []resource.DiscoveredResource @@ -204,8 +208,8 @@ func printProjectTargetsStatus(runtime *projectRuntime, discovered []sync.Discov mode = "merge" } res := getTargetStatusDetail(target, runtime.sourcePath, mode) - if err := target.NamingModeConfigError(mode); err != nil { - warnings = append(warnings, entry.Name+": "+err.Error()) + if warning := skillTargetWarning(target, mode, warningSkills); warning != "" { + warnings = append(warnings, entry.Name+": "+warning) } // A target with skills off expects nothing, so it has no drift. diff --git a/cmd/skillshare/status_render.go b/cmd/skillshare/status_render.go index dfa04290d..750d7e844 100644 --- a/cmd/skillshare/status_render.go +++ b/cmd/skillshare/status_render.go @@ -185,7 +185,7 @@ func modesNote(targets []statusTarget) string { // printSourceStatus prints where skills and agents come from, with paths // shown by show. agentCount is negative when there is no agents folder. -func printSourceStatus(skillsPath, agentsPath string, show func(string) string, skillCount, agentCount int, stats *skillignore.IgnoreStats) { +func printSourceStatus(skillsPath, agentsPath string, show func(string) string, skillCount, agentCount int, stats *skillignore.IgnoreStats, variants int) { ui.Section("Source") width := ui.RowWidth("skills", "agents") if _, err := os.Stat(skillsPath); err != nil { @@ -197,7 +197,7 @@ func printSourceStatus(skillsPath, agentsPath string, show func(string) string, if agentCount >= 0 { pathW = max(pathW, runewidth.StringWidth(agents)) } - ui.Row(ui.MarkNone, "skills", pad(skills, pathW)+" "+theme.Dim().Render(plural(skillCount, "skill")), width) + ui.Row(ui.MarkNone, "skills", pad(skills, pathW)+" "+theme.Dim().Render(sourceSkillCountText(skillCount, variants)), width) if agentCount >= 0 { ui.Row(ui.MarkNone, "agents", pad(agents, pathW)+" "+theme.Dim().Render(plural(agentCount, "agent")), width) } @@ -223,15 +223,11 @@ func printTrackedReposStatus(sourcePath string, discovered []sync.DiscoveredSkil } ui.Section("Tracked repositories") + _, repoCounts := sync.CountSkillsByRepo(discovered) width := ui.RowWidth(trackedRepos...) for _, repoName := range trackedRepos { - skillCount := 0 - for _, d := range discovered { - if d.RepoRelPath == repoName { - skillCount++ - } - } - count := plural(skillCount, "skill") + counts := repoCounts[repoName] + count := sourceSkillCountText(counts.Skills, counts.Variants) isDirty, err := git.IsDirty(filepath.Join(sourcePath, repoName)) switch { @@ -312,3 +308,11 @@ func printAuditStatus(ac config.AuditConfig) { func statusLine(name, value string) string { return theme.Primary().Bold(true).Render(pad(name, len("Version"))) + " " + value } + +func sourceSkillCountText(skills, variants int) string { + text := plural(skills, "skill") + if variants > skills { + text += ", " + plural(variants, "variant") + } + return text +} diff --git a/cmd/skillshare/status_variant_warning.go b/cmd/skillshare/status_variant_warning.go new file mode 100644 index 000000000..e084b5225 --- /dev/null +++ b/cmd/skillshare/status_variant_warning.go @@ -0,0 +1,69 @@ +package main + +import ( + "strings" + + "skillshare/internal/config" + "skillshare/internal/sourcewalk" + "skillshare/internal/sync" + "skillshare/internal/ui" +) + +// variantWarningSkills includes ignored files only for a whole-directory link. +// Keep this diagnostic inventory separate from counts and merge/copy selection. +func variantWarningSkills(source string, targets map[string]config.TargetConfig, mode string, walk sourcewalk.Options, discovered []sync.DiscoveredSkill) []sync.DiscoveredSkill { + for _, skill := range discovered { + if skill.VariantAgent != "" { + return discovered + } + } + for _, target := range targets { + if target.SkillsConfig().IsEnabled() && getTargetMode(target.SkillsConfig().Mode, mode) == "symlink" { + if all, err := sync.DiscoverSourceSkillsAll(source, walk); err == nil { + return all + } + break + } + } + return discovered +} + +func variantSymlinkWarning(target config.TargetConfig, mode string, discovered []sync.DiscoveredSkill) string { + if mode != "symlink" || !target.SkillsConfig().IsEnabled() { + return "" + } + for _, skill := range discovered { + if skill.VariantAgent != "" { + return "symlink mode exposes all agent variants; automatic agent routing requires merge or copy mode" + } + } + return "" +} + +func skillTargetWarning(target config.TargetConfig, mode string, discovered []sync.DiscoveredSkill) string { + var warnings []string + if warning := namingWarning(target, mode); warning != "" { + warnings = append(warnings, warning) + } + if warning := variantSymlinkWarning(target, mode, discovered); warning != "" { + warnings = append(warnings, warning) + } + return strings.Join(warnings, "; ") +} + +func checkVariantRouting(cfg *config.Config, result *doctorResult, discovered []sync.DiscoveredSkill) { + discovered = variantWarningSkills(cfg.EffectiveSkillsSource(), cfg.Targets, cfg.Mode, cfg.SkillsWalk(), discovered) + var details []string + for _, name := range targetNamesFromConfig(cfg.Targets) { + target := cfg.Targets[name] + mode := getTargetMode(target.SkillsConfig().Mode, cfg.Mode) + if warning := variantSymlinkWarning(target, mode, discovered); warning != "" { + ui.Row(ui.MarkWarn, name, warning, doctorWidth) + result.addWarning() + details = append(details, name+": "+warning) + } + } + if len(details) > 0 { + result.addCheck("variant_routing", checkWarning, "Agent routing unavailable in symlink mode", details) + } +} diff --git a/cmd/skillshare/status_variants_test.go b/cmd/skillshare/status_variants_test.go new file mode 100644 index 000000000..0f9c12791 --- /dev/null +++ b/cmd/skillshare/status_variants_test.go @@ -0,0 +1,104 @@ +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "skillshare/internal/config" + "skillshare/internal/sourcewalk" + "skillshare/internal/sync" +) + +func TestTrackedRepoStatusCountsLogicalVariants(t *testing.T) { + src := t.TempDir() + for _, agent := range []string{"claude", "codex"} { + for _, name := range []string{"fix", "review/fix"} { + dir := filepath.Join(src, "_repo/internal/skills", agent, name) + if err := os.MkdirAll(dir, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("# Instructions"), 0644); err != nil { + t.Fatal(err) + } + } + } + initGitRepoForTest(t, filepath.Join(src, "_repo")) + skills, trackedRepos, err := sync.DiscoverSourceSkillsLite(src) + if err != nil { + t.Fatal(err) + } + repos := buildTrackedRepoJSON(src, trackedRepos, skills) + if len(repos) != 1 || repos[0].SkillCount != 2 { + t.Fatalf("repository counts = %+v, want 2 logical skills", repos) + } + if repos[0].Status != "" || repos[0].Dirty { + t.Fatalf("tracked fixture must be a clean Git repository: %+v", repos[0]) + } + if repos[0].VariantCount != 4 { + t.Fatalf("physical count = %d, want 4", repos[0].VariantCount) + } + if text := sourceSkillCountText(repos[0].SkillCount, repos[0].VariantCount); text != "2 skills, 4 variants" { + t.Fatalf("status text = %q", text) + } + doctor := &doctorResult{} + output := captureStdout(t, func() { checkSource(&config.Config{Source: src}, sourcewalk.Options{}, doctor, skills, nil) }) + if !strings.Contains(output, "2 skills, 4 variants") || !strings.Contains(doctor.checks[0].Message, "2 skills, 4 variants") { + t.Errorf("doctor disagrees with inventory: %s, %+v", output, doctor.checks) + } + for _, name := range []string{"XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME"} { + t.Setenv(name, t.TempDir()) + } + configPath := filepath.Join(t.TempDir(), "config.yaml") + t.Setenv("SKILLSHARE_CONFIG", configPath) + if err := os.WriteFile(configPath, []byte("source: "+src+"\nmode: merge\ntargets:\n claude:\n path: "+filepath.Join(t.TempDir(), "skills")+"\n"), 0644); err != nil { + t.Fatal(err) + } + for _, args := range [][]string{{"-g", "--dry-run"}, {"-g"}} { + var syncErr error + output := stripANSIWarnings(captureStdout(t, func() { syncErr = cmdSync(args) })) + if syncErr != nil { + t.Fatal(syncErr) + } + if !strings.Contains(output, "2 skills, 4 variants to 1 target") { + t.Fatalf("sync summary must count source inventory: %s", output) + } + } + for _, suffix := range []string{"fix", "review/fix"} { + dir := filepath.Join(src, "_repo/internal/skills/claude-code", suffix) + if err := os.MkdirAll(dir, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("# Instructions"), 0644); err != nil { + t.Fatal(err) + } + } + for _, flag := range []string{"--json", "--no-tui"} { + var diffErr error + output := captureStdout(t, func() { diffErr = cmdDiff([]string{"-g", flag}) }) + if diffErr != nil { + t.Fatal(diffErr) + } + if !strings.Contains(output, "ambiguous") || !strings.Contains(output, "target override") { + t.Fatalf("diff lost selection reason: %s", output) + } + if flag == "--json" { + var result diffJSONOutput + if err := json.Unmarshal([]byte(output), &result); err != nil { + t.Fatal(err) + } + if len(result.Targets) != 1 || result.Targets[0].Synced { + t.Fatalf("warning-only target must require attention: %s", output) + } + } + } +} + +func TestDiffLocalOnlyFoldersStayInSync(t *testing.T) { + result := targetDiffResult{localCount: 1, items: []copyDiffEntry{{name: "personal", action: "remove", reason: "local only"}}} + if !result.inSync() { + t.Fatal("a local-only folder is not pending sync work") + } +} diff --git a/cmd/skillshare/sync.go b/cmd/skillshare/sync.go index 7f55dfc35..ce5baf208 100644 --- a/cmd/skillshare/sync.go +++ b/cmd/skillshare/sync.go @@ -429,7 +429,7 @@ func cmdSync(args []string) error { if !jsonOutput { // Phase 3: Summary - printSyncDone(len(discoveredSkills), len(cfg.Targets), failedTargets, dryRun, time.Since(start)) + printSyncDone(sync.CountSkills(discoveredSkills), len(cfg.Targets), failedTargets, dryRun, time.Since(start)) // Show ignored skills from .skillignore printIgnoredSkills(ignoreStats) @@ -680,18 +680,19 @@ func syncOutputJSON(results []syncTargetResult, dryRun bool, start time.Time, iS return writeJSONResult(&output, syncErr) } -// printSyncDone closes a skills sync: how many skills reached how many -// targets, or which part failed. -func printSyncDone(skills, targets, failed int, dryRun bool, took time.Duration) { +// printSyncDone closes a skills sync with source inventory and target counts, +// or which part failed. Per-target rows retain physical operation counts. +func printSyncDone(counts sync.SkillCounts, targets, failed int, dryRun bool, took time.Duration) { fmt.Println() + skills := sourceSkillCountText(counts.Skills, counts.Variants) switch { case failed > 0: ui.Done(ui.MarkFail, fmt.Sprintf("%d of %s failed", failed, plural(targets, "target")), took) case dryRun: - ui.Done(ui.MarkOK, fmt.Sprintf("Would sync %s to %s", plural(skills, "skill"), plural(targets, "target")), took) + ui.Done(ui.MarkOK, fmt.Sprintf("Would sync %s to %s", skills, plural(targets, "target")), took) ui.DryRun() default: - ui.Done(ui.MarkOK, fmt.Sprintf("Synced %s to %s", plural(skills, "skill"), plural(targets, "target")), took) + ui.Done(ui.MarkOK, fmt.Sprintf("Synced %s to %s", skills, plural(targets, "target")), took) } } diff --git a/cmd/skillshare/sync_parallel.go b/cmd/skillshare/sync_parallel.go index a3dc07b2a..32da26b21 100644 --- a/cmd/skillshare/sync_parallel.go +++ b/cmd/skillshare/sync_parallel.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "path/filepath" "strings" gosync "sync" "time" @@ -10,6 +9,7 @@ import ( "github.com/pterm/pterm" "skillshare/internal/config" + "skillshare/internal/sourcewalk" "skillshare/internal/sync" "skillshare/internal/theme" "skillshare/internal/ui" @@ -418,25 +418,5 @@ func runParallelSyncCore(entries []syncTargetEntry, source string, skills []sync // but skills/ hasn't been created yet), we resolve the longest existing ancestor // and re-append the remaining segments so that symlink aliases still converge. func canonicalPath(p string) string { - cleaned := filepath.Clean(p) - abs, err := filepath.Abs(cleaned) - if err != nil { - return cleaned - } - // Fast path: entire path exists and can be resolved. - if resolved, err := filepath.EvalSymlinks(abs); err == nil { - return resolved - } - // Slow path: walk up to the nearest existing ancestor, resolve it, - // then re-append the non-existent tail segments. - parent, tail := filepath.Dir(abs), filepath.Base(abs) - for parent != abs { - if resolved, err := filepath.EvalSymlinks(parent); err == nil { - return filepath.Join(resolved, tail) - } - abs = parent - tail = filepath.Join(filepath.Base(parent), tail) - parent = filepath.Dir(parent) - } - return abs + return sourcewalk.Canonical(p) } diff --git a/cmd/skillshare/sync_project.go b/cmd/skillshare/sync_project.go index 4bac2fffb..3f8e8d27c 100644 --- a/cmd/skillshare/sync_project.go +++ b/cmd/skillshare/sync_project.go @@ -131,7 +131,7 @@ func cmdSyncProject(root string, dryRun, force, jsonOutput, quiet bool) (syncLog if !jsonOutput { // Phase 3: Summary - printSyncDone(len(discoveredSkills), len(runtime.config.Targets), len(stats.FailedTargets), dryRun, time.Since(start)) + printSyncDone(sync.CountSkills(discoveredSkills), len(runtime.config.Targets), len(stats.FailedTargets), dryRun, time.Since(start)) // Show ignored skills from .skillignore printIgnoredSkills(ignoreStats) diff --git a/internal/config/config.go b/internal/config/config.go index 713c107d2..994ea6065 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -98,6 +98,10 @@ func NewTargetSkillsMode(naming, mode string) string { // ResourceTargetConfig holds per-resource-kind target configuration (skills, agents, etc.). type ResourceTargetConfig struct { + // SharedTargets are compatible writers to the same folder, resolved at runtime. + SharedTargets []SkillTargetIdentity `yaml:"-" json:"-"` + // Agent carries the enclosing account's identity during selection; it is not configuration. + Agent string `yaml:"-" json:"-"` Path string `yaml:"path,omitempty"` Mode string `yaml:"mode,omitempty"` // merge, symlink, or copy TargetNaming string `yaml:"target_naming,omitempty"` @@ -143,10 +147,11 @@ func (r ResourceTargetConfig) withExtensionMode() ResourceTargetConfig { // Legacy flat fields (Path/Mode/Include/Exclude) are kept for backward-compatible // YAML reading; migrateTargetConfigs moves them into Skills on load. type TargetConfig struct { - Path string `yaml:"path,omitempty"` - Mode string `yaml:"mode,omitempty"` // merge, symlink, or copy - Include []string `yaml:"include,omitempty"` - Exclude []string `yaml:"exclude,omitempty"` + sharedSkillTargets []SkillTargetIdentity + Path string `yaml:"path,omitempty"` + Mode string `yaml:"mode,omitempty"` // merge, symlink, or copy + Include []string `yaml:"include,omitempty"` + Exclude []string `yaml:"exclude,omitempty"` // Agent and ConfigDir make this target another config directory of a built-in Agent, // such as a second account. Its paths are then the Agent's own, moved into ConfigDir. @@ -188,17 +193,21 @@ type TargetInstructionsConfig struct { func (tc *TargetConfig) SkillsConfig() ResourceTargetConfig { if tc.Skills != nil { sc := *tc.Skills + sc.SharedTargets = tc.sharedSkillTargets + sc.Agent = tc.Agent if sc.TargetNaming == "" { sc.TargetNaming = tc.defaultTargetNaming } return sc } return ResourceTargetConfig{ - Path: tc.Path, - Mode: tc.Mode, - TargetNaming: tc.defaultTargetNaming, - Include: tc.Include, - Exclude: tc.Exclude, + SharedTargets: tc.sharedSkillTargets, + Agent: tc.Agent, + Path: tc.Path, + Mode: tc.Mode, + TargetNaming: tc.defaultTargetNaming, + Include: tc.Include, + Exclude: tc.Exclude, } } @@ -853,6 +862,7 @@ func decodeConfig(path string, data []byte, persist bool) (*Config, error) { if err := cfg.expandProjects(); err != nil { return nil, err } + cfg.Targets = WithSharedSkillsTargets(cfg.Targets, cfg.Mode) // Expand ~ in extras paths for i, extra := range cfg.Extras { cfg.Extras[i].Source = expandPath(extra.Source) diff --git a/internal/config/path_overlap.go b/internal/config/path_overlap.go index aff3a641d..e1de4cdb2 100644 --- a/internal/config/path_overlap.go +++ b/internal/config/path_overlap.go @@ -6,9 +6,67 @@ import ( "slices" "sort" + "skillshare/internal/sourcewalk" "skillshare/internal/utils" ) +// SkillTargetIdentity identifies a reader of a shared skills folder. +type SkillTargetIdentity struct{ Name, Agent string } + +// WithSharedSkillsTargets returns a runtime view in which compatible writers +// select the union of their skills. Conflicting settings retain the existing +// conflict diagnostic and are never combined. +func WithSharedSkillsTargets(targets map[string]TargetConfig, defaultMode string) map[string]TargetConfig { + out := make(map[string]TargetConfig, len(targets)) + groups := make(map[string][]string) + for name, tc := range targets { + // Managed project groups already combine the tools sharing a folder. + if tc.projectRoot == "" { + tc.sharedSkillTargets = nil + } + out[name] = tc + if tc.SkillsConfig().IsEnabled() { + if folder := skillsFolder(tc); folder != "" { + folder = sourcewalk.Canonical(folder) + groups[folder] = append(groups[folder], name) + } + } + } + for _, names := range groups { + if len(names) < 2 { + continue + } + slices.Sort(names) + first := out[names[0]] + compatible := true + for _, name := range names[1:] { + tc := out[name] + if !sameSkillsSettings(first.SkillsConfig(), tc.SkillsConfig(), defaultMode) { + compatible = false + break + } + } + if !compatible { + continue + } + identities := make([]SkillTargetIdentity, 0, len(names)) + for _, name := range names { + tc := out[name] + if len(tc.sharedSkillTargets) > 0 { + identities = append(identities, tc.sharedSkillTargets...) + } else { + identities = append(identities, SkillTargetIdentity{Name: name, Agent: tc.Agent}) + } + } + for _, name := range names { + tc := out[name] + tc.sharedSkillTargets = identities + out[name] = tc + } + } + return out +} + // DetectPathOverlap returns the set of target names whose configured skill // paths overlap with another enabled target — either by sharing the same // primary path or by being scanned via cross-runtime discovery (also_scans). diff --git a/internal/config/project.go b/internal/config/project.go index 25eae8369..0d96f1972 100644 --- a/internal/config/project.go +++ b/internal/config/project.go @@ -611,5 +611,5 @@ func ResolveValidProjectTargets(projectRoot string, cfg *ProjectConfig) (resolve resolved[name] = tc } - return resolved, unresolved + return WithSharedSkillsTargets(resolved, "merge"), unresolved } diff --git a/internal/config/projects.go b/internal/config/projects.go index 9feb264ba..6f9052bb7 100644 --- a/internal/config/projects.go +++ b/internal/config/projects.go @@ -158,6 +158,11 @@ func (c *Config) expandProjects() error { } skills.Path = group.SkillsPath target := TargetConfig{Skills: &skills, projectRoot: abs, defaultTargetNaming: c.TargetNaming} + if len(group.Tools) > 1 { + for _, tool := range group.Tools { + target.sharedSkillTargets = append(target.sharedSkillTargets, SkillTargetIdentity{Name: ProjectTargetName(name, tool)}) + } + } if project.Agents != nil && group.AgentsPath != "" { agents := *project.Agents agents.Path = group.AgentsPath @@ -258,6 +263,8 @@ func (c *Config) ConvertibleProjects() []ConvertibleProject { } withoutPath := func(rc ResourceTargetConfig) ResourceTargetConfig { rc.Path = "" + rc.Agent = "" + rc.SharedTargets = nil return rc } diff --git a/internal/config/projects_test.go b/internal/config/projects_test.go index 7383c345d..147d3ffcc 100644 --- a/internal/config/projects_test.go +++ b/internal/config/projects_test.go @@ -1,6 +1,7 @@ package config import ( + "fmt" "os" "path/filepath" "strings" @@ -196,3 +197,41 @@ func TestProjects_AgentsOnlyIgnoresPrefixedNaming(t *testing.T) { t.Fatalf("err = %v, invalid = %v; want app@claude valid", err, invalid) } } + +func TestConvertibleProjects_SharedAgentIdentityDoesNotMakeRootMixed(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "config.yaml") + t.Setenv("SKILLSHARE_CONFIG", path) + data := fmt.Sprintf(`source: %s +targets: + app-codex: + agent: codex + config_dir: %s + path: %s + app-universal: + path: %s + app-claude: + agent: claude + config_dir: %s + path: %s +`, filepath.Join(root, "skills"), + filepath.Join(root, "app", ".codex"), + filepath.Join(root, "app", ".agents", "skills"), + filepath.Join(root, "app", ".agents", "skills"), + filepath.Join(root, "app", ".claude"), + filepath.Join(root, "app", ".claude", "skills")) + if err := os.WriteFile(path, []byte(data), 0644); err != nil { + t.Fatal(err) + } + cfg, err := Load() + if err != nil { + t.Fatal(err) + } + found := cfg.ConvertibleProjects() + if len(found) != 1 || len(found[0].Targets) != 3 { + t.Fatalf("convertible projects = %+v", found) + } + if found[0].Project.Skills.Agent != "" || len(found[0].Project.Skills.SharedTargets) != 0 { + t.Fatalf("identity leaked: %+v", found[0].Project.Skills) + } +} diff --git a/internal/config/shared_skills_test.go b/internal/config/shared_skills_test.go new file mode 100644 index 000000000..4875dfa47 --- /dev/null +++ b/internal/config/shared_skills_test.go @@ -0,0 +1,57 @@ +package config + +import ( + "os" + "path/filepath" + "testing" +) + +func TestSharedSkillsTargetsResolveAliasesAndKeepConflicts(t *testing.T) { + root := t.TempDir() + alias := filepath.Join(t.TempDir(), "alias") + if err := os.Symlink(root, alias); err != nil { + t.Skip(err) + } + for _, incompatible := range []bool{false, true} { + targets := map[string]TargetConfig{ + "codex": {Path: filepath.Join(root, "skills")}, + "universal": {Path: filepath.Join(alias, "skills")}, + } + if incompatible { + tc := targets["universal"] + tc.Exclude = []string{"*"} + targets["universal"] = tc + } + resolved := WithSharedSkillsTargets(targets, "merge") + for name, tc := range resolved { + want := 2 + if incompatible { + want = 0 + } + if len(tc.SkillsConfig().SharedTargets) != want { + t.Fatalf("%s incompatible=%v: %+v", name, incompatible, tc.SkillsConfig()) + } + original := targets[name] + if len(original.SkillsConfig().SharedTargets) != 0 { + t.Fatal("mutated caller's configuration") + } + } + } +} + +func TestManagedProjectSharedSkillsKeepEveryToolIdentity(t *testing.T) { + root := t.TempDir() + cfg := &Config{Projects: map[string]ManagedProject{root: {Targets: []string{"codex", "universal"}, Skills: &ResourceTargetConfig{}}}} + if err := cfg.expandProjects(); err != nil { + t.Fatal(err) + } + resolved := WithSharedSkillsTargets(cfg.Targets, "merge") + if len(resolved) != 1 { + t.Fatalf("project should have one writer: %+v", resolved) + } + for _, tc := range resolved { + if len(tc.SkillsConfig().SharedTargets) != 2 { + t.Fatalf("group lost identities: %+v", tc.SkillsConfig()) + } + } +} diff --git a/internal/config/targets.go b/internal/config/targets.go index 18046a72b..183c69801 100644 --- a/internal/config/targets.go +++ b/internal/config/targets.go @@ -723,9 +723,34 @@ func GroupedProjectTargets() []GroupedProjectTarget { return result } -// MatchesTargetName checks whether a skill-declared target name matches a -// config target name. It handles alias matching (e.g. "claude" matches -// the alias "claude-code") by looking up the target spec registry. +var canonicalTargetNamesOnce sync.Once +var canonicalTargetNames map[string]string + +// CanonicalTargetName resolves registry names and aliases without treating a +// shared destination path as agent identity. Unknown names return empty. +func CanonicalTargetName(name string) string { + if _, tool, ok := SplitProjectTarget(name); ok { + name = tool + } + canonicalTargetNamesOnce.Do(func() { + specs, err := loadTargetSpecs() + if err != nil { + return + } + canonicalTargetNames = make(map[string]string) + for _, spec := range specs { + for _, alias := range append([]string{spec.Name}, spec.Aliases...) { + if _, exists := canonicalTargetNames[alias]; !exists { + canonicalTargetNames[alias] = spec.Name + } + } + } + }) + return canonicalTargetNames[name] +} + +// MatchesTargetName checks explicit target declarations, including aliases and +// targets sharing a skills path for compatibility. func MatchesTargetName(skillTarget, configTarget string) bool { if skillTarget == configTarget { return true diff --git a/internal/server/handler_diff_stream.go b/internal/server/handler_diff_stream.go index 0835be283..678fddb7f 100644 --- a/internal/server/handler_diff_stream.go +++ b/internal/server/handler_diff_stream.go @@ -98,22 +98,19 @@ func (s *Server) computeTargetDiff(name string, target config.TargetConfig, disc return dt } - filtered, err := ssync.SelectTargetSkills(discovered, name, sc) - if err != nil { - return dt - } - resolution, err := ssync.ResolveTargetSkillsForTarget(name, config.ResourceTargetConfig{ - Path: sc.Path, - TargetNaming: sc.TargetNaming, - }, filtered) + resolution, err := ssync.ResolveTargetSkillsForTarget(name, sc, discovered) if err != nil { dt.Items = append(dt.Items, diffItem{Skill: "(target naming)", Action: "skip", Reason: err.Error(), Kind: kindSkill}) return dt } // Surface collision/validation stats so the UI can show why skills were skipped dt.CollisionCount = len(resolution.Collisions) - dt.SkippedCount = len(filtered) - len(resolution.Skills) - dt.NamingSkippedCount = len(resolution.Warnings) + dt.SkippedCount = resolution.SkippedCount + dt.NamingSkippedCount = resolution.NamingSkippedCount + dt.Warnings = resolution.Warnings + for _, warning := range resolution.SelectionWarnings { + dt.Items = append(dt.Items, diffItem{Skill: "(skill selection)", Action: "skip", Reason: warning, Kind: kindSkill}) + } validNames := resolution.ValidTargetNames() manifest, _ := ssync.ReadManifest(sc.Path) legacyNames := resolution.LegacyNames(mode, sc.Path, manifest) diff --git a/internal/server/handler_overview.go b/internal/server/handler_overview.go index 8af9d6290..c06748f68 100644 --- a/internal/server/handler_overview.go +++ b/internal/server/handler_overview.go @@ -14,9 +14,10 @@ import ( ) type trackedRepoItem struct { - Name string `json:"name"` - SkillCount int `json:"skillCount"` - Dirty bool `json:"dirty"` + Name string `json:"name"` + SkillCount int `json:"skillCount"` + VariantCount int `json:"variantCount"` + Dirty bool `json:"dirty"` } func (s *Server) handleOverview(w http.ResponseWriter, r *http.Request) { @@ -69,9 +70,11 @@ func (s *Server) handleOverview(w http.ResponseWriter, r *http.Request) { } } + counts := sync.CountSkills(skills) resp := map[string]any{ "source": source, - "skillCount": len(skills), + "skillCount": counts.Skills, + "variantCount": counts.Variants, "agentCount": agentCount, "topLevelCount": topLevelCount, "targetCount": targetCount, @@ -100,25 +103,19 @@ func buildTrackedRepos(sourceDir string, skills []sync.DiscoveredSkill, walk sou return []trackedRepoItem{} } + _, counts := sync.CountSkillsByRepo(skills) items := make([]trackedRepoItem, 0, len(repoNames)) for _, repoName := range repoNames { repoPath := filepath.Join(sourceDir, repoName) - // Count skills belonging to this repo - skillCount := 0 - for _, sk := range skills { - if sk.RepoRelPath == repoName { - skillCount++ - } - } - // Check git dirty status dirty, _ := git.IsDirty(repoPath) items = append(items, trackedRepoItem{ - Name: repoName, - SkillCount: skillCount, - Dirty: dirty, + Name: repoName, + SkillCount: counts[repoName].Skills, + VariantCount: counts[repoName].Variants, + Dirty: dirty, }) } return items diff --git a/internal/server/handler_overview_test.go b/internal/server/handler_overview_test.go index e280ca14b..e96a9de6f 100644 --- a/internal/server/handler_overview_test.go +++ b/internal/server/handler_overview_test.go @@ -6,11 +6,29 @@ import ( "net/http/httptest" "os" "path/filepath" + "strings" "testing" "skillshare/internal/config" + ssync "skillshare/internal/sync" ) +func TestDiffNamingWarningIsNotPendingWork(t *testing.T) { + s, src := newTestServer(t) + addSkill(t, src, "invalid") + if err := os.WriteFile(filepath.Join(src, "invalid", "SKILL.md"), []byte("---\nname: wrong-name\n---\n# Instructions"), 0644); err != nil { + t.Fatal(err) + } + skills, err := ssync.DiscoverSourceSkills(src) + if err != nil { + t.Fatal(err) + } + diff := s.computeTargetDiff("claude", config.TargetConfig{Skills: &config.ResourceTargetConfig{Path: t.TempDir(), TargetNaming: "standard"}}, skills, "merge", src, nil) + if len(diff.Warnings) == 0 || diff.NamingSkippedCount != 1 || len(diff.Items) != 0 { + t.Fatalf("validation warning becomes a sync operation: %+v", diff) + } +} + func TestHandleOverview_Empty(t *testing.T) { s, _ := newTestServer(t) req := httptest.NewRequest(http.MethodGet, "/api/overview", nil) @@ -54,6 +72,97 @@ func TestHandleOverview_WithSkills(t *testing.T) { } } +func TestHandleOverviewAndTargets_LogicalVariants(t *testing.T) { + s, src := newTestServerWithTargets(t, map[string]string{"claude": filepath.Join(t.TempDir(), "claude"), "universal": filepath.Join(t.TempDir(), "universal")}) + for _, agent := range []string{"claude", "codex"} { + for _, name := range []string{"fix", "review"} { + addSkill(t, src, "_repo/skills/"+agent+"/"+name) + } + } + initServerGitRepo(t, filepath.Join(src, "_repo")) + for _, endpoint := range []string{"/api/overview", "/api/targets"} { + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, endpoint, nil)) + if rr.Code != http.StatusOK { + t.Fatalf("%s: %d: %s", endpoint, rr.Code, rr.Body.String()) + } + var resp map[string]any + if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if endpoint == "/api/overview" { + if resp["skillCount"] != float64(2) || resp["variantCount"] != float64(4) { + t.Fatalf("overview counts: %+v", resp) + } + repo := resp["trackedRepos"].([]any)[0].(map[string]any) + if repo["skillCount"] != float64(2) || repo["variantCount"] != float64(4) { + t.Fatalf("repo counts: %+v", repo) + } + } else { + if resp["sourceSkillCount"] != float64(2) || resp["sourceVariantCount"] != float64(4) { + t.Fatalf("source counts: %+v", resp) + } + for _, value := range resp["targets"].([]any) { + target := value.(map[string]any) + want := float64(0) + if target["name"] == "claude" { + want = 2 + } + if target["expectedSkillCount"] != want { + t.Fatalf("target counts: %+v", target) + } + } + } + } +} + +func TestTrackedVariantAmbiguityReachesPreviews(t *testing.T) { + s, src := newTestServerWithTargets(t, map[string]string{"claude": t.TempDir()}) + for _, agent := range []string{"claude", "claude-code", "codex"} { + addSkill(t, src, "_repo/skills/"+agent+"/fix") + } + for _, endpoint := range []string{"/api/diff", "/api/targets"} { + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, endpoint, nil)) + if rr.Code != http.StatusOK { + t.Fatalf("%s: %s", endpoint, rr.Body.String()) + } + if !strings.Contains(rr.Body.String(), "ambiguous") || !strings.Contains(rr.Body.String(), "target override") { + t.Errorf("%s lost selection reason: %s", endpoint, rr.Body.String()) + } + var response struct { + Diffs []struct { + Warnings []string `json:"warnings"` + Skipped int `json:"skippedCount"` + Naming int `json:"namingSkippedCount"` + Items []diffItem `json:"items"` + } `json:"diffs"` + Targets []struct { + Expected int `json:"expectedSkillCount"` + Skipped int `json:"skippedSkillCount"` + } + } + if err := json.Unmarshal(rr.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + if endpoint == "/api/targets" { + if response.Targets[0].Expected != 0 || response.Targets[0].Skipped != 2 { + t.Errorf("preview counts = %+v", response.Targets) + } + } else { + preview := response.Diffs[0] + if preview.Skipped != 2 || preview.Naming != 0 || len(preview.Items) != 2 || len(preview.Warnings) != 0 { + t.Fatalf("ambiguous preview counts: %+v", preview) + } + for _, item := range preview.Items { + if item.Action != "skip" { + t.Fatalf("ambiguous preview proposes an operation: %+v", item) + } + } + } + } +} + func TestHandleOverview_AgentCountIncludesNestedAgents(t *testing.T) { s, _ := newTestServer(t) agentsDir := s.agentsSource() diff --git a/internal/server/handler_sync.go b/internal/server/handler_sync.go index 2f4409bc6..501e9aa44 100644 --- a/internal/server/handler_sync.go +++ b/internal/server/handler_sync.go @@ -409,6 +409,7 @@ type diffItem struct { type diffTarget struct { Target string `json:"target"` + Warnings []string `json:"warnings,omitempty"` Items []diffItem `json:"items"` SkippedCount int `json:"skippedCount,omitempty"` CollisionCount int `json:"collisionCount,omitempty"` diff --git a/internal/server/handler_sync_matrix.go b/internal/server/handler_sync_matrix.go index ba2c4b801..f9f0db6d0 100644 --- a/internal/server/handler_sync_matrix.go +++ b/internal/server/handler_sync_matrix.go @@ -25,6 +25,8 @@ func syncMatrixReason(status, reason string) (string, map[string]string) { return "sync_matrix.symlink_filters_not_applicable", nil } switch status { + case "skipped": + return "sync_matrix.ambiguous_variant", nil case "synced": return "sync_matrix.synced", nil case "excluded": @@ -100,9 +102,14 @@ func (s *Server) handleSyncMatrix(w http.ResponseWriter, r *http.Request) { entries = append(entries, newSyncMatrixEntry(skill.FlatName, name, "na", "symlink mode — filters not applicable", "")) } } else { + classified, err := ssync.ClassifySkillsForTarget(skills, name, sc) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } for _, skill := range skills { - status, reason := ssync.ClassifySkillForTarget(skill.FlatName, skill.Targets, name, sc.Include, sc.Exclude) - entries = append(entries, newSyncMatrixEntry(skill.FlatName, name, status, reason, "")) + row := classified[skill.RelPath] + entries = append(entries, newSyncMatrixEntry(skill.FlatName, name, row.Status, row.Reason, "")) } } // Agents — resolve path from user config or builtin defaults @@ -141,6 +148,7 @@ func (s *Server) handleSyncMatrixPreview(w http.ResponseWriter, r *http.Request) source := s.cfg.EffectiveSkillsSource() agentsSource := s.agentsSource() targets := s.cloneTargets() + defaultMode := s.cfg.Mode s.mu.RUnlock() var body struct { @@ -187,13 +195,24 @@ func (s *Server) handleSyncMatrixPreview(w http.ResponseWriter, r *http.Request) } var entries []syncMatrixEntry + target, ok := targets[body.Target] + sc := target.SkillsConfig() + sc.Include, sc.Exclude = body.Include, body.Exclude + target.Skills = &sc + targets[body.Target] = target + target = config.WithSharedSkillsTargets(targets, defaultMode)[body.Target] + sc = target.SkillsConfig() + classified, err := ssync.ClassifySkillsForTarget(skills, body.Target, sc) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } for _, skill := range skills { - status, reason := ssync.ClassifySkillForTarget(skill.FlatName, skill.Targets, body.Target, body.Include, body.Exclude) - entries = append(entries, newSyncMatrixEntry(skill.FlatName, body.Target, status, reason, "")) + row := classified[skill.RelPath] + entries = append(entries, newSyncMatrixEntry(skill.FlatName, body.Target, row.Status, row.Reason, "")) } // Agents — resolve path from config or builtin defaults - target, ok := targets[body.Target] _, projectTool, isProject := config.SplitProjectTarget(body.Target) if (ok || isProject) && agentsSource != "" { ac := target.AgentsConfig() diff --git a/internal/server/handler_sync_matrix_test.go b/internal/server/handler_sync_matrix_test.go index 803d54f99..2fc5f6967 100644 --- a/internal/server/handler_sync_matrix_test.go +++ b/internal/server/handler_sync_matrix_test.go @@ -29,6 +29,80 @@ func TestHandleSyncMatrix_Empty(t *testing.T) { } } +func TestSyncMatrixUsesSharedVariantSelection(t *testing.T) { + s, src := newTestServerWithTargets(t, map[string]string{"claude": t.TempDir(), "codex-work": t.TempDir(), "universal": t.TempDir()}) + account := s.cfg.Targets["codex-work"] + account.Agent = "codex" + account.ConfigDir = t.TempDir() + account.Path = "" + s.cfg.Targets["codex-work"] = account + if err := s.cfg.Save(); err != nil { + t.Fatal(err) + } + for _, agent := range []string{"claude", "claude-code", "codex"} { + for _, suffix := range []string{"fix", "review/fix"} { + addSkill(t, src, "_repo/skills/"+agent+"/"+suffix) + } + } + for _, tc := range []struct { + target string + want int + }{{"claude", 0}, {"codex-work", 2}, {"universal", 0}} { + for _, method := range []string{http.MethodGet, http.MethodPost} { + t.Run(tc.target+"/"+method, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/api/sync-matrix?target="+tc.target, nil) + if method == http.MethodPost { + req = httptest.NewRequest(http.MethodPost, "/api/sync-matrix/preview", strings.NewReader(`{"target":"`+tc.target+`"}`)) + } + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, req) + if rr.Code != http.StatusOK { + t.Fatal(rr.Body.String()) + } + var response struct { + Entries []syncMatrixEntry `json:"entries"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + synced, skipped := 0, 0 + for _, row := range response.Entries { + if row.Kind == "agent" { + continue + } + if row.Status == "synced" { + synced++ + } + if row.Status == "skipped" && strings.Contains(row.Reason, "ambiguous") { + skipped++ + } + } + if synced != tc.want || (tc.target == "claude" && skipped != 4) { + t.Fatalf("matrix selected %d, skipped %d; want %d selected: %s", synced, skipped, tc.want, rr.Body.String()) + } + }) + } + } + // Draft includes must disambiguate before the shared selector checks aliases. + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/api/sync-matrix/preview", strings.NewReader(`{"target":"claude","include":["_repo__skills__claude__*"]}`))) + var response struct { + Entries []syncMatrixEntry `json:"entries"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + synced := 0 + for _, row := range response.Entries { + if row.Status == "synced" { + synced++ + } + } + if synced != 2 { + t.Fatalf("draft include failed to select exact variant: %s", rr.Body.String()) + } +} + func TestHandleSyncMatrix_WithSkillsAndTargets(t *testing.T) { tgtPath := filepath.Join(t.TempDir(), "claude-skills") s, sourceDir := newTestServerWithTargets(t, map[string]string{"claude": tgtPath}) @@ -356,3 +430,45 @@ func TestHandleSyncMatrixPreview_ProjectDraftGetsAgents(t *testing.T) { t.Fatalf("status %d, body %s", rr.Code, rr.Body.String()) } } + +func TestSyncMatrixAmbiguityReasonCode(t *testing.T) { + entry := newSyncMatrixEntry("_repo__skills__claude__fix", "claude", "skipped", "ambiguous variant", "skill") + if entry.ReasonCode != "sync_matrix.ambiguous_variant" { + t.Fatalf("reason code = %q", entry.ReasonCode) + } +} + +func TestSyncMatrixPreviewRecomputesSharedVariantSelection(t *testing.T) { + shared := t.TempDir() + s, src := newTestServerWithTargets(t, map[string]string{"codex": shared, "universal": shared}) + for _, agent := range []string{"claude", "codex"} { + addSkill(t, src, "_repo/skills/"+agent+"/fix") + } + for _, tc := range []struct { + filters string + want string + }{ + {``, "synced"}, + {`,"exclude":["unrelated"]`, "skill_target_mismatch"}, + } { + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/api/sync-matrix/preview", strings.NewReader(`{"target":"universal"`+tc.filters+`}`))) + if rr.Code != http.StatusOK { + t.Fatal(rr.Body.String()) + } + var response struct { + Entries []syncMatrixEntry `json:"entries"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + for _, row := range response.Entries { + if row.Skill == "_repo__skills__codex__fix" && row.Status != tc.want { + t.Fatalf("preview %s: got %s want %s", tc.filters, row.Status, tc.want) + } + } + } + if len(s.cfg.Targets["universal"].Exclude) != 0 { + t.Fatal("preview mutated saved filters") + } +} diff --git a/internal/server/handler_sync_test.go b/internal/server/handler_sync_test.go index c4a1f1935..5a0a5c489 100644 --- a/internal/server/handler_sync_test.go +++ b/internal/server/handler_sync_test.go @@ -17,6 +17,48 @@ import ( ssync "skillshare/internal/sync" ) +func TestHandleSync_SharedVariantsStaySynced(t *testing.T) { + for _, mode := range []string{"merge", "copy"} { + t.Run(mode, func(t *testing.T) { + dest := t.TempDir() + s, src := newTestServerWithTargets(t, map[string]string{"codex": dest, "universal": dest}) + s.cfg.Mode = mode + for _, agent := range []string{"claude", "codex"} { + addSkill(t, src, "_repo/skills/"+agent+"/fix") + } + for i := 0; i < 2; i++ { + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/api/sync", strings.NewReader(`{}`))) + if rr.Code != http.StatusOK { + t.Fatalf("sync: %d %s", rr.Code, rr.Body.String()) + } + if _, err := os.Stat(filepath.Join(dest, "_repo__skills__codex__fix", "SKILL.md")); err != nil { + t.Fatal(err) + } + } + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/api/diff", nil)) + var preview struct { + Diffs []diffTarget `json:"diffs"` + } + if rr.Code != http.StatusOK { + t.Fatalf("diff: %s", rr.Body.String()) + } + if err := json.Unmarshal(rr.Body.Bytes(), &preview); err != nil { + t.Fatal(err) + } + if len(preview.Diffs) != 2 { + t.Fatalf("missing targets: %s", rr.Body.String()) + } + for _, target := range preview.Diffs { + if len(target.Items) != 0 { + t.Fatalf("shared selection differs: %+v", target) + } + } + }) + } +} + func TestHandleSync_MergeMode(t *testing.T) { tgtPath := filepath.Join(t.TempDir(), "claude-skills") s, src := newTestServerWithTargets(t, map[string]string{"claude": tgtPath}) diff --git a/internal/server/handler_targets.go b/internal/server/handler_targets.go index f2076d5e2..9c865b529 100644 --- a/internal/server/handler_targets.go +++ b/internal/server/handler_targets.go @@ -15,31 +15,34 @@ import ( ) type targetItem struct { - Name string `json:"name"` - Project string `json:"project,omitempty"` // root of the project this target belongs to - Agent string `json:"agent,omitempty"` // the built-in Agent this is another config directory of - ConfigDir string `json:"configDir,omitempty"` - CLI string `json:"cli,omitempty"` // the executable that runs its plugin commands, when not the Agent's own - Path string `json:"path"` - Mode string `json:"mode"` - TargetNaming string `json:"targetNaming"` - Status string `json:"status"` - LinkedCount int `json:"linkedCount"` - LocalCount int `json:"localCount"` - Include []string `json:"include"` - Exclude []string `json:"exclude"` - ExpectedSkillCount int `json:"expectedSkillCount"` - SkippedSkillCount int `json:"skippedSkillCount,omitempty"` - CollisionCount int `json:"collisionCount,omitempty"` - AgentPath string `json:"agentPath,omitempty"` - AgentMode string `json:"agentMode,omitempty"` - AgentExtension string `json:"agentExtension,omitempty"` - AgentInclude []string `json:"agentInclude,omitempty"` - AgentExclude []string `json:"agentExclude,omitempty"` - AgentLinkedCount *int `json:"agentLinkedCount,omitempty"` - AgentLocalCount *int `json:"agentLocalCount,omitempty"` - AgentExpectedCount *int `json:"agentExpectedCount,omitempty"` - SkillsEnabled bool `json:"skillsEnabled"` + Name string `json:"name"` + Project string `json:"project,omitempty"` // root of the project this target belongs to + Agent string `json:"agent,omitempty"` // the built-in Agent this is another config directory of + ConfigDir string `json:"configDir,omitempty"` + CLI string `json:"cli,omitempty"` // the executable that runs its plugin commands, when not the Agent's own + Path string `json:"path"` + Mode string `json:"mode"` + TargetNaming string `json:"targetNaming"` + Status string `json:"status"` + LinkedCount int `json:"linkedCount"` + LocalCount int `json:"localCount"` + Include []string `json:"include"` + Exclude []string `json:"exclude"` + ExpectedSkillCount int `json:"expectedSkillCount"` + SkippedSkillCount int `json:"skippedSkillCount,omitempty"` + NamingSkippedSkillCount int `json:"namingSkippedSkillCount,omitempty"` + SelectionSkippedSkillCount int `json:"selectionSkippedSkillCount,omitempty"` + Warnings []string `json:"warnings,omitempty"` + CollisionCount int `json:"collisionCount,omitempty"` + AgentPath string `json:"agentPath,omitempty"` + AgentMode string `json:"agentMode,omitempty"` + AgentExtension string `json:"agentExtension,omitempty"` + AgentInclude []string `json:"agentInclude,omitempty"` + AgentExclude []string `json:"agentExclude,omitempty"` + AgentLinkedCount *int `json:"agentLinkedCount,omitempty"` + AgentLocalCount *int `json:"agentLocalCount,omitempty"` + AgentExpectedCount *int `json:"agentExpectedCount,omitempty"` + SkillsEnabled bool `json:"skillsEnabled"` // SkillsReadFrom (skills off) names the enabled targets whose skills folder // this tool still reads; SkillsAlsoReadBy (skills on) names the targets with // skills off whose tool reads this target's folder. @@ -138,22 +141,17 @@ func (s *Server) handleListTargets(w http.ResponseWriter, r *http.Request) { item.SkillsReadFrom = config.SkillsReadFrom(targets, name, projectRoot) case mode == "merge" || mode == "copy": if discoveredErr == nil { - filtered, err := ssync.SelectTargetSkills(discovered, name, sc) + resolution, err := ssync.ResolveTargetSkillsForTarget(name, sc, discovered) if err != nil { writeError(w, http.StatusBadRequest, "invalid include/exclude for target "+name+": "+err.Error()) return } - resolution, resErr := ssync.ResolveTargetSkillsForTarget(name, config.ResourceTargetConfig{ - Path: sc.Path, - TargetNaming: sc.TargetNaming, - }, filtered) - if resErr == nil { - item.ExpectedSkillCount = len(resolution.Skills) - item.SkippedSkillCount = len(filtered) - len(resolution.Skills) - item.CollisionCount = len(resolution.Collisions) - } else { - item.ExpectedSkillCount = len(filtered) - } + item.ExpectedSkillCount = len(resolution.Skills) + item.SkippedSkillCount = resolution.SkippedCount + item.NamingSkippedSkillCount = resolution.NamingSkippedCount + item.SelectionSkippedSkillCount = len(resolution.SelectionWarnings) + item.CollisionCount = len(resolution.Collisions) + item.Warnings = append(resolution.Warnings, resolution.SelectionWarnings...) } if mode == "merge" { status, linked, local := ssync.CheckStatusMerge(sc.Path, source) @@ -200,12 +198,12 @@ func (s *Server) handleListTargets(w http.ResponseWriter, r *http.Request) { } // Count source skills for drift detection - sourceSkillCount := 0 + counts := ssync.SkillCounts{} if discoveredErr == nil { - sourceSkillCount = len(discovered) + counts = ssync.CountSkills(discovered) } - writeJSON(w, map[string]any{"targets": items, "sourceSkillCount": sourceSkillCount}) + writeJSON(w, map[string]any{"targets": items, "sourceSkillCount": counts.Skills, "sourceVariantCount": counts.Variants}) } func intPtr(v int) *int { diff --git a/internal/server/handler_targets_test.go b/internal/server/handler_targets_test.go index d4fe6a921..a7978e84f 100644 --- a/internal/server/handler_targets_test.go +++ b/internal/server/handler_targets_test.go @@ -695,3 +695,44 @@ func TestHandleUpdateTarget_DisablingSkillsSkipsNamingCheck(t *testing.T) { t.Fatalf("disable with merge: got %d %s, want 200", rr.Code, rr.Body.String()) } } + +func TestHandleListTargets_SeparatesSkipRemedies(t *testing.T) { + s, src := newTestServerWithTargets(t, map[string]string{"claude": t.TempDir()}) + target := s.cfg.Targets["claude"] + target.Skills = &config.ResourceTargetConfig{Path: target.Path, TargetNaming: "standard"} + s.cfg.Targets["claude"] = target + if err := s.cfg.Save(); err != nil { + t.Fatal(err) + } + for _, path := range []string{"_repo/skills/claude/fix", "_repo/skills/claude-code/fix", "_repo/skills/codex/fix", "one/same", "two/same", "bad"} { + name := filepath.Base(path) + if name == "bad" { + name = "different" + } + dir := filepath.Join(src, filepath.FromSlash(path)) + if err := os.MkdirAll(dir, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("---\nname: "+name+"\n---\n# Instructions"), 0644); err != nil { + t.Fatal(err) + } + } + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/api/targets", nil)) + if rr.Code != http.StatusOK { + t.Fatal(rr.Body.String()) + } + var response struct { + Targets []targetItem `json:"targets"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + if len(response.Targets) != 1 { + t.Fatal(rr.Body.String()) + } + got := response.Targets[0] + if got.NamingSkippedSkillCount != 1 || got.SelectionSkippedSkillCount != 2 || got.CollisionCount != 1 || got.SkippedSkillCount != 5 { + t.Fatalf("skip remedies: %s", rr.Body.String()) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 5eea84698..f3e1238d0 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -259,7 +259,7 @@ func (s *Server) cloneTargets() map[string]config.TargetConfig { for k, v := range s.cfg.Targets { targets[k] = v } - return targets + return config.WithSharedSkillsTargets(targets, s.cfg.Mode) } // parseOpts returns install.ParseOptions from the current config. diff --git a/internal/skillserve/catalog.go b/internal/skillserve/catalog.go index f70c8067f..94d280899 100644 --- a/internal/skillserve/catalog.go +++ b/internal/skillserve/catalog.go @@ -110,8 +110,14 @@ func (b *Builder) Build() (*Catalog, error) { func (b *Builder) build(all []ssync.DiscoveredSkill) (*Catalog, error) { var err error var selected []ssync.DiscoveredSkill + var skipped map[string]string + var routed map[string]ssync.SkillTargetClassification if b.Skills != nil { - if selected, err = ssync.SelectTargetSkills(all, b.Target, *b.Skills); err != nil { + if selected, skipped, err = ssync.SelectTargetSkillsWithDiagnostics(all, b.Target, *b.Skills); err != nil { + return nil, err + } + routed, err = ssync.ClassifySkillsForTarget(all, b.Target, *b.Skills) + if err != nil { return nil, err } } else { @@ -122,16 +128,19 @@ func (b *Builder) build(all []ssync.DiscoveredSkill) (*Catalog, error) { served[s.RelPath] = true } var unserved []string + c := &Catalog{bySkill: map[string]*Skill{}, byFile: map[string]servedFile{}} for _, s := range all { - if !served[s.RelPath] { + if !served[s.RelPath] && !(s.UsesVariantRouting() && !s.Disabled && routed[s.RelPath].Status == "skill_target_mismatch") { unserved = append(unserved, s.RelPath) } + if reason, ok := skipped[s.RelPath]; ok { + c.Skipped = append(c.Skipped, Skip{Path: s.RelPath, Reason: reason}) + } } slices.SortFunc(selected, func(x, y ssync.DiscoveredSkill) int { return strings.Compare(x.RelPath, y.RelPath) }) // Deepest first, so a nested skill skipped for any reason also skips its parents, // which would otherwise publish its files as their own. - c := &Catalog{bySkill: map[string]*Skill{}, byFile: map[string]servedFile{}} for i := len(selected) - 1; i >= 0; i-- { s := selected[i] skill, files, reason := load(s) diff --git a/internal/skillserve/catalog_test.go b/internal/skillserve/catalog_test.go index 00a654149..7f0b9e48b 100644 --- a/internal/skillserve/catalog_test.go +++ b/internal/skillserve/catalog_test.go @@ -11,6 +11,7 @@ import ( "testing" "skillshare/internal/config" + "skillshare/internal/install" "skillshare/internal/skillpkg" ) @@ -108,6 +109,32 @@ func TestBuild_AppliesTargetSelectionAndDisabledState(t *testing.T) { } } +func TestBuild_ReportsAmbiguousTargetVariants(t *testing.T) { + src := t.TempDir() + for _, agent := range []string{"claude", "claude-code", "codex"} { + writeFile(t, filepath.Join(src, "_repo/skills", agent, "fix/SKILL.md"), skillMD("fix")) + } + c, err := (&Builder{Source: src, Target: "claude", Skills: &config.ResourceTargetConfig{}}).Build() + if err != nil { + t.Fatal(err) + } + if len(c.Skills) != 0 || len(c.Skipped) != 2 || !hasWarning(c, "ambiguous") || !hasWarning(c, "target override") { + t.Fatalf("ambiguous catalog silently skipped variants: skills=%v, skipped=%v", c.Skills, c.Skipped) + } + if c.Skipped[0].Path != "_repo/skills/claude-code/fix" || c.Skipped[1].Path != "_repo/skills/claude/fix" { + t.Fatalf("skip paths must retain source order: %v", c.Skipped) + } + account := config.TargetConfig{Agent: "codex", Skills: &config.ResourceTargetConfig{TargetNaming: "prefixed"}} + sc := account.SkillsConfig() + c, err = (&Builder{Source: src, Target: "codex-work", Skills: &sc}).Build() + if err != nil { + t.Fatal(err) + } + if len(c.Skills) != 1 || c.Skills[0].URI != "skill://_repo/skills/codex/fix/SKILL.md" || len(c.Skipped) != 0 { + t.Fatalf("account catalog must serve the selected physical variant: skills=%v, skipped=%v", c.Skills, c.Skipped) + } +} + func TestBuild_SkipsParentOfExcludedNestedSkill(t *testing.T) { src := t.TempDir() writeFile(t, filepath.Join(src, "suite/SKILL.md"), skillMD("suite")) @@ -413,3 +440,73 @@ func TestRead_ServesListedFileWithBackslashInName(t *testing.T) { t.Errorf("Read = %q, %v; want the listed file", data, err) } } + +func TestBuild_ServesParentWithDifferentlyRoutedVariant(t *testing.T) { + src := t.TempDir() + writeFile(t, filepath.Join(src, "_repo/parent/SKILL.md"), skillMD("parent")) + for _, agent := range []string{"claude", "codex"} { + writeFile(t, filepath.Join(src, "_repo/parent/skills", agent, "fix/SKILL.md"), skillMD("fix")) + } + for _, tc := range []struct { + name string + sc config.ResourceTargetConfig + disabled bool + }{ + {name: "excluded peer", sc: config.ResourceTargetConfig{Exclude: []string{"_repo__parent__skills__codex__fix"}}}, + {name: "peer omitted by include", sc: config.ResourceTargetConfig{Include: []string{"_repo__parent", "_repo__parent__skills__claude__fix"}}}, + {name: "disabled peer", disabled: true}, + } { + t.Run(tc.name, func(t *testing.T) { + if tc.disabled { + writeFile(t, filepath.Join(src, ".skillignore"), "_repo/parent/skills/codex/fix\n") + } + c, err := (&Builder{Source: src, Target: "claude", Skills: &tc.sc}).Build() + if err != nil { + t.Fatal(err) + } + if find(c, "skill://_repo/parent/SKILL.md") != nil { + t.Fatalf("parent exposes unserved filtered peer: skips=%v", c.Skipped) + } + }) + } + writeFile(t, filepath.Join(src, ".skillignore"), "") + for _, target := range []string{"claude", "codex"} { + c, err := (&Builder{Source: src, Target: target, Skills: &config.ResourceTargetConfig{}}).Build() + if err != nil { + t.Fatal(err) + } + if find(c, "skill://_repo/parent/SKILL.md") == nil || len(c.Skills) != 2 { + t.Fatalf("%s: skills=%v skips=%v", target, c.Skills, c.Skipped) + } + } +} + +func TestBuild_VariantParentRespectsExplicitChildTargets(t *testing.T) { + for _, override := range []bool{false, true} { + t.Run(fmt.Sprintf("override=%t", override), func(t *testing.T) { + src := t.TempDir() + writeFile(t, filepath.Join(src, "_repo/parent/SKILL.md"), skillMD("parent")) + for _, agent := range []string{"claude", "codex"} { + content := skillMD("fix") + if agent == "codex" && !override { + content = strings.Replace(content, "metadata:\n", "metadata:\n targets: [codex]\n", 1) + } + writeFile(t, filepath.Join(src, "_repo/parent/skills", agent, "fix/SKILL.md"), content) + } + if override { + store := install.NewMetadataStore() + store.SetTargetOverride("_repo/parent/skills/codex/fix", []string{"codex"}) + if err := store.Save(src); err != nil { + t.Fatal(err) + } + } + c, err := (&Builder{Source: src, Target: "claude", Skills: &config.ResourceTargetConfig{}}).Build() + if err != nil { + t.Fatal(err) + } + if find(c, "skill://_repo/parent/SKILL.md") != nil { + t.Fatalf("parent exposes explicitly restricted child: skips=%v", c.Skipped) + } + }) + } +} diff --git a/internal/sourcefs/testdata/raw_writes.tsv b/internal/sourcefs/testdata/raw_writes.tsv index 5d5d0b272..8f2c1f95a 100644 --- a/internal/sourcefs/testdata/raw_writes.tsv +++ b/internal/sourcefs/testdata/raw_writes.tsv @@ -359,7 +359,7 @@ internal/sync/agent_sync.go syncAgentsMergeCopy os.Remove targetPath target internal/sync/agent_sync.go syncAgentsSymlink os.MkdirAll filepath.Dir(targetDir) target internal/sync/agent_sync.go syncAgentsSymlink os.Remove targetDir target internal/sync/agent_sync.go syncAgentsSymlink os.RemoveAll targetDir target -internal/sync/copy.go PruneOrphanCopiesWithSkills os.RemoveAll entryPath target +internal/sync/copy.go pruneOrphanCopiesWithConfig os.RemoveAll entryPath target internal/sync/copy.go SyncTargetCopyWithSkillsOptions os.Remove targetSkillPath target internal/sync/copy.go SyncTargetCopyWithSkillsOptions os.RemoveAll targetSkillPath target internal/sync/copy.go SyncTargetCopyWithSkillsOptions os.RemoveAll targetSkillPath target diff --git a/internal/sync/classify.go b/internal/sync/classify.go index b25161d57..caae68adc 100644 --- a/internal/sync/classify.go +++ b/internal/sync/classify.go @@ -6,6 +6,42 @@ import ( "skillshare/internal/config" ) +// SkillTargetClassification is a physical skill's selection result for previews. +type SkillTargetClassification struct{ Status, Reason string } + +// ClassifySkillsForTarget evaluates the full source selection once so preview +// rows share exact-agent routing, account identity, and ambiguity handling with sync. +func ClassifySkillsForTarget(skills []DiscoveredSkill, name string, sc config.ResourceTargetConfig) (map[string]SkillTargetClassification, error) { + selection, err := selectTargetSkills(skills, name, sc) + if err != nil { + return nil, err + } + selected := make(map[string]bool, len(selection.Skills)) + for _, skill := range selection.Skills { + selected[skill.RelPath] = true + } + rows := make(map[string]SkillTargetClassification, len(skills)) + for _, skill := range skills { + targets := skill.Targets + // Inferred membership comes from the shared exact-agent selector below. + if skill.variantRouting || selected[skill.RelPath] { + targets = nil + } + status, reason := ClassifySkillForTarget(skill.FlatName, targets, name, sc.Include, sc.Exclude) + if status == "synced" && !selected[skill.RelPath] { + if warning, ok := selection.Skipped[skill.RelPath]; ok { + status, reason = "skipped", warning + } else if skill.Disabled { + status, reason = "skipped", "disabled by .skillignore" + } else { + status, reason = "skill_target_mismatch", strings.Join(skill.Targets, ", ") + } + } + rows[skill.RelPath] = SkillTargetClassification{Status: status, Reason: reason} + } + return rows, nil +} + // ClassifySkillForTarget determines whether a skill should sync to a target, // returning a status string and an optional reason. // diff --git a/internal/sync/copy.go b/internal/sync/copy.go index f80cb1d87..5ad8cf7fe 100644 --- a/internal/sync/copy.go +++ b/internal/sync/copy.go @@ -305,6 +305,12 @@ func PruneOrphanCopies(targetPath, sourcePath string, include, exclude []string, // PruneOrphanCopiesWithSkills is like PruneOrphanCopies but accepts pre-discovered skills. func PruneOrphanCopiesWithSkills(targetPath string, allSourceSkills []DiscoveredSkill, include, exclude []string, targetName, targetNaming string, dryRun bool) (*PruneResult, error) { + sc := config.ResourceTargetConfig{Path: targetPath, TargetNaming: targetNaming, Include: include, Exclude: exclude} + return pruneOrphanCopiesWithConfig(targetName, sc, allSourceSkills, dryRun) +} + +func pruneOrphanCopiesWithConfig(targetName string, sc config.ResourceTargetConfig, allSourceSkills []DiscoveredSkill, dryRun bool) (*PruneResult, error) { + targetPath := sc.Path result := &PruneResult{} manifest, err := ReadManifest(targetPath) @@ -312,12 +318,7 @@ func PruneOrphanCopiesWithSkills(targetPath string, allSourceSkills []Discovered return nil, fmt.Errorf("failed to read manifest: %w", err) } - resolution, err := ResolveTargetSkillsForTarget(targetName, config.ResourceTargetConfig{ - Path: targetPath, - TargetNaming: targetNaming, - Include: include, - Exclude: exclude, - }, allSourceSkills) + resolution, err := ResolveTargetSkillsForTarget(targetName, sc, allSourceSkills) if err != nil { return nil, err } diff --git a/internal/sync/discover_walk.go b/internal/sync/discover_walk.go index d6db7cb98..8eff1434e 100644 --- a/internal/sync/discover_walk.go +++ b/internal/sync/discover_walk.go @@ -265,6 +265,7 @@ func discoverSourceSkillsInternal(sourcePath string, opts discoverOptions) ([]Di repoRelPath := repoOf(relPath) isInRepo := repoRelPath != "" + logicalID, variantAgent := skillVariant(relPath, repoRelPath) // Root-level .skillignore fallback (for files in non-skipped dirs), // then the repo-level .skillignore inside tracked repos. With @@ -311,26 +312,35 @@ func discoverSourceSkillsInternal(sourcePath string, opts discoverOptions) ([]Di targets = utils.ParseFrontmatterList(skillFile, "targets") } + variantRouting := false if len(targets) == 0 && (opts.parseFrontmatter || opts.collectContext) { - targets = inferSkillTargetsFromRelPath(relPath) + if variantAgent != "" { + targets = []string{variantAgent} + variantRouting = true + } else { + targets = inferSkillTargetsFromRelPath(relPath) + } } // Use original sourcePath (not walkRoot) so SourcePath preserves // the caller's logical path, even if sourcePath is a symlink. skills = append(skills, DiscoveredSkill{ - SourcePath: filepath.Join(sourcePath, relPath), - RelPath: relPath, - FlatName: utils.PathToFlatName(relPath), - IsInRepo: isInRepo, - RepoRelPath: repoRelPath, - Targets: targets, - DescChars: ctx.DescChars, - BodyChars: ctx.BodyChars, - DescTokens: ctx.DescTokens, - BodyTokens: ctx.BodyTokens, - Description: ctx.Description, - LintIssues: lintIssues, - Disabled: disabled, + SourcePath: filepath.Join(sourcePath, relPath), + RelPath: relPath, + FlatName: utils.PathToFlatName(relPath), + IsInRepo: isInRepo, + RepoRelPath: repoRelPath, + LogicalID: logicalID, + VariantAgent: variantAgent, + variantRouting: variantRouting, + Targets: targets, + DescChars: ctx.DescChars, + BodyChars: ctx.BodyChars, + DescTokens: ctx.DescTokens, + BodyTokens: ctx.BodyTokens, + Description: ctx.Description, + LintIssues: lintIssues, + Disabled: disabled, }) } @@ -341,6 +351,7 @@ func discoverSourceSkillsInternal(sourcePath string, opts discoverOptions) ([]Di return nil, nil, nil, fmt.Errorf("failed to walk source directory: %w", err) } + confirmSkillVariants(skills, walkRoot) if opts.parseFrontmatter || opts.collectContext { applyTargetOverrides(skills, walkRoot) } @@ -367,6 +378,7 @@ func applyTargetOverrides(skills []DiscoveredSkill, sourceDir string) { if !ok { continue } + skills[i].variantRouting = false if len(targets) == 0 { skills[i].Targets = nil } else { diff --git a/internal/sync/execute_targets.go b/internal/sync/execute_targets.go index f70383d30..ed19f5d57 100644 --- a/internal/sync/execute_targets.go +++ b/internal/sync/execute_targets.go @@ -96,6 +96,17 @@ func ExecuteTargets(ctx context.Context, cfg *config.Config, targets map[string] sourceIncomplete := opts.Discovery.SourceIncomplete ignorePatterns := EffectiveFileIgnorePatterns(cfg.Ignore) runTargets := targets + // Resolve against the whole configuration even for a target-only sync. + allTargets := maps.Clone(cfg.Targets) + if allTargets == nil { + allTargets = make(map[string]config.TargetConfig) + } + maps.Copy(allTargets, targets) + sharedTargets := config.WithSharedSkillsTargets(allTargets, globalMode) + runTargets = maps.Clone(targets) + for name := range runTargets { + runTargets[name] = sharedTargets[name] + } dryRun, force := opts.DryRun, opts.Force if opts.ResolveExtension == nil { opts.ResolveExtension = func(ext string) (*ExtensionSpec, error) { diff --git a/internal/sync/filter.go b/internal/sync/filter.go index 32eed9a4d..01066618f 100644 --- a/internal/sync/filter.go +++ b/internal/sync/filter.go @@ -205,37 +205,96 @@ func suggestFlatNames(pattern string, skills []DiscoveredSkill) []string { // skills that pass its include/exclude filters and whose frontmatter targets // name it or declare none. func SelectTargetSkills(skills []DiscoveredSkill, targetName string, sc config.ResourceTargetConfig) ([]DiscoveredSkill, error) { + selection, err := selectTargetSkills(skills, targetName, sc) + return selection.Skills, err +} + +// SelectTargetSkillsWithDiagnostics also returns selection diagnostics keyed by +// source-relative physical path. Expected exclusions and mismatches are not warnings. +func SelectTargetSkillsWithDiagnostics(skills []DiscoveredSkill, targetName string, sc config.ResourceTargetConfig) ([]DiscoveredSkill, map[string]string, error) { + selection, err := selectTargetSkills(skills, targetName, sc) + return selection.Skills, selection.Skipped, err +} + +type targetSkillSelection struct { + Skills []DiscoveredSkill + Warnings []string + Skipped map[string]string // Physical relative path to its selection diagnostic +} + +func selectTargetSkills(skills []DiscoveredSkill, targetName string, sc config.ResourceTargetConfig) (targetSkillSelection, error) { enabled := slices.DeleteFunc(slices.Clone(skills), func(s DiscoveredSkill) bool { return s.Disabled }) filtered, err := FilterSkills(enabled, sc.Include, sc.Exclude) if err != nil { - return nil, err + return targetSkillSelection{}, err } - return FilterSkillsByTarget(filtered, targetName), nil + if len(sc.SharedTargets) == 0 { + return filterSkillsByTarget(filtered, targetName, targetAgent(targetName, sc)), nil + } + selected := make(map[string]bool) + skipped := make(map[string]string) + for _, identity := range sc.SharedTargets { + part := filterSkillsByTarget(filtered, identity.Name, targetAgent(identity.Name, config.ResourceTargetConfig{Agent: identity.Agent})) + for _, skill := range part.Skills { + selected[skill.RelPath] = true + } + for rel, warning := range part.Skipped { + skipped[rel] = warning + } + } + result := targetSkillSelection{Skills: make([]DiscoveredSkill, 0, len(selected)), Skipped: make(map[string]string)} + for _, skill := range filtered { + if selected[skill.RelPath] { + result.Skills = append(result.Skills, skill) + } else if warning, ok := skipped[skill.RelPath]; ok { + result.Skipped[skill.RelPath] = warning + result.Warnings = append(result.Warnings, warning) + } + } + return result, nil } -// FilterSkillsByTarget removes skills whose Targets field does not include -// the given target name. Skills with nil Targets (no field declared) pass -// through unconditionally. -func FilterSkillsByTarget(skills []DiscoveredSkill, targetName string) []DiscoveredSkill { - filtered := make([]DiscoveredSkill, 0, len(skills)) +func filterSkillsByTarget(skills []DiscoveredSkill, targetName, agent string) targetSkillSelection { + variants := make(map[string]int) for _, skill := range skills { + if skill.variantRouting && skill.VariantAgent == agent { + variants[skill.LogicalID]++ + } + } + selection := targetSkillSelection{Skills: make([]DiscoveredSkill, 0, len(skills))} + for _, skill := range skills { + if skill.variantRouting { + if skill.VariantAgent == agent { + if variants[skill.LogicalID] > 1 { + warning := fmt.Sprintf("Target %q: skipped ambiguous %s variant %s; use include/exclude or a target override to select one", targetName, agent, skill.RelPath) + selection.Warnings = append(selection.Warnings, warning) + if selection.Skipped == nil { + selection.Skipped = make(map[string]string) + } + selection.Skipped[skill.RelPath] = warning + } else { + selection.Skills = append(selection.Skills, skill) + } + } + continue + } if skill.Targets == nil { - filtered = append(filtered, skill) + selection.Skills = append(selection.Skills, skill) continue } for _, t := range skill.Targets { if config.MatchesTargetName(t, targetName) { - filtered = append(filtered, skill) + selection.Skills = append(selection.Skills, skill) break } } } - return filtered + return selection } // FilterAgentsByTarget removes agents whose frontmatter targets field does not // include the given target name. Agents with nil Targets (no field declared) -// pass through unconditionally. Mirrors FilterSkillsByTarget. +// pass through unconditionally. Uses the same explicit target matching as skill selection. func FilterAgentsByTarget(agents []resource.DiscoveredResource, targetName string) []resource.DiscoveredResource { filtered := make([]resource.DiscoveredResource, 0, len(agents)) for _, agent := range agents { diff --git a/internal/sync/filter_target_test.go b/internal/sync/filter_target_test.go index 5d473db5b..b19a19379 100644 --- a/internal/sync/filter_target_test.go +++ b/internal/sync/filter_target_test.go @@ -21,70 +21,6 @@ func TestSelectTargetSkills_AppliesDisabledFiltersAndTargets(t *testing.T) { assertFlatNames(t, got, []string{"keep"}) } -func TestFilterSkillsByTarget_NilPassesThrough(t *testing.T) { - skills := []DiscoveredSkill{ - {FlatName: "no-targets", Targets: nil}, - } - result := FilterSkillsByTarget(skills, "claude") - if len(result) != 1 { - t.Errorf("nil Targets should pass through, got %d", len(result)) - } -} - -func TestFilterSkillsByTarget_ExactMatch(t *testing.T) { - skills := []DiscoveredSkill{ - {FlatName: "claude-only", Targets: []string{"claude"}}, - {FlatName: "cursor-only", Targets: []string{"cursor"}}, - } - result := FilterSkillsByTarget(skills, "claude") - if len(result) != 1 || result[0].FlatName != "claude-only" { - t.Errorf("expected only claude-only, got %v", result) - } -} - -func TestFilterSkillsByTarget_CrossModeMatch(t *testing.T) { - skills := []DiscoveredSkill{ - {FlatName: "cross-mode", Targets: []string{"claude"}}, - } - // "claude-code" is an alias for claude - result := FilterSkillsByTarget(skills, "claude-code") - if len(result) != 1 { - t.Errorf("cross-mode match should work, got %d results", len(result)) - } -} - -func TestFilterSkillsByTarget_NoMatch(t *testing.T) { - skills := []DiscoveredSkill{ - {FlatName: "claude-only", Targets: []string{"claude"}}, - } - result := FilterSkillsByTarget(skills, "cursor") - if len(result) != 0 { - t.Errorf("expected 0 results, got %d", len(result)) - } -} - -func TestFilterSkillsByTarget_MultipleTargets(t *testing.T) { - skills := []DiscoveredSkill{ - {FlatName: "multi", Targets: []string{"claude", "cursor"}}, - } - result := FilterSkillsByTarget(skills, "cursor") - if len(result) != 1 { - t.Errorf("skill with multiple targets should match, got %d", len(result)) - } -} - -func TestFilterSkillsByTarget_MixedNilAndSpecific(t *testing.T) { - skills := []DiscoveredSkill{ - {FlatName: "all-targets", Targets: nil}, - {FlatName: "claude-only", Targets: []string{"claude"}}, - {FlatName: "cursor-only", Targets: []string{"cursor"}}, - } - result := FilterSkillsByTarget(skills, "claude") - if len(result) != 2 { - t.Errorf("expected 2 results (nil + claude-only), got %d", len(result)) - } -} - func TestFilterAgentsByTarget_NilPassesThrough(t *testing.T) { agents := []resource.DiscoveredResource{{FlatName: "no-targets.md", Targets: nil}} if got := FilterAgentsByTarget(agents, "claude"); len(got) != 1 { diff --git a/internal/sync/skill_run.go b/internal/sync/skill_run.go index f7df1e2ca..65070566b 100644 --- a/internal/sync/skill_run.go +++ b/internal/sync/skill_run.go @@ -79,7 +79,9 @@ func SyncSkillTarget(t SkillTarget, skills []DiscoveredSkill, opts SkillRunOptio } res.UnmatchedIncludes = result.UnmatchedIncludes prune, err := PruneOrphanLinksWithSkills(PruneOptions{ - TargetPath: sc.Path, SourcePath: opts.Source, Skills: skills, + SharedTargets: sc.SharedTargets, + Agent: sc.Agent, + TargetPath: sc.Path, SourcePath: opts.Source, Skills: skills, Include: sc.Include, Exclude: sc.Exclude, TargetNaming: sc.TargetNaming, TargetName: t.Name, DryRun: opts.DryRun, Force: opts.Force, }) @@ -101,7 +103,7 @@ func SyncSkillTarget(t SkillTarget, skills []DiscoveredSkill, opts SkillRunOptio break } res.UnmatchedIncludes = result.UnmatchedIncludes - prune, err := PruneOrphanCopiesWithSkills(sc.Path, skills, sc.Include, sc.Exclude, t.Name, sc.TargetNaming, opts.DryRun) + prune, err := pruneOrphanCopiesWithConfig(t.Name, sc, skills, opts.DryRun) res.addPrune(prune, err) default: @@ -125,6 +127,9 @@ func SyncSkillTarget(t SkillTarget, skills []DiscoveredSkill, opts SkillRunOptio if len(res.KeptLocal) > 0 { res.Warnings = append(res.Warnings, fmt.Sprintf("%s: %s", res.Name, keptLocalWarning(res.KeptLocal))) } + if warning := variantRemovalWarning(t.Name, sc, skills, res.Pruned, opts.DryRun); warning != "" { + res.Warnings = append(res.Warnings, warning) + } return res } diff --git a/internal/sync/sync.go b/internal/sync/sync.go index fb698105f..598ca74e7 100644 --- a/internal/sync/sync.go +++ b/internal/sync/sync.go @@ -20,20 +20,23 @@ var DiagOutput io.Writer = os.Stdout // DiscoveredSkill represents a skill found during recursive source directory scan. type DiscoveredSkill struct { - SourcePath string // Full path: ~/.config/skillshare/skills/_team/frontend/ui - RelPath string // Relative path from source: _team/frontend/ui - FlatName string // Flat name for target: _team__frontend__ui - IsInRepo bool // Whether this skill is inside a tracked repo (_-prefixed directory) - RepoRelPath string // Tracked repo root relative to source (_team, or org/_team via --into); set when IsInRepo - Targets []string // From SKILL.md frontmatter; nil = all targets - DescChars int // Rune count of name + description (populated when collectContext) - BodyChars int // Rune count of body after frontmatter (populated when collectContext) - DescTokens int // Estimated tokens of name + description (populated when collectContext) - BodyTokens int // Estimated tokens of body (populated when collectContext) - Description string // Frontmatter description text (populated when collectContext) - LintIssues []LintIssue // Lint issues (populated when collectContext) - Disabled bool // Whether this skill is ignored by .skillignore - Local bool // Found in a target folder rather than the source; see TargetSkills + SourcePath string // Full path: ~/.config/skillshare/skills/_team/frontend/ui + RelPath string // Relative path from source: _team/frontend/ui + FlatName string // Flat name for target: _team__frontend__ui + IsInRepo bool // Whether this skill is inside a tracked repo (_-prefixed directory) + RepoRelPath string // Tracked repo root relative to source (_team, or org/_team via --into); set when IsInRepo + LogicalID string // Repository + full prefix/suffix identity for recognized agent variants + VariantAgent string // Canonical agent from a tracked skills// layout + variantRouting bool // Targets were inferred from VariantAgent rather than explicitly declared + Targets []string // From SKILL.md frontmatter; nil = all targets + DescChars int // Rune count of name + description (populated when collectContext) + BodyChars int // Rune count of body after frontmatter (populated when collectContext) + DescTokens int // Estimated tokens of name + description (populated when collectContext) + BodyTokens int // Estimated tokens of body (populated when collectContext) + Description string // Frontmatter description text (populated when collectContext) + LintIssues []LintIssue // Lint issues (populated when collectContext) + Disabled bool // Whether this skill is ignored by .skillignore + Local bool // Found in a target folder rather than the source; see TargetSkills } // isSkillIgnored checks whether a skill inside a tracked repo should be @@ -747,15 +750,17 @@ type PruneResult struct { // PruneOptions holds parameters for PruneOrphanLinks / PruneOrphanCopies. type PruneOptions struct { - TargetPath string - SourcePath string - Skills []DiscoveredSkill // pre-discovered; if nil, will be discovered from SourcePath - Include []string - Exclude []string - TargetNaming string - TargetName string - DryRun bool - Force bool + SharedTargets []config.SkillTargetIdentity + Agent string + TargetPath string + SourcePath string + Skills []DiscoveredSkill // pre-discovered; if nil, will be discovered from SourcePath + Include []string + Exclude []string + TargetNaming string + TargetName string + DryRun bool + Force bool // ManagedOnly removes only entries that are provably skillshare's: broken // links into the source and manifest-tracked links and directories. The name heuristic and // broken-external-link cleanup are skipped. For directories that are not a @@ -807,10 +812,12 @@ func PruneOrphanLinksWithSkills(opts PruneOptions) (*PruneResult, error) { manifestChanged := false resolution, err := ResolveTargetSkillsForTarget(targetName, config.ResourceTargetConfig{ - Path: targetPath, - TargetNaming: targetNaming, - Include: include, - Exclude: exclude, + SharedTargets: opts.SharedTargets, + Agent: opts.Agent, + Path: targetPath, + TargetNaming: targetNaming, + Include: include, + Exclude: exclude, }, allSourceSkills) if err != nil { return nil, err diff --git a/internal/sync/target_naming.go b/internal/sync/target_naming.go index d038e74cf..c9d4743af 100644 --- a/internal/sync/target_naming.go +++ b/internal/sync/target_naming.go @@ -30,11 +30,14 @@ type ResolvedTargetSkill struct { // target after include/exclude filters, target filters, standard validation, // and collision handling are applied. type TargetSkillResolution struct { - Naming string - Skills []ResolvedTargetSkill - Warnings []string - Collisions []NameCollision - UnmatchedIncludes []UnmatchedInclude + Naming string + Skills []ResolvedTargetSkill + Warnings []string + SelectionWarnings []string // Ambiguity diagnostics, separate from naming validation + Collisions []NameCollision + UnmatchedIncludes []UnmatchedInclude + SkippedCount int // Physical candidates rejected by selection, validation, or collisions + NamingSkippedCount int // Subset rejected by naming validation } // UnmatchedIncludeWarnings renders one diagnostic per include pattern that @@ -67,14 +70,17 @@ func (u UnmatchedInclude) Warning() string { // ResolveTargetSkillsForTarget applies a target's filters and target_naming // policy to discovered skills and returns the effective target-visible skills. func ResolveTargetSkillsForTarget(targetName string, sc config.ResourceTargetConfig, allSkills []DiscoveredSkill) (*TargetSkillResolution, error) { - filtered, err := SelectTargetSkills(allSkills, targetName, sc) + selection, err := selectTargetSkills(allSkills, targetName, sc) if err != nil { return nil, fmt.Errorf("failed to apply filters for target %s: %w", targetName, err) } + filtered, warnings := selection.Skills, selection.Warnings naming := config.EffectiveTargetNaming(sc.TargetNaming) result := &TargetSkillResolution{ Naming: naming, + SelectionWarnings: warnings, + SkippedCount: len(warnings), UnmatchedIncludes: FindUnmatchedIncludes(sc.Include, allSkills), } @@ -160,6 +166,8 @@ func ResolveTargetSkillsForTarget(targetName string, sc config.ResourceTargetCon result.Skills = append(result.Skills, candidate) } + result.NamingSkippedCount = len(result.Warnings) + result.SkippedCount += len(filtered) - len(result.Skills) return result, nil } @@ -210,8 +218,9 @@ const maxListed = 5 // skills named apart from their folder. It names only the first few of each, so // a source with thousands of invalid names does not flood the output. func printResolutionSummary(r *TargetSkillResolution) { - if n := len(r.Warnings); n > 0 { - printListed(fmt.Sprintf("%d skill(s) skipped (naming validation)", n), r.Warnings) + warnings := append(append([]string{}, r.Warnings...), r.SelectionWarnings...) + if n := len(warnings); n > 0 { + printListed(fmt.Sprintf("%d skill(s) skipped (selection or naming)", n), warnings) } if n := len(r.Collisions); n > 0 { fmt.Fprintf(DiagOutput, " %d name collision(s) excluded\n", n) diff --git a/internal/sync/variants.go b/internal/sync/variants.go new file mode 100644 index 000000000..bd6f3c9e9 --- /dev/null +++ b/internal/sync/variants.go @@ -0,0 +1,169 @@ +package sync + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "skillshare/internal/config" + "skillshare/internal/sourcewalk" +) + +// confirmSkillVariants requires a matching suffix under a second canonical +// agent. Check the source tree so ignoring one peer does not turn the remaining +// agent's instructions into a shared skill. +func confirmSkillVariants(skills []DiscoveredSkill, source string) { + confirmed := make(map[string]bool) + checked := make(map[string]bool) + for i := range skills { + sk := &skills[i] + if sk.LogicalID == "" { + continue + } + parts := strings.Split(sk.LogicalID, "\x00") + agentRoot := filepath.Join(source, filepath.FromSlash(strings.TrimSuffix(sk.RelPath, "/"+parts[2]))) + parentIsSkill := hasVariantParentSkill(agentRoot) + if !parentIsSkill && !checked[sk.LogicalID] { + checked[sk.LogicalID] = true + root := filepath.Join(source, parts[0], filepath.FromSlash(parts[1])) + agents, _ := sourcewalk.ReadDir(root, sourcewalk.Options{}) + for _, entry := range agents { + if !entry.IsDir() || hasVariantParentSkill(filepath.Join(root, entry.Name())) { + continue + } + agent := config.CanonicalTargetName(entry.Name()) + if agent == "" || agent == sk.VariantAgent { + continue + } + if info, err := os.Stat(filepath.Join(root, entry.Name(), filepath.FromSlash(parts[2]), "SKILL.md")); err == nil && !info.IsDir() { + confirmed[sk.LogicalID] = true + break + } + } + } + if parentIsSkill || !confirmed[sk.LogicalID] { + sk.LogicalID, sk.VariantAgent = "", "" + if sk.variantRouting { + sk.Targets = inferSkillTargetsFromRelPath(sk.RelPath) + sk.variantRouting = false + } + } + } +} + +// Agent-named skills own their nested skills; they are not variant containers. +func hasVariantParentSkill(dir string) bool { + info, err := os.Stat(filepath.Join(dir, "SKILL.md")) + return err == nil && !info.IsDir() +} + +// skillVariant recognizes only repository-relative skills//. +// The outer recognized component owns the complete suffix, including nested skills, +// unless the agent directory is itself a skill (checked by confirmSkillVariants). +func skillVariant(relPath, repo string) (id, agent string) { + if repo == "" { + return "", "" + } + parts := strings.Split(strings.TrimPrefix(relPath, repo+"/"), "/") + for i := 0; i+2 < len(parts); i++ { + if parts[i] != "skills" { + continue + } + if agent = config.CanonicalTargetName(parts[i+1]); agent != "" { + return repo + "\x00" + strings.Join(parts[:i+1], "/") + "\x00" + strings.Join(parts[i+2:], "/"), agent + } + } + return "", "" +} + +// UsesVariantRouting reports whether agent routing was inferred from the layout. +// Explicit frontmatter targets and source-local overrides retain their own policy. +func (s DiscoveredSkill) UsesVariantRouting() bool { return s.variantRouting } + +// SkillCounts distinguishes enabled logical skills from physical source entries. +type SkillCounts struct { + Skills int + Variants int +} + +// CountSkills summarizes enabled source inventory without dropping physical entries. +func CountSkills(skills []DiscoveredSkill) SkillCounts { + counts, _ := CountSkillsByRepo(skills) + return counts +} + +// CountSkillsByRepo summarizes source and repository inventory using discovery identity. +func CountSkillsByRepo(skills []DiscoveredSkill) (SkillCounts, map[string]SkillCounts) { + var total SkillCounts + repos := make(map[string]SkillCounts) + seen := make(map[string]bool) + for _, skill := range skills { + if skill.Disabled { + continue + } + id := skill.LogicalID + if id == "" { + id = skill.RelPath + } + r := repos[skill.RepoRelPath] + total.Variants++ + r.Variants++ + if !seen[id] { + total.Skills++ + r.Skills++ + seen[id] = true + } + repos[skill.RepoRelPath] = r + } + return total, repos +} + +func targetAgent(name string, sc config.ResourceTargetConfig) string { + if sc.Agent != "" { + name = sc.Agent + } + return config.CanonicalTargetName(name) +} + +// variantRemovalWarning explains the upgrade effect only for removed entries +// whose known physical/naming IDs belong to automatically excluded variants. +func variantRemovalWarning(name string, sc config.ResourceTargetConfig, skills []DiscoveredSkill, pruned []string, dryRun bool) string { + if len(pruned) == 0 { + return "" + } + removed := make(map[string]bool, len(pruned)) + for _, entry := range pruned { + removed[entry] = true + } + mismatches := make(map[string]bool) + selection, err := selectTargetSkills(skills, name, sc) + if err != nil { + return "" + } + selected := make(map[string]bool, len(selection.Skills)) + for _, skill := range selection.Skills { + selected[skill.RelPath] = true + } + for _, skill := range skills { + if !skill.variantRouting || selected[skill.RelPath] || skill.Disabled { + continue + } + if allowed, _ := ShouldSyncFlatName(skill.FlatName, sc.Include, sc.Exclude); !allowed { + continue + } + for _, candidate := range targetNameCandidates(skill) { + if removed[candidate.name] { + mismatches[candidate.name] = true + } + } + } + if len(mismatches) == 0 { + return "" + } + action := "removed" + if dryRun { + action = "would remove" + } + return fmt.Sprintf("%s: automatic agent routing %s %d managed variant entries because their agent does not match this folder's targets or their selection is ambiguous; use a source-local target override to select the desired variant (an empty override means all targets)", name, action, len(mismatches)) +} diff --git a/internal/sync/variants_test.go b/internal/sync/variants_test.go new file mode 100644 index 000000000..7fa614a1c --- /dev/null +++ b/internal/sync/variants_test.go @@ -0,0 +1,392 @@ +package sync + +import ( + "bytes" + "context" + "os" + "path/filepath" + "strings" + "testing" + + "skillshare/internal/config" + "skillshare/internal/install" +) + +func TestTrackedAgentCategoriesRemainOrdinarySkills(t *testing.T) { + src := t.TempDir() + for _, category := range []string{"agents", "continue", "pi", "warp", "factory", "copilot"} { + writeSkillMD(t, filepath.Join(src, "_repo/skills", category, category+"-planner"), "# Instructions") + } + for _, lite := range []bool{false, true} { + var skills []DiscoveredSkill + var err error + if lite { + skills, _, err = DiscoverSourceSkillsLite(src) + } else { + skills, err = DiscoverSourceSkills(src) + } + if err != nil { + t.Fatal(err) + } + for _, sk := range skills { + if sk.LogicalID != "" || sk.VariantAgent != "" { + t.Fatalf("category inferred as variant: %+v", sk) + } + } + if !lite { + selected, err := SelectTargetSkills(skills, "claude", config.ResourceTargetConfig{}) + if err != nil || len(selected) != 6 { + t.Fatalf("category selection = %d, %v", len(selected), err) + } + } + } +} + +func TestTrackedVariantsSharedFolder(t *testing.T) { + for _, mode := range []string{"merge", "copy"} { + t.Run(mode, func(t *testing.T) { + src, dest := t.TempDir(), t.TempDir() + for _, agent := range []string{"claude", "codex"} { + writeSkillMD(t, filepath.Join(src, "_repo/skills", agent, "fix"), "# Instructions for "+agent) + } + skills, err := DiscoverSourceSkills(src) + if err != nil { + t.Fatal(err) + } + targets := map[string]config.TargetConfig{ + "codex": {Path: dest}, "universal": {Path: dest}, + } + cfg := &config.Config{Source: src, Mode: mode, Targets: targets} + for i := 0; i < 2; i++ { + result, err := ExecuteTargets(context.Background(), cfg, targets, ExecuteOptions{Kinds: []string{"skill"}, Discovery: TargetDiscovery{Skills: skills}}) + if err != nil || len(result.Failed) != 0 { + t.Fatalf("sync: %+v, %v", result, err) + } + for _, r := range result.Results { + if len(r.Pruned) != 0 { + t.Fatalf("shared variant pruned: %+v", r) + } + } + got, err := os.ReadFile(filepath.Join(dest, "_repo__skills__codex__fix", "SKILL.md")) + if err != nil || string(got) != "# Instructions for codex" { + t.Fatalf("Codex lost variant: %q, %v", got, err) + } + } + }) + } +} + +func TestTrackedVariantsRouteAndPreserveBytes(t *testing.T) { + src := t.TempDir() + for _, agent := range []string{"claude-code", "codex"} { + for _, name := range []string{"fix", "review/fix"} { + writeSkillMD(t, filepath.Join(src, "_repo/internal/skills", agent, name), "---\nname: fix\ndescription: Review changes\n---\nInstructions for "+agent+"\n") + } + } + skills, err := DiscoverSourceSkills(src) + if err != nil { + t.Fatal(err) + } + if len(skills) != 4 { + t.Fatalf("physical entries = %d, want 4", len(skills)) + } + for _, tc := range []struct { + name, agent string + want int + }{ + {"claude", "", 2}, {"claude-code", "", 2}, {"codex", "", 2}, + {"codex-work", "codex", 2}, {"universal", "", 0}, {"cursor", "", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + for _, mode := range []string{"merge", "copy"} { + target := config.TargetConfig{Agent: tc.agent, Path: filepath.Join(t.TempDir(), "skills"), Mode: mode} + selected, err := SelectTargetSkills(skills, tc.name, target.SkillsConfig()) + if err != nil || len(selected) != tc.want { + t.Fatalf("selected = %d, want %d: %v", len(selected), tc.want, err) + } + run := SyncSkillTarget(SkillTarget{Name: tc.name, Target: target, Mode: mode}, skills, SkillRunOptions{Source: src}) + if run.Err != nil || len(run.Linked) != tc.want { + t.Fatalf("%s sync = %+v", mode, run) + } + for _, sk := range selected { + want, err := os.ReadFile(filepath.Join(sk.SourcePath, "SKILL.md")) + if err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(filepath.Join(target.Path, sk.FlatName, "SKILL.md")) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatalf("%s changed bytes for %s", mode, sk.RelPath) + } + } + } + }) + } +} + +func TestTrackedVariantRoutingPrecedence(t *testing.T) { + src := t.TempDir() + paths := []string{"_repo/claude/skills/codex/inferred", "_repo/skills/codex/explicit", "_repo/skills/codex/all", "_repo/skills/codex/override"} + for _, path := range paths { + // A second canonical agent distinguishes this family from a category. + peer := strings.Replace(path, "/skills/codex/", "/skills/claude/", 1) + writeSkillMD(t, filepath.Join(src, peer), "---\nmetadata:\n targets: [unused]\n---\n# Peer") + content := "# Instructions" + if filepath.Base(path) == "explicit" || filepath.Base(path) == "override" { + content = "---\nmetadata:\n targets: [custom]\n---\n# Instructions" + } + writeSkillMD(t, filepath.Join(src, path), content) + } + store := install.NewMetadataStore() + store.SetTargetOverride(paths[2], nil) + store.SetTargetOverride(paths[3], []string{"claude"}) + if err := store.Save(src); err != nil { + t.Fatal(err) + } + skills, err := DiscoverSourceSkills(src) + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + want []string + }{ + {"codex", []string{paths[0], paths[2]}}, {"universal", []string{paths[2]}}, + {"custom", []string{paths[1], paths[2]}}, {"claude", []string{paths[2], paths[3]}}, + } { + got, err := SelectTargetSkills(skills, tc.name, config.ResourceTargetConfig{}) + if err != nil { + t.Fatal(err) + } + if len(got) != len(tc.want) { + t.Errorf("%s paths = %v, want %v", tc.name, got, tc.want) + continue + } + for _, sk := range got { + found := false + for _, want := range tc.want { + found = found || sk.RelPath == want + } + if !found { + t.Errorf("%s unexpectedly receives %s", tc.name, sk.RelPath) + } + } + } +} + +func TestTrackedVariantAliasAmbiguity(t *testing.T) { + src := t.TempDir() + for _, agent := range []string{"claude", "claude-code", "codex"} { + writeSkillMD(t, filepath.Join(src, "_repo/skills", agent, "fix"), "# Instructions") + } + skills, err := DiscoverSourceSkills(src) + if err != nil { + t.Fatal(err) + } + got, err := SelectTargetSkills(skills, "claude", config.ResourceTargetConfig{}) + if err != nil || len(got) != 0 { + t.Fatalf("ambiguous Claude variants selected = %v: %v", got, err) + } + resolution, err := ResolveTargetSkillsForTarget("claude", config.ResourceTargetConfig{}, skills) + if err != nil || len(resolution.SelectionWarnings) == 0 || len(resolution.Warnings) != 0 || resolution.NamingSkippedCount != 0 { + t.Fatalf("ambiguous variants need a diagnostic: %+v, %v", resolution, err) + } + got, err = SelectTargetSkills(skills, "claude", config.ResourceTargetConfig{Include: []string{"_repo__skills__claude__fix"}}) + if err != nil || len(got) != 1 { + t.Fatalf("explicit include should resolve ambiguity: %v, %v", got, err) + } +} + +func TestTrackedVariantCountsKeepRepositoryPrefixAndSuffix(t *testing.T) { + src := t.TempDir() + for _, repo := range []string{"_one", "org/_two"} { + if err := os.MkdirAll(filepath.Join(src, repo, ".git"), 0755); err != nil { + t.Fatal(err) + } + for _, prefix := range []string{"internal/skills", "other/skills"} { + for _, suffix := range []string{"fix", "review/skills/codex/fix"} { + for _, agent := range []string{"claude", "codex"} { + writeSkillMD(t, filepath.Join(src, repo, prefix, agent, suffix), "# Instructions") + } + } + } + } + // Unknown agent layouts and ordinary skills remain independent physical skills. + for _, path := range []string{"_one/skills/unknown/fix", "_one/skills/shared/fix", "skills/claude/fix", "skills/codex/fix"} { + writeSkillMD(t, filepath.Join(src, path), "# Instructions") + } + full, err := DiscoverSourceSkills(src) + if err != nil { + t.Fatal(err) + } + lite, _, err := DiscoverSourceSkillsLite(src) + if err != nil { + t.Fatal(err) + } + for _, skills := range [][]DiscoveredSkill{full, lite} { + counts, repos := CountSkillsByRepo(skills) + if counts.Skills != 12 || counts.Variants != 20 { + t.Errorf("source counts = %+v, want 12 skills/20 variants", counts) + } + if repos["_one"].Skills != 6 || repos["org/_two"].Skills != 4 { + t.Errorf("repo counts = %+v", repos) + } + } +} + +func TestTrackedVariantIgnoresAndPhysicalContext(t *testing.T) { + src := t.TempDir() + for _, path := range []string{"_repo/skills/claude/fix", "_repo/skills/codex/fix", "_repo/skills/claude/hidden", "_repo/skills/codex/hidden"} { + writeSkillMD(t, filepath.Join(src, path), "---\nname: fix\ndescription: Review changes\n---\n# Instructions") + } + if err := os.WriteFile(filepath.Join(src, ".skillignore"), []byte("**/hidden\n_repo/skills/claude/fix\n"), 0644); err != nil { + t.Fatal(err) + } + skills, err := DiscoverSourceSkillsForAnalyze(src) + if err != nil { + t.Fatal(err) + } + counts := CountSkills(skills) + if counts.Skills != 1 || counts.Variants != 1 { + t.Fatalf("active counts = %+v", counts) + } + selected, err := SelectTargetSkills(skills, "claude", config.ResourceTargetConfig{Include: []string{"*"}}) + if err != nil || len(selected) != 0 { + t.Fatalf("ignored Claude gets substitute: %+v, %v", selected, err) + } + for _, mode := range []string{"merge", "symlink"} { + target := config.TargetConfig{Mode: mode} + loaded, err := TargetSkills("codex", target, mode, src, skills) + if err != nil { + t.Fatal(err) + } + want := 1 + if mode == "symlink" { + want = 4 + } + if len(loaded) != want { + t.Fatalf("%s physical context entries = %d, want %d", mode, len(loaded), want) + } + for _, sk := range loaded { + if sk.BodyChars == 0 { + t.Fatalf("missing physical context for %s", sk.RelPath) + } + } + } +} + +func TestTrackedVariantUpgradeDisclosesPrunedEntries(t *testing.T) { + for _, mode := range []string{"merge", "copy"} { + t.Run(mode, func(t *testing.T) { + src := t.TempDir() + store := install.NewMetadataStore() + for _, agent := range []string{"claude", "codex"} { + rel := "_repo/skills/" + agent + "/fix" + writeSkillMD(t, filepath.Join(src, rel), "# Instructions for "+agent) + store.SetTargetOverride(rel, nil) + } + if err := store.Save(src); err != nil { + t.Fatal(err) + } + // Empty overrides reproduce the unrestricted selection of pre-upgrade discovery. + legacy, err := DiscoverSourceSkills(src) + if err != nil { + t.Fatal(err) + } + target := SkillTarget{Name: "universal", Target: config.TargetConfig{Path: t.TempDir(), Mode: mode}, Mode: mode} + before := SyncSkillTarget(target, legacy, SkillRunOptions{Source: src}) + if before.Err != nil || len(before.Linked) != 2 { + t.Fatalf("unrestricted sync: %+v", before) + } + store.RemoveTargetOverrides("_repo") + if err := store.Save(src); err != nil { + t.Fatal(err) + } + inferred, err := DiscoverSourceSkills(src) + if err != nil { + t.Fatal(err) + } + for _, dryRun := range []bool{true, false} { + after := SyncSkillTarget(target, inferred, SkillRunOptions{Source: src, DryRun: dryRun}) + warnings := strings.Join(after.Warnings, "\n") + if after.Err != nil || len(after.Pruned) != 2 { + t.Fatalf("upgrade prune: %+v", after) + } + if !strings.Contains(warnings, "automatic agent routing") || !strings.Contains(warnings, "target override") { + t.Fatalf("upgrade removals need routing and recovery explanation: %+v", after) + } + } + for _, sk := range inferred { + if _, err := os.Stat(filepath.Join(sk.SourcePath, "SKILL.md")); err != nil { + t.Fatal(err) + } + if _, err := os.Lstat(filepath.Join(target.Target.Path, sk.FlatName)); !os.IsNotExist(err) { + t.Fatalf("mismatched target entry survived: %s, %v", sk.FlatName, err) + } + } + store.SetTargetOverride("_repo/skills/codex/fix", []string{"universal"}) + if err := store.Save(src); err != nil { + t.Fatal(err) + } + restored, err := DiscoverSourceSkills(src) + if err != nil { + t.Fatal(err) + } + recovery := SyncSkillTarget(target, restored, SkillRunOptions{Source: src}) + if recovery.Err != nil || len(recovery.Linked) != 1 || len(recovery.Pruned) != 0 { + t.Fatalf("override recovery: %+v", recovery) + } + }) + } +} + +func TestTrackedVariantAmbiguousPruneExplainsRemoval(t *testing.T) { + for _, mode := range []string{"merge", "copy"} { + t.Run(mode, func(t *testing.T) { + src := t.TempDir() + for _, agent := range []string{"claude", "codex"} { + writeSkillMD(t, filepath.Join(src, "_repo/skills", agent, "fix"), "# Instructions") + } + target := SkillTarget{Name: "claude", Target: config.TargetConfig{Path: t.TempDir()}, Mode: mode} + skills, err := DiscoverSourceSkills(src) + if err != nil { + t.Fatal(err) + } + if result := SyncSkillTarget(target, skills, SkillRunOptions{Source: src}); result.Err != nil || len(result.Linked) != 1 { + t.Fatalf("initial sync: %+v", result) + } + writeSkillMD(t, filepath.Join(src, "_repo/skills/claude-code/fix"), "# Alias makes selection ambiguous") + skills, err = DiscoverSourceSkills(src) + if err != nil { + t.Fatal(err) + } + result := SyncSkillTarget(target, skills, SkillRunOptions{Source: src}) + if result.Err != nil || len(result.Pruned) != 1 || !strings.Contains(strings.Join(result.Warnings, "\n"), "ambiguous") { + t.Fatalf("silent ambiguous removal: %+v", result) + } + }) + } +} + +func TestNestedAgentNamedSkillsRemainOrdinary(t *testing.T) { + src := t.TempDir() + for _, agent := range []string{"codex", "gemini"} { + writeSkillMD(t, filepath.Join(src, "_repo/skills", agent), "# Parent skill") + writeSkillMD(t, filepath.Join(src, "_repo/skills", agent, "review"), "# Nested skill") + } + skills, err := DiscoverSourceSkills(src) + if err != nil { + t.Fatal(err) + } + for _, skill := range skills { + if skill.LogicalID != "" { + t.Fatalf("ordinary nested skill inferred as variant: %+v", skill) + } + } + selected, err := SelectTargetSkills(skills, "claude", config.ResourceTargetConfig{}) + if err != nil || len(selected) != 4 { + t.Fatalf("selected = %v, %v", selected, err) + } +} diff --git a/proposals/648-agent-skill-variants.md b/proposals/648-agent-skill-variants.md new file mode 100644 index 000000000..3a76df606 --- /dev/null +++ b/proposals/648-agent-skill-variants.md @@ -0,0 +1,179 @@ +# Agent-specific variants of a tracked skill + +## Problem + +Issue: [#648](https://github.com/runkids/skillshare/issues/648). + +A tracked repository is a Git repository installed under Skillshare's source directory. +Some producers ship intentionally different files for the same skill, one per agent: + +```text +_roborev/internal/skills/claude/roborev-fix/SKILL.md +_roborev/internal/skills/codex/roborev-fix/SKILL.md +``` + +At Skillshare revision `e64fac67`, these become two discovered skills with no inferred +target restriction. With default flat target naming, status reports `_roborev: 2 skills`; +merge sync sends both files to both Claude and Codex. This was reproduced with actual producer files from +[roborev revision 626dea47](https://github.com/kenn-io/roborev/tree/626dea478c5d5ab5c1d25845ce1474120f9c0f7b/internal/skills). + +The Claude file uses `/roborev-fix` and `dangerouslyDisableSandbox`; the Codex file +uses `$roborev-fix` and `sandbox_permissions`. Choosing one file globally or merging +their contents would discard instructions needed by the other agent. + +Per-target include/exclude filters and source-local target overrides already route +the copies correctly. `.skillignore` can hide unused variants. These controls +require consumers to describe the producer's layout and still count copies separately. + +## Implemented behavior + +This PR implements logical counting and exact-agent routing. Sparse checkout remains deferred. + +Represent one logical skill with several physical variants inside a tracked repository. +Keep every variant's source path, files, and bytes intact; select existing files +for each target without format conversion or synthesized frontmatter. + +### Identity and detection + +For a recognized layout, identify a logical skill by this tuple: + +```text +(tracked repository, shared parent before agent component, complete suffix after agent component) +(_roborev, internal/skills, roborev-fix) +``` + +Only the agent component differs between variants. Preserve the entire suffix: +`internal/skills/{claude,codex}/review/roborev-fix` is a different logical skill +from `internal/skills/{claude,codex}/roborev-fix`. +Different repositories or different shared parents never merge, even when their +`SKILL.md` names or final directory names are identical. Repositories nested with +`--into` retain their actual repository boundary. + +Recognition is automatic for repository-relative `skills//` +paths only when the same complete suffix occurs under at least two distinct canonical +agents beneath the same repository-relative `skills/` parent. Aliases of one agent +do not provide that second identity. A lone `skills/agents/planner` or +`skills/continue/helper` category remains ordinary, even when its name is a registry +alias. The outer recognized component owns the complete suffix, unless the agent-named +directory is itself a skill; its nested skills remain ordinary skills. Ordinary skills +and unknown layouts keep existing discovery behavior. + +### Routing and precedence + +Extend the existing shared discovery and target-selection paths rather than adding +separate variant walkers or per-command routing rules: + +- Discovery retains physical entries and attaches logical identity and agent identity. +- Resolve an agent through the configuration's target registry and canonical aliases. + Account targets such as `codex-work` use their configured `Agent: codex` identity. + Do not maintain another tool-name list or infer identity from a target's folder. +- Automatic routing selects the exact agent variant: Claude receives Claude's file, + Codex receives Codex's file, and an unrelated target receives neither by inference. + Compatible targets sharing a destination folder use the union of their configured + agent identities for automatic selection. Thus Codex and `universal` sharing + `~/.agents/skills` both select the Codex variants and neither prunes them. This + shared folder exposes the union to every reader; it does not isolate agents. + Existing overlap/conflict diagnostics still reject incompatible settings. +- Routing precedence is source-local target override > explicit frontmatter targets > + recognized variant-agent inference > existing `inferSkillTargetsFromRelPath`. + Generic host-style path inference cannot override a recognized variant's agent. + An empty source-local override still means all targets. Existing explicit target + matching stays compatible. +- `.skillignore`, disabled state, and per-target include/exclude filters still apply + to physical entries. An include cannot resurrect an ignored file; an excluded + matching variant does not cause selection of another agent's variant. +- Missing matches, unknown agent directories, and ambiguous matches never cause a + sibling or lexicographically first variant to be chosen. Report ambiguous + variants in naming/sync diagnostics; do not invent a fallback to an agent named + `shared` or `default`. + Unrecognized paths retain ordinary discovery behavior rather than guessed routing. + +Use `SelectTargetSkills` and existing target naming/resolution as the common selection +boundary for CLI/server sync, previews, status, diff, doctor, analyze, `skill move`, +and target-scoped skillserve catalogs. Selection preserves the physical entries; +missing matches select nothing and ambiguous automatic matches are skipped with +a diagnostic. +Repository grouping belongs in discovery metadata, not in a status-only deduplicator. + +### Counts, compatibility, and sync modes + +Source and repository summaries distinguish logical skills from physical variants: +two logical skills with Claude and Codex copies are `2 skills, 4 variants`. +Sync results continue to count actual links, copies, updates, skips, and errors per +target; grouping must not reduce those totals or hide a failed variant operation. +Physical operation/catalog IDs remain stable. Grouping alone must not reduce analyze +or context-cost totals, which measure the physical files actually exposed to a target. +Ignored variants follow existing enabled/ignored reporting rather than inflating +the active logical count. A group with no enabled variant contributes no active skill. + +Retain physical relative paths and flat names for existing filters, overrides, +uninstall operations, and destination naming. Do not silently rename installed +entries or broaden existing filters. Decide any future logical-name filter syntax +and migration separately, with compatibility tests. + +In merge/copy mode, a target with no matching agent identity, including a universal-only +configuration, receives no agent-specific variant automatically. An explicit per-variant +target override can select the desired copy; an empty override preserves that variant's +old all-target behavior. Recognition is automatic on upgrade. Sync removes old managed +entries whose inferred agent does not match the target, reports the automatic-routing +reason through CLI/server warnings (including dry-run), and names target overrides as +the recovery option. Source files remain intact; no opt-in configuration is added. + +Per-skill routing applies to merge and copy modes. Full-directory symlink mode +exposes the complete source tree and cannot enforce variant selection or ignores; +status and doctor must explain that limitation and recommend merge or copy where +selective exposure is needed. Do not claim logical counts describe runtime exposure. +No new content rewrite is introduced. Existing prefixed copy naming may still +rewrite the copied `name:` field; source bytes and agent-specific instructions stay intact. + +### Acceptance cases + +Every case uses automatic recognition for the bounded tracked-source layout. + +| Case | Expected result | +|---|---| +| One name, Claude/Codex files | One logical skill, two variants; exact file routed to each agent | +| Two names, Claude/Codex files | Two logical skills, four variants; two operations per target | +| Different contents | Source bytes unchanged; merge/flat or standard copy preserves selected file bytes | +| Prefixed copy naming | Only established naming transformation; agent-specific instructions preserved | +| Same basename elsewhere | Distinct repositories, parents, and full nested suffixes remain separate | +| Repository installed with `--into` | Actual tracked root scopes grouping and existing override keys | +| `--into codex/skills`: `_repo/internal/skills/claude/fix` | Recognized Claude variant wins over outer Codex host inference unless explicitly overridden | +| Single agent-like category or aliases of one agent only | Ordinary skills; no inferred variant routing or logical grouping | +| Root/repository ignores and disabled variant | Existing precedence; no ignored variant selected or substituted | +| Per-target includes/excludes | Legacy physical flat-name patterns retain their selection semantics | +| Frontmatter and source-local overrides | Explicit routing wins; empty override retains all-target meaning | +| Canonical alias and account target | Same exact agent variant selected using registry/`Agent` identity | +| Shared target directory | Compatible targets select the union of agent identities without pruning one another; incompatible settings retain overlap diagnostics | +| Universal-only or unmatched target, merge/copy | No automatic variant; explicit target override selects a copy, empty override preserves all-target behavior | +| Missing, unknown, shared, or ambiguous variant | No guessed substitute; applicable diagnostic or ordinary discovery | +| CLI/server/status/diff/doctor/analyze/`skill move`/target-scoped skillserve | Same selected physical entries and reasons; physical IDs and context-cost totals stay accurate | +| Merge/copy failure | Actual work/error counts remain independent of logical source counts | +| Full-directory symlink | Limitation visible; no promise that variant routing restricts exposed files | + +## Alternatives Considered + +- Keep manual filters/overrides: useful today, but neither logical grouping nor automatic routing. +- Deduplicate by basename or content: merges unrelated skills or misses intentionally different files. +- Convert one canonical file for every agent: a separate feature; the producer already supplies variants. +- Use sparse checkout: an optional later optimization, unnecessary for correct identity and routing. + +## Scope + +- [ ] Small (1-3 files, < 200 lines) +- [ ] Medium (3-10 files, 200-500 lines) +- [x] Large (10+ files, 500+ lines): provisional implementation and tests estimate. + +The implementation extends shared discovery and selection, source/repository count +outputs, tests, and public docs. Status JSON adds `variant_count`, overview JSON adds +`variantCount`, and targets JSON adds `sourceVariantCount`; existing skill counts in +these source summaries become logical counts. Resource rows and operation/context +totals remain physical. No new persisted configuration or schema version is added. +Sparse checkout, content conversion, and a new naming/filter migration are outside this proposal's first implementation. + +## Deferred + +Sparse checkout, producer-declared shared/default fallbacks, and a grouped resource-list +UI remain outside this implementation. Physical resource rows retain their paths so +install/uninstall, filters, and override keys remain compatible. Existing empty +frontmatter list behavior is preserved; source-local empty overrides mean all targets. diff --git a/skills/skillshare/SKILL.md b/skills/skillshare/SKILL.md index 571488beb..50a4fffc4 100644 --- a/skills/skillshare/SKILL.md +++ b/skills/skillshare/SKILL.md @@ -25,6 +25,14 @@ Check `skillshare --help` if the installed version differs from these when location matters instead of relying on auto-detection. - Skills are directories containing `SKILL.md`; agents are single Markdown files. Source paths can be customized. Use the configured sources instead of assuming defaults. +- Tracked `skills///SKILL.md` copies form one logical skill + per repository/prefix/suffix. Merge/copy select the exact agent variant (including + aliases and account `agent:` identity). Recognition requires the same suffix under + two distinct canonical agents. Compatible targets sharing a folder select the + union of their agent identities; a universal-only target does not infer an agent. + Status counts logical skills and physical variants; lists and sync operations retain + physical names. Explicit targets/overrides and physical filters still apply. + Whole-directory symlink mode exposes all variants. See [sync.md](references/sync.md). - Use native agents targets for agents. Use extras for arbitrary file resources or when flattening/content transformation is required; `extension:` works only on extras targets. - Shared memory notes live in the `memory` extra. Use `extras memory` to manage Markdown diff --git a/skills/skillshare/references/sync.md b/skills/skillshare/references/sync.md index d62e18265..d2820fef9 100644 --- a/skills/skillshare/references/sync.md +++ b/skills/skillshare/references/sync.md @@ -36,6 +36,24 @@ Sync runs every target. A target whose sync fails, or whose own settings are inv - `copy`: real-file copies with `.skillshare-manifest.json` tracking managed entries. - `symlink`: whole target directory symlinked to source. +Tracked repositories with `skills///SKILL.md` use exact +agent routing in merge/copy mode only when the same complete suffix occurs beneath +at least two distinct canonical agents under the same `skills/` parent. A lone +agent-like category remains ordinary. Canonical aliases and account `agent:` +identities match. Compatible targets sharing a skills folder select the union of +their agent identities, preserving each other's managed variants; incompatible +settings retain overlap/conflict diagnostics. Source-local target overrides beat nonempty +frontmatter targets, then variant inference, then old host-path inference. An empty +override sends that physical variant to all targets. Ignores and filters keep using +physical relative/flat names, and ambiguous aliases need an explicit selection. +Agent-named folders that contain their own SKILL.md remain ordinary skills, including their nested skills. +Source/repository status counts logical skills and reports physical variants; +resource rows, sync results, and context cost count actual files. Full-directory +symlink mode exposes all files. No conversion or sparse checkout is performed. +On upgrade, merge/copy removes previously managed variants that do not match the +target's Agent, with an automatic-routing warning (also in dry-run). Restore a +desired copy with a source-local target override; an empty override targets all. + Copy mode note: - `skillshare doctor` duplicate checks ignore manifest-managed copy entries (expected mirrors of source). - Duplicate warnings in copy mode are for true local copies that collide with source skill names. diff --git a/tests/integration/doctor_source_links_test.go b/tests/integration/doctor_source_links_test.go index 046907c4e..c6276dfc3 100644 --- a/tests/integration/doctor_source_links_test.go +++ b/tests/integration/doctor_source_links_test.go @@ -63,7 +63,7 @@ func TestDoctor_UndeclaredSourceLinks(t *testing.T) { out := parseDoctorJSON(t, jsonResult.Stdout) count := 0 for _, check := range out.Checks { - if check.Name == "source" && !strings.Contains(check.Message, "(1 skills)") { + if check.Name == "source" && !strings.Contains(check.Message, "(1 skill)") { t.Errorf("linked skill must remain undiscovered: %+v", check) } if check.Name != "undeclared_source_links" { diff --git a/tests/integration/sync_target_naming_test.go b/tests/integration/sync_target_naming_test.go index bab4ea7c1..cce91f208 100644 --- a/tests/integration/sync_target_naming_test.go +++ b/tests/integration/sync_target_naming_test.go @@ -80,7 +80,7 @@ targets: result := sb.RunCLI("sync") result.AssertSuccess(t) - result.AssertAnyOutputContains(t, "skill(s) skipped (naming validation)") + result.AssertAnyOutputContains(t, "skill(s) skipped (selection or naming)") result.AssertAnyOutputContains(t, "skipped frontend/dev because") if !sb.IsSymlink(filepath.Join(targetPath, "alpha")) { diff --git a/tests/integration/variants_test.go b/tests/integration/variants_test.go new file mode 100644 index 000000000..789f078ad --- /dev/null +++ b/tests/integration/variants_test.go @@ -0,0 +1,223 @@ +//go:build !online + +package integration + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "skillshare/internal/install" + "skillshare/internal/testutil" +) + +func TestVariants_SharedFolderSyncStatusAndDiff(t *testing.T) { + for _, project := range []bool{false, true} { + for _, mode := range []string{"merge", "copy"} { + scope := "global" + if project { + scope = "project" + } + t.Run(scope+"/"+mode, func(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + root, source := sb.Root, sb.SourcePath + dest := filepath.Join(sb.Home, ".agents", "skills") + flag := "-g" + if project { + root = sb.SetupProjectDir("codex", "universal") + source = filepath.Join(root, ".skillshare", "skills") + dest = filepath.Join(root, ".agents", "skills") + flag = "-p" + sb.WriteProjectConfig(root, "targets:\n - name: codex\n mode: "+mode+"\n - name: universal\n mode: "+mode+"\n") + } else { + sb.WriteConfig("source: " + source + "\nmode: " + mode + "\ntargets:\n codex: {}\n universal: {}\n") + } + for _, agent := range []string{"claude", "codex"} { + dir := filepath.Join(source, "_repo/internal/skills", agent, "fix") + if err := os.MkdirAll(dir, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("# Instructions for "+agent), 0644); err != nil { + t.Fatal(err) + } + } + initGitRepo(t, filepath.Join(source, "_repo")) + for i := 0; i < 2; i++ { + sb.RunCLIInDir(root, "sync", flag, "--json").AssertSuccess(t) + got, err := os.ReadFile(filepath.Join(dest, "_repo__internal__skills__codex__fix", "SKILL.md")) + if err != nil || string(got) != "# Instructions for codex" { + t.Fatalf("variant lost after sync %d: %q, %v", i, got, err) + } + } + status := sb.RunCLIInDir(root, "status", flag, "--json") + status.AssertSuccess(t) + var counts struct { + Skills int `json:"skill_count"` + Variants int `json:"variant_count"` + } + if err := json.Unmarshal([]byte(status.Stdout), &counts); err != nil { + t.Fatal(err) + } + if counts.Skills != 1 || counts.Variants != 2 { + t.Fatalf("inventory: %s", status.Stdout) + } + diff := sb.RunCLIInDir(root, "diff", flag, "--json") + diff.AssertSuccess(t) + var preview struct { + Targets []struct { + Synced bool `json:"synced"` + } `json:"targets"` + } + if err := json.Unmarshal([]byte(diff.Stdout), &preview); err != nil { + t.Fatal(err) + } + if len(preview.Targets) != 2 { + t.Fatalf("diff targets: %s", diff.Stdout) + } + for _, target := range preview.Targets { + if !target.Synced { + t.Fatalf("shared folder disagrees with sync: %s", diff.Stdout) + } + } + // A target-only run still respects its configured co-writer. + sb.RunCLIInDir(root, "sync", flag, "--json", "universal").AssertSuccess(t) + if _, err := os.Stat(filepath.Join(dest, "_repo__internal__skills__codex__fix", "SKILL.md")); err != nil { + t.Fatal(err) + } + }) + } + } +} + +func TestVariants_CategoryAndNamingWarningsDoNotCreatePendingDiff(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + sb.CreateNestedSkill("_repo/skills/agents/planner", map[string]string{"SKILL.md": "---\nname: planner\n---\n# Planner"}) + sb.CreateSkill("invalid", map[string]string{"SKILL.md": "---\nname: wrong-name\n---\n# Invalid"}) + target := sb.CreateTarget("claude") + sb.WriteConfig("source: " + sb.SourcePath + "\ntarget_naming: standard\ntargets:\n claude:\n path: " + target + "\n") + sb.RunCLI("sync", "-g").AssertSuccess(t) + if _, err := os.Stat(filepath.Join(target, "planner", "SKILL.md")); err != nil { + t.Fatal(err) + } + result := sb.RunCLI("diff", "-g", "--json") + result.AssertSuccess(t) + var preview struct { + Targets []struct { + Synced bool `json:"synced"` + } `json:"targets"` + } + if err := json.Unmarshal([]byte(result.Stdout), &preview); err != nil { + t.Fatal(err) + } + if len(preview.Targets) != 1 || !preview.Targets[0].Synced { + t.Fatalf("naming warning becomes pending work: %s", result.Stdout) + } +} + +func TestVariants_AccountSyncAndPrune(t *testing.T) { + for _, mode := range []string{"merge", "copy"} { + t.Run(mode, func(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + for _, agent := range []string{"codex", "claude"} { + sb.CreateNestedSkill("_repo/skills/"+agent+"/fix", map[string]string{"SKILL.md": "# " + agent}) + } + dest := filepath.Join(sb.Home, "account", "skills") + config := "source: " + sb.SourcePath + "\nmode: " + mode + "\ntargets:\n codex-work:\n agent: codex\n config_dir: " + filepath.Join(sb.Home, "account") + "\n path: " + dest + "\n" + sb.WriteConfig(config) + for i := 0; i < 2; i++ { + sb.RunCLI("sync", "-g").AssertSuccess(t) + } + selected := filepath.Join(dest, "_repo__skills__codex__fix", "SKILL.md") + if got := sb.ReadFile(selected); got != "# codex" { + t.Fatalf("account bytes = %q", got) + } + if sb.FileExists(filepath.Join(dest, "_repo__skills__claude__fix")) { + t.Fatal("account received other agent") + } + sb.WriteConfig(config + " exclude: ['*codex*']\n") + sb.RunCLI("sync", "-g").AssertSuccess(t) + if sb.FileExists(selected) { + t.Fatal("excluded account variant was not pruned") + } + }) + } +} + +func TestVariants_ProjectAmbiguityAndOverrides(t *testing.T) { + for _, mode := range []string{"merge", "copy"} { + t.Run(mode, func(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + root := sb.SetupProjectDir("claude") + source := filepath.Join(root, ".skillshare", "skills") + cfg := "targets:\n - name: claude\n mode: " + mode + "\n" + sb.WriteProjectConfig(root, cfg) + for _, agent := range []string{"claude", "claude-code", "codex"} { + dir := filepath.Join(source, "_repo", "skills", agent, "fix") + if err := os.MkdirAll(dir, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("# "+agent), 0644); err != nil { + t.Fatal(err) + } + } + dest := filepath.Join(root, ".claude", "skills") + sb.RunCLIInDir(root, "sync", "-p").AssertSuccess(t) + for _, agent := range []string{"claude", "claude-code"} { + if sb.FileExists(filepath.Join(dest, "_repo__skills__"+agent+"__fix")) { + t.Fatal("ambiguous variant synced") + } + } + sb.WriteProjectConfig(root, cfg+" include: ['_repo__skills__claude__fix']\n") + sb.RunCLIInDir(root, "sync", "-p").AssertSuccess(t) + if !sb.FileExists(filepath.Join(dest, "_repo__skills__claude__fix", "SKILL.md")) { + t.Fatal("include did not resolve ambiguity") + } + sb.WriteProjectConfig(root, cfg) + store := install.NewMetadataStore() + store.SetTargetOverride("_repo/skills/codex/fix", []string{"claude"}) + if err := store.Save(source); err != nil { + t.Fatal(err) + } + sb.RunCLIInDir(root, "sync", "-p").AssertSuccess(t) + if got := sb.ReadFile(filepath.Join(dest, "_repo__skills__codex__fix", "SKILL.md")); got != "# codex" { + t.Fatalf("override lost bytes: %q", got) + } + if sb.FileExists(filepath.Join(dest, "_repo__skills__claude__fix")) { + t.Fatal("newly ambiguous variant was not pruned") + } + }) + } +} + +func TestVariants_InitAndStatusAgree(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + if err := os.Remove(sb.ConfigPath); err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + remote := createSkillsRemote(t, sb.Root, map[string]string{ + "_repo/skills/codex/fix": "# codex fix", "_repo/skills/claude/fix": "# claude fix", + "_repo/skills/codex/review": "# codex review", "_repo/skills/claude/review": "# claude review", + }) + result := sb.RunCLI("init", "--remote", remote, "--no-skill") + result.AssertSuccess(t) + result.AssertOutputContains(t, "2 skills") + result.AssertOutputNotContains(t, "4 skills") + status := sb.RunCLI("status", "-g", "--json") + status.AssertSuccess(t) + var counts struct { + Skills int `json:"skill_count"` + Variants int `json:"variant_count"` + } + if err := json.Unmarshal([]byte(status.Stdout), &counts); err != nil { + t.Fatal(err) + } + if counts.Skills != 2 || counts.Variants != 4 { + t.Fatalf("status: %s", status.Stdout) + } +} diff --git a/ui/src/api/types/resources.ts b/ui/src/api/types/resources.ts index 3ebb48ff0..92658cafd 100644 --- a/ui/src/api/types/resources.ts +++ b/ui/src/api/types/resources.ts @@ -1,6 +1,7 @@ export interface TrackedRepo { name: string; skillCount: number; + variantCount: number; dirty: boolean; } @@ -9,6 +10,7 @@ export interface Overview { agentsSource?: string; extrasSource?: string; skillCount: number; + variantCount: number; agentCount: number; topLevelCount: number; targetCount: number; diff --git a/ui/src/api/types/sync.ts b/ui/src/api/types/sync.ts index 438847881..ceb0d705c 100644 --- a/ui/src/api/types/sync.ts +++ b/ui/src/api/types/sync.ts @@ -1,7 +1,7 @@ export interface SyncMatrixEntry { skill: string; target: string; - status: 'synced' | 'excluded' | 'not_included' | 'skill_target_mismatch' | 'na'; + status: 'synced' | 'excluded' | 'not_included' | 'skill_target_mismatch' | 'skipped' | 'na'; reason: string; reasonCode?: string; reasonParams?: Record; @@ -104,6 +104,7 @@ export interface FolderConflict { export interface DiffTarget { target: string; + warnings?: string[]; items: { skill: string; action: string; reason?: string; kind?: 'skill' | 'agent' }[]; skippedCount?: number; collisionCount?: number; diff --git a/ui/src/api/types/targets.ts b/ui/src/api/types/targets.ts index caf54a129..e850243f3 100644 --- a/ui/src/api/types/targets.ts +++ b/ui/src/api/types/targets.ts @@ -52,6 +52,9 @@ export interface Target { exclude: string[]; expectedSkillCount: number; skippedSkillCount?: number; + namingSkippedSkillCount?: number; + selectionSkippedSkillCount?: number; + warnings?: string[]; collisionCount?: number; agentPath?: string; agentMode?: string; diff --git a/ui/src/components/memory/MemoryTools.test.tsx b/ui/src/components/memory/MemoryTools.test.tsx index 34505e07a..28080ea2e 100644 --- a/ui/src/components/memory/MemoryTools.test.tsx +++ b/ui/src/components/memory/MemoryTools.test.tsx @@ -14,7 +14,7 @@ vi.mock('../../api/client', async (load) => { const actual = await load(); return { ...actual, api: { ...actual.api, getOverview: vi.fn() } }; }); -const overview: Overview = { source: '/skills', skillCount: 0, agentCount: 0, topLevelCount: 0, targetCount: 0, +const overview: Overview = { source: '/skills', skillCount: 0, variantCount: 0, agentCount: 0, topLevelCount: 0, targetCount: 0, mode: 'merge', version: 'dev', trackedRepos: [], isProjectMode: false, configDir: '/config' }; const renderTools = () => { const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); diff --git a/ui/src/components/sync/syncView.test.ts b/ui/src/components/sync/syncView.test.ts index fbccddd8f..6c28be0fa 100644 --- a/ui/src/components/sync/syncView.test.ts +++ b/ui/src/components/sync/syncView.test.ts @@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { api, type DiffTarget, type Target } from '../../api/client'; import { hooksApi, type HookPlan } from '../../api/hooks'; import { mcpApi, type MCPPlan } from '../../api/mcp'; -import { changeSets, countChanges, countEdited, discardable, extraGroups, failureExplanation, groupByFolder, groupInSync, HOOKS_CHANGED, hooksGroups, MCP_CHANGED, mcpGroups, otherWarnings, pendingCount, resourceGroups, runSync, skippedHintKey, type SyncFailure } from './syncView'; +import { changeSets, countChanges, countEdited, discardable, extraGroups, failureExplanation, groupByFolder, groupInSync, HOOKS_CHANGED, hooksGroups, MCP_CHANGED, mcpGroups, otherWarnings, pendingCount, resourceGroups, runSync, skippedHintKeys, type SyncFailure } from './syncView'; vi.mock('../../api/client', async (load) => ({ ...await load(), api: { sync: vi.fn(), syncExtras: vi.fn() } })); vi.mock('../../api/mcp', async (load) => ({ ...await load(), mcpApi: { preview: vi.fn(), configure: vi.fn() } })); @@ -20,6 +20,11 @@ const diff: DiffTarget[] = [ ]; describe('resourceGroups', () => { + it('shows selection warnings as read-only rows even with force', () => { + const diffs: DiffTarget[] = [{ target: 'claude', items: [{ skill: '(skill selection)', action: 'skip', reason: 'Target "claude": skipped ambiguous claude variant _repo/skills/claude/fix; use include/exclude or a target override to select one' }] }]; + const groups = resourceGroups(diffs, [target('claude')], new Set(['skill']), true).groups; + expect([countChanges(groups), groups[0].rows[0].name, groups[0].rows[0].text, groups[0].rows[0].detail]).toEqual([0, '_repo/skills/claude/fix', 'sync.skipped.ambiguousVariant', undefined]); + }); it('counts kept local copies only when force is on', () => { const targets = [target('claude'), target('codex')]; const all = new Set(['skill', 'agent'] as const); @@ -302,12 +307,14 @@ describe('failureExplanation', () => { }); }); -describe('skippedHintKey', () => { +describe('skippedHintKeys', () => { it.each([ - [{ collisionCount: 1 }, 'sync.skipped.hint'], - [{ namingSkippedCount: 1 }, 'sync.skipped.hintNaming'], - [{ collisionCount: 1, namingSkippedCount: 1 }, 'sync.skipped.hintMixed'], + [{ skippedCount: 2 }, ['sync.skipped.hintSelection']], + [{ collisionCount: 1 }, ['sync.skipped.hint']], + [{ namingSkippedCount: 1 }, ['sync.skipped.hintNaming']], + [{ collisionCount: 1, namingSkippedCount: 1 }, ['sync.skipped.hintMixed']], + [{ skippedCount: 5, collisionCount: 1, namingSkippedCount: 1, items: [{ skill: '(skill selection)', action: 'skip' }] }, ['sync.skipped.hintMixed', 'sync.skipped.hintSelection']], ])('explains %o with %s', (counts, key) => { - expect(skippedHintKey({ target: 'codex', items: [], ...counts })).toBe(key); + expect(skippedHintKeys({ target: 'codex', items: [], ...counts })).toEqual(key); }); }); diff --git a/ui/src/components/sync/syncView.ts b/ui/src/components/sync/syncView.ts index 15351fc67..f50b7180b 100644 --- a/ui/src/components/sync/syncView.ts +++ b/ui/src/components/sync/syncView.ts @@ -1,3 +1,4 @@ +import { targetWarning } from '../targets/targetView'; import { api, type DiffTarget, type ExtraDiffResult, type Skill, type SyncMatrixEntry, type SyncResponse, type Target } from '../../api/client'; import { hooksApi, type HookPlan } from '../../api/hooks'; import { mcpApi, type MCPPlan } from '../../api/mcp'; @@ -58,9 +59,11 @@ export function resourceGroups(diffs: DiffTarget[], targets: Target[], parts: Se if (!parts.has(part) || item.action === 'local') continue; // Agents always sync as symlinks, whatever the target mode. const copy = part === 'skill' && target?.mode === 'copy'; - const row = { key: `${d.target}/${part}/${item.skill}`, part, name: part === 'agent' ? formatAgentDisplayName(item.skill) : item.skill } as const; + const warning = item.skill === '(target naming)' || item.skill === '(skill selection)'; + const row = { key: `${d.target}/${part}/${item.skill}${warning ? `/${item.reason}` : ''}`, part, name: part === 'agent' ? formatAgentDisplayName(item.skill) : item.skill } as const; // A kept item: a local folder holds the new name, so sync keeps the old entry, with or without force. - if (item.skill === '(target naming)' || item.action === 'kept') rows.push({ ...row, icon: 'kept', text: null, detail: item.reason, counts: false }); + if (item.skill === '(skill selection)') rows.push({ ...row, name: targetWarning(item.reason ?? '')?.path ?? d.target, icon: 'kept', text: 'sync.skipped.ambiguousVariant', counts: false }); + else if (warning || item.action === 'kept') rows.push({ ...row, icon: 'kept', text: null, detail: item.reason, counts: false }); else if (item.skill === '(entire directory)') rows.push({ ...row, name: target?.path ?? item.skill, icon: 'add', text: 'sync.row.folder', counts: true }); else if (item.action === 'link') rows.push({ ...row, icon: 'add', text: item.reason?.startsWith('missing') ? 'sync.row.recopy' : copy ? 'sync.row.newCopy' : 'sync.row.newLink', counts: true }); else if (item.action === 'update') rows.push({ ...row, icon: 'update', text: item.reason === COPY_TO_LINK ? 'sync.row.copyToLink' : copy ? 'sync.row.updateCopy' : 'sync.row.updateLink', counts: true }); @@ -334,8 +337,11 @@ export async function runSync(run: SyncRun) { return { resources, failures }; } -/** The hint for a target's skipped skills: name collisions, naming rules, or both. */ -export function skippedHintKey(d: DiffTarget) { - if (!d.namingSkippedCount) return 'sync.skipped.hint' as const; - return d.collisionCount ? 'sync.skipped.hintMixed' as const : 'sync.skipped.hintNaming' as const; +/** Each independent remedy needed for the skipped skills. */ +export function skippedHintKeys(d: DiffTarget) { + const keys = []; + if (d.namingSkippedCount) keys.push(d.collisionCount ? 'sync.skipped.hintMixed' as const : 'sync.skipped.hintNaming' as const); + else if (d.collisionCount) keys.push('sync.skipped.hint' as const); + if (d.items.some((item) => item.skill === '(skill selection)') || (!d.namingSkippedCount && !d.collisionCount && d.skippedCount)) keys.push('sync.skipped.hintSelection' as const); + return keys; } diff --git a/ui/src/components/targets/FilterSection.tsx b/ui/src/components/targets/FilterSection.tsx index d0f2042a6..d38bbfce3 100644 --- a/ui/src/components/targets/FilterSection.tsx +++ b/ui/src/components/targets/FilterSection.tsx @@ -44,6 +44,7 @@ export default function FilterSection({ kind, mode, name, include, exclude, onCh const reason = (e: SyncMatrixEntry) => { switch (e.status) { + case 'skipped': return t('sync.skipped.ambiguousVariant'); case 'synced': return t(include.length ? 'targetDetail.reason.included' : 'targetDetail.reason.noFilter'); case 'excluded': return t('targetDetail.reason.excluded', { pattern: e.reason }); case 'not_included': return t('targetDetail.reason.notIncluded'); @@ -140,7 +141,7 @@ export default function FilterSection({ kind, mode, name, include, exclude, onCh ); return next ? ( - ) : ( diff --git a/ui/src/components/targets/targetView.test.ts b/ui/src/components/targets/targetView.test.ts index 67c23c793..3d809b573 100644 --- a/ui/src/components/targets/targetView.test.ts +++ b/ui/src/components/targets/targetView.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import type { SyncMatrixEntry, Target } from '../../api/client'; -import { joinList, targetHealth, togglePatterns } from './targetView'; +import { joinList, targetHealth, targetSkipHints, targetWarning, togglePatterns } from './targetView'; const target = (over: Partial): Target => ({ name: 'claude', path: '~/.claude/skills', mode: 'merge', targetNaming: 'flat', status: 'merged', @@ -49,3 +49,18 @@ describe('joinList', () => { .toEqual(['MCP 與 GEMINI.md', 'MCP 與指令檔', 'MCP and GEMINI.md']); }); }); + +it('excludes an ambiguous physical candidate without changing other filters', () => { + expect(togglePatterns(row('_repo__skills__codex__fix', 'skipped'), ['*fix'], ['old'])).toEqual({ include: ['*fix'], exclude: ['old', '_repo__skills__codex__fix'] }); +}); +it('keeps diagnostic paths while localizing selection and naming warnings separately', () => { + expect(targetWarning('Target "codex": skipped ambiguous codex variant _repo/skills/codex/fix; use include/exclude or a target override to select one')).toEqual({ key: 'sync.skipped.ambiguousVariant', path: '_repo/skills/codex/fix' }); + expect(targetWarning("Target 'codex': skipped broken because SKILL.md name could not be read: error")).toEqual({ key: 'sync.skipped.hintNaming', path: 'broken' }); +}); + +describe('targetSkipHints', () => { + it('keeps ambiguity separate from naming and collisions', () => { + expect(targetSkipHints(target({ skippedSkillCount: 5, namingSkippedSkillCount: 1, selectionSkippedSkillCount: 2, collisionCount: 1 }))).toEqual(['sync.skipped.hintMixed', 'sync.skipped.hintSelection']); + expect(targetSkipHints(target({ targetNaming: 'standard', skippedSkillCount: 2, selectionSkippedSkillCount: 2 }))).toEqual(['sync.skipped.hintSelection']); + }); +}); diff --git a/ui/src/components/targets/targetView.ts b/ui/src/components/targets/targetView.ts index 064c472b6..a1cdcf538 100644 --- a/ui/src/components/targets/targetView.ts +++ b/ui/src/components/targets/targetView.ts @@ -43,6 +43,8 @@ export function togglePatterns(entry: SyncMatrixEntry, include: string[], exclud return include.includes(name) && include.length > 1 ? { include: include.filter((p) => p !== name), exclude } : { include, exclude: [...exclude, name] }; + case 'skipped': + return { include, exclude: [...new Set([...exclude, name])] }; case 'not_included': return { include: [...include, name], exclude }; case 'excluded': @@ -65,3 +67,20 @@ export function joinList(items: string[], locale: string) { return before + (locale === 'zh-TW' ? '與' : '和') + after; }).join(''); } + +/** Keep source paths while translating skillshare-owned diagnostic prose. */ +export function targetWarning(warning: string): { key: string; path: string } | null { + const selection = warning.match(/^Target ".*": skipped ambiguous .* variant (.+); use include\/exclude/); + if (selection) return { key: 'sync.skipped.ambiguousVariant', path: selection[1] }; + const naming = warning.match(/^Target '.*': skipped (.+) because /); + return naming ? { key: 'sync.skipped.hintNaming', path: naming[1] } : null; +} + +/** Independent remedies for skills omitted from this target. */ +export function targetSkipHints(target: Target) { + const keys = []; + if (target.namingSkippedSkillCount) keys.push(target.collisionCount ? 'sync.skipped.hintMixed' as const : 'sync.skipped.hintNaming' as const); + else if (target.collisionCount) keys.push('sync.skipped.hint' as const); + if (target.selectionSkippedSkillCount) keys.push('sync.skipped.hintSelection' as const); + return keys; +} diff --git a/ui/src/i18n/locales/de.json b/ui/src/i18n/locales/de.json index b9771e638..c90dfde3e 100644 --- a/ui/src/i18n/locales/de.json +++ b/ui/src/i18n/locales/de.json @@ -1999,6 +1999,7 @@ "sync.skipped.hint": "weil zwei Ordner gleich enden. Stelle {name} auf flat-Benennung um, um beide zu behalten.", "sync.skipped.hintNaming": "weil ihr SKILL.md-Name ungültig ist oder nicht zum Ordner passt. Stelle {name} auf flat-Benennung um, um sie zu behalten.", "sync.skipped.hintMixed": "wegen ungültiger SKILL.md-Namen und Ordnern, die gleich enden. Stelle {name} auf flat-Benennung um, um sie zu behalten.", + "sync.skipped.hintSelection": "Agentenvarianten müssen explizit ausgewählt werden. Verwende include/exclude oder eine Zielüberschreibung, um eine auszuwählen.", "sync.skipped.open": "Ziel öffnen", "sync.local.one": "{count} Eintrag existiert nur in einem Ziel", "sync.local.other": "{count} Einträge existieren nur in einem Ziel", @@ -3504,5 +3505,7 @@ "memory.starterHint": "Die Startnotizen sind bereit. Ergänze eine Vorliebe, Entscheidung oder bestätigte Erkenntnis.", "memory.recentlyUpdated": "Zuletzt aktualisiert", "memory.updated": "Aktualisiert: {time}", - "memory.configuredHint": "Konfiguriert bedeutet, dass die Anweisungsdatei hierher verweist, nicht dass ein Agent sie gelesen hat." + "memory.configuredHint": "Konfiguriert bedeutet, dass die Anweisungsdatei hierher verweist, nicht dass ein Agent sie gelesen hat.", + "sync.skipped.ambiguousVariant": "Mehrdeutige Agent-Variante; mit include/exclude oder einer Zielüberschreibung eine auswählen.", + "dashboard.trackedRepos.variantCount": "{count} Varianten" } diff --git a/ui/src/i18n/locales/en.json b/ui/src/i18n/locales/en.json index 684c8cec5..31dabfca9 100644 --- a/ui/src/i18n/locales/en.json +++ b/ui/src/i18n/locales/en.json @@ -1999,6 +1999,7 @@ "sync.skipped.hint": "because two folders end in the same name. Switch {name} to flat naming to keep both.", "sync.skipped.hintNaming": "because their SKILL.md name is invalid or doesn't match its folder. Switch {name} to flat naming to keep them.", "sync.skipped.hintMixed": "because of invalid SKILL.md names and folders that end in the same name. Switch {name} to flat naming to keep them.", + "sync.skipped.hintSelection": "agent variants need an explicit selection. Use include/exclude or a target override to select one.", "sync.skipped.open": "Open target", "sync.local.one": "{count} item exists only in a target", "sync.local.other": "{count} items exist only in a target", @@ -3504,5 +3505,7 @@ "memory.starterHint": "Your starter notes are ready. Add a preference, decision, or verified lesson.", "memory.recentlyUpdated": "Recently updated", "memory.updated": "Updated {time}", - "memory.configuredHint": "Configured means the instruction file points here, not that an agent has read it." + "memory.configuredHint": "Configured means the instruction file points here, not that an agent has read it.", + "sync.skipped.ambiguousVariant": "Ambiguous agent variant; use include/exclude or a target override to select one.", + "dashboard.trackedRepos.variantCount": "{count} variants" } diff --git a/ui/src/i18n/locales/es.json b/ui/src/i18n/locales/es.json index c08a68420..1f214d1d0 100644 --- a/ui/src/i18n/locales/es.json +++ b/ui/src/i18n/locales/es.json @@ -1999,6 +1999,7 @@ "sync.skipped.hint": "porque dos carpetas terminan con el mismo nombre. Cambia {name} a nombres flat para conservar ambos.", "sync.skipped.hintNaming": "porque su nombre en SKILL.md no es válido o no coincide con su carpeta. Cambia {name} a nombres flat para conservarlos.", "sync.skipped.hintMixed": "por nombres de SKILL.md no válidos y carpetas que terminan con el mismo nombre. Cambia {name} a nombres flat para conservarlos.", + "sync.skipped.hintSelection": "las variantes de agente necesitan una selección explícita. Usa include/exclude o una configuración de destino para seleccionar una.", "sync.skipped.open": "Abrir destino", "sync.local.one": "{count} elemento existe solo en un destino", "sync.local.other": "{count} elementos existen solo en un destino", @@ -3504,5 +3505,7 @@ "memory.starterHint": "Las notas iniciales están listas. Añade una preferencia, decisión o lección verificada.", "memory.recentlyUpdated": "Actualizadas recientemente", "memory.updated": "Actualizada {time}", - "memory.configuredHint": "Configurado significa que el archivo de instrucciones apunta aquí, no que un agente lo haya leído." + "memory.configuredHint": "Configurado significa que el archivo de instrucciones apunta aquí, no que un agente lo haya leído.", + "sync.skipped.ambiguousVariant": "Variante de agente ambigua; usa include/exclude o una asignación de destino para elegir una.", + "dashboard.trackedRepos.variantCount": "{count} variantes" } diff --git a/ui/src/i18n/locales/fa.json b/ui/src/i18n/locales/fa.json index b920f7215..1df4b1d39 100644 --- a/ui/src/i18n/locales/fa.json +++ b/ui/src/i18n/locales/fa.json @@ -1999,6 +1999,7 @@ "sync.skipped.hint": "چون نام دو پوشه یکسان تمام می‌شود. برای نگه‌داشتن هر دو، {name} را به نام‌گذاری flat تغییر دهید.", "sync.skipped.hintNaming": "چون نام SKILL.md آن‌ها نامعتبر است یا با نام پوشه یکی نیست. برای نگه‌داشتن آن‌ها، {name} را به نام‌گذاری flat تغییر دهید.", "sync.skipped.hintMixed": "چون نام‌های نامعتبر در SKILL.md و پوشه‌هایی با پایان نام یکسان وجود دارد. برای نگه‌داشتن آن‌ها، {name} را به نام‌گذاری flat تغییر دهید.", + "sync.skipped.hintSelection": "گونه‌های عامل به انتخاب صریح نیاز دارند. با include/exclude یا بازنویسی مقصد، یکی را انتخاب کنید.", "sync.skipped.open": "باز کردن هدف", "sync.local.one": "{count} مورد فقط در یک هدف وجود دارد", "sync.local.other": "{count} مورد فقط در یک هدف وجود دارند", @@ -3504,5 +3505,7 @@ "memory.starterHint": "یادداشت‌های اولیه آماده‌اند. یک ترجیح، تصمیم یا درس تأییدشده اضافه کنید.", "memory.recentlyUpdated": "به‌روزرسانی‌های اخیر", "memory.updated": "به‌روزرسانی: {time}", - "memory.configuredHint": "پیکربندی‌شده یعنی فایل دستورالعمل به اینجا اشاره می‌کند، نه اینکه یک عامل آن را خوانده است." + "memory.configuredHint": "پیکربندی‌شده یعنی فایل دستورالعمل به اینجا اشاره می‌کند، نه اینکه یک عامل آن را خوانده است.", + "sync.skipped.ambiguousVariant": "گونهٔ عامل مبهم است؛ با include/exclude یا بازنویسی مقصد یکی را انتخاب کنید.", + "dashboard.trackedRepos.variantCount": "{count} گونه" } diff --git a/ui/src/i18n/locales/fr.json b/ui/src/i18n/locales/fr.json index 389314a82..e7f4a1180 100644 --- a/ui/src/i18n/locales/fr.json +++ b/ui/src/i18n/locales/fr.json @@ -1999,6 +1999,7 @@ "sync.skipped.hint": "car deux dossiers se terminent par le même nom. Passez {name} en nommage flat pour garder les deux.", "sync.skipped.hintNaming": "car leur nom dans SKILL.md est invalide ou ne correspond pas à leur dossier. Passez {name} en nommage flat pour les garder.", "sync.skipped.hintMixed": "à cause de noms SKILL.md invalides et de dossiers qui se terminent par le même nom. Passez {name} en nommage flat pour les garder.", + "sync.skipped.hintSelection": "les variantes par agent nécessitent une sélection explicite. Utilisez include/exclude ou une configuration de cible pour en sélectionner une.", "sync.skipped.open": "Ouvrir la cible", "sync.local.one": "{count} élément n'existe que dans une cible", "sync.local.other": "{count} éléments n'existent que dans une cible", @@ -3504,5 +3505,7 @@ "memory.starterHint": "Les notes initiales sont prêtes. Ajoutez une préférence, une décision ou une leçon vérifiée.", "memory.recentlyUpdated": "Mises à jour récentes", "memory.updated": "Mise à jour {time}", - "memory.configuredHint": "Configuré signifie que le fichier d’instructions pointe ici, pas qu’un agent l’a lu." + "memory.configuredHint": "Configuré signifie que le fichier d’instructions pointe ici, pas qu’un agent l’a lu.", + "sync.skipped.ambiguousVariant": "Variante d’agent ambiguë ; utilisez include/exclude ou une cible explicite pour en sélectionner une.", + "dashboard.trackedRepos.variantCount": "{count} variantes" } diff --git a/ui/src/i18n/locales/id.json b/ui/src/i18n/locales/id.json index db3429153..2eb152c53 100644 --- a/ui/src/i18n/locales/id.json +++ b/ui/src/i18n/locales/id.json @@ -1999,6 +1999,7 @@ "sync.skipped.hint": "karena dua folder berakhiran nama yang sama. Ubah {name} ke penamaan flat agar keduanya tetap ada.", "sync.skipped.hintNaming": "karena nama SKILL.md-nya tidak valid atau tidak sama dengan nama foldernya. Ubah {name} ke penamaan flat agar tetap ada.", "sync.skipped.hintMixed": "karena ada nama SKILL.md yang tidak valid dan folder yang berakhiran nama yang sama. Ubah {name} ke penamaan flat agar tetap ada.", + "sync.skipped.hintSelection": "varian agen memerlukan pilihan eksplisit. Gunakan include/exclude atau pengaturan tujuan untuk memilih satu.", "sync.skipped.open": "Buka target", "sync.local.one": "{count} item hanya ada di target", "sync.local.other": "{count} item hanya ada di target", @@ -3504,5 +3505,7 @@ "memory.starterHint": "Catatan awal sudah siap. Tambahkan preferensi, keputusan, atau pelajaran terverifikasi.", "memory.recentlyUpdated": "Baru diperbarui", "memory.updated": "Diperbarui {time}", - "memory.configuredHint": "Dikonfigurasi berarti berkas instruksi mengarah ke sini, bukan berarti agen sudah membacanya." + "memory.configuredHint": "Dikonfigurasi berarti berkas instruksi mengarah ke sini, bukan berarti agen sudah membacanya.", + "sync.skipped.ambiguousVariant": "Varian agen ambigu; gunakan include/exclude atau penggantian target untuk memilih satu.", + "dashboard.trackedRepos.variantCount": "{count} varian" } diff --git a/ui/src/i18n/locales/ja.json b/ui/src/i18n/locales/ja.json index 5fe3bbcec..693de00c5 100644 --- a/ui/src/i18n/locales/ja.json +++ b/ui/src/i18n/locales/ja.json @@ -1999,6 +1999,7 @@ "sync.skipped.hint": "2 つのフォルダ名の末尾が同じためです。両方残すには {name} を flat 命名に切り替えてください。", "sync.skipped.hintNaming": "SKILL.md の名前が規則に合わないか、フォルダ名と異なるためです。残すには {name} を flat 命名に切り替えてください。", "sync.skipped.hintMixed": "規則に合わない SKILL.md の名前と、末尾が同じフォルダ名があるためです。残すには {name} を flat 命名に切り替えてください。", + "sync.skipped.hintSelection": "エージェント別のバリアントを明示的に選択する必要があります。include/exclude またはターゲットの上書き設定で選択してください。", "sync.skipped.open": "ターゲットを開く", "sync.local.one": "{count} 件はターゲットにだけ存在します", "sync.local.other": "{count} 件はターゲットにだけ存在します", @@ -3504,5 +3505,7 @@ "memory.starterHint": "初期ノートを用意しました。好み、決定事項、検証済みの知見を追加してください。", "memory.recentlyUpdated": "最近の更新", "memory.updated": "更新:{time}", - "memory.configuredHint": "設定済みは指示ファイルがここを指していることを示し、エージェントが読んだことを意味しません。" + "memory.configuredHint": "設定済みは指示ファイルがここを指していることを示し、エージェントが読んだことを意味しません。", + "sync.skipped.ambiguousVariant": "エージェントのバリアントを特定できません。include/exclude またはターゲットの上書きで1つ選択してください。", + "dashboard.trackedRepos.variantCount": "{count} バリアント" } diff --git a/ui/src/i18n/locales/ko.json b/ui/src/i18n/locales/ko.json index b01edfd50..d490c811b 100644 --- a/ui/src/i18n/locales/ko.json +++ b/ui/src/i18n/locales/ko.json @@ -1999,6 +1999,7 @@ "sync.skipped.hint": "두 폴더의 이름 끝이 같기 때문입니다. 둘 다 유지하려면 {name}을(를) flat 이름 방식으로 바꾸세요.", "sync.skipped.hintNaming": "SKILL.md 이름이 규칙에 맞지 않거나 폴더 이름과 다르기 때문입니다. 유지하려면 {name}을(를) flat 이름 방식으로 바꾸세요.", "sync.skipped.hintMixed": "규칙에 맞지 않는 SKILL.md 이름과 이름 끝이 같은 폴더가 있기 때문입니다. 유지하려면 {name}을(를) flat 이름 방식으로 바꾸세요.", + "sync.skipped.hintSelection": "에이전트 변형을 명시적으로 선택해야 합니다. include/exclude 또는 대상 재정의로 하나를 선택하세요.", "sync.skipped.open": "대상 열기", "sync.local.one": "항목 {count}개는 대상에만 있습니다", "sync.local.other": "항목 {count}개는 대상에만 있습니다", @@ -3504,5 +3505,7 @@ "memory.starterHint": "초기 노트가 준비되었습니다. 선호 사항, 결정 또는 검증된 교훈을 추가하세요.", "memory.recentlyUpdated": "최근 업데이트", "memory.updated": "업데이트: {time}", - "memory.configuredHint": "설정됨은 지침 파일이 여기를 가리킨다는 뜻이며, 에이전트가 읽었다는 뜻은 아닙니다." + "memory.configuredHint": "설정됨은 지침 파일이 여기를 가리킨다는 뜻이며, 에이전트가 읽었다는 뜻은 아닙니다.", + "sync.skipped.ambiguousVariant": "에이전트 변형이 모호합니다. include/exclude 또는 대상 재정의로 하나를 선택하세요.", + "dashboard.trackedRepos.variantCount": "변형 {count}개" } diff --git a/ui/src/i18n/locales/pt-BR.json b/ui/src/i18n/locales/pt-BR.json index 854a30a7d..44bfbbda7 100644 --- a/ui/src/i18n/locales/pt-BR.json +++ b/ui/src/i18n/locales/pt-BR.json @@ -1999,6 +1999,7 @@ "sync.skipped.hint": "porque duas pastas terminam com o mesmo nome. Mude {name} para nomes flat para manter as duas.", "sync.skipped.hintNaming": "porque o nome no SKILL.md é inválido ou não corresponde à pasta. Mude {name} para nomes flat para mantê-los.", "sync.skipped.hintMixed": "por nomes de SKILL.md inválidos e pastas que terminam com o mesmo nome. Mude {name} para nomes flat para mantê-los.", + "sync.skipped.hintSelection": "as variantes de agente precisam de uma seleção explícita. Use include/exclude ou uma configuração de destino para selecionar uma.", "sync.skipped.open": "Abrir destino", "sync.local.one": "{count} item existe só em um destino", "sync.local.other": "{count} itens existem só em um destino", @@ -3504,5 +3505,7 @@ "memory.starterHint": "As notas iniciais estão prontas. Adicione uma preferência, decisão ou lição verificada.", "memory.recentlyUpdated": "Atualizadas recentemente", "memory.updated": "Atualizada {time}", - "memory.configuredHint": "Configurado significa que o arquivo de instruções aponta para cá, não que um agente o tenha lido." + "memory.configuredHint": "Configurado significa que o arquivo de instruções aponta para cá, não que um agente o tenha lido.", + "sync.skipped.ambiguousVariant": "Variante de agente ambígua; use include/exclude ou uma substituição de destino para selecionar uma.", + "dashboard.trackedRepos.variantCount": "{count} variantes" } diff --git a/ui/src/i18n/locales/zh-CN.json b/ui/src/i18n/locales/zh-CN.json index e0745c7a5..21b8e46f3 100644 --- a/ui/src/i18n/locales/zh-CN.json +++ b/ui/src/i18n/locales/zh-CN.json @@ -1999,6 +1999,7 @@ "sync.skipped.hint": "因为有两个文件夹名称结尾相同。将 {name} 改为 flat 命名即可保留两者。", "sync.skipped.hintNaming": "因为 SKILL.md 的名称不合规则,或与文件夹名称不同。将 {name} 改为 flat 命名即可保留。", "sync.skipped.hintMixed": "因为有 SKILL.md 名称不合规则,也有文件夹名称结尾相同。将 {name} 改为 flat 命名即可保留。", + "sync.skipped.hintSelection": "代理变体需要明确选择。请使用 include/exclude 或目标覆盖来选择其中一个。", "sync.skipped.open": "打开目标", "sync.local.one": "{count} 项只存在于目标中", "sync.local.other": "{count} 项只存在于目标中", @@ -3504,5 +3505,7 @@ "memory.starterHint": "初始笔记已准备好。添加一项偏好、决策或已验证的经验。", "memory.recentlyUpdated": "最近更新", "memory.updated": "更新时间:{time}", - "memory.configuredHint": "已配置表示指令文件已指向这里,不代表 agent 已读取。" + "memory.configuredHint": "已配置表示指令文件已指向这里,不代表 agent 已读取。", + "sync.skipped.ambiguousVariant": "代理变体不明确;请用 include/exclude 或目标覆盖选择一个。", + "dashboard.trackedRepos.variantCount": "{count} 个变体" } diff --git a/ui/src/i18n/locales/zh-TW.json b/ui/src/i18n/locales/zh-TW.json index 81dfd1b2f..9e5adcf37 100644 --- a/ui/src/i18n/locales/zh-TW.json +++ b/ui/src/i18n/locales/zh-TW.json @@ -1999,6 +1999,7 @@ "sync.skipped.hint": "因為有兩個資料夾名稱結尾相同。將 {name} 改為 flat 命名即可保留兩者。", "sync.skipped.hintNaming": "因為 SKILL.md 的名稱不合規則,或與資料夾名稱不同。將 {name} 改為 flat 命名即可保留。", "sync.skipped.hintMixed": "因為有 SKILL.md 名稱不合規則,也有資料夾名稱結尾相同。將 {name} 改為 flat 命名即可保留。", + "sync.skipped.hintSelection": "代理變體需要明確選擇。請使用 include/exclude 或目標覆寫來選擇其中一個。", "sync.skipped.open": "開啟目標", "sync.local.one": "{count} 項只存在於目標中", "sync.local.other": "{count} 項只存在於目標中", @@ -3504,5 +3505,7 @@ "memory.starterHint": "起始筆記已備妥。加入一項偏好、決策或已驗證的經驗。", "memory.recentlyUpdated": "最近更新", "memory.updated": "更新時間:{time}", - "memory.configuredHint": "已設定表示指令檔已指向這裡,不代表 agent 已經讀過。" + "memory.configuredHint": "已設定表示指令檔已指向這裡,不代表 agent 已經讀過。", + "sync.skipped.ambiguousVariant": "代理變體不明確;請用 include/exclude 或目標覆寫選擇一個。", + "dashboard.trackedRepos.variantCount": "{count} 個變體" } diff --git a/ui/src/pages/AuditPage.tsx b/ui/src/pages/AuditPage.tsx index 912ad7e83..9f7f28714 100644 --- a/ui/src/pages/AuditPage.tsx +++ b/ui/src/pages/AuditPage.tsx @@ -45,7 +45,7 @@ export default function AuditPage() { useEffect(() => () => stream.current?.close(), []); - const counts = { skills: overview.data?.skillCount, agents: overview.data?.agentCount }; + const counts = { skills: (overview.data?.variantCount ?? overview.data?.skillCount), agents: overview.data?.agentCount }; const installed = counts[kind]; const data = getCachedAuditResult(queryClient, kind, installed); const scannedAt = queryClient.getQueryState(queryKeys.audit.all(kind))?.dataUpdatedAt; diff --git a/ui/src/pages/AuditRulesPage.tsx b/ui/src/pages/AuditRulesPage.tsx index 39932a928..aa024dc86 100644 --- a/ui/src/pages/AuditRulesPage.tsx +++ b/ui/src/pages/AuditRulesPage.tsx @@ -68,7 +68,7 @@ export default function AuditRulesPage() { }, [rules]); // Findings from the last scan, so a rule can show what it catches right now. - const scan = getCachedAuditResult(queryClient, 'skills', overview.data?.skillCount); + const scan = getCachedAuditResult(queryClient, 'skills', (overview.data?.variantCount ?? overview.data?.skillCount)); const hits = useMemo(() => { const map = new Map(); for (const result of scan?.results ?? []) { diff --git a/ui/src/pages/DashboardPage.tsx b/ui/src/pages/DashboardPage.tsx index 167056cfc..3b28f4390 100644 --- a/ui/src/pages/DashboardPage.tsx +++ b/ui/src/pages/DashboardPage.tsx @@ -62,7 +62,7 @@ function useTargetHealth() { if (tgt.status === 'has files' && tgt.mode === 'symlink') return { kind: 'warn', label: t('targets.state.migrate'), detail: t('targets.syncing.migrate'), pending: 0 }; if (tgt.status === 'unknown') return { kind: 'off', label: tgt.status, detail: '', pending: 0 }; const counted = tgt.status === 'has files' || (tgt.mode === 'merge' && tgt.status === 'merged') || (tgt.mode === 'copy' && tgt.status === 'copied'); - const pending = counted ? Math.max(0, (tgt.expectedSkillCount || sourceSkillCount) - tgt.linkedCount) : 0; + const pending = counted ? Math.max(0, (tgt.expectedSkillCount ?? sourceSkillCount) - tgt.linkedCount) : 0; const linked = tgt.linkedCount > 0 ? t(tgt.mode === 'copy' ? 'dashboard.targets.managed' : 'dashboard.targets.linked', { count: tgt.linkedCount }) : ''; @@ -500,7 +500,7 @@ function TrackedRepos({ repos }: { repos: Overview['trackedRepos'] }) { {repo.name.replace(/^_/, '')} - {t(plural('dashboard.trackedRepos.skillCount', repo.skillCount), { count: repo.skillCount })} + {t(plural('dashboard.trackedRepos.skillCount', repo.skillCount), { count: repo.skillCount })}{(repo.variantCount ?? repo.skillCount) > repo.skillCount && <>{', '}{t('dashboard.trackedRepos.variantCount', { count: repo.variantCount! })}} {repo.dirty ? t('dashboard.trackedRepos.modified') : t('dashboard.trackedRepos.clean')} diff --git a/ui/src/pages/ResourceDetailPage.tsx b/ui/src/pages/ResourceDetailPage.tsx index 909e23e1c..da02621d4 100644 --- a/ui/src/pages/ResourceDetailPage.tsx +++ b/ui/src/pages/ResourceDetailPage.tsx @@ -548,6 +548,8 @@ function TargetsSection({ resource }: { resource: Skill }) { return t('resourceDetail.targets.excludedBy', { pattern: entry.reason }); case 'not_included': return t('resourceDetail.targets.notIncluded'); + case 'skipped': + return t('sync.skipped.ambiguousVariant'); case 'skill_target_mismatch': return t('resourceDetail.targets.mismatch'); case 'na': diff --git a/ui/src/pages/SyncPage.test.tsx b/ui/src/pages/SyncPage.test.tsx index 1ea53d8c0..7bf54dba3 100644 --- a/ui/src/pages/SyncPage.test.tsx +++ b/ui/src/pages/SyncPage.test.tsx @@ -104,16 +104,18 @@ describe('Sync page last sync', () => { it('does not offer Discard all for a skill a symlink-mode target already exposes', async () => { const skill = (flatName: string) => ({ name: flatName, kind: 'skill', flatName, relPath: flatName, sourcePath: '', isInRepo: true }); - vi.mocked(api.listTargets).mockResolvedValue({ targets: [target('codex')], sourceSkillCount: 1 }); + const warning = `Target 'codex': skipped broken because SKILL.md name "different" does not match directory name "broken"`; + vi.mocked(api.listTargets).mockResolvedValue({ targets: [target('codex', { targetNaming: 'standard' })], sourceSkillCount: 2 }); vi.mocked(api.diff).mockResolvedValue({ - diffs: [{ target: 'codex', items: [{ skill: 'fresh', action: 'link', reason: 'new' }] }], + diffs: [{ target: 'codex', skippedCount: 1, namingSkippedCount: 1, warnings: [warning], items: [{ skill: 'fresh', action: 'link', reason: 'new' }, { skill: '(skill selection)', action: 'skip', reason: warning }] }], ignored_count: 0, ignored_skills: [], ignore_root: '', ignore_repos: [], } as never); - vi.mocked(api.listSkills).mockResolvedValue({ resources: [skill('fresh')] } as never); + vi.mocked(api.listSkills).mockResolvedValue({ resources: [skill('fresh'), skill('broken')] } as never); // claude links the whole source folder, so fresh is already live there. vi.mocked(api.getSyncMatrix).mockResolvedValue({ entries: [ { skill: 'fresh', target: 'codex', status: 'synced', reason: '' }, { skill: 'fresh', target: 'claude', status: 'na', reason: 'symlink mode — filters not applicable', reasonCode: 'sync_matrix.symlink_filters_not_applicable' }, + { skill: 'broken', target: 'codex', status: 'synced', reason: '' }, ] } as never); renderPage(); diff --git a/ui/src/pages/SyncPage.tsx b/ui/src/pages/SyncPage.tsx index 8cb0caa95..ea5d53c7b 100644 --- a/ui/src/pages/SyncPage.tsx +++ b/ui/src/pages/SyncPage.tsx @@ -14,7 +14,7 @@ import { useToast } from '../components/Toast'; import { hookLabel, hookMessage, rootName } from '../components/hooks/hooksView'; import MCPNotices from '../components/mcp/MCPNotices'; import { describeMessage, mcpClient, targetLabel } from '../components/mcp/mcpView'; -import { changeSets, countChanges, countEdited, discardable, receivesSkill, tally, extraGroups, groupByFolder, groupInSync, HOOKS_CHANGED, hooksGroups, MCP_CHANGED, mcpGroups, otherWarnings, resourceGroups, runSync, skippedHintKey, type ChangeGroup, type Part, type RowIcon, type SyncFailure } from '../components/sync/syncView'; +import { changeSets, countChanges, countEdited, discardable, receivesSkill, tally, extraGroups, groupByFolder, groupInSync, HOOKS_CHANGED, hooksGroups, MCP_CHANGED, mcpGroups, otherWarnings, resourceGroups, runSync, skippedHintKeys, type ChangeGroup, type Part, type RowIcon, type SyncFailure } from '../components/sync/syncView'; import FolderConflictNotice from '../components/sync/FolderConflictNotice'; import SyncResult from '../components/sync/SyncResult'; import UnmatchedNotices from '../components/sync/UnmatchedNotices'; @@ -459,7 +459,7 @@ export default function SyncPage() { {t(plural('sync.skipped', d.skippedCount ?? 0), { count: d.skippedCount ?? 0, name: d.target })}{' '} - {t(skippedHintKey(d), { name: d.target })} + {skippedHintKeys(d).map((key) => t(key, { name: d.target })).join(' ')} {t('sync.skipped.open')} diff --git a/ui/src/pages/TargetDetailPage.test.tsx b/ui/src/pages/TargetDetailPage.test.tsx index b722c7c92..ac2573518 100644 --- a/ui/src/pages/TargetDetailPage.test.tsx +++ b/ui/src/pages/TargetDetailPage.test.tsx @@ -39,7 +39,10 @@ function renderPage(codex: Partial, universal: Partial = {}) { } describe('Target page shared skills folder', () => { - beforeEach(() => vi.clearAllMocks()); + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(api.previewSyncMatrix).mockResolvedValue({ entries: [] }); + }); it('warns under the mode picker and sets the draft to the other target\'s mode', async () => { const user = userEvent.setup(); diff --git a/ui/src/pages/TargetDetailPage.tsx b/ui/src/pages/TargetDetailPage.tsx index 4d16efca7..0292bb0ee 100644 --- a/ui/src/pages/TargetDetailPage.tsx +++ b/ui/src/pages/TargetDetailPage.tsx @@ -12,6 +12,7 @@ import SegmentedControl from '../components/SegmentedControl'; import { PageSkeleton } from '../components/Skeleton'; import { useToast } from '../components/Toast'; import FilterSection, { ModePicker } from '../components/targets/FilterSection'; +import { targetWarning, targetSkipHints } from '../components/targets/targetView'; import RemoveTargetDialog from '../components/targets/RemoveTargetDialog'; import SkillsOffDialog from '../components/targets/SkillsOffDialog'; import TargetMCP from '../components/targets/TargetMCP'; @@ -253,6 +254,11 @@ function TargetEditor({ target, targets }: { target: Target; targets: Target[] } } /> + {target.warnings?.map((warning) => { + const diagnostic = targetWarning(warning); + return
{diagnostic ? <>{diagnostic.path}: {t(diagnostic.key, { name: target.name })} : warning}
; + })} + {tabs.length > 1 && (