Commit Graph
82 Commits
Author SHA1 Message Date
Willie 9a4fbdc18f feat(sync): add agent sync engine with merge, symlink, and copy modes
Add SyncAgents() dispatcher supporting all three sync modes:
- merge: per-file symlinks with local file preservation
- symlink: whole directory symlink to agent source
- copy: file copy with content-diff detection

Add CheckAgentCollisions() to detect agents that flatten to the same
filename from different subdirectories.

Add PruneOrphanAgentLinks() for merge mode and PruneOrphanAgentCopies()
for copy mode to clean up stale agent files in targets.

Add CollectAgents() to copy non-symlinked .md files from target back
to agent source directory.

18 tests covering all modes, collision detection, pruning, and collect.
2026-04-07 18:05:40 +08:00
Willie 9ff006988a fix(sync): canonicalize paths for relative symlinks, atomic reformat
Two correctness improvements from Codex review:

1. EvalSymlinks before relative-link decisions: shouldUseRelative and
   createLink now resolve symlinked ancestors via EvalSymlinks so that
   a project opened through a symlinked workspace, or a target dir that
   traverses a symlink, produces correct relative paths (or falls back
   to absolute when paths diverge from the project root).

2. Atomic reformat via reformatLink: instead of remove→create (which
   loses the link on createLink failure), reformat now creates a temp
   link and renames it over the original. On Unix this is atomic; on
   Windows it falls back to remove→create when rename fails.

Tests added for symlinked project root, divergent target symlink,
and reformatLink atomic swap.
2026-04-07 17:26:37 +08:00
Willie adec63727b fix(sync): prevent infinite reformat loop on Windows junction fallback
On Windows without Developer Mode, createLink falls back to an NTFS
junction (always absolute). linkNeedsReformat would then return true
on every sync, causing a remove→recreate loop.

Add build-tagged canCreateRelativeLink(): returns true on Unix, and
on Windows probes once with sync.Once by creating a test relative
symlink in a temp dir. linkNeedsReformat skips reformat when the
platform cannot create relative links.

Also use filepath.Clean instead of filepath.Abs in resolveReadlink
(input is already absolute, avoids unnecessary os.Getwd).

Addresses PR #122 review feedback.
2026-04-07 17:26:37 +08:00
Willie de0291c37c fix(sync): handle root projectRoot prefix, use abs paths for Windows Rel
- shouldUseRelative: avoid double separator when projectRoot is /
- symlink_windows.go: use pre-resolved absTarget/absSource for Rel
- extras.go: check os.Remove error on wrong symlink replacement
2026-04-07 17:26:37 +08:00
Willie 3316c9073e fix(sync): resolve relative readlink against link parent, check os.Remove errors
filepath.Abs(dest) on a relative readlink result resolves against CWD,
not the symlink's parent directory. This broke the 'already correct'
check when comparing relative symlinks to absolute source paths.

Add resolveReadlink() helper that joins relative targets with
filepath.Dir(linkPath) before calling filepath.Abs.

Also check os.Remove errors in all reformat paths instead of ignoring
them silently.

Addresses PR #122 review feedback.
2026-04-07 17:26:37 +08:00
Willie e51fe60254 fix(sync): upgrade existing absolute symlinks to relative in project mode
sync previously skipped symlinks that pointed to the correct source,
even if their format (absolute vs relative) didn't match the expected
mode. This meant existing absolute symlinks in project mode were never
converted to relative on subsequent syncs.

Add linkNeedsReformat(dest, wantRelative) helper that checks whether
the raw readlink result has the wrong format. All four 'already
correct' skip points now check format and recreate when mismatched:

- SyncTargetMergeWithSkills (skills merge mode)
- SyncTarget (skills symlink mode)
- syncExtraSymlinkMode (extras directory symlink)
- syncOneExtraFile (extras per-file merge)

Global mode is unaffected: shouldUseRelative returns false, so
linkNeedsReformat never triggers on absolute links.

