mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-20 12:23:22 +00:00
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 <egg358358@gmail.com>
This commit is contained in:
co-authored by
Willie
parent
23c9453f87
commit
85bcf589a7
@@ -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" <<YAML
|
||||
source: $fixture/source
|
||||
mode: $mode
|
||||
targets:
|
||||
codex-work:
|
||||
agent: codex
|
||||
config_dir: $fixture/account-$mode
|
||||
YAML
|
||||
skillshare sync -g
|
||||
skillshare sync -g
|
||||
cmp "$fixture/source/_repo/skills/codex/fix/SKILL.md" "$fixture/account-$mode/skills/_repo__skills__codex__fix/SKILL.md"
|
||||
test ! -e "$fixture/account-$mode/skills/_repo__skills__claude__fix"
|
||||
python3 - "$SKILLSHARE_CONFIG" <<'PY'
|
||||
from pathlib import Path
|
||||
import sys
|
||||
p = Path(sys.argv[1])
|
||||
p.write_text(p.read_text() + " exclude: ['*codex*']\n")
|
||||
PY
|
||||
skillshare sync -g
|
||||
test ! -e "$fixture/account-$mode/skills/_repo__skills__codex__fix"
|
||||
done
|
||||
printf 'account variants PASS\n'
|
||||
```
|
||||
|
||||
Expected:
|
||||
- exit_code: 0
|
||||
- account variants PASS
|
||||
|
||||
### 2. Project ambiguity and explicit selection
|
||||
|
||||
```bash
|
||||
set -euo pipefail
|
||||
fixture=$(mktemp -d "$HOME/variants-project.XXXXXX")
|
||||
for mode in merge copy; do
|
||||
project="$fixture/$mode"
|
||||
mkdir -p "$project/.skillshare/skills/_repo/skills"
|
||||
for agent in claude claude-code codex; do
|
||||
mkdir -p "$project/.skillshare/skills/_repo/skills/$agent/fix"
|
||||
printf '# %s\n' "$agent" > "$project/.skillshare/skills/_repo/skills/$agent/fix/SKILL.md"
|
||||
done
|
||||
cat > "$project/.skillshare/config.yaml" <<YAML
|
||||
targets:
|
||||
- name: claude
|
||||
mode: $mode
|
||||
YAML
|
||||
cd "$project"
|
||||
skillshare sync -p
|
||||
test ! -e .claude/skills/_repo__skills__claude__fix
|
||||
test ! -e .claude/skills/_repo__skills__claude-code__fix
|
||||
cat > .skillshare/config.yaml <<YAML
|
||||
targets:
|
||||
- name: claude
|
||||
mode: $mode
|
||||
include: ['_repo__skills__claude__fix']
|
||||
YAML
|
||||
skillshare sync -p
|
||||
cmp .skillshare/skills/_repo/skills/claude/fix/SKILL.md .claude/skills/_repo__skills__claude__fix/SKILL.md
|
||||
test ! -e .claude/skills/_repo__skills__claude-code__fix
|
||||
done
|
||||
printf 'project variants PASS\n'
|
||||
```
|
||||
|
||||
Expected:
|
||||
- exit_code: 0
|
||||
- project variants PASS
|
||||
|
||||
## Pass Criteria
|
||||
|
||||
Both steps exit successfully, all file/JSON assertions pass, and both PASS markers appear.
|
||||
@@ -0,0 +1,235 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/install"
|
||||
"skillshare/internal/sync"
|
||||
)
|
||||
|
||||
func consumerVariantSource(t *testing.T) string {
|
||||
t.Helper()
|
||||
source := t.TempDir()
|
||||
for _, agent := range []string{"claude", "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("# Fix instructions\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
initGitRepoForTest(t, filepath.Join(source, "_repo"))
|
||||
t.Setenv("SKILLSHARE_CONFIG", filepath.Join(t.TempDir(), "config.yaml"))
|
||||
for _, key := range []string{"XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME"} {
|
||||
t.Setenv(key, t.TempDir())
|
||||
}
|
||||
return source
|
||||
}
|
||||
|
||||
func TestConsumerVariantInventorySummaries(t *testing.T) {
|
||||
source := consumerVariantSource(t)
|
||||
discovered, err := sync.DiscoverSourceSkills(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := captureStdout(t, func() { displayTrackedRepos([]string{"_repo"}, discovered, source) })
|
||||
if !strings.Contains(output, "1 skill, 2 variants") {
|
||||
t.Errorf("list summary: %s", output)
|
||||
}
|
||||
cfg := &config.Config{Source: source, AgentsSource: t.TempDir(), Mode: "merge", Targets: map[string]config.TargetConfig{}}
|
||||
output = captureStdout(t, func() {
|
||||
count, _, err := firstSync(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Errorf("firstSync count = %d, want logical 1", count)
|
||||
}
|
||||
})
|
||||
if !strings.Contains(output, "1 skill, 2 variants to 0 tools") {
|
||||
t.Errorf("init summary: %s", output)
|
||||
}
|
||||
parsed, err := install.ParseSource(filepath.Join(source, "_repo"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.Source = t.TempDir()
|
||||
output = captureStdout(t, func() {
|
||||
if _, err := handleTrackedRepoInstall(parsed, cfg, install.InstallOptions{Kind: "skill"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
if !strings.Contains(output, "1 skill, 2 variants") {
|
||||
t.Errorf("install summary: %s", output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsumerVariantSymlinkDiagnostics(t *testing.T) {
|
||||
for _, project := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "global", true: "project"}[project], func(t *testing.T) {
|
||||
source := consumerVariantSource(t)
|
||||
cfg := &config.Config{Source: source, AgentsSource: t.TempDir(), Mode: "symlink", Targets: map[string]config.TargetConfig{
|
||||
"claude": {Path: filepath.Join(t.TempDir(), "skills")},
|
||||
}}
|
||||
if err := cfg.Save(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root := t.TempDir()
|
||||
if project {
|
||||
pc := &config.ProjectConfig{Sources: config.ProjectSources{Skills: source}, Targets: []config.ProjectTargetEntry{{Name: "claude", Path: cfg.Targets["claude"].Path, Mode: "symlink"}}}
|
||||
if err := pc.Save(root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
const want = "symlink mode exposes all agent variants"
|
||||
output := captureStdout(t, func() {
|
||||
var err error
|
||||
if project {
|
||||
err = cmdStatusProject(root)
|
||||
} else {
|
||||
err = printTargetsStatus(cfg, mustDiscoverConsumerVariants(t, source))
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
if !strings.Contains(output, want) {
|
||||
t.Errorf("status diagnostic: %s", output)
|
||||
}
|
||||
output = captureStdout(t, func() {
|
||||
var err error
|
||||
if project {
|
||||
err = cmdStatusProjectJSON(root)
|
||||
} else {
|
||||
err = cmdStatus([]string{"-g", "--json"})
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
var status statusJSONOutput
|
||||
if err := json.Unmarshal([]byte(output), &status); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status.SkillCount != 1 || status.VariantCount != 2 {
|
||||
t.Errorf("JSON inventory = %d/%d, want 1/2", status.SkillCount, status.VariantCount)
|
||||
}
|
||||
if len(status.Targets) != 1 || !strings.Contains(status.Targets[0].Warning, want) {
|
||||
t.Errorf("JSON diagnostic: %s", output)
|
||||
}
|
||||
result := &doctorResult{}
|
||||
captureStdout(t, func() { checkSyncDrift(cfg, result, mustDiscoverConsumerVariants(t, source), nil) })
|
||||
if len(result.checks) < 1 || !strings.Contains(strings.Join(result.checks[0].Details, " "), want) {
|
||||
t.Errorf("doctor diagnostic: %+v", result.checks)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func mustDiscoverConsumerVariants(t *testing.T, source string) []sync.DiscoveredSkill {
|
||||
t.Helper()
|
||||
skills, err := sync.DiscoverSourceSkills(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return skills
|
||||
}
|
||||
|
||||
func TestConsumerVariantDiagnosticScope(t *testing.T) {
|
||||
disabled := false
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
target config.TargetConfig
|
||||
mode string
|
||||
skills []sync.DiscoveredSkill
|
||||
}{
|
||||
{name: "merge", mode: "merge", skills: []sync.DiscoveredSkill{{VariantAgent: "codex"}}},
|
||||
{name: "copy", mode: "copy", skills: []sync.DiscoveredSkill{{VariantAgent: "codex"}}},
|
||||
{name: "ordinary", mode: "symlink", skills: []sync.DiscoveredSkill{{RelPath: "ordinary"}}},
|
||||
{name: "skills off", mode: "symlink", target: config.TargetConfig{Skills: &config.ResourceTargetConfig{Enabled: &disabled}}, skills: []sync.DiscoveredSkill{{VariantAgent: "codex"}}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := variantSymlinkWarning(tc.target, tc.mode, tc.skills); got != "" {
|
||||
t.Errorf("unexpected warning: %s", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFirstSyncSharedVariants(t *testing.T) {
|
||||
for _, mode := range []string{"merge", "copy"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
source := consumerVariantSource(t)
|
||||
dest := t.TempDir()
|
||||
cfg := &config.Config{Source: source, AgentsSource: t.TempDir(), Mode: mode, Targets: map[string]config.TargetConfig{
|
||||
"codex": {Path: dest}, "universal": {Path: dest},
|
||||
}}
|
||||
captureStdout(t, func() {
|
||||
if _, _, err := firstSync(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
if _, err := os.Stat(filepath.Join(dest, "_repo__skills__codex__fix", "SKILL.md")); err != nil {
|
||||
t.Fatalf("init pruned shared Codex variant: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIgnoredVariantsSymlinkWarning(t *testing.T) {
|
||||
for _, project := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "global", true: "project"}[project], func(t *testing.T) {
|
||||
source := consumerVariantSource(t)
|
||||
if err := os.WriteFile(filepath.Join(source, ".skillignore"), []byte("**\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := &config.Config{Source: source, AgentsSource: t.TempDir(), Mode: "symlink", Targets: map[string]config.TargetConfig{"claude": {Path: filepath.Join(t.TempDir(), "skills")}}}
|
||||
if err := cfg.Save(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root := t.TempDir()
|
||||
if project {
|
||||
pc := &config.ProjectConfig{Sources: config.ProjectSources{Skills: source}, Targets: []config.ProjectTargetEntry{{Name: "claude", Path: cfg.Targets["claude"].Path, Mode: "symlink"}}}
|
||||
if err := pc.Save(root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
output := captureStdout(t, func() {
|
||||
var err error
|
||||
if project {
|
||||
err = cmdStatusProjectJSON(root)
|
||||
} else {
|
||||
err = cmdStatus([]string{"-g", "--json"})
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
var status statusJSONOutput
|
||||
if err := json.Unmarshal([]byte(output), &status); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status.SkillCount != 0 || status.VariantCount != 0 {
|
||||
t.Fatalf("ignored inventory counted: %s", output)
|
||||
}
|
||||
if len(status.Targets) != 1 || !strings.Contains(status.Targets[0].Warning, "symlink mode exposes all agent variants") {
|
||||
t.Fatalf("ignored variants still exposed without warning: %s", output)
|
||||
}
|
||||
discovered, err := sync.DiscoverSourceSkills(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result := &doctorResult{}
|
||||
captureStdout(t, func() { checkVariantRouting(cfg, result, discovered) })
|
||||
if len(result.checks) != 1 || result.checks[0].Status != checkWarning {
|
||||
t.Fatalf("doctor missed ignored variants: %+v", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+25
-23
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
gosync "sync"
|
||||
@@ -147,9 +148,11 @@ type targetDiffResult struct {
|
||||
dstMtime time.Time // newest file mtime in target dir
|
||||
}
|
||||
|
||||
// inSync reports that sync has nothing to do for the target. Folders only the
|
||||
// inSync reports no pending work or selection diagnostics. Folders only the
|
||||
// target holds stay listed, but sync never touches them.
|
||||
func (r targetDiffResult) inSync() bool { return r.errMsg == "" && r.syncCount == 0 }
|
||||
func (r targetDiffResult) inSync() bool {
|
||||
return r.errMsg == "" && r.syncCount == 0 && !slices.ContainsFunc(r.items, func(item copyDiffEntry) bool { return item.action == "skip" })
|
||||
}
|
||||
|
||||
type copyDiffEntry struct {
|
||||
action string // "add", "modify", "remove"
|
||||
@@ -435,22 +438,22 @@ func cmdDiffGlobal(targetName string, kind resourceKindFilter, opts diffRenderOp
|
||||
return entries[i].name < entries[j].name
|
||||
})
|
||||
|
||||
// Pre-filter skills per target and compute total for progress bar
|
||||
// Resolve each target once, preserving selection diagnostics for the preview.
|
||||
type filteredEntry struct {
|
||||
targetEntry
|
||||
filtered []sync.DiscoveredSkill
|
||||
resolution *sync.TargetSkillResolution
|
||||
}
|
||||
var fentries []filteredEntry
|
||||
totalSkills := 0
|
||||
hasCopyMode := false
|
||||
for _, e := range entries {
|
||||
sc := e.target.SkillsConfig()
|
||||
filtered, err := sync.SelectTargetSkills(discovered, e.name, sc)
|
||||
resolution, err := sync.ResolveTargetSkillsForTarget(e.name, sc, discovered)
|
||||
if err != nil {
|
||||
return fmt.Errorf("target %s has invalid include/exclude config: %w", e.name, err)
|
||||
}
|
||||
fentries = append(fentries, filteredEntry{e, filtered})
|
||||
totalSkills += len(filtered)
|
||||
fentries = append(fentries, filteredEntry{e, resolution})
|
||||
totalSkills += len(resolution.Skills)
|
||||
if e.mode == "copy" {
|
||||
hasCopyMode = true
|
||||
}
|
||||
@@ -476,7 +479,7 @@ func cmdDiffGlobal(targetName string, kind resourceKindFilter, opts diffRenderOp
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
progress.startTarget(fe.name)
|
||||
r := collectTargetDiff(fe.name, fe.target, cfg.EffectiveSkillsSource(), fe.mode, fe.filtered, sync.EffectiveFileIgnorePatterns(cfg.Ignore), progress)
|
||||
r := collectTargetDiff(fe.name, fe.target, cfg.EffectiveSkillsSource(), fe.mode, fe.resolution, sync.EffectiveFileIgnorePatterns(cfg.Ignore), progress)
|
||||
progress.doneTarget(fe.name, r)
|
||||
results[idx] = r
|
||||
}(i, fe)
|
||||
@@ -575,7 +578,7 @@ func diffOutputJSONWithExtras(results []targetDiffResult, extrasResults []extraD
|
||||
return writeJSON(&o)
|
||||
}
|
||||
|
||||
func collectTargetDiff(name string, target config.TargetConfig, source, mode string, filtered []sync.DiscoveredSkill, ignorePatterns []string, dp *diffProgress) targetDiffResult {
|
||||
func collectTargetDiff(name string, target config.TargetConfig, source, mode string, resolution *sync.TargetSkillResolution, ignorePatterns []string, dp *diffProgress) targetDiffResult {
|
||||
sc := target.SkillsConfig()
|
||||
r := targetDiffResult{
|
||||
name: name,
|
||||
@@ -588,17 +591,7 @@ func collectTargetDiff(name string, target config.TargetConfig, source, mode str
|
||||
_, err := os.Lstat(sc.Path)
|
||||
if err != nil {
|
||||
r.errMsg = fmt.Sprintf("Cannot access target: %v", err)
|
||||
dp.add(len(filtered))
|
||||
return r
|
||||
}
|
||||
|
||||
resolution, err := sync.ResolveTargetSkillsForTarget(name, config.ResourceTargetConfig{
|
||||
Path: sc.Path,
|
||||
TargetNaming: sc.TargetNaming,
|
||||
}, filtered)
|
||||
if err != nil {
|
||||
r.errMsg = err.Error()
|
||||
dp.add(len(filtered))
|
||||
dp.add(len(resolution.Skills))
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -611,7 +604,7 @@ func collectTargetDiff(name string, target config.TargetConfig, source, mode str
|
||||
if utils.IsSymlinkOrJunction(sc.Path) {
|
||||
r.mode = "symlink"
|
||||
collectSymlinkDiff(&r, sc.Path, source)
|
||||
dp.add(len(filtered))
|
||||
dp.add(len(resolution.Skills))
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -625,7 +618,14 @@ func collectTargetDiff(name string, target config.TargetConfig, source, mode str
|
||||
} else {
|
||||
// Merge mode (instant)
|
||||
collectMergeDiff(&r, sc.Path, sourceSkills, sourceMap, legacyNames)
|
||||
dp.add(len(filtered))
|
||||
dp.add(len(resolution.Skills))
|
||||
}
|
||||
|
||||
for _, warning := range resolution.SelectionWarnings {
|
||||
r.items = append(r.items, copyDiffEntry{action: "skip", name: "(skill selection)", reason: warning})
|
||||
}
|
||||
if len(resolution.SelectionWarnings) > 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":
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
+13
-12
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+22
-20
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -611,5 +611,5 @@ func ResolveValidProjectTargets(projectRoot string, cfg *ProjectConfig) (resolve
|
||||
resolved[name] = tc
|
||||
}
|
||||
|
||||
return resolved, unresolved
|
||||
return WithSharedSkillsTargets(resolved, "merge"), unresolved
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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})
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 23 and column 89.
|
@@ -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.
|
||||
//
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+70
-11
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
+34
-27
@@ -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/<agent>/<suffix> 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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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/<known agent>/<suffix>.
|
||||
// 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))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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/<known-agent>/<suffix>`
|
||||
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.
|
||||
@@ -25,6 +25,14 @@ Check `skillshare <command> --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/<known-agent>/<skill-path>/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
|
||||
|
||||
@@ -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/<known-agent>/<skill-path>/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.
|
||||
|
||||
@@ -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" {
|
||||
|
||||
@@ -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")) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<string, string>;
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -14,7 +14,7 @@ vi.mock('../../api/client', async (load) => {
|
||||
const actual = await load<typeof import('../../api/client')>();
|
||||
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 } } });
|
||||
|
||||
@@ -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<typeof import('../../api/client')>(), api: { sync: vi.fn(), syncExtras: vi.fn() } }));
|
||||
vi.mock('../../api/mcp', async (load) => ({ ...await load<typeof import('../../api/mcp')>(), 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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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 ? (
|
||||
<button key={e.skill} type="button" className="ss-r link !min-h-[42px] w-full text-left" onClick={() => onChange(next)} title={t(on ? 'targetDetail.clickExclude' : 'targetDetail.clickInclude')} disabled={disabled}>
|
||||
<button key={e.skill} type="button" className="ss-r link !min-h-[42px] w-full text-left" onClick={() => onChange(next)} title={t(on || e.status === 'skipped' ? 'targetDetail.clickExclude' : 'targetDetail.clickInclude')} disabled={disabled}>
|
||||
{cells}
|
||||
</button>
|
||||
) : (
|
||||
|
||||
@@ -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>): 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']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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} گونه"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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} バリアント"
|
||||
}
|
||||
|
||||
@@ -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}개"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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} 个变体"
|
||||
}
|
||||
|
||||
@@ -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} 個變體"
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<string, string[]>();
|
||||
for (const result of scan?.results ?? []) {
|
||||
|
||||
@@ -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'] }) {
|
||||
<Github size={15} />
|
||||
<span className="flex flex-col min-w-0 flex-1 gap-px">
|
||||
<span className="font-mono text-[13px] font-semibold truncate">{repo.name.replace(/^_/, '')}</span>
|
||||
<span className="text-[13px] text-ink-2">{t(plural('dashboard.trackedRepos.skillCount', repo.skillCount), { count: repo.skillCount })}</span>
|
||||
<span className="text-[13px] text-ink-2">{t(plural('dashboard.trackedRepos.skillCount', repo.skillCount), { count: repo.skillCount })}{(repo.variantCount ?? repo.skillCount) > repo.skillCount && <>{', '}{t('dashboard.trackedRepos.variantCount', { count: repo.variantCount! })}</>}</span>
|
||||
</span>
|
||||
<span className={`ss-st ${repo.dirty ? 'warn' : 'ok'}`}>
|
||||
{repo.dirty ? t('dashboard.trackedRepos.modified') : t('dashboard.trackedRepos.clean')}
|
||||
|
||||
@@ -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':
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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() {
|
||||
<TriangleAlert size={15} className="ml-6 shrink-0 text-warn" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<b>{t(plural('sync.skipped', d.skippedCount ?? 0), { count: d.skippedCount ?? 0, name: d.target })}</b>{' '}
|
||||
<span className="text-ink-2">{t(skippedHintKey(d), { name: d.target })}</span>
|
||||
<span className="text-ink-2">{skippedHintKeys(d).map((key) => t(key, { name: d.target })).join(' ')}</span>
|
||||
</span>
|
||||
<Link to={`/targets/${encodeURIComponent(d.target)}`} className="shrink-0 font-semibold">{t('sync.skipped.open')}</Link>
|
||||
</div>
|
||||
|
||||
@@ -39,7 +39,10 @@ function renderPage(codex: Partial<Target>, universal: Partial<Target> = {}) {
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
@@ -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 <div key={warning} className="ss-note warn mb-3" role="status"><span>{diagnostic ? <><span className="font-mono">{diagnostic.path}</span>: {t(diagnostic.key, { name: target.name })}</> : warning}</span></div>;
|
||||
})}
|
||||
|
||||
{tabs.length > 1 && (
|
||||
<nav className="ss-tabs mb-7" aria-label={t('targetDetail.tabs')}>
|
||||
{tabs.filter((k) => k !== 'instructions').map((k) => (
|
||||
@@ -375,8 +381,11 @@ function TargetEditor({ target, targets }: { target: Target; targets: Target[] }
|
||||
<span className="flex items-center gap-1.5 text-[13px] text-ink-3"><Info size={14} className="shrink-0" />{t('targetDetail.prefixedNeedsCopy')}</span>
|
||||
)}
|
||||
{namingClash && sharedNote(namingClash, 'naming')}
|
||||
{saved.naming !== 'flat' && (target.skippedSkillCount ?? 0) > 0 && (
|
||||
<span className="text-[13px] text-warn">{t(plural('targetDetail.skipped', target.skippedSkillCount), { count: target.skippedSkillCount })}</span>
|
||||
{targetSkipHints(target).length > 0 && (
|
||||
<span className="text-[13px] text-warn">
|
||||
{t(plural('sync.skipped', target.skippedSkillCount ?? 0), { count: target.skippedSkillCount ?? 0, name: target.name })}{' '}
|
||||
{targetSkipHints(target).map((key) => t(key, { name: target.name })).join(' ')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -40,6 +40,8 @@ Next
|
||||
skillshare collect copy local-only skills into source
|
||||
```
|
||||
|
||||
Ambiguous agent variants appear as `(skill selection)` skip rows with a diagnostic. Use `include`/`exclude` or a source-local target override to select the desired variant. These rows explain skipped selection; they are not changes that sync can apply.
|
||||
|
||||
## Interactive TUI
|
||||
|
||||
On a TTY, `diff` opens an interactive view: targets on the left, and what differs for the selected target on the right, down to file-level diffs. The keys are listed at the bottom of the screen. Use `--no-tui`, or pipe the output, for plain text.
|
||||
|
||||
@@ -57,6 +57,8 @@ Next
|
||||
skillshare sync bring the targets up to date
|
||||
```
|
||||
|
||||
For tracked repositories with agent variants, the Source line shows `N skills, M variants`: logical skills and physical copies. The `variant_routing` check warns when symlink mode exposes all variants instead of selecting by agent; use merge or copy mode for selective routing.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Something isn't working and you don't know why
|
||||
|
||||
@@ -6,6 +6,10 @@ sidebar_position: 3
|
||||
|
||||
Add skills from GitHub repos, git URLs, or local paths.
|
||||
|
||||
Tracked repositories report `Found N skills, M variants` when agent-specific copies
|
||||
represent fewer logical skills. All physical variants remain installed in the source;
|
||||
merge and copy sync select the matching agent's instructions.
|
||||
|
||||
## Overview
|
||||
|
||||
```mermaid
|
||||
|
||||
@@ -122,7 +122,7 @@ Skills
|
||||
old-draft local · disabled
|
||||
|
||||
Tracked repos
|
||||
✓ _team-skills up to date · 3 skills
|
||||
✓ _team-skills up to date · 3 skills, 5 variants
|
||||
|
||||
8 skills · 3 tracked, 3 remote, 2 local
|
||||
Add -v for sources and install dates
|
||||
@@ -155,7 +155,7 @@ Skills
|
||||
Installed 2026-01-15
|
||||
|
||||
Tracked repos
|
||||
✓ _team-skills up to date · 3 skills
|
||||
✓ _team-skills up to date · 3 skills, 5 variants
|
||||
! _other-repo has changes · 5 skills
|
||||
|
||||
12 skills · 8 tracked, 3 remote, 1 local
|
||||
|
||||
@@ -55,6 +55,8 @@ Version CLI 0.24.0 · skill 0.21.12
|
||||
|
||||
Shows the skills folder and how many skills it holds. When an agents folder exists, it is shown on a second line with its agent count. An active `.skillignore` adds a line with its pattern and ignored-skill counts.
|
||||
|
||||
Source and tracked-repository counts are logical: matching agent-specific copies count as one skill. When the physical count differs, text output shows both, for example `2 skills, 4 variants`. Target linked/copied counts still describe physical entries selected for that target.
|
||||
|
||||
### Tracked Repositories
|
||||
|
||||
Lists git repositories installed with `--track`, each with its skill count. `✓` means the repository is clean; `!` adds `uncommitted changes`, or the git error when its status cannot be read.
|
||||
@@ -86,6 +88,8 @@ Targets skills agents
|
||||
|
||||
**agents column:** `✓ 8` is the number of linked agents (up-to-date copies count as linked). `! 7/8` means some are missing; run `skillshare sync agents`. Only the agents this target syncs count: those left after `.agentignore`, the target's agents include/exclude and each agent's `targets` frontmatter. In copy fallback, identical local files that skillshare does not own are kept and counted as `· 1 local`. `—` means the target has no agents folder. The column is left out when there is no agents source.
|
||||
|
||||
In both global and project mode, `status` and `doctor` warn when agent variants are present and a skills target uses symlink mode: the whole-directory link exposes every variant. Use merge or copy mode for automatic agent routing.
|
||||
|
||||
### Extras
|
||||
|
||||
When extras are configured, each extra target gets a row:
|
||||
@@ -135,9 +139,10 @@ skillshare status --json
|
||||
}
|
||||
},
|
||||
"skill_count": 12,
|
||||
"variant_count": 17,
|
||||
"tracked_repos": [
|
||||
{"name": "_team-skills", "skill_count": 5, "dirty": false},
|
||||
{"name": "_personal-repo", "skill_count": 3, "dirty": true}
|
||||
{"name": "_team-skills", "skill_count": 5, "variant_count": 10, "dirty": false},
|
||||
{"name": "_personal-repo", "skill_count": 3, "variant_count": 3, "dirty": true}
|
||||
],
|
||||
"targets": [
|
||||
{
|
||||
@@ -168,7 +173,9 @@ skillshare status --json
|
||||
}
|
||||
```
|
||||
|
||||
A target gets a `warning` string only when sync would reject it, for example `prefixed` naming outside copy mode; the text says how to fix it.
|
||||
`skill_count` counts logical skills; `variant_count` counts physical source entries. Both fields appear at the top level and in each tracked repository. Target `synced_count` remains a physical count.
|
||||
|
||||
A target can have a `warning` string for a configuration error, such as `prefixed` naming outside copy mode, or for the symlink-mode agent-routing limitation. The text explains how to address it.
|
||||
|
||||
A tracked repo whose git status cannot be read has `"status": "unknown"` and `message` holding the error; `dirty` is then false and not meaningful.
|
||||
|
||||
|
||||
@@ -15,6 +15,14 @@ ownership and conflict checks rather than skill symlinks. See [mcp](/docs/refere
|
||||
Operations like `install` and `uninstall` only modify source — sync propagates to targets. This lets you batch changes, preview with `--dry-run`, and control when targets update. See [Why Sync is a Separate Step](/docs/understand/source-and-targets#why-sync-is-a-separate-step).
|
||||
:::
|
||||
|
||||
## Agent-specific skill variants
|
||||
|
||||
In a tracked repository, `skills/<known-agent>/<skill-path>/SKILL.md` is recognized as an agent-specific variant only when the same complete skill path exists under at least two distinct canonical agents beneath the same `skills/` parent. Aliases of one agent alone do not qualify. A lone category such as `skills/agents/planner` remains an ordinary skill.
|
||||
|
||||
In merge/copy mode, variants route to the matching agent, including aliases and account targets. Compatible targets sharing one skills folder select the union of their agent identities: Codex and `universal` sharing `~/.agents/skills` keep the Codex variants. Each reader sees that shared union; incompatible settings still produce overlap/conflict diagnostics. Explicit source-local target overrides and frontmatter routing retain precedence, and ignores and include/exclude filters still apply.
|
||||
|
||||
Source and repository summaries count logical skills once and show physical variants separately, for example `2 skills, 4 variants`. Per-target sync operations remain physical counts. Whole-directory symlink mode exposes every variant; `status` and `doctor` explain this limitation and recommend merge or copy for automatic routing.
|
||||
|
||||
## When to Use
|
||||
|
||||
- After installing, uninstalling, or editing skills — propagate changes to all targets
|
||||
|
||||
@@ -69,6 +69,56 @@ targets: [claude, cursor]
|
||||
|
||||
**Tracked repos:** targets set in the dashboard for a skill inside a tracked repo are stored in the source's `.metadata.json` instead of its SKILL.md, so the clone stays clean and `update` keeps working. That setting takes precedence over the skill's `metadata.targets`.
|
||||
|
||||
### Agent-specific variants in tracked repositories
|
||||
|
||||
A tracked repository can ship separate instructions for each agent:
|
||||
|
||||
```text
|
||||
_team/internal/skills/claude/review/SKILL.md
|
||||
_team/internal/skills/codex/review/SKILL.md
|
||||
```
|
||||
|
||||
Skillshare recognizes repository-relative `skills/<known-agent>/<skill-path>`
|
||||
layouts automatically, including canonical aliases such as `claude-code` and
|
||||
repositories installed under `--into`. Merge and copy sync select the matching
|
||||
agent's file. A target with `agent: codex`, such as a second Codex account, gets
|
||||
the Codex variant. A shared skills directory does not establish agent identity:
|
||||
`universal` does not automatically receive the Codex variant.
|
||||
|
||||
The repository, complete path before the agent component, and complete path after
|
||||
it identify one logical skill. Different repositories, prefixes, or suffixes
|
||||
stay separate. A single recognized variant still uses agent routing. Unknown
|
||||
agent directories and layouts outside tracked repositories keep ordinary behavior;
|
||||
`shared` and `default` have no inferred fallback meaning.
|
||||
|
||||
Source-local target overrides take precedence over nonempty frontmatter targets,
|
||||
then recognized variant inference, then existing host-style path inference.
|
||||
An empty source-local override means all targets. Explicit target declarations
|
||||
keep their existing matching behavior. Ignores and include/exclude filters apply
|
||||
to physical paths as before. Missing matches select nothing; duplicate canonical
|
||||
aliases in one group are skipped with a sync warning until filters or overrides
|
||||
select one.
|
||||
|
||||
`status` and dashboard source/repository totals count logical skills. Four files
|
||||
for two skills appear as `2 skills, 4 variants` in text status. Status JSON adds
|
||||
`variant_count` beside logical `skill_count`; overview JSON uses `variantCount`,
|
||||
and the targets API exposes `sourceVariantCount`. Variant counts are physical
|
||||
enabled file totals, including ordinary skills. Resource lists, operation IDs,
|
||||
sync totals, and context-cost reports retain physical entries. Source files are
|
||||
unchanged; existing prefixed copy naming can still rewrite the copy's `name:`.
|
||||
|
||||
Full-directory symlink mode exposes every source variant and cannot enforce
|
||||
this routing. Use merge or copy for agent selection. Targets sharing a destination
|
||||
directory also cannot keep different selections isolated; existing overlap
|
||||
diagnostics apply. Sparse checkout is not supported by this recognition.
|
||||
|
||||
After upgrading, merge/copy sync removes previously managed variants whose agent
|
||||
does not match the target. The CLI and server warn when automatic agent routing
|
||||
removes those entries, including during dry-run. Set a source-local target override
|
||||
for the desired variant to restore it; an empty override restores all-target routing.
|
||||
The source files remain intact. The targets column shows effective routing, including
|
||||
inference; it does not imply that the producer declared that field.
|
||||
|
||||
**Aliases:** Target names support aliases. `claude` matches a target configured as `claude-code`. See [Supported Targets](/docs/reference/targets/supported-targets).
|
||||
|
||||
📖 [Skill format — targets field](/docs/understand/skill-format#targets)
|
||||
|
||||
@@ -40,6 +40,8 @@ Next
|
||||
skillshare collect copy local-only skills into source
|
||||
```
|
||||
|
||||
エージェントのバリアントが曖昧な場合、診断付きの `(skill selection)` スキップ行が表示されます。`include`/`exclude` またはソース側のターゲット上書きで必要なバリアントを選択してください。この行は選択がスキップされた理由を示し、sync で適用できる変更ではありません。
|
||||
|
||||
## インタラクティブ TUI
|
||||
|
||||
TTY 上では、`diff` はインタラクティブな画面を開きます。左側にターゲット、右側に選択したターゲットの差分が表示され、ファイル単位の diff まで確認できます。キーは画面下部に表示されます。プレーンテキストにするには `--no-tui` を使うか、出力をパイプしてください。
|
||||
|
||||
@@ -57,6 +57,8 @@ Next
|
||||
skillshare sync bring the targets up to date
|
||||
```
|
||||
|
||||
エージェント別バリアントを含む追跡リポジトリでは、Source 行に `N skills, M variants`(論理スキル数と物理コピー数)が表示されます。`variant_routing` チェックは、symlink モードがエージェント別に選択せず全バリアントを公開する場合に警告します。選択的なルーティングには merge または copy モードを使用してください。
|
||||
|
||||
## 使うタイミング
|
||||
|
||||
- 何かがうまく動かないが、原因がわからないとき
|
||||
|
||||
@@ -6,6 +6,8 @@ sidebar_position: 3
|
||||
|
||||
GitHub リポジトリ、git URL、またはローカルパスから Skill を追加します。
|
||||
|
||||
Tracked repo の Agent 別コピーが少数の論理 Skill を表す場合、`Found N skills, M variants` と表示します。すべての物理バリアントを Source に保持し、merge/copy Sync は一致する Agent の指示を選択します。
|
||||
|
||||
## 概要
|
||||
|
||||
```mermaid
|
||||
|
||||
@@ -120,7 +120,7 @@ Skills
|
||||
old-draft local · disabled
|
||||
|
||||
Tracked repos
|
||||
✓ _team-skills up to date · 3 skills
|
||||
✓ _team-skills up to date · 3 skills, 5 variants
|
||||
|
||||
8 skills · 3 tracked, 3 remote, 2 local
|
||||
Add -v for sources and install dates
|
||||
@@ -153,7 +153,7 @@ Skills
|
||||
Installed 2026-01-15
|
||||
|
||||
Tracked repos
|
||||
✓ _team-skills up to date · 3 skills
|
||||
✓ _team-skills up to date · 3 skills, 5 variants
|
||||
! _other-repo has changes · 5 skills
|
||||
|
||||
12 skills · 8 tracked, 3 remote, 1 local
|
||||
|
||||
+10
-3
@@ -55,6 +55,8 @@ Version CLI 0.24.0 · skill 0.21.12
|
||||
|
||||
skills フォルダとその中の skill 数を表示します。agents フォルダがある場合は、2 行目にフォルダと agent 数を表示します。`.skillignore` が有効な場合は、パターン数と除外された skill 数の行が加わります。
|
||||
|
||||
Source と tracked repository の数は論理スキル数です。対応するエージェント別コピーは一つのスキルとして数えます。物理的な数が異なる場合は `2 skills, 4 variants` のように両方を表示します。Target の linked/copied 数は、その target に選択された物理エントリ数のままです。
|
||||
|
||||
### Tracked Repositories
|
||||
|
||||
`--track` でインストールした git リポジトリと、それぞれの skill 数を一覧表示します。`✓` はリポジトリに未コミットの変更がないことを示します。`!` には `uncommitted changes`、または git status を読み取れない場合はそのエラーが付きます。
|
||||
@@ -86,6 +88,8 @@ Targets skills agents
|
||||
|
||||
**agents 列:** `✓ 8` はリンク済みの agent 数です(最新のコピーもリンク済みとして数えます)。`! 7/8` は一部が欠けていることを示します。`skillshare sync agents` を実行してください。数えるのはこの target が sync する agent だけで、`.agentignore`、target の agents の include/exclude、各 agent の `targets` frontmatter で残ったものです。copy fallback では、skillshare が所有していない同一内容のローカルファイルは保持され、`· 1 local` として数えられます。`—` はその target に agents フォルダがないことを示します。agents source がない場合、この列は省略されます。
|
||||
|
||||
グローバル・プロジェクト両モードで、エージェント別バリアントが存在し、skills target が symlink mode を使う場合、`status` と `doctor` は警告します。ディレクトリ全体へのリンクはすべてのバリアントを公開するためです。エージェント別の自動ルーティングには merge または copy mode を使ってください。
|
||||
|
||||
### Extras
|
||||
|
||||
extras を設定している場合、extra の target ごとに 1 行表示します:
|
||||
@@ -135,9 +139,10 @@ skillshare status --json
|
||||
}
|
||||
},
|
||||
"skill_count": 12,
|
||||
"variant_count": 17,
|
||||
"tracked_repos": [
|
||||
{"name": "_team-skills", "skill_count": 5, "dirty": false},
|
||||
{"name": "_personal-repo", "skill_count": 3, "dirty": true}
|
||||
{"name": "_team-skills", "skill_count": 5, "variant_count": 10, "dirty": false},
|
||||
{"name": "_personal-repo", "skill_count": 3, "variant_count": 3, "dirty": true}
|
||||
],
|
||||
"targets": [
|
||||
{
|
||||
@@ -168,7 +173,9 @@ skillshare status --json
|
||||
}
|
||||
```
|
||||
|
||||
`warning` 文字列は、sync がその Target を拒否する場合(例:copy 以外の mode での `prefixed` naming)にのみ付き、修正方法も示されます。
|
||||
`skill_count` は論理スキル数、`variant_count` は物理ソースエントリ数です。トップレベルと各 tracked repository に両方のフィールドを含みます。Target の `synced_count` は物理的な数のままです。
|
||||
|
||||
Target の `warning` は、copy 以外の mode での `prefixed` naming などの設定エラーや、symlink mode のエージェントルーティング制限を示します。対処方法も表示します。
|
||||
|
||||
git status を読み取れない tracked repo は `"status": "unknown"` となり、`message` にエラーが入ります。この場合 `dirty` は false で、意味を持ちません。
|
||||
|
||||
|
||||
@@ -14,6 +14,14 @@ MCP 接続設定には `skillshare sync mcp` を、skills、agents、extras、MC
|
||||
`install` や `uninstall` のような操作は source のみを変更します — sync は targets に反映します。これにより、変更をバッチ処理し、`--dry-run` でプレビューし、targets が更新されるタイミングを制御できます。[Why Sync is a Separate Step](/docs/understand/source-and-targets#why-sync-is-a-separate-step) を参照してください。
|
||||
:::
|
||||
|
||||
## エージェント別スキルバリアント
|
||||
|
||||
Tracked repository 内の `skills/<known-agent>/<skill-path>/SKILL.md` は、同じ `skills/` 親ディレクトリ内の二つ以上の異なる正規エージェントに同じ完全なスキルパスがある場合にのみ、エージェント別バリアントと認識されます。一つのエージェントの別名だけでは該当しません。単独の `skills/agents/planner` カテゴリは通常のスキルのままです。
|
||||
|
||||
Merge/copy mode では、別名やアカウント target を含め、対応するエージェントにルーティングします。同じ skills フォルダを共有する互換性のある targets は、エージェント ID の和集合を選択します。Codex と `universal` が `~/.agents/skills` を共有する場合、Codex のバリアントが保持されます。各読み取り側にはこの和集合が公開され、互換性のない設定には重複・競合の診断が引き続き表示されます。明示的なソースローカル target 上書きと frontmatter のルーティングが優先され、無視規則と include/exclude フィルタも適用されます。
|
||||
|
||||
Source と repository の概要は論理スキルを一度だけ数え、`2 skills, 4 variants` のように物理バリアントを別に表示します。Target ごとの同期操作は物理的な数のままです。ディレクトリ全体の symlink mode はすべてのバリアントを公開します。`status` と `doctor` はこの制限を説明し、自動ルーティングには merge または copy を推奨します。
|
||||
|
||||
## 使うタイミング
|
||||
|
||||
- Skill をインストール、uninstall、編集した後 — 変更をすべての targets に反映する
|
||||
|
||||
@@ -79,6 +79,25 @@ targets: [claude, cursor]
|
||||
|
||||
**Tracked repo:** dashboard で tracked repo 内の Skill に設定した targets は、その SKILL.md ではなく source の `.metadata.json` に保存される。そのため clone はクリーンなままで、`update` も通常どおり動作する。この設定は Skill の `metadata.targets` より優先される。
|
||||
|
||||
### Tracked repo 内の Agent 別バリアント {#agent-specific-variants-in-tracked-repositories}
|
||||
|
||||
```text
|
||||
_team/internal/skills/claude/review/SKILL.md
|
||||
_team/internal/skills/codex/review/SKILL.md
|
||||
```
|
||||
|
||||
Tracked repo 内の `skills/<既知の-agent>/<完全なスキルパス>/SKILL.md` は Agent 別バリアントとして自動認識されます。例:`_team/internal/skills/{claude,codex}/review/SKILL.md`。リポジトリ、Agent より前の完全なパス、Agent より後の完全なパスで1つの論理 Skill を識別します。バリアントが1つだけでも Agent による振り分けが適用され、`--into` 配下のリポジトリも対象です。
|
||||
|
||||
**merge/copy:** 一致する Agent のファイルだけを選択します。`claude-code` などの登録済みエイリアスと、アカウント Target の `agent: codex` にも対応します。ディレクトリの共有は Agent の同一性を意味せず、`universal` が Codex バリアントを自動で受け取ることはありません。一致がなければ他のバリアントで代用せず、同じグループに同一 Agent のエイリアスが重複する場合は警告してスキップします。フィルターや上書き設定で明示的に選択してください。
|
||||
|
||||
優先順位は Source の `.metadata.json` にある Target の上書き > 空でない frontmatter targets > バリアントの Agent 推論 > 従来のホストパス推論です。Source の空の上書きは全 Target を意味し、明示的な Target 宣言の既存の照合規則は維持されます。`.skillignore` と include/exclude は引き続き物理パスに適用されます。未知の Agent、`shared`/`default`、tracked repo 外の配置は通常の discovery のままで、代替バリアントは推論しません。
|
||||
|
||||
`status` と dashboard の Source/リポジトリ総数は論理 Skill 数です。2つの Skill の4ファイルは `2 skills, 4 variants` と表示されます。JSON の `skill_count`/`skillCount` は論理数、`variant_count`/`variantCount` と Target API の `sourceVariantCount` は通常の Skill を含む有効な物理ファイル総数です。リソース一覧、操作 ID、Sync 結果、コンテキストコストは物理ファイル単位のままです。
|
||||
|
||||
**symlink:** ディレクトリ全体が公開されるため、バリアントの振り分けは適用できません。Agent ごとの選択には merge/copy を使ってください。同じ出力ディレクトリを共有する Target 間でも異なる選択を分離できず、既存のパス重複診断が適用されます。Source ファイルは変更しませんが、従来の prefixed copy 命名ではコピーの `name:` が書き換わる場合があります。Sparse checkout は行いません。
|
||||
|
||||
アップグレード後の merge/copy は、Agent が一致しない既存の管理対象バリアントを Target から削除します。CLI/サーバーの警告で自動ルーティングによる削除と復元方法を説明し、dry-run でも通知します。Source の Target 上書きで必要なコピーを復元でき、空の上書きは全 Target を意味します。Source ファイルは残ります。Target 欄は推論を含む有効なルーティングを示し、提供元の宣言とは限りません。
|
||||
|
||||
**エイリアス:** Target 名はエイリアスに対応しています。`claude` は `claude-code` として設定された
|
||||
Target に一致します。[対応する Target](/docs/reference/targets/supported-targets) を参照してください。
|
||||
|
||||
|
||||
@@ -40,6 +40,8 @@ Next
|
||||
skillshare collect copy local-only skills into source
|
||||
```
|
||||
|
||||
에이전트 변형이 모호하면 진단과 함께 `(skill selection)` 건너뛰기 행이 표시됩니다. `include`/`exclude` 또는 소스의 대상 재정의로 원하는 변형을 선택하세요. 이 행은 선택을 건너뛴 이유를 설명하며 sync로 적용할 변경 사항이 아닙니다.
|
||||
|
||||
## 인터랙티브 TUI
|
||||
|
||||
TTY에서 `diff`는 대화형 화면을 엽니다. 왼쪽에는 target, 오른쪽에는 선택한 target의 차이가 표시되며 파일 단위 diff까지 볼 수 있습니다. 키는 화면 아래쪽에 표시됩니다. 일반 텍스트로 보려면 `--no-tui`를 사용하거나 출력을 파이프하세요.
|
||||
|
||||
@@ -57,6 +57,8 @@ Next
|
||||
skillshare sync bring the targets up to date
|
||||
```
|
||||
|
||||
에이전트 변형이 있는 추적 저장소의 Source 줄에는 `N skills, M variants`가 표시됩니다. 이는 논리적 스킬 수와 물리적 복사본 수입니다. `variant_routing` 검사는 symlink 모드가 에이전트별 선택 없이 모든 변형을 노출할 때 경고합니다. 선택적 라우팅에는 merge 또는 copy 모드를 사용하세요.
|
||||
|
||||
## 사용 시점
|
||||
|
||||
- 뭔가 작동하지 않는데 원인을 모를 때
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user