From a9ae5349a2d3556b62277f1e0bfbd9166d164895 Mon Sep 17 00:00:00 2001 From: Willie Date: Thu, 8 Oct 2026 15:30:14 +0800 Subject: [PATCH 1/5] feat(extras): choose which files each target syncs, and edit targets in place A directory extra used to sync every file to every target, so a tool that only wanted a few docs got the whole folder. Each target can now set gitignore-style include/exclude patterns, matched on the path inside the source. Merge targets prune links to files that stop matching; copy targets keep earlier copies, since nothing records which copied files are ours. Filters are rejected for symlink mode and single-file extras, and sync warns when an include matches nothing. The dashboard previously forced users to delete and re-add a target or an extra to change it. Edit target now changes the folder, file name, mode, flatten and filters with a live preview; Edit extra renames an extra or points it at another source folder. A moved target or source drops the links left at the old place and syncs right away. CLI: --include/--exclude on extras init, and --add-include, --add-exclude, --remove-include, --remove-exclude on extras . Refs #435 --- cmd/skillshare/completion_bash.go | 4 +- cmd/skillshare/completion_fish.go | 6 + cmd/skillshare/completion_nushell.go | 6 + cmd/skillshare/completion_powershell.go | 2 +- cmd/skillshare/completion_zsh.go | 6 + cmd/skillshare/diff_extras.go | 1 + cmd/skillshare/extras.go | 3 +- cmd/skillshare/extras_collect.go | 8 +- cmd/skillshare/extras_init.go | 20 +- cmd/skillshare/extras_init_prompt.go | 2 + cmd/skillshare/extras_list.go | 2 +- cmd/skillshare/extras_list_tui.go | 2 +- cmd/skillshare/extras_mode.go | 45 ++- cmd/skillshare/extras_remove_target.go | 1 + cmd/skillshare/status_render.go | 2 +- internal/config/config.go | 5 + internal/config/extras_validate.go | 29 ++ internal/config/extras_validate_file_test.go | 4 + internal/server/handler_extras.go | 23 +- internal/server/handler_extras_edit.go | 347 ++++++++++++++++++ internal/server/handler_extras_edit_test.go | 141 +++++++ internal/server/server.go | 3 + internal/sync/extras.go | 34 +- internal/sync/extras_filter.go | 127 +++++++ internal/sync/extras_filter_test.go | 107 ++++++ internal/sync/extras_run.go | 2 +- internal/sync/extras_test.go | 18 +- schemas/config.schema.json | 12 + schemas/project-config.schema.json | 12 + skills/skillshare/references/extras.md | 11 + tests/integration/extras_filter_test.go | 92 +++++ ui/src/api/extras.ts | 19 +- ui/src/api/types/extras.ts | 16 + ui/src/components/extras/ExtraEditDialogs.tsx | 315 ++++++++++++++++ ui/src/components/targets/FilterSection.tsx | 38 +- ui/src/i18n/locales/de.json | 31 +- ui/src/i18n/locales/en.json | 31 +- ui/src/i18n/locales/es.json | 31 +- ui/src/i18n/locales/fa.json | 31 +- ui/src/i18n/locales/fr.json | 31 +- ui/src/i18n/locales/id.json | 31 +- ui/src/i18n/locales/ja.json | 31 +- ui/src/i18n/locales/ko.json | 31 +- ui/src/i18n/locales/pt-BR.json | 31 +- ui/src/i18n/locales/zh-CN.json | 31 +- ui/src/i18n/locales/zh-TW.json | 31 +- ui/src/lib/queryKeys.ts | 1 + ui/src/pages/ExtrasPage.test.tsx | 31 ++ ui/src/pages/ExtrasPage.tsx | 42 ++- website/docs/reference/commands/extras.md | 56 ++- .../docs/reference/targets/configuration.md | 2 + .../current/reference/commands/extras.md | 45 ++- .../reference/targets/configuration.md | 2 + .../current/reference/commands/extras.md | 45 ++- .../reference/targets/configuration.md | 2 + .../current/reference/commands/extras.md | 45 ++- .../reference/targets/configuration.md | 2 + .../current/reference/commands/extras.md | 45 ++- .../reference/targets/configuration.md | 2 + 59 files changed, 2028 insertions(+), 98 deletions(-) create mode 100644 internal/server/handler_extras_edit.go create mode 100644 internal/server/handler_extras_edit_test.go create mode 100644 internal/sync/extras_filter.go create mode 100644 internal/sync/extras_filter_test.go create mode 100644 tests/integration/extras_filter_test.go create mode 100644 ui/src/components/extras/ExtraEditDialogs.tsx diff --git a/cmd/skillshare/completion_bash.go b/cmd/skillshare/completion_bash.go index 989bd7bde..8735c286e 100644 --- a/cmd/skillshare/completion_bash.go +++ b/cmd/skillshare/completion_bash.go @@ -70,8 +70,8 @@ _skillshare() { local enable_flags="--dry-run -n --kind --help -h" local disable_flags="--dry-run -n --kind --help -h" local analyze_flags="--verbose -v --filter --no-tui --json --help -h" - local extras_flags="--mode --target --flatten --no-flatten --add-target --as --remove-target --prune --help -h" - local extras_init_flags="--target --mode --source --file --as --flatten --force --no-tui --help -h" + local extras_flags="--mode --target --flatten --no-flatten --add-include --add-exclude --remove-include --remove-exclude --add-target --as --remove-target --prune --help -h" + local extras_init_flags="--target --mode --source --file --as --flatten --include --exclude --force --no-tui --help -h" local extras_list_flags="--json --no-tui --help -h" local extras_remove_flags="--force -f --help -h" local extras_collect_flags="--from --dry-run --force -f --help -h" diff --git a/cmd/skillshare/completion_fish.go b/cmd/skillshare/completion_fish.go index bd4c868f2..21c5c9a80 100644 --- a/cmd/skillshare/completion_fish.go +++ b/cmd/skillshare/completion_fish.go @@ -424,6 +424,8 @@ complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l mo complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l source -r -F -d 'Custom source directory' complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l file -r -F -d 'Single-file extra' complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l as -r -d 'Target filename' +complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l include -r -d 'Sync only matching files' +complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l exclude -r -d 'Skip matching files' complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l flatten -d 'Flatten subdirectory files' complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l force -d 'Overwrite existing extra' complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l no-tui -d 'Skip interactive TUI' @@ -437,6 +439,10 @@ complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fis complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l target -r -F -d 'Target for --mode' complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l flatten -d 'Enable flatten' complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l no-flatten -d 'Disable flatten' +complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l add-include -r -d 'Add an include pattern' +complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l add-exclude -r -d 'Add an exclude pattern' +complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l remove-include -r -d 'Remove an include pattern' +complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l remove-exclude -r -d 'Remove an exclude pattern' complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l add-target -r -F -d 'Add a target' complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l as -r -d 'Target filename' complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l remove-target -r -F -d 'Detach a target' diff --git a/cmd/skillshare/completion_nushell.go b/cmd/skillshare/completion_nushell.go index d8f3da431..67fa9f092 100644 --- a/cmd/skillshare/completion_nushell.go +++ b/cmd/skillshare/completion_nushell.go @@ -689,6 +689,12 @@ export extern "skillshare extras" [ --as: string # Target filename --flatten # Flatten subdirectory files --no-flatten # Disable flatten + --include: string # init: sync only matching files + --exclude: string # init: skip matching files + --add-include: string # Add an include pattern + --add-exclude: string # Add an exclude pattern + --remove-include: string # Remove an include pattern + --remove-exclude: string # Remove an exclude pattern --add-target: string # Add a target --remove-target: string # Detach a target --prune # With --remove-target: delete managed files diff --git a/cmd/skillshare/completion_powershell.go b/cmd/skillshare/completion_powershell.go index 350ae5029..d75f54f08 100644 --- a/cmd/skillshare/completion_powershell.go +++ b/cmd/skillshare/completion_powershell.go @@ -211,7 +211,7 @@ $_skillshareCompleter = { 'mcp' = '--tools-allow', '--tools-deny', '--pi-options', '--target', '--from', '--url', '--file', '--sync', '--replace', '--disabled', '--keep-files', '--revision', '--dry-run', '-n', '--json', '--no-dns', '--live', '--timeout', '--http', '--tls-cert', '--tls-key', '--check', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g' 'plugin' = '--target', '--from', '--plugin', '--name', '--source-ref', '--entry', '--revision', '--dry-run', '-n', '--json', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g' 'extras memory' = '--from', '--version', '--search', '--update-mode', '--json', '--help', '-h', '--project', '-p', '--global', '-g' - 'extras' = '--mode', '--target', '--source', '--file', '--as', '--flatten', '--no-flatten', '--add-target', '--remove-target', '--prune', '--from', '--dry-run', '--force', '-f', '--json', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g' + 'extras' = '--mode', '--target', '--source', '--file', '--as', '--flatten', '--no-flatten', '--include', '--exclude', '--add-include', '--add-exclude', '--remove-include', '--remove-exclude', '--add-target', '--remove-target', '--prune', '--from', '--dry-run', '--force', '-f', '--json', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g' 'status' = '--json', '--help', '-h', '--project', '-p', '--global', '-g' 'new' = '--pattern', '-P', '--dry-run', '-n', '--help', '-h', '--project', '-p', '--global', '-g' 'search' = '--json', '--list', '-l', '--hub', '--limit', '-n', '--help', '-h', '--project', '-p', '--global', '-g' diff --git a/cmd/skillshare/completion_zsh.go b/cmd/skillshare/completion_zsh.go index 013544723..83d15313d 100644 --- a/cmd/skillshare/completion_zsh.go +++ b/cmd/skillshare/completion_zsh.go @@ -667,6 +667,8 @@ _skillshare() { '--file[Single-file extra]:file:_files' '--as[Target filename]:filename:' '--flatten[Flatten subdirectory files]' + '*--include[Sync only matching files]:pattern:' + '*--exclude[Skip matching files]:pattern:' '--force[Overwrite existing extra]' '--no-tui[Skip interactive TUI]' ) @@ -699,6 +701,10 @@ _skillshare() { '--target[Target for --mode]:path:_files -/' '--flatten[Enable flatten]' '--no-flatten[Disable flatten]' + '*--add-include[Add an include pattern]:pattern:' + '*--add-exclude[Add an exclude pattern]:pattern:' + '*--remove-include[Remove an include pattern]:pattern:' + '*--remove-exclude[Remove an exclude pattern]:pattern:' '--add-target[Add a target]:path:_files -/' '--as[Target filename]:filename:' '--remove-target[Detach a target]:path:_files -/' diff --git a/cmd/skillshare/diff_extras.go b/cmd/skillshare/diff_extras.go index 35e658644..cdd7f82e7 100644 --- a/cmd/skillshare/diff_extras.go +++ b/cmd/skillshare/diff_extras.go @@ -70,6 +70,7 @@ func collectExtrasDiff(extras []config.ExtraConfig, sourceResolver func(config.E } for _, t := range extra.Targets { + files := sync.ExtraTargetFiles(files, t) mode := sync.ExtraTargetMode(t.Mode, extra.File != "") r := extraDiffResult{ extraName: extra.Name, diff --git a/cmd/skillshare/extras.go b/cmd/skillshare/extras.go index 97c190cc5..ab0af75ec 100644 --- a/cmd/skillshare/extras.go +++ b/cmd/skillshare/extras.go @@ -19,7 +19,8 @@ func cmdExtras(args []string) error { if hasFlag(args, "--remove-target") { return cmdExtrasRemoveTarget(args) } - if sub != "init" && (hasFlag(args, "--mode") || hasFlag(args, "--flatten") || hasFlag(args, "--no-flatten")) { + if sub != "init" && (hasFlag(args, "--mode") || hasFlag(args, "--flatten") || hasFlag(args, "--no-flatten") || + hasFlag(args, "--add-include") || hasFlag(args, "--add-exclude") || hasFlag(args, "--remove-include") || hasFlag(args, "--remove-exclude")) { return cmdExtrasMode(args) } diff --git a/cmd/skillshare/extras_collect.go b/cmd/skillshare/extras_collect.go index 6a2360010..9822859a1 100644 --- a/cmd/skillshare/extras_collect.go +++ b/cmd/skillshare/extras_collect.go @@ -83,7 +83,7 @@ func extrasCollectGlobal(name, fromPath string, dryRun, force bool, start time.T } sourceDir := config.ResolveExtrasSourceDir(*extra, cfg.EffectiveExtrasSource(), cfg.EffectiveSkillsSource()) - return runCollect(sourceDir, targetPath, extra.Name, target.Mode, dryRun, force, target.Flatten, "global", config.ConfigPath(), start, "") + return runCollect(sourceDir, targetPath, extra.Name, target, dryRun, force, "global", config.ConfigPath(), start, "") } func extrasCollectProject(cwd, name, fromPath string, dryRun, force bool, start time.Time) error { @@ -109,7 +109,7 @@ func extrasCollectProject(cwd, name, fromPath string, dryRun, force bool, start } sourceDir := config.ResolveExtrasSourceDirProject(*extra, projCfg.EffectiveExtrasSource(cwd), cwd) - return runCollect(sourceDir, expandedPath, extra.Name, target.Mode, dryRun, force, target.Flatten, "project", config.ProjectConfigPath(cwd), start, cwd) + return runCollect(sourceDir, expandedPath, extra.Name, target, dryRun, force, "project", config.ProjectConfigPath(cwd), start, cwd) } // errSingleFileCollect: collect walks a whole target directory, which for a @@ -148,8 +148,8 @@ func resolveCollectExtra(extras []config.ExtraConfig, name, fromPath string, mod return found, config.ExtraTargetConfig{Path: fromPath}, nil } -func runCollect(sourceDir, targetPath, name, mode string, dryRun, force, flatten bool, scope, cfgPath string, start time.Time, projectRoot string) error { - result, err := sync.CollectExtraFiles(sourceDir, targetPath, mode, dryRun, force, flatten, projectRoot) +func runCollect(sourceDir, targetPath, name string, target config.ExtraTargetConfig, dryRun, force bool, scope, cfgPath string, start time.Time, projectRoot string) error { + result, err := sync.CollectExtraFiles(sourceDir, targetPath, target.Mode, dryRun, force, target.Flatten, projectRoot, target.Include, target.Exclude) if err != nil { return err } diff --git a/cmd/skillshare/extras_init.go b/cmd/skillshare/extras_init.go index 305027b54..b2f122284 100644 --- a/cmd/skillshare/extras_init.go +++ b/cmd/skillshare/extras_init.go @@ -15,7 +15,7 @@ import ( func cmdExtrasInit(args []string) error { start := time.Now() - mode, rest, err := parseModeArgs(args, "--target", "--mode", "--source", "--file", "--as") + mode, rest, err := parseModeArgs(args, "--target", "--mode", "--source", "--file", "--as", "--include", "--exclude") if err != nil { return err } @@ -35,6 +35,7 @@ func cmdExtrasInit(args []string) error { var syncMode string var sourceOverride string var file, as string + var include, exclude []string var force bool var noTUI bool var flatten bool @@ -70,6 +71,16 @@ func cmdExtrasInit(args []string) error { } i++ as = rest[i] + case "--include", "--exclude": + if i+1 >= len(rest) { + return fmt.Errorf("%s requires a pattern", rest[i]) + } + if rest[i] == "--include" { + include = append(include, rest[i+1]) + } else { + exclude = append(exclude, rest[i+1]) + } + i++ case "--flatten": flatten = true case "--force": @@ -101,7 +112,7 @@ func cmdExtrasInit(args []string) error { initTargets := make([]extrasInitTarget, 0, len(targets)) for _, t := range targets { - initTargets = append(initTargets, extrasInitTarget{path: t, mode: syncMode, flatten: flatten, as: as}) + initTargets = append(initTargets, extrasInitTarget{path: t, mode: syncMode, flatten: flatten, as: as, include: include, exclude: exclude}) } opts := extrasInitOptions{name: name, source: sourceOverride, file: file, targets: initTargets, force: force} if err := validateExtrasInit(opts); err != nil { @@ -130,7 +141,7 @@ type extrasInitOptions struct { func (o extrasInitOptions) extra() config.ExtraConfig { extra := config.ExtraConfig{Name: o.name, Source: o.source, File: o.file} for _, t := range o.targets { - et := config.ExtraTargetConfig{Path: t.path, Flatten: t.flatten, As: t.as} + et := config.ExtraTargetConfig{Path: t.path, Flatten: t.flatten, As: t.as, Include: t.include, Exclude: t.exclude} if t.mode != "" { et.Mode = t.mode } @@ -336,6 +347,8 @@ func printExtrasInitHelp() { {"--as ", "Target filename for every --target (requires --file; default: the --file name)"}, {"--mode ", "Sync mode: merge (default), copy, symlink; import, prepend or append for single-file extras"}, {"--flatten", "Flatten files from subdirectories into target root (folder extras only)"}, + {"--include ", "Sync only files matching this .gitignore pattern (repeatable; folder extras only)"}, + {"--exclude ", "Skip files matching this .gitignore pattern (repeatable; folder extras only)"}, {"--force", "Overwrite if extra already exists"}, {"-p, --project", "Create in project mode (.skillshare/)"}, {"-g, --global", "Create in global mode (~/.config/skillshare/)"}, @@ -347,6 +360,7 @@ func printExtrasInitHelp() { helpRow{"skillshare extras init rules --source ~/company-shared/rules --target ~/.claude/rules", ""}, helpRow{"skillshare extras init rules --target ~/.claude/rules --force", ""}, helpRow{"skillshare extras init agents --target ~/.claude/agents --flatten", ""}, + helpRow{"skillshare extras init docs --target ~/.claude/docs --include index.md --include learning.md", ""}, helpRow{"skillshare extras init prompts --target .claude/prompts -p", ""}, helpRow{"skillshare extras init review -p --source .skillshare/extras/prompts \\", ""}, helpRow{" --file review.md --target .claude/commands", ""}, diff --git a/cmd/skillshare/extras_init_prompt.go b/cmd/skillshare/extras_init_prompt.go index 05e361e70..f966b8f8f 100644 --- a/cmd/skillshare/extras_init_prompt.go +++ b/cmd/skillshare/extras_init_prompt.go @@ -22,6 +22,8 @@ type extrasInitTarget struct { mode string flatten bool as string // single file: target filename ("" = the source file name) + include []string + exclude []string } // extrasInitAnswers is what the extras init questions collect. diff --git a/cmd/skillshare/extras_list.go b/cmd/skillshare/extras_list.go index cd7d37d10..6139095cf 100644 --- a/cmd/skillshare/extras_list.go +++ b/cmd/skillshare/extras_list.go @@ -90,7 +90,7 @@ func buildExtrasListEntries(extras []config.ExtraConfig, extrasSource, extension } else if _, err := os.Stat(resolvedPath); os.IsNotExist(err) { ti.Status = "not synced" } else { - ti.Status = sync.CheckSyncStatus(files, sourceDir, resolvedPath, m, t.Flatten, outputExt) + ti.Status = sync.CheckSyncStatus(sync.ExtraTargetFiles(files, t), sourceDir, resolvedPath, m, t.Flatten, outputExt) } entry.Targets = append(entry.Targets, ti) diff --git a/cmd/skillshare/extras_list_tui.go b/cmd/skillshare/extras_list_tui.go index 2d6432ca3..736dff0f1 100644 --- a/cmd/skillshare/extras_list_tui.go +++ b/cmd/skillshare/extras_list_tui.go @@ -1078,7 +1078,7 @@ func (m extrasListTUIModel) doCollect(name, targetPath string) (string, error) { collected := 0 for _, t := range targets { resolved := config.ExpandPath(t.Path) - result, err := sync.CollectExtraFiles(sourceDir, resolved, t.Mode, false, false, t.Flatten, m.projectRoot()) + result, err := sync.CollectExtraFiles(sourceDir, resolved, t.Mode, false, false, t.Flatten, m.projectRoot(), t.Include, t.Exclude) if err != nil { return "", fmt.Errorf("collect from %s: %w", t.Path, err) } diff --git a/cmd/skillshare/extras_mode.go b/cmd/skillshare/extras_mode.go index f294090b4..3e20b0d06 100644 --- a/cmd/skillshare/extras_mode.go +++ b/cmd/skillshare/extras_mode.go @@ -14,10 +14,18 @@ import ( func cmdExtrasMode(args []string) error { start := time.Now() - mode, rest, err := parseModeArgs(args, "--target", "--mode") + mode, rest, err := parseModeArgs(args, "--target", "--mode", "--add-include", "--add-exclude", "--remove-include", "--remove-exclude") if err != nil { return err } + parsedFilters, rest, err := parseFilterFlags(rest) + if err != nil { + return err + } + if parsedFilters.Agents.hasUpdates() { + return fmt.Errorf("agent filter flags are not supported for extras; use --add-include/--add-exclude/--remove-include/--remove-exclude") + } + filters := parsedFilters.Skills cwd, _ := os.Getwd() mode = resolveAutoMode(mode, cwd) @@ -62,8 +70,8 @@ func cmdExtrasMode(args []string) error { if name == "" { return fmt.Errorf("extras name is required: skillshare extras --mode [--target ]") } - if syncMode == "" && !flattenSet { - return fmt.Errorf("--mode or --flatten/--no-flatten is required") + if syncMode == "" && !flattenSet && !filters.hasUpdates() { + return fmt.Errorf("--mode, --flatten/--no-flatten, or an include/exclude flag is required") } if syncMode != "" { @@ -161,7 +169,21 @@ func cmdExtrasMode(args []string) error { return err } } - if _, updated := findExtraByName(extras, name); updated.File != "" || config.ManagedExtraMode(syncMode) { + var filterChanges []string + if filters.hasUpdates() { + var filterErr error + if err := applyExtraTarget(extras, name, targetPath, func(t *config.ExtraTargetConfig) { + filterChanges, filterErr = applyFilterUpdates(&t.Include, &t.Exclude, filters) + }); err != nil { + return err + } + if filterErr != nil { + return filterErr + } + } + // Filters rule out single files and symlink mode, so check them whenever + // either side changes. + if _, updated := findExtraByName(extras, name); updated.File != "" || config.ManagedExtraMode(syncMode) || syncMode == "symlink" || filters.hasUpdates() { if err := config.ValidateExtraConfig(updated); err != nil { return err } @@ -182,10 +204,17 @@ func cmdExtrasMode(args []string) error { if flattenSet { parts = append(parts, fmt.Sprintf("flatten=%v", flattenVal)) } + parts = append(parts, filterChanges...) + if len(parts) == 0 { + parts = append(parts, "no changes") + } ui.Done(ui.MarkOK, fmt.Sprintf("Updated %s target %s: %s", name, shortenPath(targetPath), strings.Join(parts, ", ")), 0) e := oplog.NewEntry("extras-mode", "ok", time.Since(start)) e.Args = map[string]any{"name": name, "target": targetPath, "mode": syncMode, "flatten": flattenVal} + if len(filterChanges) > 0 { + e.Args["filters"] = filterChanges + } oplog.WriteWithLimit(configPath, oplog.OpsFile, e, logMaxEntries()) //nolint:errcheck return nil @@ -248,7 +277,7 @@ func applyExtraTarget(extras []config.ExtraConfig, name, targetPath string, appl } func printExtrasModeHelp() { - printHelp("skillshare extras --mode [--target ]", "Change the sync mode or flatten setting of an extra's target.", + printHelp("skillshare extras --mode [--target ]", "Change the sync mode, flatten setting, or file filters of an extra's target.\nFilters use .gitignore patterns on paths inside the source: draft* matches\nat any depth, images/ covers a folder. Files that stop matching are pruned\non the next sync in merge mode; copy mode leaves them in place.", helpGroup{title: "Arguments", rows: []helpRow{ {"name", "Extra name (e.g., rules, commands)"}, }}, @@ -256,6 +285,10 @@ func printExtrasModeHelp() { {"--mode ", "New sync mode: merge, copy, or symlink"}, {"--flatten", "Enable flatten (sync subdirectory files into target root)"}, {"--no-flatten", "Disable flatten"}, + {"--add-include ", "Sync only files matching this pattern (repeatable)"}, + {"--add-exclude ", "Skip files matching this pattern (repeatable)"}, + {"--remove-include ", "Remove an include pattern"}, + {"--remove-exclude ", "Remove an exclude pattern"}, {"--target ", "Target directory path (optional if extra has only one target)"}, {"-p, --project", "Use project mode (.skillshare/)"}, {"-g, --global", "Use global mode (~/.config/skillshare/)"}, @@ -263,6 +296,8 @@ func printExtrasModeHelp() { helpExamples( helpRow{"skillshare extras rules --mode copy", ""}, helpRow{"skillshare extras agents --flatten", ""}, + helpRow{"skillshare extras docs --target ~/.claude/docs --add-include index.md --add-include learning.md", ""}, + helpRow{"skillshare extras docs --add-exclude \"draft*\" --add-exclude images/", ""}, ), ) } diff --git a/cmd/skillshare/extras_remove_target.go b/cmd/skillshare/extras_remove_target.go index 1e659c66c..1fcfeb232 100644 --- a/cmd/skillshare/extras_remove_target.go +++ b/cmd/skillshare/extras_remove_target.go @@ -195,6 +195,7 @@ func managedExtraTargetFiles(target config.ExtraTargetConfig, sourceDir, extensi if err != nil { return nil, err } + files = sync.ExtraTargetFiles(files, target) outputExt := "" if target.Extension != "" { diff --git a/cmd/skillshare/status_render.go b/cmd/skillshare/status_render.go index a9568f7df..a0bdfab3e 100644 --- a/cmd/skillshare/status_render.go +++ b/cmd/skillshare/status_render.go @@ -271,7 +271,7 @@ func printExtrasStatus(extras []config.ExtraConfig, sourceDirFn func(config.Extr continue } mode := sync.ExtraTargetMode(t.Mode, extra.File != "") - ui.Row(ui.MarkNone, extra.Name, pad(shortenPath(t.Path), pathW)+" "+theme.Dim().Render(plural(len(files), "file")+" · "+mode), width) + ui.Row(ui.MarkNone, extra.Name, pad(shortenPath(t.Path), pathW)+" "+theme.Dim().Render(plural(len(sync.ExtraTargetFiles(files, t)), "file")+" · "+mode), width) } } } diff --git a/internal/config/config.go b/internal/config/config.go index 155317c87..78c8de9bb 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -296,6 +296,11 @@ type ExtraTargetConfig struct { Flatten bool `yaml:"flatten,omitempty"` // flatten subdirectories into target root Extension string `yaml:"extension,omitempty"` // transform script applied during sync (implies copy) As string `yaml:"as,omitempty"` // target filename for a single-file extra (default: the extra's file) + // Include and Exclude select which source files sync to this target, as + // .gitignore-style patterns on the path inside the source (directory + // extras with merge or copy mode only). + Include []string `yaml:"include,omitempty"` + Exclude []string `yaml:"exclude,omitempty"` } // ExtraConfig holds configuration for a non-skill resource type (rules, commands, etc.). diff --git a/internal/config/extras_validate.go b/internal/config/extras_validate.go index 289a941d1..d07ace425 100644 --- a/internal/config/extras_validate.go +++ b/internal/config/extras_validate.go @@ -2,6 +2,7 @@ package config import ( "fmt" + "path" "regexp" "slices" "strings" @@ -102,6 +103,20 @@ func validateExtraTarget(file string, t ExtraTargetConfig) error { if err := ValidateExtraFlatten(t.Flatten, t.Mode); err != nil { return err } + if len(t.Include) > 0 || len(t.Exclude) > 0 { + if file != "" { + return fmt.Errorf("include and exclude cannot be used with a single-file extra") + } + if t.Mode == "symlink" { + return fmt.Errorf("include and exclude cannot be used with symlink mode (symlink links the entire directory)") + } + if err := validateExtraPatterns("include", t.Include); err != nil { + return err + } + if err := validateExtraPatterns("exclude", t.Exclude); err != nil { + return err + } + } if file == "" { if t.As != "" { return fmt.Errorf("as requires file") @@ -131,3 +146,17 @@ func validateExtraFilename(field, name string) error { } return nil } + +// validateExtraPatterns rejects .gitignore-style patterns whose path segments +// are not valid globs, so a typo fails at config time instead of matching +// nothing during sync. +func validateExtraPatterns(field string, patterns []string) error { + for _, p := range patterns { + for _, seg := range strings.Split(strings.TrimPrefix(strings.TrimSpace(p), "!"), "/") { + if _, err := path.Match(seg, ""); err != nil { + return fmt.Errorf("invalid %s pattern %q: %w", field, p, err) + } + } + } + return nil +} diff --git a/internal/config/extras_validate_file_test.go b/internal/config/extras_validate_file_test.go index 43e1fcd1c..4e81f7474 100644 --- a/internal/config/extras_validate_file_test.go +++ b/internal/config/extras_validate_file_test.go @@ -29,6 +29,10 @@ func TestValidateExtraConfig_SingleFile(t *testing.T) { {"extension with single-file copy", ExtraConfig{Name: "i", File: "AGENTS.md", Targets: []ExtraTargetConfig{{Path: "/t", Mode: "copy", Extension: "x"}}}, "extension cannot be used with a single-file extra"}, {"extension on directory extra", ExtraConfig{Name: "rules", Targets: []ExtraTargetConfig{{Path: "/t", Mode: "copy", Extension: "x"}}}, ""}, {"unknown mode", ExtraConfig{Name: "i", Targets: []ExtraTargetConfig{{Path: "/t", Mode: "bogus"}}}, "invalid mode"}, + {"filters on directory extra", ExtraConfig{Name: "docs", Targets: []ExtraTargetConfig{{Path: "/t", Include: []string{"*.md"}, Exclude: []string{"draft*"}}}}, ""}, + {"filters with symlink", ExtraConfig{Name: "docs", Targets: []ExtraTargetConfig{{Path: "/t", Mode: "symlink", Include: []string{"*.md"}}}}, "symlink"}, + {"filters with file", ExtraConfig{Name: "i", File: "AGENTS.md", Targets: []ExtraTargetConfig{{Path: "/t", Exclude: []string{"x"}}}}, "single-file"}, + {"invalid filter pattern", ExtraConfig{Name: "docs", Targets: []ExtraTargetConfig{{Path: "/t", Include: []string{"guides/[a"}}}}, "invalid include pattern"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/internal/server/handler_extras.go b/internal/server/handler_extras.go index 9326051e0..37ea8152d 100644 --- a/internal/server/handler_extras.go +++ b/internal/server/handler_extras.go @@ -46,12 +46,15 @@ type extrasListEntry struct { // extrasTargetInfo is the per-target sync status inside an extra entry. type extrasTargetInfo struct { - Path string `json:"path"` - Mode string `json:"mode"` - Flatten bool `json:"flatten"` - Extension string `json:"extension,omitempty"` - As string `json:"as,omitempty"` // single-file extra: target filename - Status string `json:"status"` // "synced", "drift", "modified", "not synced", "no source" + Path string `json:"path"` + Mode string `json:"mode"` + Flatten bool `json:"flatten"` + Extension string `json:"extension,omitempty"` + As string `json:"as,omitempty"` // single-file extra: target filename + Include []string `json:"include,omitempty"` + Exclude []string `json:"exclude,omitempty"` + FileCount int `json:"file_count"` // source files this target syncs after include/exclude + Status string `json:"status"` // "synced", "drift", "modified", "not synced", "no source" } // extrasSourceDir returns the source directory for the named extra in the @@ -143,7 +146,11 @@ func (s *Server) handleExtras(w http.ResponseWriter, r *http.Request) { Flatten: t.Flatten, Extension: t.Extension, As: t.As, + Include: t.Include, + Exclude: t.Exclude, } + targetFiles := syncpkg.ExtraTargetFiles(files, t) + ti.FileCount = len(targetFiles) if extra.File != "" { ti.Status = syncpkg.ExtraFileStatus(syncpkg.NewExtraFile(sourceDir, extra.File, targetPath, t.As, m)) @@ -184,7 +191,7 @@ func (s *Server) handleExtras(w http.ResponseWriter, r *http.Request) { log.Printf("warning: extension %q for extra %q could not be resolved (%v); sync status may be inaccurate", t.Extension, extra.Name, serr) } } - ti.Status = syncpkg.CheckSyncStatus(files, sourceDir, targetPath, m, t.Flatten, outputExt) + ti.Status = syncpkg.CheckSyncStatus(targetFiles, sourceDir, targetPath, m, t.Flatten, outputExt) } entry.Targets = append(entry.Targets, ti) @@ -302,7 +309,7 @@ func (s *Server) handleExtrasDiff(w http.ResponseWriter, r *http.Request) { } targetPath := resolveExtrasTargetPath(projectRoot, t.Path) - items := buildExtrasDiffItems(files, sourceDir, targetPath, m, t.Flatten, outputExt) + items := buildExtrasDiffItems(syncpkg.ExtraTargetFiles(files, t), sourceDir, targetPath, m, t.Flatten, outputExt) synced := len(items) == 0 out = append(out, extrasDiffEntry{ diff --git a/internal/server/handler_extras_edit.go b/internal/server/handler_extras_edit.go new file mode 100644 index 000000000..3a845854b --- /dev/null +++ b/internal/server/handler_extras_edit.go @@ -0,0 +1,347 @@ +package server + +import ( + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "slices" + "strings" + "time" + + "skillshare/internal/config" + syncpkg "skillshare/internal/sync" +) + +// handleExtrasPreview — POST /api/extras/{name}/preview +// Shows what draft include and exclude patterns do to the extra's source files. +func (s *Server) handleExtrasPreview(w http.ResponseWriter, r *http.Request) { + var body struct { + Include []string `json:"include"` + Exclude []string `json:"exclude"` + } + if err := decodeJSON(w, r, &body, defaultJSONBodyLimit); err != nil { + if !errors.Is(err, errBodyTooLarge) { + writeError(w, http.StatusBadRequest, "invalid JSON body") + } + return + } + + s.mu.RLock() + extras := s.extrasConfig() + idx := slices.IndexFunc(extras, func(e config.ExtraConfig) bool { return e.Name == r.PathValue("name") }) + if idx < 0 { + s.mu.RUnlock() + writeError(w, http.StatusNotFound, "extra not found: "+r.PathValue("name")) + return + } + sourceDir := s.extrasSourceDir(extras[idx]) + s.mu.RUnlock() + + files, err := syncpkg.DiscoverExtraFiles(sourceDir) + if err != nil { + writeError(w, http.StatusBadRequest, "source not readable: "+err.Error()) + return + } + writeJSON(w, map[string]any{ + "files": syncpkg.PreviewExtraFilter(files, body.Include, body.Exclude), + "unmatched": syncpkg.UnmatchedIncludes(files, body.Include), + }) +} + +// handleExtrasEditTarget — PUT /api/extras/{name}/targets +// Replaces one target's settings. A new folder or file name removes what +// skillshare put at the old place (copies stay) and syncs the extra; other +// changes only write config and take effect on the next sync. +func (s *Server) handleExtrasEditTarget(w http.ResponseWriter, r *http.Request) { + start := time.Now() + name := r.PathValue("name") + + var body struct { + Path string `json:"path"` // the target as stored in config + Target struct { + Path string `json:"path"` + Mode string `json:"mode"` + Flatten bool `json:"flatten"` + Extension string `json:"extension"` + As string `json:"as"` + Include []string `json:"include"` + Exclude []string `json:"exclude"` + } `json:"target"` + } + if err := decodeJSON(w, r, &body, defaultJSONBodyLimit); err != nil { + if !errors.Is(err, errBodyTooLarge) { + writeError(w, http.StatusBadRequest, "invalid JSON body") + } + return + } + if body.Path == "" || body.Target.Path == "" { + writeError(w, http.StatusBadRequest, "path is required") + return + } + + s.mu.Lock() + defer s.mu.Unlock() + + extras := s.extrasConfig() + idx := slices.IndexFunc(extras, func(e config.ExtraConfig) bool { return e.Name == name }) + if idx == -1 { + writeError(w, http.StatusNotFound, "extra not found: "+name) + return + } + extra := extras[idx] + tIdx := slices.IndexFunc(extra.Targets, func(t config.ExtraTargetConfig) bool { return t.Path == body.Path }) + if tIdx == -1 { + writeError(w, http.StatusNotFound, "target not found: "+body.Path) + return + } + old := extra.Targets[tIdx] + + in := body.Target + next := config.ExtraTargetConfig{Path: in.Path, Mode: in.Mode, Flatten: in.Flatten, Extension: in.Extension, As: in.As, Include: in.Include, Exclude: in.Exclude} + if next.Extension != "" { + // A transform extension only makes sense with copy mode. + next.Mode = "copy" + } + if next.Mode == "symlink" { + // One link to the whole folder cannot leave files out. + next.Include, next.Exclude = nil, nil + } + newPath := filepath.Clean(resolveExtrasTargetPath(s.projectRoot, next.Path)) + if !s.IsProjectMode() { + next.Path = newPath + } + oldPath := filepath.Clean(resolveExtrasTargetPath(s.projectRoot, old.Path)) + for j, t := range extra.Targets { + if j != tIdx && filepath.Clean(resolveExtrasTargetPath(s.projectRoot, t.Path)) == newPath { + writeError(w, http.StatusConflict, "target already exists: "+in.Path) + return + } + } + if err := config.ValidateExtraConfig(config.ExtraConfig{Name: name, File: extra.File, Targets: []config.ExtraTargetConfig{next}}); err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + + prev := extra.Targets + extras[idx].Targets = slices.Clone(prev) + extras[idx].Targets[tIdx] = next + if err := s.validateExtra(name); err != nil { + extras[idx].Targets = prev + if !writeExtraTargetConflict(w, err, in.Path) { + writeError(w, http.StatusBadRequest, err.Error()) + } + return + } + if err := s.saveAndReloadConfig(); err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + + moved := newPath != oldPath || next.As != old.As + resp := map[string]any{"success": true, "name": name, "target": next.Path} + status, msg := "ok", "" + if moved { + sourceDir := s.extrasSourceDir(extra) + oldMode := syncpkg.ExtraTargetMode(old.Mode, extra.File != "") + var errs []string + resp["pruned"], errs = clearExtraTarget(extra.File, sourceDir, oldPath, old.As, oldMode) + results := s.syncExtras(name, false, false) + resp["extras"] = results + if len(errs) > 0 { + resp["prune_errors"] = errs + } + if status, _ = extrasSyncStatus(results); len(errs) > 0 { + status, msg = "partial", errs[0] + } + } + + s.writeOpsLog("extras-target", status, start, map[string]any{ + "name": name, "target": next.Path, "from": old.Path, "action": "edit", "scope": "ui", + }, msg) + writeJSON(w, resp) +} + +// handleExtrasEdit — PATCH /api/extras/{name} +// Renames an extra or points it at another source folder. A rename keeps the +// folder: an extra in its default folder gets that folder as its source. A new +// source must already exist; the old folder is left as it is, and every target +// is relinked to the new one. +func (s *Server) handleExtrasEdit(w http.ResponseWriter, r *http.Request) { + start := time.Now() + name := r.PathValue("name") + + var body struct { + Name string `json:"name"` + // Source is left alone when omitted; "" means the default folder. Global: + // a path; project: relative to the project root or a path inside it. + Source *string `json:"source"` + } + if err := decodeJSON(w, r, &body, defaultJSONBodyLimit); err != nil { + if !errors.Is(err, errBodyTooLarge) { + writeError(w, http.StatusBadRequest, "invalid JSON body") + } + return + } + + s.mu.Lock() + defer s.mu.Unlock() + + extras := s.extrasConfig() + idx := slices.IndexFunc(extras, func(e config.ExtraConfig) bool { return e.Name == name }) + if idx == -1 { + writeError(w, http.StatusNotFound, "extra not found: "+name) + return + } + extra := extras[idx] + oldSource := s.extrasSourceDir(extra) + next := extra + + if body.Name != "" && body.Name != name { + // Sync skips agent target folders for the extra named agents, and the + // memory notes live in the extra named memory. + for _, special := range []string{"agents", "memory"} { + if strings.EqualFold(name, special) || strings.EqualFold(body.Name, special) { + writeError(w, http.StatusBadRequest, "an extra cannot be renamed to or from "+special) + return + } + } + if err := config.ValidateExtraName(body.Name); err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + others := slices.DeleteFunc(slices.Clone(extras), func(e config.ExtraConfig) bool { return e.Name == name }) + if err := config.ValidateExtraNameUnique(body.Name, others); err != nil { + writeError(w, http.StatusConflict, err.Error()) + return + } + next.Name = body.Name + if next.Source == "" { + source, err := s.storedExtraSource(oldSource) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + next.Source = source + } + } + + if body.Source != nil { + source := *body.Source + if source != "" && s.IsProjectMode() { + if abs := config.ExpandPath(source); filepath.IsAbs(abs) { + if rel, err := filepath.Rel(s.projectRoot, abs); err == nil { + source = rel + } + } + if err := config.ValidateProjectExtraSource(source); err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + source = filepath.ToSlash(filepath.Clean(source)) + } else if source != "" { + source = filepath.Clean(config.ExpandPath(source)) + } + next.Source = source + } + newSource := s.extrasSourceDir(next) + relink := filepath.Clean(newSource) != filepath.Clean(oldSource) + if relink { + if extra.File != "" { + if info, err := os.Stat(filepath.Join(newSource, extra.File)); err != nil || info.IsDir() { + writeError(w, http.StatusBadRequest, fmt.Sprintf("%s not found in %s", extra.File, newSource)) + return + } + } else if info, err := os.Stat(newSource); err != nil || !info.IsDir() { + writeError(w, http.StatusBadRequest, "folder not found: "+newSource) + return + } + } + + extras[idx] = next + if err := s.validateExtra(next.Name); err != nil { + extras[idx] = extra + writeError(w, http.StatusBadRequest, err.Error()) + return + } + + // Links into the old folder go before the config points elsewhere, so the + // next sync does not leave them behind. + var pruneErrs []string + if relink { + for _, t := range extra.Targets { + mode := syncpkg.ExtraTargetMode(t.Mode, extra.File != "") + _, errs := clearExtraTarget(extra.File, oldSource, resolveExtrasTargetPath(s.projectRoot, t.Path), t.As, mode) + pruneErrs = append(pruneErrs, errs...) + } + } + if err := s.saveAndReloadConfig(); err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + + resp := map[string]any{"success": true, "name": next.Name} + status, msg := "ok", "" + if relink { + results := s.syncExtras(next.Name, false, false) + resp["extras"] = results + status, _ = extrasSyncStatus(results) + } + if len(pruneErrs) > 0 { + resp["prune_errors"] = pruneErrs + status, msg = "partial", pruneErrs[0] + } + + s.writeOpsLog("extras-edit", status, start, map[string]any{ + "name": next.Name, "from": name, "source": next.Source, "scope": "ui", + }, msg) + writeJSON(w, resp) +} + +// clearExtraTarget removes what skillshare put at one target: links into +// sourceDir in merge mode, the folder link in symlink mode, and a single-file +// target goes back to how it was. Copies stay, since nothing records which +// copied files are skillshare's. +func clearExtraTarget(file, sourceDir, targetPath, as, mode string) (int, []string) { + if file != "" { + changed, err := syncpkg.RestoreExtraTarget(syncpkg.NewExtraFile(sourceDir, file, targetPath, as, mode)) + if err != nil { + return 0, []string{err.Error()} + } + if changed { + return 1, nil + } + return 0, nil + } + if mode == "symlink" { + dest, err := filepath.EvalSymlinks(targetPath) + src, srcErr := filepath.EvalSymlinks(sourceDir) + if err != nil || srcErr != nil || dest != src { + return 0, nil + } + } + return syncpkg.PruneExtraTargetFiles(targetPath, sourceDir, mode, nil) +} + +// storedExtraSource is dir as an extra's source field: absolute in global +// mode, relative to the project root in project mode. +func (s *Server) storedExtraSource(dir string) (string, error) { + if !s.IsProjectMode() { + return dir, nil + } + rel, err := filepath.Rel(s.projectRoot, dir) + if err != nil { + return "", err + } + return filepath.ToSlash(rel), nil +} + +// validateExtra runs the ownership and import checks for one extra against the +// whole config. Callers must hold s.mu. +func (s *Server) validateExtra(name string) error { + if s.IsProjectMode() { + return s.projectCfg.ValidateExtras(s.projectRoot, name) + } + return s.cfg.ValidateExtras(name) +} diff --git a/internal/server/handler_extras_edit_test.go b/internal/server/handler_extras_edit_test.go new file mode 100644 index 000000000..dfecc3bfc --- /dev/null +++ b/internal/server/handler_extras_edit_test.go @@ -0,0 +1,141 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "skillshare/internal/config" +) + +// newDocsExtraServer serves a docs extra holding index.md and draft.md with +// one merge target, and returns the server, the extra's folder and the target. +func newDocsExtraServer(t *testing.T, target config.ExtraTargetConfig) (*Server, string, string) { + t.Helper() + if target.Path == "" { + target.Path = t.TempDir() + } + s, skillsDir := newTestServerWithExtras(t, []config.ExtraConfig{{Name: "docs", Targets: []config.ExtraTargetConfig{target}}}, "") + docs := filepath.Join(filepath.Dir(skillsDir), "extras", "docs") + os.WriteFile(filepath.Join(docs, "index.md"), []byte("i"), 0644) + os.WriteFile(filepath.Join(docs, "draft.md"), []byte("d"), 0644) + return s, docs, target.Path +} + +func serveExtras(s *Server, method, path, body string) *httptest.ResponseRecorder { + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, httptest.NewRequest(method, path, strings.NewReader(body))) + return rr +} + +func TestHandleExtras_ListsTargetFilterAndFileCount(t *testing.T) { + s, _, _ := newDocsExtraServer(t, config.ExtraTargetConfig{Exclude: []string{"draft*"}}) + + rr := serveExtras(s, http.MethodGet, "/api/extras", "") + + var resp struct { + Extras []extrasListEntry `json:"extras"` + } + json.Unmarshal(rr.Body.Bytes(), &resp) + if ti := resp.Extras[0].Targets[0]; ti.FileCount != 1 || len(ti.Exclude) != 1 { + t.Errorf("target = %+v, want file_count 1 and the exclude pattern", ti) + } +} + +func TestHandleExtrasPreview_NamesTheExcludePattern(t *testing.T) { + s, _, _ := newDocsExtraServer(t, config.ExtraTargetConfig{}) + + rr := serveExtras(s, http.MethodPost, "/api/extras/docs/preview", `{"exclude":["draft*"],"include":["*.md","nope.md"]}`) + + body := rr.Body.String() + if !strings.Contains(body, `{"file":"draft.md","status":"excluded","reason":"draft*"}`) || !strings.Contains(body, `"unmatched":["nope.md"]`) { + t.Errorf("unexpected preview: %s", body) + } +} + +func TestHandleExtrasEditTarget_NewPathRemovesOldLinksAndSyncs(t *testing.T) { + s, _, oldTgt := newDocsExtraServer(t, config.ExtraTargetConfig{}) + serveExtras(s, http.MethodPost, "/api/extras/sync", `{"name":"docs"}`) + newTgt := t.TempDir() + + rr := serveExtras(s, http.MethodPut, "/api/extras/docs/targets", `{"path":"`+oldTgt+`","target":{"path":"`+newTgt+`"}}`) + + if rr.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String()) + } + if _, err := os.Lstat(filepath.Join(oldTgt, "index.md")); !os.IsNotExist(err) { + t.Errorf("old link should be gone, lstat err = %v", err) + } + if _, err := os.Lstat(filepath.Join(newTgt, "index.md")); err != nil { + t.Errorf("new target should be synced: %v", err) + } +} + +func TestHandleExtrasEditTarget_SymlinkDropsFilters(t *testing.T) { + s, _, tgt := newDocsExtraServer(t, config.ExtraTargetConfig{Include: []string{"index.md"}}) + + rr := serveExtras(s, http.MethodPut, "/api/extras/docs/targets", `{"path":"`+tgt+`","target":{"path":"`+tgt+`","mode":"symlink","include":["index.md"]}}`) + + if rr.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String()) + } + if got := s.cfg.Extras[0].Targets[0]; got.Mode != "symlink" || got.Include != nil { + t.Errorf("target = %+v, want symlink with no include", got) + } +} + +func TestHandleExtrasEdit_RenameKeepsTheFolder(t *testing.T) { + s, docs, _ := newDocsExtraServer(t, config.ExtraTargetConfig{}) + + rr := serveExtras(s, http.MethodPatch, "/api/extras/docs", `{"name":"notes"}`) + + if rr.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String()) + } + if got := s.cfg.Extras[0]; got.Name != "notes" || got.Source != docs { + t.Errorf("extra = %+v, want notes with source %s", got, docs) + } +} + +func TestHandleExtrasEdit_RenameFromAgentsRejected(t *testing.T) { + s, _ := newTestServerWithExtras(t, []config.ExtraConfig{{Name: "agents", Targets: []config.ExtraTargetConfig{{Path: t.TempDir()}}}}, "") + + rr := serveExtras(s, http.MethodPatch, "/api/extras/agents", `{"name":"helpers"}`) + + if rr.Code != http.StatusBadRequest { + t.Errorf("expected 400, got %d: %s", rr.Code, rr.Body.String()) + } +} + +func TestHandleExtrasEdit_MissingSourceRejected(t *testing.T) { + s, _, _ := newDocsExtraServer(t, config.ExtraTargetConfig{}) + + rr := serveExtras(s, http.MethodPatch, "/api/extras/docs", `{"source":"`+filepath.Join(t.TempDir(), "nope")+`"}`) + + if rr.Code != http.StatusBadRequest { + t.Errorf("expected 400, got %d: %s", rr.Code, rr.Body.String()) + } +} + +func TestHandleExtrasEdit_NewSourceRelinksTargets(t *testing.T) { + s, _, tgt := newDocsExtraServer(t, config.ExtraTargetConfig{}) + serveExtras(s, http.MethodPost, "/api/extras/sync", `{"name":"docs"}`) + newSrc := t.TempDir() + os.WriteFile(filepath.Join(newSrc, "guide.md"), []byte("g"), 0644) + + rr := serveExtras(s, http.MethodPatch, "/api/extras/docs", `{"source":"`+newSrc+`"}`) + + if rr.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String()) + } + if _, err := os.Lstat(filepath.Join(tgt, "index.md")); !os.IsNotExist(err) { + t.Errorf("link into the old folder should be gone, lstat err = %v", err) + } + if dest, err := os.Readlink(filepath.Join(tgt, "guide.md")); err != nil || !strings.HasPrefix(dest, newSrc) { + t.Errorf("guide.md should link into the new folder, got %q, %v", dest, err) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 27d0cd57a..b2f810c87 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -648,6 +648,9 @@ func (s *Server) registerRoutes() { s.mux.HandleFunc("DELETE /api/extras/{name}", s.handleExtrasDelete) s.mux.HandleFunc("POST /api/extras/{name}/targets", s.handleExtrasAddTarget) s.mux.HandleFunc("DELETE /api/extras/{name}/targets", s.handleExtrasRemoveTarget) + s.mux.HandleFunc("PUT /api/extras/{name}/targets", s.handleExtrasEditTarget) + s.mux.HandleFunc("POST /api/extras/{name}/preview", s.handleExtrasPreview) + s.mux.HandleFunc("PATCH /api/extras/{name}", s.handleExtrasEdit) // Extensions (transform extensions management) s.mux.HandleFunc("GET /api/extensions", s.handleExtensionsList) diff --git a/internal/sync/extras.go b/internal/sync/extras.go index d98994d05..b490d8ac9 100644 --- a/internal/sync/extras.go +++ b/internal/sync/extras.go @@ -86,6 +86,13 @@ func DiscoverExtraFiles(sourcePath string) ([]string, error) { // When dryRun is true the function counts what would happen but makes no // filesystem changes. func SyncExtra(sourcePath, targetPath, mode string, dryRun, force, flatten bool, projectRoot string, spec *ExtensionSpec) (*ExtraResult, error) { + return syncExtraDir(sourcePath, targetPath, mode, dryRun, force, flatten, projectRoot, spec, nil, nil) +} + +// syncExtraDir is SyncExtra limited to the source files that pass include and +// exclude (see FilterExtraFiles). Files filtered out count as absent, so merge +// prunes their links like links to deleted source files. +func syncExtraDir(sourcePath, targetPath, mode string, dryRun, force, flatten bool, projectRoot string, spec *ExtensionSpec, include, exclude []string) (*ExtraResult, error) { if spec != nil { // Transform extensions emit generated files into the target, so only // copy semantics apply. Reject merge/symlink here so the API and the @@ -93,7 +100,7 @@ func SyncExtra(sourcePath, targetPath, mode string, dryRun, force, flatten bool, if mode != "" && mode != "copy" { return nil, fmt.Errorf("extension %q requires copy mode, got %q", spec.Name, mode) } - return syncExtraTransform(sourcePath, targetPath, spec, dryRun, force, flatten) + return syncExtraTransform(sourcePath, targetPath, spec, dryRun, force, flatten, include, exclude) } if mode == "" { mode = "merge" @@ -101,12 +108,15 @@ func SyncExtra(sourcePath, targetPath, mode string, dryRun, force, flatten bool, if flatten && mode == "symlink" { return nil, fmt.Errorf("flatten cannot be used with symlink mode") } + if mode == "symlink" && (len(include) > 0 || len(exclude) > 0) { + return nil, fmt.Errorf("include and exclude cannot be used with symlink mode") + } switch mode { case "symlink": return syncExtraSymlinkMode(sourcePath, targetPath, dryRun, force, projectRoot) case "merge", "copy": - return syncExtraPerFile(sourcePath, targetPath, mode, dryRun, force, flatten, projectRoot) + return syncExtraPerFile(sourcePath, targetPath, mode, dryRun, force, flatten, projectRoot, include, exclude) default: return nil, fmt.Errorf("unsupported extras sync mode: %q", mode) } @@ -116,13 +126,14 @@ func SyncExtra(sourcePath, targetPath, mode string, dryRun, force, flatten bool, // transformed output into targetPath using copy semantics. Output files are // renamed per spec.OutputExt. It does not prune output-looking orphans because // copy targets do not carry ownership metadata. -func syncExtraTransform(sourcePath, targetPath string, spec *ExtensionSpec, dryRun, force, flatten bool) (*ExtraResult, error) { +func syncExtraTransform(sourcePath, targetPath string, spec *ExtensionSpec, dryRun, force, flatten bool, include, exclude []string) (*ExtraResult, error) { result := &ExtraResult{} - files, err := DiscoverExtraFiles(sourcePath) + files, warnings, err := discoverExtraTargetFiles(sourcePath, include, exclude) if err != nil { return nil, err } + result.Warnings = warnings absSrc, err := filepath.Abs(sourcePath) if err != nil { return nil, fmt.Errorf("failed to resolve source path: %w", err) @@ -304,7 +315,7 @@ func syncExtraSymlinkMode(sourcePath, targetPath string, dryRun, force bool, pro // syncExtraPerFile handles merge (symlink) and copy modes on a per-file basis. // Merge copies instead when file links are unavailable; those copies are // tracked so later syncs keep them updated and pruned like links. -func syncExtraPerFile(sourcePath, targetPath, mode string, dryRun, force, flatten bool, projectRoot string) (*ExtraResult, error) { +func syncExtraPerFile(sourcePath, targetPath, mode string, dryRun, force, flatten bool, projectRoot string, include, exclude []string) (*ExtraResult, error) { result := &ExtraResult{} var copies *copyTracker @@ -316,10 +327,11 @@ func syncExtraPerFile(sourcePath, targetPath, mode string, dryRun, force, flatte } } - files, err := DiscoverExtraFiles(sourcePath) + files, warnings, err := discoverExtraTargetFiles(sourcePath, include, exclude) if err != nil { return nil, err } + result.Warnings = append(result.Warnings, warnings...) absSrc, err := filepath.Abs(sourcePath) if err != nil { @@ -778,7 +790,8 @@ type ExtraCollectResult struct { // (identical content is still skipped). // When flatten is true, collected files are placed in the source root // (basename only) rather than preserving the target subdirectory structure. -func CollectExtraFiles(sourceDir, targetDir, mode string, dryRun, force, flatten bool, projectRoot string) (*ExtraCollectResult, error) { +// Files that include and exclude leave out of the target are skipped. +func CollectExtraFiles(sourceDir, targetDir, mode string, dryRun, force, flatten bool, projectRoot string, include, exclude []string) (*ExtraCollectResult, error) { result := &ExtraCollectResult{} // Without file links the collected files stay in place, as copies. if !canCreateFileLink() { @@ -799,6 +812,7 @@ func CollectExtraFiles(sourceDir, targetDir, mode string, dryRun, force, flatten // Source paths claimed this run: with flatten, two target files can share // a basename, and the second must not overwrite the first. claimed := make(map[string]bool) + filter := newExtraFilter(include, exclude) err := filepath.Walk(targetDir, func(path string, info os.FileInfo, walkErr error) error { if walkErr != nil { @@ -836,6 +850,12 @@ func CollectExtraFiles(sourceDir, targetDir, mode string, dryRun, force, flatten if flatten { destRel = filepath.Base(rel) } + // A file the target's filters leave out would be pruned again by the + // next sync, so it stays where it is. + if !filter.keeps(destRel) { + result.Skipped++ + return nil + } destPath := filepath.Join(sourceDir, destRel) if claimed[destPath] { result.Errors = append(result.Errors, fmt.Sprintf("skipped %s: %s already collected from another file", rel, destRel)) diff --git a/internal/sync/extras_filter.go b/internal/sync/extras_filter.go new file mode 100644 index 000000000..ae54e06fd --- /dev/null +++ b/internal/sync/extras_filter.go @@ -0,0 +1,127 @@ +package sync + +import ( + "fmt" + + "skillshare/internal/config" + "skillshare/internal/skillignore" +) + +// extraFilter decides which source files (paths relative to the extra's +// source) a target syncs. include and exclude use .gitignore syntax: a pattern +// without "/" matches at any depth and "dir/" covers a folder. +type extraFilter struct{ inc, exc *skillignore.Matcher } + +func newExtraFilter(include, exclude []string) extraFilter { + return extraFilter{skillignore.Compile(include), skillignore.Compile(exclude)} +} + +func (f extraFilter) included(rel string) bool { + return !f.inc.HasRules() || f.inc.Match(rel, false) +} + +func (f extraFilter) keeps(rel string) bool { + return f.included(rel) && !f.exc.Match(rel, false) +} + +// FilterExtraFiles keeps the source files that pass include and exclude. +func FilterExtraFiles(files, include, exclude []string) []string { + if len(include) == 0 && len(exclude) == 0 { + return files + } + f := newExtraFilter(include, exclude) + var kept []string + for _, rel := range files { + if f.keeps(rel) { + kept = append(kept, rel) + } + } + return kept +} + +// UnmatchedIncludes returns the include patterns that select no file at all. +func UnmatchedIncludes(files, include []string) []string { + var unmatched []string + for _, p := range include { + m := skillignore.Compile([]string{p}) + if !m.HasRules() { + continue // blank or comment + } + if !matchesAnyFile(m, files) { + unmatched = append(unmatched, p) + } + } + return unmatched +} + +// ExtraTargetFiles narrows an extra's source files to the ones target syncs. +func ExtraTargetFiles(files []string, target config.ExtraTargetConfig) []string { + return FilterExtraFiles(files, target.Include, target.Exclude) +} + +// ExtraFilterEntry is one source file in a filter preview. Status is +// "synced", "not_included", or "excluded"; Reason names the exclude pattern +// that dropped an excluded file. +type ExtraFilterEntry struct { + File string `json:"file"` + Status string `json:"status"` + Reason string `json:"reason,omitempty"` +} + +// PreviewExtraFilter reports what include and exclude do to each source file. +func PreviewExtraFilter(files, include, exclude []string) []ExtraFilterEntry { + f := newExtraFilter(include, exclude) + excludes := make([]*skillignore.Matcher, len(exclude)) + for i, p := range exclude { + excludes[i] = skillignore.Compile([]string{p}) + } + entries := make([]ExtraFilterEntry, 0, len(files)) + for _, rel := range files { + e := ExtraFilterEntry{File: rel, Status: "synced"} + switch { + case !f.included(rel): + e.Status = "not_included" + case !f.keeps(rel): + e.Status = "excluded" + for i, m := range excludes { + if m.Match(rel, false) { + e.Reason = exclude[i] + break + } + } + } + entries = append(entries, e) + } + return entries +} + +// UnmatchedIncludeWarning is the sync warning for an include pattern that +// selects no file. +func UnmatchedIncludeWarning(pattern string) string { + return fmt.Sprintf("include %q matches no file", pattern) +} + +func matchesAnyFile(m *skillignore.Matcher, files []string) bool { + for _, rel := range files { + if m.Match(rel, false) { + return true + } + } + return false +} + +// discoverExtraTargetFiles lists the source files one target syncs, with a +// warning for each include pattern that selects nothing. +func discoverExtraTargetFiles(sourcePath string, include, exclude []string) ([]string, []string, error) { + files, err := DiscoverExtraFiles(sourcePath) + if err != nil { + return nil, nil, err + } + kept := FilterExtraFiles(files, include, exclude) + unmatched := UnmatchedIncludes(files, include) + warnings := make([]string, 0, len(unmatched)) + for _, p := range unmatched { + warnings = append(warnings, UnmatchedIncludeWarning(p)) + } + return kept, warnings, nil +} diff --git a/internal/sync/extras_filter_test.go b/internal/sync/extras_filter_test.go new file mode 100644 index 000000000..d8a699375 --- /dev/null +++ b/internal/sync/extras_filter_test.go @@ -0,0 +1,107 @@ +package sync + +import ( + "os" + "path/filepath" + "slices" + "testing" + + "skillshare/internal/config" +) + +var filterTestFiles = []string{"draft.md", "guides/draft-2.md", "guides/setup.md", "images/logo.png", "index.md"} + +func TestFilterExtraFiles_GitignoreSemantics(t *testing.T) { + tests := []struct { + name string + include, exclude []string + want []string + }{ + {"no filters keeps all", nil, nil, filterTestFiles}, + {"bare name matches at any depth", []string{"setup.md"}, nil, []string{"guides/setup.md"}}, + {"glob without slash matches at any depth", nil, []string{"draft*"}, []string{"guides/setup.md", "images/logo.png", "index.md"}}, + {"trailing slash covers a folder", nil, []string{"images/"}, []string{"draft.md", "guides/draft-2.md", "guides/setup.md", "index.md"}}, + {"double star matches nested files", []string{"**/*.png"}, nil, []string{"images/logo.png"}}, + {"exclude applies after include", []string{"guides/"}, []string{"draft*"}, []string{"guides/setup.md"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := FilterExtraFiles(filterTestFiles, tt.include, tt.exclude) + if !slices.Equal(got, tt.want) { + t.Errorf("got %v, want %v", got, tt.want) + } + }) + } +} + +func TestUnmatchedIncludes_ReportsPatternWithNoFile(t *testing.T) { + unmatched := UnmatchedIncludes(filterTestFiles, []string{"index.md", "index.mdd"}) + + if !slices.Equal(unmatched, []string{"index.mdd"}) { + t.Errorf("unmatched = %v, want [index.mdd]", unmatched) + } +} + +func filterTestExtra(tgt string, target config.ExtraTargetConfig) config.ExtraConfig { + target.Path = tgt + return config.ExtraConfig{Name: "docs", Targets: []config.ExtraTargetConfig{target}} +} + +func TestRunExtraTargets_IncludeSyncsOnlyMatches(t *testing.T) { + src, tgt := setupExtrasTest(t, map[string]string{"index.md": "i", "draft.md": "d"}) + + run := RunExtraTargets(filterTestExtra(tgt, config.ExtraTargetConfig{Include: []string{"index.md"}}), src, runTestOptions()) + + if r := run.Targets[0]; r.Err != nil || r.Result.Synced != 1 { + t.Fatalf("expected one synced file, got %+v", r) + } + if _, err := os.Lstat(filepath.Join(tgt, "draft.md")); !os.IsNotExist(err) { + t.Errorf("draft.md must not be synced, lstat err = %v", err) + } +} + +func TestRunExtraTargets_NarrowedFilterPrunesMergeLinks(t *testing.T) { + src, tgt := setupExtrasTest(t, map[string]string{"index.md": "i", "draft.md": "d"}) + RunExtraTargets(filterTestExtra(tgt, config.ExtraTargetConfig{}), src, runTestOptions()) + + run := RunExtraTargets(filterTestExtra(tgt, config.ExtraTargetConfig{Exclude: []string{"draft*"}}), src, runTestOptions()) + + if r := run.Targets[0]; r.Err != nil || r.Result.Pruned != 1 { + t.Fatalf("expected the draft.md link pruned, got %+v", r) + } +} + +func TestRunExtraTargets_CopyKeepsFilteredOutFiles(t *testing.T) { + src, tgt := setupExtrasTest(t, map[string]string{"index.md": "i", "draft.md": "d"}) + RunExtraTargets(filterTestExtra(tgt, config.ExtraTargetConfig{Mode: "copy"}), src, runTestOptions()) + + RunExtraTargets(filterTestExtra(tgt, config.ExtraTargetConfig{Mode: "copy", Exclude: []string{"draft*"}}), src, runTestOptions()) + + if _, err := os.Stat(filepath.Join(tgt, "draft.md")); err != nil { + t.Errorf("copy mode must keep draft.md, stat err = %v", err) + } +} + +func TestRunExtraTargets_WarnsUnmatchedInclude(t *testing.T) { + src, tgt := setupExtrasTest(t, map[string]string{"index.md": "i"}) + + run := RunExtraTargets(filterTestExtra(tgt, config.ExtraTargetConfig{Include: []string{"index.mdd"}}), src, runTestOptions()) + + if r := run.Targets[0]; !slices.Contains(r.Result.Warnings, UnmatchedIncludeWarning("index.mdd")) { + t.Errorf("expected unmatched include warning, got %v", r.Result.Warnings) + } +} + +func TestCollectExtraFiles_SkipsFilteredOutFiles(t *testing.T) { + src, tgt := setupExtrasTest(t, nil) + os.WriteFile(filepath.Join(tgt, "draft.md"), []byte("d"), 0644) + + result, err := CollectExtraFiles(src, tgt, "", false, false, false, "", nil, []string{"draft*"}) + + if err != nil || result.Collected != 0 { + t.Fatalf("expected nothing collected, got %+v, err %v", result, err) + } + if _, err := os.Stat(filepath.Join(src, "draft.md")); !os.IsNotExist(err) { + t.Errorf("draft.md must stay out of the source, stat err = %v", err) + } +} diff --git a/internal/sync/extras_run.go b/internal/sync/extras_run.go index 4bb8d58fa..b5ceea37d 100644 --- a/internal/sync/extras_run.go +++ b/internal/sync/extras_run.go @@ -92,7 +92,7 @@ func runExtraTarget(extra config.ExtraConfig, t config.ExtraTargetConfig, source // sync just that file to /; others sync the directory. func SyncExtraTarget(extra config.ExtraConfig, target config.ExtraTargetConfig, sourceDir, targetPath, mode string, dryRun, force bool, projectRoot string, spec *ExtensionSpec) (*ExtraResult, error) { if extra.File == "" { - return SyncExtra(sourceDir, targetPath, mode, dryRun, force, target.Flatten, projectRoot, spec) + return syncExtraDir(sourceDir, targetPath, mode, dryRun, force, target.Flatten, projectRoot, spec, target.Include, target.Exclude) } if spec != nil { return nil, fmt.Errorf("extensions are not supported for single-file extras") diff --git a/internal/sync/extras_test.go b/internal/sync/extras_test.go index 0fbab90ed..14fe3e04b 100644 --- a/internal/sync/extras_test.go +++ b/internal/sync/extras_test.go @@ -431,7 +431,7 @@ func TestCollectExtraFiles(t *testing.T) { os.MkdirAll(targetDir, 0755) os.WriteFile(filepath.Join(targetDir, "rule1.md"), []byte("# Rule 1"), 0644) - result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, false, "") + result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, false, "", nil, nil) if err != nil { t.Fatalf("CollectExtraFiles: %v", err) } @@ -466,7 +466,7 @@ func TestCollectExtraFiles_DryRun(t *testing.T) { os.MkdirAll(targetDir, 0755) os.WriteFile(filepath.Join(targetDir, "rule1.md"), []byte("# Rule 1"), 0644) - result, err := CollectExtraFiles(sourceDir, targetDir, "", true, false, false, "") + result, err := CollectExtraFiles(sourceDir, targetDir, "", true, false, false, "", nil, nil) if err != nil { t.Fatalf("CollectExtraFiles dry run: %v", err) } @@ -500,7 +500,7 @@ func TestCollectExtraFiles_SkipsExisting(t *testing.T) { os.WriteFile(filepath.Join(sourceDir, "rule1.md"), []byte("source version"), 0644) os.WriteFile(filepath.Join(targetDir, "rule1.md"), []byte("target version"), 0644) - result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, false, "") + result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, false, "", nil, nil) if err != nil { t.Fatalf("CollectExtraFiles: %v", err) } @@ -521,7 +521,7 @@ func TestCollectExtraFiles_ForceOverwritesExisting(t *testing.T) { os.WriteFile(filepath.Join(sourceDir, "rule1.md"), []byte("source version"), 0644) os.WriteFile(filepath.Join(targetDir, "rule1.md"), []byte("target version"), 0644) - if _, err := CollectExtraFiles(sourceDir, targetDir, "", false, true, false, ""); err != nil { + if _, err := CollectExtraFiles(sourceDir, targetDir, "", false, true, false, "", nil, nil); err != nil { t.Fatalf("CollectExtraFiles: %v", err) } @@ -539,7 +539,7 @@ func TestCollectExtraFiles_ForceSkipsIdentical(t *testing.T) { os.WriteFile(filepath.Join(sourceDir, "rule1.md"), []byte("same"), 0644) os.WriteFile(filepath.Join(targetDir, "rule1.md"), []byte("same"), 0644) - result, err := CollectExtraFiles(sourceDir, targetDir, "copy", false, true, false, "") + result, err := CollectExtraFiles(sourceDir, targetDir, "copy", false, true, false, "", nil, nil) if err != nil { t.Fatalf("CollectExtraFiles: %v", err) } @@ -555,7 +555,7 @@ func TestCollectExtraFiles_CopyModeKeepsTargetFile(t *testing.T) { os.MkdirAll(targetDir, 0755) os.WriteFile(filepath.Join(targetDir, "rule1.md"), []byte("# Rule 1"), 0644) - if _, err := CollectExtraFiles(sourceDir, targetDir, "copy", false, false, false, ""); err != nil { + if _, err := CollectExtraFiles(sourceDir, targetDir, "copy", false, false, false, "", nil, nil); err != nil { t.Fatalf("CollectExtraFiles: %v", err) } @@ -799,7 +799,7 @@ func TestCollectExtraFiles_Flatten(t *testing.T) { // New local file in target (not from source) os.WriteFile(filepath.Join(targetDir, "new-agent.md"), []byte("# New Agent"), 0644) - result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, true, "") + result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, true, "", nil, nil) if err != nil { t.Fatalf("CollectExtraFiles: %v", err) } @@ -830,7 +830,7 @@ func TestCollectExtraFiles_FlattenSkipsExisting(t *testing.T) { os.WriteFile(filepath.Join(sourceDir, "conflict.md"), []byte("source version"), 0644) os.WriteFile(filepath.Join(targetDir, "conflict.md"), []byte("target version"), 0644) - result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, true, "") + result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, true, "", nil, nil) if err != nil { t.Fatalf("CollectExtraFiles: %v", err) } @@ -851,7 +851,7 @@ func TestCollectExtraFiles_ForceFlattenCollisionKeepsFirst(t *testing.T) { os.WriteFile(filepath.Join(targetDir, "a", "x.md"), []byte("A"), 0644) os.WriteFile(filepath.Join(targetDir, "b", "x.md"), []byte("B"), 0644) - result, err := CollectExtraFiles(sourceDir, targetDir, "", false, true, true, "") + result, err := CollectExtraFiles(sourceDir, targetDir, "", false, true, true, "", nil, nil) if err != nil { t.Fatalf("CollectExtraFiles: %v", err) } diff --git a/schemas/config.schema.json b/schemas/config.schema.json index f5ce5f70e..5eb782096 100644 --- a/schemas/config.schema.json +++ b/schemas/config.schema.json @@ -520,6 +520,18 @@ "description": "When true, files from subdirectories are synced directly into the target root instead of preserving directory structure.", "default": false }, + "include": { + "type": "array", + "items": { "type": "string" }, + "description": "Sync only source files that match one of these .gitignore-style patterns (path inside the source). A pattern without '/' matches at any depth; 'dir/' covers a folder. Not allowed with symlink mode or a single-file extra.", + "examples": [["index.md", "learning.md"], ["guides/", "**/*.md"]] + }, + "exclude": { + "type": "array", + "items": { "type": "string" }, + "description": "Skip source files that match one of these .gitignore-style patterns. Applied after include. Not allowed with symlink mode or a single-file extra.", + "examples": [["draft*", "images/"]] + }, "extension": { "type": "string", "description": "Transform each file through an extension before writing it to this target (copy mode only). A bare name resolves under the extensions directory; a path (containing a separator or starting with '.') is used directly.", diff --git a/schemas/project-config.schema.json b/schemas/project-config.schema.json index f8be4f6a6..ef2811f5d 100644 --- a/schemas/project-config.schema.json +++ b/schemas/project-config.schema.json @@ -455,6 +455,18 @@ "description": "When true, files from subdirectories are synced directly into the target root instead of preserving directory structure.", "default": false }, + "include": { + "type": "array", + "items": { "type": "string" }, + "description": "Sync only source files that match one of these .gitignore-style patterns (path inside the source). A pattern without '/' matches at any depth; 'dir/' covers a folder. Not allowed with symlink mode or a single-file extra.", + "examples": [["index.md", "learning.md"], ["guides/", "**/*.md"]] + }, + "exclude": { + "type": "array", + "items": { "type": "string" }, + "description": "Skip source files that match one of these .gitignore-style patterns. Applied after include. Not allowed with symlink mode or a single-file extra.", + "examples": [["draft*", "images/"]] + }, "extension": { "type": "string", "description": "Transform each file through an extension before writing it to this target (copy mode only). A bare name resolves under the extensions directory; a path (containing a separator or starting with '.') is used directly.", diff --git a/skills/skillshare/references/extras.md b/skills/skillshare/references/extras.md index 3ede69354..e2474ff33 100644 --- a/skills/skillshare/references/extras.md +++ b/skills/skillshare/references/extras.md @@ -37,6 +37,7 @@ skillshare extras init rules --no-tui ... # Skip prompts | `--as ` | File name at every target (default: `--file` name); requires `--file` | | `--mode ` | Sync mode: `merge` (default), `copy`, `symlink`; `import`, `prepend` or `append` only with `--file` | | `--flatten` | Sync subdirectory files into the target root; not with `symlink` or `--file` | +| `--include` / `--exclude ` | Sync only / skip matching files (`.gitignore` syntax on the path inside the source; repeatable); not with `symlink` or `--file` | | `--no-tui` | Skip interactive prompts | | `-p` / `-g` | Force project / global mode | @@ -52,6 +53,16 @@ skillshare extras personal --add-target ~/.claude --as CLAUDE.md --mode import `--as` sets the target filename for a single-file extra; it defaults to `file`. Run `skillshare sync extras` after adding the target. +```bash +skillshare extras docs --target ~/.claude/docs --add-include index.md +skillshare extras docs --target ~/.cursor/docs --add-exclude "draft*" --add-exclude images/ +``` + +`--add-include`, `--add-exclude`, `--remove-include` and `--remove-exclude` change one +target's file filters. A pattern without `/` matches at any depth; `dir/` covers a folder. +The next sync removes links to files that stop matching in `merge` mode; `copy` mode leaves +copied files in place. `sync` warns when an include matches no file. + ## extras list Show all configured extras with sync status per target. diff --git a/tests/integration/extras_filter_test.go b/tests/integration/extras_filter_test.go new file mode 100644 index 000000000..e0ba15591 --- /dev/null +++ b/tests/integration/extras_filter_test.go @@ -0,0 +1,92 @@ +//go:build !online + +package integration + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "skillshare/internal/testutil" +) + +// setupDocsExtra writes a docs extra with index.md and draft.md synced to one +// target, with extraTarget appended to the target entry, and returns the +// target directory. +func setupDocsExtra(t *testing.T, sb *testutil.Sandbox, extraTarget string) string { + t.Helper() + sb.CreateSkill("placeholder", map[string]string{"SKILL.md": "# Placeholder"}) + claude := sb.CreateTarget("claude") + + docsSource := filepath.Join(filepath.Dir(sb.SourcePath), "extras", "docs") + os.MkdirAll(docsSource, 0755) + os.WriteFile(filepath.Join(docsSource, "index.md"), []byte("# Index"), 0644) + os.WriteFile(filepath.Join(docsSource, "draft.md"), []byte("# Draft"), 0644) + + docsTarget := filepath.Join(sb.Home, ".claude", "docs") + os.MkdirAll(docsTarget, 0755) + + sb.WriteConfig(`source: ` + sb.SourcePath + ` +targets: + claude: + path: ` + claude + ` +extras: + - name: docs + targets: + - path: ` + docsTarget + extraTarget + ` +`) + return docsTarget +} + +func TestExtras_AddExclude_NextSyncPrunesExcludedLink(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + docsTarget := setupDocsExtra(t, sb, "") + sb.RunCLI("sync", "extras").AssertSuccess(t) + + sb.RunCLI("extras", "docs", "--add-exclude", "draft*", "-g").AssertSuccess(t) + sb.RunCLI("sync", "extras").AssertSuccess(t) + + if _, err := os.Lstat(filepath.Join(docsTarget, "draft.md")); !os.IsNotExist(err) { + t.Errorf("draft.md link should be pruned, lstat err = %v", err) + } + if !sb.IsSymlink(filepath.Join(docsTarget, "index.md")) { + t.Error("index.md should stay linked") + } +} + +func TestExtras_Init_IncludeWritesTargetFilter(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + setupDocsExtra(t, sb, "") + notesTarget := filepath.Join(sb.Home, ".claude", "notes") + + sb.RunCLI("extras", "init", "notes", "--target", notesTarget, "--include", "index.md", "-g").AssertSuccess(t) + + if cfg := sb.ReadFile(sb.ConfigPath); !strings.Contains(cfg, "include:\n - index.md") { + t.Errorf("expected include in config, got:\n%s", cfg) + } +} + +func TestExtras_Mode_SymlinkRejectedWithFilters(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + setupDocsExtra(t, sb, "\n include: [index.md]") + + result := sb.RunCLI("extras", "docs", "--mode", "symlink", "-g") + + result.AssertFailure(t) + result.AssertAnyOutputContains(t, "symlink") +} + +func TestSyncExtras_WarnsUnmatchedInclude(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + setupDocsExtra(t, sb, "\n include: [index.mdd]") + + result := sb.RunCLI("sync", "extras") + + result.AssertSuccess(t) + result.AssertAnyOutputContains(t, `include "index.mdd" matches no file`) +} diff --git a/ui/src/api/extras.ts b/ui/src/api/extras.ts index df0fe004b..4dbad4eb5 100644 --- a/ui/src/api/extras.ts +++ b/ui/src/api/extras.ts @@ -1,5 +1,5 @@ import { apiFetch } from './http'; -import type { ExtensionInfo, Extra, ExtraDiffResult, ExtrasSyncResult } from './types/extras'; +import type { ExtensionInfo, Extra, ExtraDiffResult, ExtraEditResult, ExtraFilterEntry, ExtrasSyncResult } from './types/extras'; export const extrasApi = { listExtras: () => apiFetch<{ extras: Extra[] }>('/extras'), @@ -53,6 +53,23 @@ export const extrasApi = { method: 'POST', body: JSON.stringify(target), }), + previewExtraFilter: (name: string, include: string[], exclude: string[]) => + apiFetch<{ files: ExtraFilterEntry[]; unmatched: string[] | null }>(`/extras/${encodeURIComponent(name)}/preview`, { + method: 'POST', + body: JSON.stringify({ include, exclude }), + }), + // A new path or file name also clears the old place and syncs. + editExtraTarget: (name: string, path: string, target: { path: string; mode: string; flatten: boolean; extension: string; as: string; include: string[]; exclude: string[] }) => + apiFetch(`/extras/${encodeURIComponent(name)}/targets`, { + method: 'PUT', + body: JSON.stringify({ path, target }), + }), + // source: omitted = unchanged, '' = the default folder; a new source relinks every target. + editExtra: (name: string, data: { name?: string; source?: string }) => + apiFetch(`/extras/${encodeURIComponent(name)}`, { + method: 'PATCH', + body: JSON.stringify(data), + }), removeExtraTarget: (name: string, path: string) => apiFetch<{ success: boolean }>(`/extras/${encodeURIComponent(name)}/targets`, { method: 'DELETE', diff --git a/ui/src/api/types/extras.ts b/ui/src/api/types/extras.ts index 12061f31d..ded862782 100644 --- a/ui/src/api/types/extras.ts +++ b/ui/src/api/types/extras.ts @@ -5,6 +5,9 @@ export interface ExtraTarget { flatten: boolean; extension?: string; // transform extension name; presence implies copy mode as?: string; // single-file extra: target filename + include?: string[]; + exclude?: string[]; + file_count: number; // source files this target syncs after include/exclude status: string; // "synced" | "drift" | "modified" | "not synced" | "no source" } @@ -18,6 +21,19 @@ export interface Extra { targets: ExtraTarget[]; } +export interface ExtraFilterEntry { + file: string; + status: 'synced' | 'not_included' | 'excluded'; + reason?: string; // the exclude pattern that dropped the file +} + +/** What an edit that moves files returns: the sync it ran and any old-location cleanup errors. */ +export interface ExtraEditResult { + success: boolean; + extras?: ExtrasSyncResult[]; + prune_errors?: string[]; +} + export interface ExtensionInfo { name: string; description?: string; diff --git a/ui/src/components/extras/ExtraEditDialogs.tsx b/ui/src/components/extras/ExtraEditDialogs.tsx new file mode 100644 index 000000000..7cc598aee --- /dev/null +++ b/ui/src/components/extras/ExtraEditDialogs.tsx @@ -0,0 +1,315 @@ +import { useState, type ReactNode } from 'react'; +import { keepPreviousData, useQuery } from '@tanstack/react-query'; +import { X } from 'lucide-react'; +import { api } from '../../api/client'; +import type { Extra, ExtraEditResult, ExtraTarget } from '../../api/client'; +import { queryKeys } from '../../lib/queryKeys'; +import { buildSyncToast, sumEntry, syncToastType } from '../../lib/extrasSyncToast'; +import { shortenHome } from '../../lib/paths'; +import { useToast } from '../Toast'; +import { useT, plural } from '../../i18n'; +import Button from '../Button'; +import DialogShell from '../DialogShell'; +import { Select } from '../Input'; +import FilterSection from '../targets/FilterSection'; + +/** /, for a single-file extra's source or target file, with the separator the folder already uses (a backslash on Windows). */ +export const joinFile = (dir: string, file: string) => { + const sep = dir.lastIndexOf('\\') > dir.lastIndexOf('/') ? '\\' : '/'; + return `${dir.replace(/[\\/]+$/, '')}${sep}${file}`; +}; + +export const MODES = ['merge', 'copy', 'symlink'] as const; +// A single file can't be a directory symlink; import writes an @ line instead. +export const FILE_MODES = ['merge', 'copy', 'import', 'prepend', 'append'] as const; + +const Mono = ({ children }: { children: ReactNode }) => {children}; + +/** Reports a save: the sync it ran when files moved, else a plain saved toast. */ +function useSaveToast() { + const { toast } = useToast(); + const t = useT(); + return (name: string, res: ExtraEditResult) => { + if (res.prune_errors?.length) toast(t('extras.edit.pruneFailed', { error: res.prune_errors.join('; ') }), 'error'); + if (!res.extras) { + toast(t('extras.edit.saved', { name }), 'success'); + return; + } + const totals = sumEntry(res.extras.find((e) => e.name === name)); + toast(buildSyncToast(t('extras.toast.syncOne', { name }), t('extras.toast.syncOneFailed', { name }), totals, false, t), syncToastType(totals)); + }; +} + +function DialogFrame({ title, subtitle, saving, canSave, saveLabel, onClose, onSave, children }: { + title: string; + subtitle: ReactNode; + saving: boolean; + canSave: boolean; + saveLabel: string; + onClose: () => void; + onSave: () => void; + children: ReactNode; +}) { + const t = useT(); + return ( + +
+
+