Also fix macOS /var → /private/var path mismatch in
TestSyncProject_RelativeSymlinks by EvalSymlinks on expected path.
2026-04-07 17:26:37 +08:00
Willie fe244e8289 refactor(sync): simplify shouldUseRelative and hoist extras computation
- Use utils.PathHasPrefix/PathsEqual for Windows case-insensitivity
- Eliminate redundant filepath.Clean call
- Hoist shouldUseRelative in syncExtraPerFile (compute once, pass bool)
- Add invariant comment in SyncTargetMergeWithSkills
2026-04-07 17:26:37 +08:00
Willie bbf2e4343e feat(sync): unify extras symlinks through createLink
Replace direct os.Symlink calls in extras.go with createLink, gaining:
- Relative symlink support in project mode
- Windows junction fallback for extras (previously missing)

Thread projectRoot through SyncExtra, CollectExtraFiles, and all callers.

Ref: #120
2026-04-07 17:26:37 +08:00
Willie 3c8c56002d feat(sync): wire projectRoot through merge and symlink sync paths
SyncTargetMerge, SyncTargetMergeWithSkills, CreateSymlink, and SyncTarget
now accept projectRoot. When non-empty, createLink uses relative symlinks
for paths under the project root.

All existing callers pass empty string (global mode, no behavior change).

Ref: #120
2026-04-07 17:26:37 +08:00
Willie 1d62b15713 feat(sync): add relative parameter to createLink
Unix: computes filepath.Rel from link dir to source, falls back to
absolute on error.
Windows: tries os.Symlink with relative path first (Developer Mode),
falls back to mklink /J with absolute paths.

All existing call sites pass false (no behavior change yet).

Ref: #120
2026-04-07 17:26:37 +08:00
Willie c450078c69 feat(sync): add shouldUseRelative helper for project-mode relative symlinks
Determines whether both source and target paths are under the project
root, in which case relative symlinks are portable and can be committed
to git.

Ref: #120
2026-04-07 17:26:37 +08:00
Willie 343e29cfe5 fix(ui,server): harden target management, toggle, and tracked-repo UX
- Enable frontmatter parsing in DiscoverSourceSkillsAll so /api/skills
  returns saved targets (fixes target display reverting to All)
- Skip tracked-repo skills in batch/single target handlers to prevent
  dirty git state; reject with 400 for single-skill endpoint
- Add RefreshMetaHashes to recompute audit hashes after SKILL.md edits;
  batch handler refreshes outside the write lock
- Show 'Uninstall Repo' with confirm dialog for tracked-repo members
  instead of the always-failing individual uninstall action
- Return 409 Conflict when enabling a skill disabled by glob pattern
  in .skillignore/.skillignore.local instead of false success
- Preserve IsInRepo flag for root-skillignore-disabled skills so they
  remain visible in the Tracked tab after disable
- Update changelog and website changelog for v0.18.7
2026-04-04 17:05:22 +08:00
Willie f01ec9ec12 fix(sync): summarize resolution warnings instead of printing each one
With 25000+ skipped skills (standard naming + name collisions),
the CLI sync output was flooded with per-skill warning lines.

Now prints a concise summary:
  12345 skill(s) skipped (naming validation)
  456 name collision(s) excluded

Applied to both merge and copy sync modes.
2026-04-01 00:32:49 +08:00
Willie ccdafd3293 feat(sync): add target_naming config option (flat/standard)
Add per-target target_naming setting that controls how skill directories
are named in sync targets. 'flat' (default) preserves the existing
flattened __ separator behavior. 'standard' uses the SKILL.md name field
directly, following the Agent Skills specification.

Standard mode:
- Validates SKILL.md names match directory basenames
- Detects and skips name collisions with warnings
- Auto-migrates managed entries when switching from flat to standard
- Preserves legacy entries when bare name is already occupied

Also includes:
- Per-target toggle via CLI (--target-naming), TUI (N key), and Web UI
- Collision output redesigned as deduplicated compact summary
- Config inheritance: global target_naming → per-target override
- JSON schema + UI validation for the new field

Closes #110
2026-04-01 00:32:49 +08:00
Willie 18fac69e56 fix(collect): resolve inherited mode and stale manifest on copy→merge switch 2026-03-29 04:59:23 +08:00
Willie f51cc8106b feat(sync): add DiscoverSourceSkillsAll with Disabled field
New discovery function that includes .skillignore-d skills marked with
Disabled=true. Existing discovery functions are unchanged — Disabled
defaults to false for backward compatibility.
2026-03-29 04:59:23 +08:00
Willie 41dd81b7f2 refactor: migrate all callers to SkillsConfig() / EnsureSkills()
44 files across CLI commands, sync engine, and server handlers now use
SkillsConfig() for reads and EnsureSkills() for writes instead of
accessing flat TargetConfig fields directly.

Key changes:
- sync engine (SyncTargetMerge/Copy/Symlink): reads sc := target.SkillsConfig()
- target commands: filter add/remove and mode set use EnsureSkills()
- target TUI: mode picker, filter ops, detail panel all via SkillsConfig()
- server handlers: backup, restore, targets, sync, diff, collect, analyze
- init/init_project: new target creation uses Skills sub-key
- doctor, status, diff: target display reads from SkillsConfig()
- computeTargetDiff: accepts config.TargetConfig directly (was anon struct)
2026-03-29 04:59:23 +08:00
Willie dbce8ffa20 fix: update registry.yaml path and clean up formatting
Update registry.yaml path references from ~/.config/skillshare/
to ~/.config/skillshare/skills/ in schema description, quick
reference docs, and migration guide. Fix whitespace alignment
in lint.go constants and remove blank line in skill.go imports.
2026-03-27 02:17:54 +08:00
Willie 64ed9b046e feat(analyze): add malformed-frontmatter lint rule and polish UI/TUI
- Surface YAML parse errors from calcContextFromContent as a new
  "malformed-frontmatter" lint issue instead of silently ignoring them
- Fix help text to say "Top 10" (was "Top 5") matching actual constant
- Shorten TUI list title to target name only; move skill count to
  stats line so the header no longer wraps on narrow terminals
- Truncate long skill names in TUI to keep token counts visible
- Change "All Skills" icon block to green (matches Skills summary card)
2026-03-26 19:20:52 +08:00
Willie d377e6bbf6 refactor(analyze): simplify lint engine and fix review findings
- Eliminate double YAML parse: extend calcContextFromContent to return
  name, remove parseFrontmatterName helper
- Pre-compute lint icons (lintIconError/lintIconWarning) to avoid
  lipgloss.NewStyle() allocation per render frame
- Use tc.Red/tc.Yellow for Quality section icons (consistency)
- Extract check type string constants (checkFieldEmpty, etc.)
- Panic on embedded rule load failure instead of silent nil return
- Rename "Targets: all" to "Restricted to" (only shown when set)
- Fix struct field alignment (gofmt)
2026-03-26 19:20:52 +08:00
Willie 57ce3f507f feat(analyze): wire lint into discovery and analyze data flow
Populate LintIssues during skill discovery (collectContext path) and
propagate them through analyzeSkillEntry so JSON output includes lint
findings per skill.
2026-03-26 19:20:52 +08:00
Willie f5e5588290 test(analyze): add unit tests for all 7 lint rules 2026-03-26 19:20:52 +08:00
Willie 2e43e3726c feat(analyze): add lint rules YAML and LintSkill engine 2026-03-26 19:20:52 +08:00
Willie 2811a19fcf feat(analyze): return description from calcContextFromContent for TUI 2026-03-26 19:20:52 +08:00
Willie 620141af2b feat(analyze): add context analysis command
Analyze context window usage per target, showing always-loaded
(description) vs on-demand (body) token costs.

- Single-pass discovery with frontmatter-aware char/token counting
- Per-target filtering (include/exclude/symlink mode)
- Unified output when all targets have identical skills
- Verbose mode shows top 10 largest descriptions
- Project mode (-p) support
- JSON output (--json)
- Integration tests
2026-03-26 19:20:52 +08:00
Willie 31ad27e966 test(extras): add FlattenRel and CheckSyncStatus unit tests
FlattenRel: 100% coverage (flatten, no-flatten, collision).
CheckSyncStatus: 0% → 84% (synced, drift, flatten synced, flatten
drift, flatten collision not drift, copy mode).
2026-03-25 21:14:16 +08:00
Willie 2ce1544dd1 docs: add flatten documentation, changelog, and contributor
Extras command docs, config reference, built-in skill, website
changelog, release notes. Add mk-imagine to README contributors.