{title}

+

{subtitle}

+
+ +
+
{children}
+
+ + + +
+
+ ); +} + +/** Where a target syncs, how, and which files: everything Add target sets, plus the file filters. */ +export function EditTargetDialog({ extra, target, extensions, markFor, onClose, onSaved }: { + extra: Extra; + target: ExtraTarget; + extensions: string[]; + markFor: (path: string) => ReactNode; + onClose: () => void; + onSaved: () => void; +}) { + const t = useT(); + const { toast } = useToast(); + const report = useSaveToast(); + const single = Boolean(extra.file); + const [path, setPath] = useState(target.path); + const [mode, setMode] = useState(target.mode); + const [flatten, setFlatten] = useState(target.flatten); + const [extension, setExtension] = useState(target.extension ?? ''); + const [as, setAs] = useState(target.as ?? ''); + const [filters, setFilters] = useState({ include: target.include ?? [], exclude: target.exclude ?? [] }); + const [saving, setSaving] = useState(false); + + const filtered = !single && mode !== 'symlink'; + const preview = useQuery({ + queryKey: queryKeys.extrasPreview(extra.name, filters.include, filters.exclude), + queryFn: () => api.previewExtraFilter(extra.name, filters.include, filters.exclude), + placeholderData: keepPreviousData, + enabled: filtered && extra.source_exists, + }); + const files = preview.data?.files ?? []; + const entries = files.map((f) => ({ skill: f.file, target: path, status: f.status, reason: f.reason ?? '' })); + const dropped = files.filter((f) => f.status !== 'synced').length; + const unmatched = preview.data?.unmatched ?? []; + + const trimmed = path.trim(); + const moved = trimmed !== target.path || as.trim() !== (target.as ?? ''); + const patterns = (target.include?.length ?? 0) + (target.exclude?.length ?? 0); + const flat = flatten && mode !== 'symlink'; + const filtersChanged = filters.include.join('\n') !== (target.include ?? []).join('\n') || filters.exclude.join('\n') !== (target.exclude ?? []).join('\n'); + const canSave = trimmed !== '' && !saving; + + const save = async () => { + setSaving(true); + try { + const res = await api.editExtraTarget(extra.name, target.path, { + path: trimmed, mode: extension ? 'copy' : mode, flatten: flat, extension, as: as.trim(), + include: filtered ? filters.include : [], exclude: filtered ? filters.exclude : [], + }); + report(extra.name, res); + onSaved(); + } catch (err) { + toast((err as Error).message, 'error'); + setSaving(false); + } + }; + + const was = (value: string) => {t('extras.edit.was', { value: shortenHome(value) })}; + + return ( + {extra.name} → {shortenHome(target.path)}} + saving={saving} + canSave={canSave} + saveLabel={t(moved ? 'extras.edit.saveAndSync' : 'common.save')} + onClose={onClose} + onSave={() => void save()} + > +
+ {markFor(trimmed)} +
+ + setPath(e.target.value)} disabled={saving} /> + {trimmed !== target.path && was(target.path)} +
+
+
+ {single ? ( +
+ + setAs(e.target.value)} disabled={saving} /> +
+ ) : ( +
+ {t('extras.modal.colExtension')} + ({ value: m, label: m, description: t(single ? `extras.fileModeDescription.${m}` : `extras.modeDescription.${m}`) }))} + disabled={saving || Boolean(extension)} + /> +
+ {!single && ( +
+ {t('extras.flatten')} + + + {t(flat ? 'extras.flattenOn' : 'extras.flattenOff')} + +
+ )} +
+ {moved && ( +
+ {t(target.mode === 'copy' ? 'extras.edit.moveCopyNote' : 'extras.edit.moveNote', { from: shortenHome(target.path), to: shortenHome(trimmed) })} +
+ )} + + {!single && ( +
+

{t('extras.edit.files')}

+ {mode === 'symlink' ? ( +
+ {patterns > 0 ? t(plural('extras.edit.symlinkClears', patterns), { count: patterns }) : t('targetDetail.symlinkNoFilters')} +
+ ) : ( + <> + 0 ? ( +
+ {unmatched.map((p) => t('extras.edit.unmatched', { pattern: p, name: extra.name })).join(' ')} +
+ ) : undefined} + /> + {dropped > 0 && filtersChanged && !moved && ( +
+ {mode === 'copy' + ? t('extras.edit.copyNote', { path: shortenHome(target.path) }) + : t(plural('extras.edit.pruneNote', dropped), { count: dropped, name: extra.name })} +
+ )} + + )} +
+ )} +
+ ); +} + +/** Name and source folder of an extra. A new folder relinks every target; a new name changes only the config. */ +export function EditExtraDialog({ extra, sharedDir, onClose, onSaved }: { + extra: Extra; + sharedDir: string; + onClose: () => void; + onSaved: () => void; +}) { + const t = useT(); + const { toast } = useToast(); + const report = useSaveToast(); + const [name, setName] = useState(extra.name); + const wasCustom = extra.source_type === 'per-extra'; + const [custom, setCustom] = useState(wasCustom); + const [source, setSource] = useState(wasCustom ? shortenHome(extra.source_dir) : ''); + const [saving, setSaving] = useState(false); + + const trimmedName = name.trim(); + const trimmedSource = source.trim(); + const renamed = trimmedName !== extra.name; + // Back to the shared folder means the folder named after the extra there. + const sourceChanged = custom ? trimmedSource !== '' && trimmedSource !== shortenHome(extra.source_dir) : wasCustom; + const canSave = trimmedName !== '' && (renamed || sourceChanged) && !(custom && trimmedSource === '') && !saving; + + const save = async () => { + setSaving(true); + try { + const res = await api.editExtra(extra.name, { + ...(renamed && { name: trimmedName }), + ...(sourceChanged && { source: custom ? trimmedSource : '' }), + }); + report(trimmedName, res); + onSaved(); + } catch (err) { + toast((err as Error).message, 'error'); + setSaving(false); + } + }; + + const sharedPath = joinFile(shortenHome(sharedDir), wasCustom ? trimmedName || '…' : extra.name); + const newPath = custom ? trimmedSource : sharedPath; + + return ( + {shortenHome(extra.file ? joinFile(extra.source_dir, extra.file) : extra.source_dir)}} + saving={saving} + canSave={canSave} + saveLabel={t(sourceChanged ? 'extras.edit.saveAndSync' : 'common.save')} + onClose={onClose} + onSave={() => void save()} + > +
+ + setName(e.target.value)} disabled={saving} /> + {renamed && {t('extras.edit.was', { value: extra.name })}} +
+
+ {t('extras.modal.source')} + setSource(e.target.value)} placeholder={t('extras.modal.sourcePathPlaceholder')} aria-label={t('extras.sourceType.custom')} disabled={saving} /> + + ) : ( + {sharedPath} + )} + {sourceChanged && {t('extras.edit.was', { value: shortenHome(extra.source_dir) })}} +
+ {sourceChanged ? ( +
{t('extras.edit.relinkNote', { path: newPath })}
+ ) : renamed && ( +
{t('extras.edit.renameNote', { path: shortenHome(extra.source_dir) })}
+ )} +
+ ); +} diff --git a/ui/src/components/targets/FilterSection.tsx b/ui/src/components/targets/FilterSection.tsx index 5f5265968..67c0c7718 100644 --- a/ui/src/components/targets/FilterSection.tsx +++ b/ui/src/components/targets/FilterSection.tsx @@ -1,4 +1,4 @@ -import { Fragment, useState } from 'react'; +import { Fragment, useState, type ReactNode } from 'react'; import { Link } from 'react-router-dom'; import { ChevronDown, ChevronRight } from 'lucide-react'; import type { SyncMatrixEntry } from '../../api/client'; @@ -8,7 +8,7 @@ import { useI18n, useT, plural } from '../../i18n'; import PatternInput from './PatternInput'; import { joinList, patternName, togglePatterns } from './targetView'; -type Kind = 'skill' | 'agent'; +type Kind = 'skill' | 'agent' | 'file'; const MODES = ['merge', 'copy', 'symlink'] as const; // Sentences that end in a full-width stop run on without a space. const CJK_STOP = /[。!?]$/; @@ -31,13 +31,15 @@ interface Props { alsoReadBy?: string[]; /** Targets with skills on whose folder this tool also reads, so it sees their skills twice */ readsFrom?: string[]; + /** Shown in place of the include hint, such as an include that matches nothing */ + includeWarning?: ReactNode; } /** Include and exclude patterns with a live preview; a click on a preview row edits them. */ -export default function FilterSection({ kind, mode, name, include, exclude, onChange, entries, loaded, loading, error, disabled, alsoReadBy = [], readsFrom = [] }: Props) { +export default function FilterSection({ kind, mode, name, include, exclude, onChange, entries, loaded, loading, error, disabled, alsoReadBy = [], readsFrom = [], includeWarning }: Props) { const { t, locale } = useI18n(); const [help, setHelp] = useState(false); - const agent = kind === 'agent'; + const files = kind === 'file'; const synced = entries.filter((e) => e.status === 'synced').length; const reason = (e: SyncMatrixEntry) => { @@ -50,7 +52,7 @@ export default function FilterSection({ kind, mode, name, include, exclude, onCh } }; - const baseHint = t(agent ? 'targetDetail.includeHint.agents' : 'targetDetail.includeHint.skills'); + const baseHint = t(`targetDetail.includeHint.${kind}s`); const includeHint = alsoReadBy.length > 0 ? baseHint + (CJK_STOP.test(baseHint) ? '' : ' ') + t('targetDetail.alsoReadBy.filterHint', { names: joinList(alsoReadBy, locale) }) : baseHint; @@ -71,7 +73,7 @@ export default function FilterSection({ kind, mode, name, include, exclude, onCh <> {loaded && (

- {t(plural(`targetDetail.summary.${agent ? 'agents' : 'skills'}`, entries.length), { synced, total: entries.length, name })} + {t(plural(`targetDetail.summary.${kind}s`, entries.length), { synced, total: entries.length, name })}

)} {readers} @@ -79,12 +81,12 @@ export default function FilterSection({ kind, mode, name, include, exclude, onCh
onChange({ include: next, exclude })} disabled={disabled} /> - {includeHint} + {includeWarning ?? {includeHint}}
onChange({ include, exclude: next })} disabled={disabled} /> - {t(agent ? 'targetDetail.excludeHint.agents' : 'targetDetail.excludeHint.skills')} + {t(`targetDetail.excludeHint.${kind}s`)}