Ref: #97
2026-03-25 21:14:16 +08:00
Willie 5d9dd0cdbb feat(extras): add flatten option to extras sync engine
When flatten=true, SyncExtra maps subdirectory files to target root
using filepath.Base(). First file wins on collision, subsequent are
skipped with warnings. Includes config validation, sync-time guard,
CheckSyncStatus collision handling, and CollectExtraFiles support.

Ref: #97
2026-03-25 21:14:16 +08:00
Willie 8c0e97ac13 feat: add remove action (R key) to target list TUI
Press R on a selected target to show a confirmation overlay.
Confirming exits the TUI and dispatches the full target remove
flow (backup + unlink + config update), matching the existing
exit-with-action pattern used by the skill list TUI.

Supports both global and project modes.
2026-03-19 16:33:24 +08:00
Willie dc82b93d05 fix: address code review findings for auto-create target dirs
- Remove early return in dry-run so linked/copied counts are populated
  correctly (P1: UI preview no longer hides Sync Now button)
- Use local quietDryRun flag instead of mutating global DiagOutput
  to suppress per-skill messages (P2: safe under parallel sync)
- Use "Will create" for dry-run, "Created" for actual sync (P3)
- Include dir_created in allUpToDate check so empty source + missing
  dir still shows Sync Now in the preview modal
2026-03-19 04:16:36 +08:00
Willie 643e3c5c07 fix: auto-create missing target directories with notification (#87)
v0.17.5 blocked sync when target directories didn't exist, which
prevented first-time users on fresh CLI installs from syncing.

Sync now auto-creates missing directories and reports what it did
in CLI output, dry-run preview, and the Web UI. Init also creates
target directories when it detects an installed CLI tool.

Web UI: Sync Preview modal stays open after sync with a success
banner instead of immediately closing, so users can review results.

Closes #87
2026-03-19 03:57:08 +08:00
Willie 6b3858620f feat(skillignore): add .skillignore.local for local pattern overrides
Allow users to override shared .skillignore patterns without modifying
the committed file. ReadMatcher transparently merges .skillignore +
.skillignore.local (local appended last so !negation rules win).

- Matcher.HasLocal flag tracks .local presence for CLI reporting
- IgnoreStats gains RootLocalFile, RepoLocalFiles, HasLocal() method
- sync/status/doctor show ".local active" indicator
- 6 unit tests + 2 integration tests
- Docs: file-structure, sync, status, doctor, best-practices, creating-skills, org-sharing
2026-03-18 22:35:02 +08:00
Willie 92603f5be6 feat: add config save validation and sync safety checks
Validate config semantics (source path, sync modes, target paths) at
save time (API + CLI) instead of failing at sync time with cryptic
errors. Sync no longer auto-creates missing target directories — fails
fast to catch typos like ~/.cusor/skills. Dry-run also validates paths.

- ValidateConfig / ValidateProjectConfig with warnings + errors
- handlePutConfig returns 400 for invalid configs, 200 + warnings
- handleSync pre-checks via ValidateConfig
- ensureRealTargetDir shared helper (replaces duplicated blocks)
- UI: warning toast on config save, warning banners on sync/preview
- Dashboard shows full absolute source path
2026-03-18 22:35:02 +08:00
Willie b2f5592cdb refactor(discovery): extract shared walk, add DiscoverSourceSkillsWithStats
Unify ~160 lines of duplicated walk logic from DiscoverSourceSkills and
DiscoverSourceSkillsLite into a single discoverSourceSkillsInternal
function controlled by discoverOptions (parseFrontmatter, collectIgnored,
collectTracked).

Add DiscoverSourceSkillsWithStats which returns IgnoreStats populated
with root/repo .skillignore file paths, active patterns, and ignored
skill relPaths. When collectIgnored is true, CanSkipDir is bypassed so
the file-level Match check can record every ignored SKILL.md path.

Add Patterns() method to skillignore.Matcher to expose the original
pattern strings stored during Compile().
2026-03-18 00:19:30 +08:00
Willie 4214cb1038 feat(skillignore): upgrade to full gitignore-compatible syntax
Replace the naive string matcher (~40 lines) with a proper gitignore
implementation (~200 lines, no external deps) supporting **, ?, [abc],
!negation, /anchored, pattern/ (dir-only), and \#/\! escapes.

New Matcher API (Compile, ReadMatcher, Match, CanSkipDir, HasRules)
replaces the old Match/ReadPatterns functions (kept as deprecated
wrappers). Call sites in sync.go and install_discovery.go updated.
Also fixes isDir=true for install discovery (skill paths are dirs).

100% test coverage on skillignore package (~150 table-driven cases).
Added 7 sync discovery tests and 5 install integration tests covering
**, !negation, pattern/, [Tt] char class, and combined patterns.
2026-03-18 00:19:30 +08:00
Willie 1c537797bb feat(discovery): add SkipDir optimization and root-level .skillignore
Skip entire ignored directory trees during walk instead of filtering
at SKILL.md level. Support root-level .skillignore at source root
for globally muting skills or excluding patterns.

Root patterns checked first (can skip entire tracked repos), then
repo-level patterns. Both layers use filepath.SkipDir for performance.

Ref: #83
2026-03-18 00:19:30 +08:00
Willie 6e89577948 refactor(discovery): extract isSkillIgnored helper, unify tracked repo detection
- Extract duplicate .skillignore filtering block into isSkillIgnored()
- Use utils.IsTrackedRepoDir consistently in DiscoverSourceSkillsLite
- Fix unchecked os.WriteFile in skillignore test
2026-03-18 00:19:30 +08:00
Willie d925bf4e58 fix(discovery): respect .skillignore in source discovery (#83)
DiscoverSourceSkills and DiscoverSourceSkillsLite now load .skillignore
from tracked repos and skip matching paths during walk. This prevents
false warnings in doctor/status/list for vendored SKILL.md files
(e.g. .venv/ inside a tracked repo).

Extract shared skillignore package from internal/install so both
install-time and source discovery use the same filtering logic.
2026-03-18 00:19:30 +08:00
Willie 7858cb2c40 feat(api): add sync-matrix API and ClassifySkillForTarget
Backend for Filter Studio feature:
- ClassifySkillForTarget() in internal/sync/classify.go — determines
  skill sync status per target (synced/excluded/not_included/
  skill_target_mismatch) with reason strings
- firstMatchingPattern() helper in filter.go for exclude reason reporting
- GET /api/sync-matrix — returns full skill×target classification matrix
- POST /api/sync-matrix/preview — what-if preview with draft patterns
- 8 classify unit tests + 7 handler tests (empty, filters, query param,
  preview, invalid pattern, missing target)
2026-03-17 04:48:42 +08:00
Willie 767ad31ec3 fix(collect): skip .git directories when pulling nested skills to source
copyDirectoryWithState did not skip .git/ dirs, causing collect to fail
on git-cloned repos (e.g. obra/superpowers) — filepath.Walk would abort
on .git pack files, leaving only empty directories in source.

Add copyDirectorySkipGit() variant and use it in PullSkill. Existing
copyDirectory (used by copy-mode sync) is unchanged.
2026-03-13 13:37:12 +08:00
Willie 405a2f907a feat(extras): add mode command for CLI, TUI, and Web UI
Add ability to change sync mode of an extra's target across all three
interfaces: CLI (`extras mode`/shorthand `extras <name> --mode`),
TUI (`M` key with mode picker overlay), and Web UI (inline Select
dropdown per target with PATCH /api/extras/{name}/mode endpoint).

Fix sync behavior so symlinks from a previous mode are auto-replaced
without --force, while regular files still require explicit --force.

Consolidate sync mode list into config.ExtraSyncModes single source
of truth. Fix Select component missing disabled prop and add viewport
collision detection with useLayoutEffect.

Includes 8 integration tests covering mode command happy path, error
cases, shorthand syntax, and mode-switch sync behavior.
2026-03-12 16:45:02 +08:00
Willie d97e5a7c33 refactor(extras): consolidate duplicate logic and fix sync --all --json output
- Move checkExtrasSyncStatus to sync.CheckSyncStatus (shared)
- Add sync.EffectiveMode helper to replace inline mode defaults
- Add config.ValidateExtraMode to centralize mode validation
- Fix sync --all --json outputting two separate JSON objects
  by merging extras into the skills JSON output
- Fix swallowed JSON decode error in handleExtrasSync
- Remove dead symlink check in CollectExtraFiles (filepath.Walk
  follows symlinks so the check was unreachable)
- Fix integration test extras paths to use extras/<name>/ layout
2026-03-12 16:45:02 +08:00
Willie a786c1fe79 feat(extras): add init TUI wizard, collect command, and sync --json
- extras init TUI: multi-step bubbletea wizard (name → target → mode → confirm)
- extras collect: reverse-sync local files from target back to extras source
  with --from, --dry-run flags and dual-mode (global/project) support
- sync extras --json: structured JSON output for sync extras command
- CollectExtraFiles in internal/sync with tests
2026-03-12 16:45:02 +08:00
Willie 7223ac52f4 fix(sync): preserve non-json dry-run output stream
Keep sync dry-run diagnostics on stdout by default to avoid non-JSON behavior regressions. Introduce sync.DiagOutput so JSON mode can silence diagnostics via io.Discard at command entry and restore after execution. Update search JSON integration assertion to match fully silent progress behavior.
2026-03-06 02:15:36 +08:00
Willie 6b4a8782bd fix(cli): ensure --json mode outputs pure JSON to stdout
Address code review feedback from PR #67:

- Move all dry-run diagnostic messages (internal/sync) from stdout to
  stderr so they don't pollute JSON output
- Suppress UI output (spinners, headers, warnings) in uninstall --json
  mode by adding jsonOutput guards across all phases
- Return nil after writeJSONError to prevent dual output (JSON + plain
  text error) in install and sync commands
- Handle json.MarshalIndent error in writeJSONError with stderr fallback
- Merge duplicated discovery logic (JSON vs non-JSON branches) in sync,
  sync_project, diff, and collect using nullable spinner pattern
- Remove checkRepoDirty alias in status.go, call isRepoDirty directly
- Remove extractJSON test workaround — tests now assert stdout is valid
  JSON directly, enforcing the clean-stdout contract
2026-03-06 02:15:36 +08:00
Willie 1b8940a630 fix(extras): copy-mode idempotency and display mode label
- Add contentEqual() byte comparison for copy-mode idempotency check:
  re-running sync extras no longer marks identical copies as conflicts
- Restore mode default in CLI handler so display shows "(merge)"
  instead of "()" for targets with no explicit mode
2026-03-04 12:16:32 +08:00
Willie 55bc5289c6 refactor(extras): simplify after code review
- Fix bug: pass `rest` (not `args`) to cmdSyncExtras in --all path
- Return error from cmdSyncExtras when totalErrors > 0
- Remove empty if-block dead code in syncOneExtraFile
- Remove redundant mode default (SyncExtra already defaults to merge)
- Consolidate capitalize/capitalizeFirst into single Unicode-safe helper
- Remove trivial copyExtraFile wrapper, call copyFile directly
- Warn when --all is used in project mode (extras are global only)
- Cache os.UserHomeDir() at package level for shortenPath
- Use source file set instead of per-file os.Stat in pruneExtraOrphans
2026-03-04 12:16:32 +08:00
Willie 65c7d75c41 style: fix gofmt alignment in extras_test.go and ui.go 2026-03-04 12:16:32 +08:00
Willie fbccdb9628 feat(sync): add extras sync engine — walk, symlink/copy, prune 2026-03-04 12:16:32 +08:00
Willie 38f8f1c796 fix(symlink): resolve symlinked source/target dirs across all Walk callsites
filepath.Walk/WalkDir silently skip symlinked root directories because
os.Lstat sees the root as a non-directory symlink and never enters it.
This affected update, uninstall, reconcile, and server handlers when
the source directory was a symlink (common with dotfiles managers).

Extract ResolveSymlink() from sync.go into internal/utils/path.go and
apply it at every filepath.Walk/WalkDir callsite on source/target dirs.

Also add containment guards to resolveGroupSkills (uninstall) and
resolveGroupUpdatable (update) to reject group directories that are
symlinks pointing outside the source tree.
2026-03-02 10:05:57 +08:00